@duvoai/cli 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../src/bin/create-program.ts", "../../src/api/agent-folder-schemas.ts", "../../src/errors.ts", "../../src/client/client.ts", "../../src/output/should-color.ts", "../../src/output/green.ts", "../../src/output/json.ts", "../../src/output/text.ts", "../../src/config/defaults.ts", "../../src/config/env.ts", "../../src/config/store.ts", "../../src/config/paths.ts", "../../src/config/resolve.ts", "../../src/commands/shared/profile-flag.ts", "../../src/commands/shared/require-auth.ts", "../../src/commands/shared/trim-required.ts", "../../src/commands/agent-folders/create.ts", "../../src/commands/shared/confirm.ts", "../../src/commands/agent-folders/delete.ts", "../../src/output/table-header.ts", "../../src/output/table.ts", "../../src/commands/agent-folders/list.ts", "../../src/commands/agent-folders/move-agents.ts", "../../src/commands/agent-folders/update.ts", "../../src/commands/agent-folders/index.ts", "../../src/commands/agents/create.ts", "../../../packages/shared/src/analytics/events.ts", "../../../packages/shared/src/billing/customer-portal.ts", "../../../packages/shared/src/billing/entitlements.ts", "../../../packages/shared/src/billing/invoices.ts", "../../../packages/shared/src/billing/plan-versions.ts", "../../../packages/shared/src/billing/plan-display.ts", "../../../packages/shared/src/billing/subscription-details.ts", "../../../packages/shared/src/billing/subscription-status.ts", "../../../packages/shared/src/billing/usage.ts", "../../../packages/shared/src/types/agent-run.ts", "../../../packages/shared/src/schemas/automation-message.ts", "../../../packages/shared/src/schemas/run-evaluation.ts", "../../../packages/shared/src/constants/models.ts", "../../../packages/shared/src/constants/agent.ts", "../../../packages/shared/src/constants/browser.ts", "../../../packages/shared/src/constants/build.ts", "../../../packages/shared/src/constants/case-queue.ts", "../../../packages/shared/src/constants/e2b.ts", "../../../packages/shared/src/constants/evaluation-rubrics.ts", "../../../packages/shared/src/constants/human-request.ts", "../../../packages/shared/src/constants/integration-credentials.ts", "../../../packages/shared/src/constants/plugins.ts", "../../../packages/shared/src/constants/solutions.ts", "../../../packages/shared/src/constants/triggers.ts", "../../../packages/shared/src/cookies/constants.ts", "../../../packages/shared/src/clarity-screenshare/types.ts", "../../../packages/shared/src/clarity-v2/api-schema.ts", "../../../packages/shared/src/types/clarity.ts", "../../../packages/shared/src/clarity-v2/process-data.ts", "../../../packages/shared/src/clarity-v2/validators.ts", "../../../packages/shared/src/error-handling/stringify-error.ts", "../../../packages/shared/src/error-handling/make-sentry-reporter.ts", "../../../packages/shared/src/organization-roles.ts", "../../../packages/shared/src/roles.ts", "../../../packages/shared/src/schemas/api-keys.ts", "../../../packages/shared/src/schemas/ask-user-question.ts", "../../../packages/shared/src/schemas/browser-replay.ts", "../../../packages/shared/src/schemas/clarity-screenshare-session.ts", "../../../packages/shared/src/schemas/error.ts", "../../../packages/shared/src/schemas/human-request.ts", "../../../packages/shared/src/schemas/logo.ts", "../../../packages/shared/src/schemas/success.ts", "../../../packages/shared/src/types/admin-organization.ts", "../../../packages/shared/src/types/organization.ts", "../../../packages/shared/src/types/agent-api.ts", "../../../packages/shared/src/types/agent-config.ts", "../../../packages/shared/src/types/agent-feedback.ts", "../../../packages/shared/src/types/agent-folder-api.ts", "../../../packages/shared/src/types/agent-learning.ts", "../../../packages/shared/src/types/browser-agent.ts", "../../../packages/shared/src/types/build-api.ts", "../../../packages/shared/src/types/case-approval.ts", "../../../packages/shared/src/types/case-queue-filters.ts", "../../../packages/shared/src/types/case-queue-folder-api.ts", "../../../packages/shared/src/types/case-queue-labels.ts", "../../../packages/shared/src/types/case-triggers.ts", "../../../packages/shared/src/types/cases-ui.ts", "../../../packages/shared/src/types/clarity-overview.ts", "../../../packages/shared/src/types/composio.ts", "../../../packages/shared/src/types/credentials.ts", "../../../packages/shared/src/types/feature-flags.ts", "../../../packages/shared/src/types/files-api.ts", "../../../packages/shared/src/types/global-admin.ts", "../../../packages/shared/src/types/integration.ts", "../../../packages/shared/src/types/job-list.ts", "../../../packages/shared/src/types/mcp-workflow.ts", "../../../packages/shared/src/types/plugin-api.ts", "../../../packages/shared/src/types/profile.ts", "../../../packages/shared/src/types/recording-session.ts", "../../../packages/shared/src/types/run-config.ts", "../../../packages/shared/src/types/skill-api.ts", "../../../packages/shared/src/types/team.ts", "../../../packages/shared/src/types/team-invitation.ts", "../../../packages/shared/src/types/team-insights.ts", "../../../packages/shared/src/types/team-invite-link.ts", "../../../packages/shared/src/utils/agent-run-api-key.ts", "../../../packages/shared/src/utils/case-queue-filter-params.ts", "../../../packages/shared/src/utils/composio.ts", "../../../packages/shared/src/utils/domain.ts", "../../../packages/shared/src/utils/extract-agent-mention-ids.ts", "../../../packages/shared/src/utils/extract-system-prompt-text.ts", "../../../packages/shared/src/utils/get-sentry-environment.ts", "../../../packages/shared/src/utils/has-instructions.ts", "../../../packages/shared/src/utils/json/safe-parse-json.ts", "../../../packages/shared/src/utils/label-color-hue.ts", "../../../packages/shared/src/utils/mcp-server-label.ts", "../../../packages/shared/src/utils/normalize-agent-config.ts", "../../../packages/shared/src/utils/p-retry.ts", "../../../packages/shared/src/utils/parse-agent-config.ts", "../../../packages/shared/src/utils/parse-run-config.ts", "../../../node_modules/.pnpm/jsonrepair@3.13.2/node_modules/jsonrepair/src/utils/JSONRepairError.ts", "../../../node_modules/.pnpm/jsonrepair@3.13.2/node_modules/jsonrepair/src/utils/stringUtils.ts", "../../../node_modules/.pnpm/jsonrepair@3.13.2/node_modules/jsonrepair/src/regular/jsonrepair.ts", "../../src/api/agent-schemas.ts", "../../src/commands/agents/get.ts", "../../src/commands/shared/pagination.ts", "../../src/commands/agents/list.ts", "../../src/api/schedule-schemas.ts", "../../src/commands/agents/schedules.ts", "../../src/commands/agents/update.ts", "../../src/commands/agents/index.ts", "../../src/api/parse-fields.ts", "../../src/api/read-input.ts", "../../src/commands/api-render.ts", "../../src/commands/api.ts", "../../src/api/build-schemas.ts", "../../src/api/json-value.ts", "../../src/commands/builds/create.ts", "../../src/commands/builds/get.ts", "../../src/commands/builds/list.ts", "../../src/commands/builds/update.ts", "../../src/commands/builds/index.ts", "../../src/commands/cases/parse-case-ids.ts", "../../src/commands/cases/bulk-delegate.ts", "../../src/commands/cases/bulk-delete.ts", "../../src/commands/cases/bulk-retry.ts", "../../src/commands/cases/bulk-update-status.ts", "../../src/commands/cases/clear.ts", "../../src/commands/cases/create.ts", "../../src/commands/cases/delete.ts", "../../src/commands/cases/get.ts", "../../src/commands/cases/labels.ts", "../../src/commands/cases/list.ts", "../../src/commands/cases/runs.ts", "../../src/commands/cases/index.ts", "../../src/commands/files/content.ts", "../../src/commands/files/content-set.ts", "../../src/commands/files/delete.ts", "../../src/commands/files/download-url.ts", "../../src/commands/files/list.ts", "../../src/commands/files/rename.ts", "../../src/commands/files/upload-url.ts", "../../src/commands/files/index.ts", "../../src/commands/login.ts", "../../src/config/profiles.ts", "../../src/commands/logout.ts", "../../src/commands/plugins/list.ts", "../../src/commands/plugins/index.ts", "../../src/output/format.ts", "../../src/commands/profiles/render-list.ts", "../../src/commands/profiles/list.ts", "../../src/commands/profiles/remove.ts", "../../src/commands/profiles/rename.ts", "../../src/commands/profiles/use.ts", "../../src/commands/profiles/index.ts", "../../src/commands/queue-labels/index.ts", "../../src/commands/queues/agents.ts", "../../src/commands/queues/create.ts", "../../src/commands/queues/delete.ts", "../../src/commands/queues/get.ts", "../../src/commands/queues/list.ts", "../../src/commands/queues/update.ts", "../../src/commands/queues/index.ts", "../../src/api/run-schemas.ts", "../../src/commands/runs/get.ts", "../../src/commands/runs/list.ts", "../../src/commands/runs/messages.ts", "../../src/commands/runs/respond.ts", "../../src/commands/runs/send-message.ts", "../../src/commands/runs/start.ts", "../../src/commands/runs/stop.ts", "../../src/commands/runs/index.ts", "../../src/api/sandbox-schemas.ts", "../../src/commands/sandboxes/create.ts", "../../src/commands/sandboxes/files.ts", "../../src/commands/sandboxes/prepare-upload-url.ts", "../../src/commands/sandboxes/upload.ts", "../../src/commands/sandboxes/index.ts", "../../src/commands/skills/delete.ts", "../../src/commands/skills/download.ts", "../../src/commands/skills/file-get.ts", "../../src/commands/skills/file-update.ts", "../../src/commands/skills/files.ts", "../../src/commands/skills/generate.ts", "../../src/commands/skills/list.ts", "../../src/commands/skills/index.ts", "../../src/commands/team/members.ts", "../../src/commands/team/index.ts", "../../src/commands/whoami.ts", "../../src/bin/duvo.ts"],
4
- "sourcesContent": ["import { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { Command } from \"commander\";\n\nimport { registerAgentFolders } from \"@/commands/agent-folders/index.js\";\nimport { registerAgents } from \"@/commands/agents/index.js\";\nimport { registerApi } from \"@/commands/api.js\";\nimport { registerBuilds } from \"@/commands/builds/index.js\";\nimport { registerCases } from \"@/commands/cases/index.js\";\nimport { registerFiles } from \"@/commands/files/index.js\";\nimport { registerLogin } from \"@/commands/login.js\";\nimport { registerLogout } from \"@/commands/logout.js\";\nimport { registerPlugins } from \"@/commands/plugins/index.js\";\nimport { registerProfiles } from \"@/commands/profiles/index.js\";\nimport { registerQueueLabels } from \"@/commands/queue-labels/index.js\";\nimport { registerQueues } from \"@/commands/queues/index.js\";\nimport { registerRuns } from \"@/commands/runs/index.js\";\nimport { registerSandboxes } from \"@/commands/sandboxes/index.js\";\nimport { registerSkills } from \"@/commands/skills/index.js\";\nimport { registerTeam } from \"@/commands/team/index.js\";\nimport { registerWhoami } from \"@/commands/whoami.js\";\n\nconst packageJsonPath = join(\n dirname(fileURLToPath(import.meta.url)),\n \"../../package.json\"\n);\nconst { version } = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as {\n version: string;\n};\n\n/**\n * Build a fresh `Command` tree for the CLI. Shared between the real\n * binary (`bin/duvo.ts`) and the test harness so tests can never\n * silently drift out of sync with the production command set.\n */\nexport function createProgram(): Command {\n const program = new Command();\n\n program\n .name(\"duvo\")\n .description(\"Command-line interface for the Duvo public API\")\n .version(version)\n .option(\n \"--profile <name>\",\n \"use a specific profile for this invocation (overrides default profile)\"\n );\n\n registerLogin(program);\n registerLogout(program);\n registerWhoami(program);\n registerProfiles(program);\n registerApi(program);\n registerAgents(program);\n registerAgentFolders(program);\n registerBuilds(program);\n registerRuns(program);\n registerQueues(program);\n registerQueueLabels(program);\n registerCases(program);\n registerSandboxes(program);\n registerFiles(program);\n registerPlugins(program);\n registerSkills(program);\n registerTeam(program);\n\n return program;\n}\n", "import { z } from \"zod\";\n\nconst publicAgentFolderSchema = z.object({\n id: z.string(),\n name: z.string(),\n team_id: z.string().nullish(),\n parent_folder_id: z.string().nullish(),\n created_at: z.string().nullish(),\n updated_at: z.string().nullish(),\n agent_count: z.number().nullish(),\n subfolder_count: z.number().nullish(),\n});\n\nexport type PublicAgentFolder = z.infer<typeof publicAgentFolderSchema>;\n\nexport const listAgentFoldersResponseSchema = z.object({\n folders: z.array(publicAgentFolderSchema),\n});\n\nexport type ListAgentFoldersResponse = z.infer<\n typeof listAgentFoldersResponseSchema\n>;\n\nexport const folderResponseSchema = z.object({\n folder: publicAgentFolderSchema,\n});\n\nexport type FolderResponse = z.infer<typeof folderResponseSchema>;\n\nexport const deleteFolderResponseSchema = z.object({\n success: z.boolean(),\n});\n\nexport type DeleteFolderResponse = z.infer<typeof deleteFolderResponseSchema>;\n\nexport const moveAgentsResponseSchema = z.object({\n success: z.boolean(),\n moved_count: z.number(),\n});\n\nexport type MoveAgentsResponse = z.infer<typeof moveAgentsResponseSchema>;\n", "export const EXIT_CODE = {\n SUCCESS: 0,\n GENERIC: 1,\n AUTH: 2,\n NOT_FOUND: 3,\n} as const;\n\nexport type ExitCode = (typeof EXIT_CODE)[keyof typeof EXIT_CODE];\n\nexport class CliError extends Error {\n public readonly exitCode: ExitCode;\n\n constructor(message: string, exitCode: ExitCode = EXIT_CODE.GENERIC) {\n super(message);\n this.name = \"CliError\";\n this.exitCode = exitCode;\n }\n}\n\nexport class AuthCliError extends CliError {\n constructor(message: string) {\n super(message, EXIT_CODE.AUTH);\n this.name = \"AuthCliError\";\n }\n}\n\n/** Signals a cooperative user-driven cancel (Ctrl-C, answering \"no\"). */\nexport class CancelCliError extends CliError {\n constructor(message = \"Cancelled.\") {\n super(message, EXIT_CODE.GENERIC);\n this.name = \"CancelCliError\";\n }\n}\n\nexport function handleCliError(error: unknown): never {\n if (error instanceof CliError) {\n process.stderr.write(`${error.message}\\n`);\n process.exit(error.exitCode);\n }\n\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`error: ${message}\\n`);\n process.exit(EXIT_CODE.GENERIC);\n}\n", "import { CliError, EXIT_CODE } from \"@/errors.js\";\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\nexport type HttpRequestOptions = {\n method: string;\n path: string;\n apiKey: string;\n apiBaseUrl: string;\n /** JSON body. Omitted for GET/HEAD-style requests. */\n body?: unknown;\n /** Appended to the resolved URL. */\n searchParams?: URLSearchParams;\n /** Request timeout in ms. Defaults to {@link DEFAULT_REQUEST_TIMEOUT_MS}. */\n timeoutMs?: number;\n};\n\nexport type HttpUploadOptions = {\n path: string;\n apiKey: string;\n apiBaseUrl: string;\n /** Multipart form fields. File parts go through `Blob`. */\n formData: FormData;\n /** Request timeout in ms. Defaults to {@link DEFAULT_REQUEST_TIMEOUT_MS}. */\n timeoutMs?: number;\n};\n\n/**\n * Makes an authenticated request to the Duvo public API and returns the\n * parsed JSON response. Maps well-known status codes to `CliError` with\n * the right exit code; other non-2xx responses throw a generic\n * `CliError` containing the server's response body.\n *\n * Empty response bodies resolve to `null`. Non-JSON responses resolve to\n * the raw text \u2014 the caller decides how to render it.\n */\nexport async function httpRequest(\n options: HttpRequestOptions\n): Promise<unknown> {\n const url = buildUrl(options.apiBaseUrl, options.path, options.searchParams);\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${options.apiKey}`,\n Accept: \"application/json\",\n };\n\n const timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n const init: RequestInit = {\n method: options.method,\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n };\n if (options.body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n init.body = JSON.stringify(options.body);\n }\n\n try {\n const response = await fetch(url, init);\n return await handleResponse(response, options.method, options.path);\n } catch (error) {\n if (isTimeoutError(error)) {\n throw new CliError(\n `Request timed out after ${timeoutMs}ms: ${options.method} ${options.path}`\n );\n }\n\n throw error;\n }\n}\n\n/**\n * Uploads a multipart/form-data request to the Duvo public API and\n * returns the parsed JSON response. The browser fetch builds the\n * `Content-Type` header (with the multipart boundary) from the\n * `FormData` body \u2014 do not set it manually.\n */\nexport async function httpUpload(options: HttpUploadOptions): Promise<unknown> {\n const url = buildUrl(options.apiBaseUrl, options.path, undefined);\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${options.apiKey}`,\n Accept: \"application/json\",\n };\n\n const timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n const init: RequestInit = {\n method: \"POST\",\n headers,\n body: options.formData,\n signal: AbortSignal.timeout(timeoutMs),\n };\n\n try {\n const response = await fetch(url, init);\n return await handleResponse(response, \"POST\", options.path);\n } catch (error) {\n if (isTimeoutError(error)) {\n throw new CliError(\n `Request timed out after ${timeoutMs}ms: POST ${options.path}`\n );\n }\n\n throw error;\n }\n}\n\nfunction isTimeoutError(error: unknown): boolean {\n return (\n error instanceof DOMException &&\n (error.name === \"TimeoutError\" || error.name === \"AbortError\")\n );\n}\n\n/**\n * Resolves an API path against the configured base URL. The base URL must\n * be an origin only (scheme + host + optional port) \u2014 any path component\n * is discarded, because `new URL(\"/v1/agents\", \"https://host/foo/\")`\n * resolves to `https://host/v1/agents`, not `https://host/foo/v1/agents`.\n */\nconst ABSOLUTE_URL = /^[a-zA-Z][a-zA-Z\\d+.-]*:\\/\\//;\n\nfunction buildUrl(\n base: string,\n path: string,\n searchParams: URLSearchParams | undefined\n): URL {\n if (ABSOLUTE_URL.test(path)) {\n throw new CliError(\n `Invalid path \"${path}\". Expected an API path like \"/v1/agents\" \u2014 absolute URLs are not allowed.`\n );\n }\n\n const normalized = path.startsWith(\"/\") ? path : `/${path}`;\n const url = new URL(normalized, ensureTrailingSlash(base));\n if (searchParams) {\n for (const [key, value] of searchParams) {\n url.searchParams.append(key, value);\n }\n }\n\n return url;\n}\n\nfunction ensureTrailingSlash(base: string): string {\n return base.endsWith(\"/\") ? base : `${base}/`;\n}\n\nasync function handleResponse(\n response: Response,\n method: string,\n path: string\n): Promise<unknown> {\n if (response.status === 401) {\n throw new CliError(\n \"Unauthorized. Check that the API key is valid.\",\n EXIT_CODE.AUTH\n );\n }\n\n if (response.status === 404) {\n throw new CliError(`Not found: ${method} ${path}`, EXIT_CODE.NOT_FOUND);\n }\n\n if (!response.ok) {\n const detail = await safeReadText(response);\n const suffix = detail.length > 0 ? `: ${detail}` : \"\";\n throw new CliError(\n `Request failed (${response.status} ${response.statusText})${suffix}`\n );\n }\n\n const text = await safeReadText(response);\n if (text.length === 0) {\n return null;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nasync function safeReadText(response: Response): Promise<string> {\n try {\n return await response.text();\n } catch {\n return \"\";\n }\n}\n", "/**\n * Returns whether ANSI styling should be emitted. Honors `NO_COLOR` and\n * skips styling when stdout is not a TTY so piped output stays clean.\n */\nexport function shouldColor(): boolean {\n if (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== \"\") {\n return false;\n }\n\n return Boolean(process.stdout.isTTY);\n}\n", "import { shouldColor } from \"./should-color.js\";\n\nconst GREEN = \"\\x1b[32m\";\nconst RESET = \"\\x1b[0m\";\n\nexport function green(text: string): string {\n if (!shouldColor()) {\n return text;\n }\n\n return `${GREEN}${text}${RESET}`;\n}\n", "/**\n * Prints a value as pretty JSON (2-space indent) to stdout. This is the\n * stable output contract \u2014 scripts should always be able to `| jq` the\n * result. No colour, no truncation.\n */\nexport function printJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2));\n}\n", "export type KeyValueEntry = {\n label: string;\n value: string;\n};\n\n/**\n * Renders a labelled key/value block for single-resource views.\n * Labels are left-padded to the widest label so values line up.\n */\nexport function renderKeyValue(entries: readonly KeyValueEntry[]): string {\n if (entries.length === 0) {\n return \"\";\n }\n\n const labelWidth = Math.max(...entries.map((e) => e.label.length));\n return entries\n .map((entry) => `${entry.label.padEnd(labelWidth)} ${entry.value}`)\n .join(\"\\n\");\n}\n", "import { type Config } from \"@/config/types.js\";\n\nexport const DEFAULT_API_BASE_URL = \"https://api.duvo.ai\";\n\nexport function emptyConfig(): Config {\n return { defaultProfile: null, profiles: {} };\n}\n", "import { z } from \"zod\";\n\nconst optionalEnvString = z\n .string()\n .optional()\n .transform((value) =>\n value === undefined || value === \"\" ? undefined : value\n );\n\nconst CliEnvSchema = z.object({\n DUVO_PROFILE: optionalEnvString,\n DUVO_API_KEY: optionalEnvString,\n DUVO_API_BASE_URL: optionalEnvString,\n});\n\nexport type CliEnv = z.output<typeof CliEnvSchema>;\n\nexport function parseCliEnv(env: NodeJS.ProcessEnv): CliEnv {\n return CliEnvSchema.parse(env);\n}\n", "import { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nimport { DEFAULT_API_BASE_URL, emptyConfig } from \"@/config/defaults.js\";\nimport { getConfigPath } from \"@/config/paths.js\";\nimport { type Config, type Profile } from \"@/config/types.js\";\n\nconst FILE_MODE = 0o600;\nconst DIR_MODE = 0o700;\n\nexport async function readConfig(): Promise<Config> {\n const path = getConfigPath();\n try {\n const raw = await readFile(path, \"utf8\");\n const parsed = JSON.parse(raw) as unknown;\n return normalizeConfig(parsed);\n } catch (error) {\n if (isNotFound(error)) {\n return emptyConfig();\n }\n\n throw error;\n }\n}\n\nexport async function writeConfig(config: Config): Promise<void> {\n const path = getConfigPath();\n await mkdir(dirname(path), { recursive: true, mode: DIR_MODE });\n await writeFile(path, JSON.stringify(config, null, 2), {\n mode: FILE_MODE,\n encoding: \"utf8\",\n });\n}\n\nexport async function deleteConfig(): Promise<boolean> {\n const path = getConfigPath();\n try {\n await rm(path);\n return true;\n } catch (error) {\n if (isNotFound(error)) {\n return false;\n }\n\n throw error;\n }\n}\n\n/**\n * Accepts the legacy single-profile shape ({ apiKey, apiBaseUrl }) and\n * migrates it into the named-profile shape under the \"default\" name. Any\n * fields we don't recognize are dropped.\n */\nfunction normalizeConfig(parsed: unknown): Config {\n if (parsed === null || typeof parsed !== \"object\") {\n return emptyConfig();\n }\n\n const record = parsed as Record<string, unknown>;\n\n // Legacy single-profile migration.\n if (\n typeof record.apiKey === \"string\" &&\n record.profiles === undefined &&\n record.defaultProfile === undefined\n ) {\n const apiBaseUrl =\n typeof record.apiBaseUrl === \"string\"\n ? record.apiBaseUrl\n : DEFAULT_API_BASE_URL;\n return {\n defaultProfile: \"default\",\n profiles: {\n default: { apiKey: record.apiKey, apiBaseUrl },\n },\n };\n }\n\n const profiles: Record<string, Profile> = {};\n const rawProfiles =\n record.profiles && typeof record.profiles === \"object\"\n ? (record.profiles as Record<string, unknown>)\n : {};\n for (const [name, value] of Object.entries(rawProfiles)) {\n if (value === null || typeof value !== \"object\") {\n continue;\n }\n\n const profile = value as Record<string, unknown>;\n if (typeof profile.apiKey !== \"string\") {\n continue;\n }\n\n const apiBaseUrl =\n typeof profile.apiBaseUrl === \"string\"\n ? profile.apiBaseUrl\n : DEFAULT_API_BASE_URL;\n profiles[name] = { apiKey: profile.apiKey, apiBaseUrl };\n }\n\n const defaultProfile =\n typeof record.defaultProfile === \"string\" &&\n record.defaultProfile in profiles\n ? record.defaultProfile\n : null;\n\n return { defaultProfile, profiles };\n}\n\nfunction isNotFound(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code: unknown }).code === \"ENOENT\"\n );\n}\n", "import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst CONFIG_DIR_NAME = \"duvo\";\nconst CONFIG_FILE_NAME = \"config.json\";\n\nfunction getConfigDir(): string {\n const xdg = process.env.XDG_CONFIG_HOME;\n if (xdg && xdg.length > 0) {\n return join(xdg, CONFIG_DIR_NAME);\n }\n\n return join(homedir(), \".config\", CONFIG_DIR_NAME);\n}\n\nexport function getConfigPath(): string {\n return join(getConfigDir(), CONFIG_FILE_NAME);\n}\n", "import { DEFAULT_API_BASE_URL } from \"@/config/defaults.js\";\nimport { type CliEnv, parseCliEnv } from \"@/config/env.js\";\nimport { readConfig } from \"@/config/store.js\";\nimport { type Config } from \"@/config/types.js\";\nimport { AuthCliError } from \"@/errors.js\";\n\nexport type ResolvedConfig = {\n apiKey: string | null;\n apiBaseUrl: string;\n /** Name of the profile we resolved to, or null if we fell through to env-only. */\n profileName: string | null;\n};\n\nexport type ResolveOptions = {\n /** From the --profile CLI flag. Takes precedence over env and stored default. */\n profileFlag?: string | undefined;\n};\n\n/**\n * Selection precedence:\n * profile: --profile flag > DUVO_PROFILE env > config.defaultProfile\n * apiKey: DUVO_API_KEY env > profile.apiKey\n * baseUrl: DUVO_API_BASE_URL env > profile.apiBaseUrl > default\n *\n * If --profile is given but unknown, this throws (caller maps to exit 2).\n * DUVO_PROFILE being unset/unknown falls through silently so users can use\n * env overrides without breaking other shells.\n */\nexport async function resolveConfig(\n options: ResolveOptions = {}\n): Promise<ResolvedConfig> {\n const config = await readConfig();\n return selectEffectiveConfig(config, options, parseCliEnv(process.env));\n}\n\nexport function selectEffectiveConfig(\n config: Config,\n options: ResolveOptions,\n env: CliEnv\n): ResolvedConfig {\n const profileName = selectProfileName(config, options, env);\n const profile = profileName ? (config.profiles[profileName] ?? null) : null;\n\n const apiKey = env.DUVO_API_KEY ?? profile?.apiKey ?? null;\n const apiBaseUrl =\n env.DUVO_API_BASE_URL ?? profile?.apiBaseUrl ?? DEFAULT_API_BASE_URL;\n\n return { apiKey, apiBaseUrl, profileName };\n}\n\nfunction selectProfileName(\n config: Config,\n options: ResolveOptions,\n env: CliEnv\n): string | null {\n const flag = options.profileFlag;\n if (flag && flag.length > 0) {\n if (!(flag in config.profiles)) {\n throw new UnknownProfileError(flag);\n }\n\n return flag;\n }\n\n if (env.DUVO_PROFILE && env.DUVO_PROFILE in config.profiles) {\n return env.DUVO_PROFILE;\n }\n\n return config.defaultProfile;\n}\n\nexport class UnknownProfileError extends AuthCliError {\n constructor(public readonly profileName: string) {\n super(\n `Profile \"${profileName}\" does not exist. Run \\`duvo profiles list\\` to see available profiles.`\n );\n this.name = \"UnknownProfileError\";\n }\n}\n", "import { type Command } from \"commander\";\n\n/**\n * Pulls the global `--profile` option off the root command. Commander\n * merges parent options into `opts()` for subcommands, but the value\n * lives on the root \u2014 this helper walks up to find it regardless of how\n * deep the subcommand sits.\n */\nexport function getProfileFlag(command: Command): string | undefined {\n let node: Command | null = command;\n while (node) {\n const opts = node.opts<{ profile?: string }>();\n if (opts.profile) {\n return opts.profile;\n }\n\n node = node.parent ?? null;\n }\n\n return undefined;\n}\n", "import { type Command } from \"commander\";\n\nimport { resolveConfig, type ResolvedConfig } from \"@/config/resolve.js\";\nimport { AuthCliError } from \"@/errors.js\";\n\nimport { getProfileFlag } from \"./profile-flag.js\";\n\nexport type AuthenticatedConfig = ResolvedConfig & { apiKey: string };\n\n/**\n * Resolves the effective profile for this invocation and guarantees an\n * API key is present. Intended for every command that hits the API \u2014\n * throws `AuthCliError` (exit code 2) if no key is stored or passed via\n * env, so callers can assume `apiKey` is a non-null string.\n */\nexport async function requireAuthenticatedConfig(\n command: Command\n): Promise<AuthenticatedConfig> {\n const resolved = await resolveConfig({\n profileFlag: getProfileFlag(command),\n });\n if (!resolved.apiKey) {\n throw new AuthCliError(\n \"Not logged in. Run `duvo login` to save an API key.\"\n );\n }\n\n return { ...resolved, apiKey: resolved.apiKey };\n}\n", "import { CliError } from \"@/errors.js\";\n\n/**\n * Trims a CLI flag value and rejects whitespace-only input. Returns the\n * trimmed string when valid, throws `CliError` otherwise. Use for any\n * required-when-passed flag (folder IDs, names, etc.) so we never send\n * an empty string to the API.\n */\nexport function trimRequired(value: string, flag: string): string {\n const trimmed = value.trim();\n if (trimmed.length === 0) {\n throw new CliError(`${flag} must not be empty`);\n }\n\n return trimmed;\n}\n", "import { type Command } from \"commander\";\n\nimport { folderResponseSchema } from \"@/api/agent-folder-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { trimRequired } from \"../shared/trim-required.js\";\n\ntype CreateOptions = {\n name: string;\n parent?: string;\n json?: boolean;\n};\n\ntype RequestBody = {\n name: string;\n parent_folder_id?: string;\n};\n\nexport function registerAgentFoldersCreate(folders: Command): void {\n folders\n .command(\"create\")\n .description(\"Create a new agent folder\")\n .requiredOption(\"--name <name>\", \"human-readable folder name\")\n .option(\n \"--parent <id>\",\n \"parent folder ID (omit to create at the root level)\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function createAction(this: Command, options: CreateOptions) {\n const name = trimRequired(options.name, \"--name\");\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const body: RequestBody = { name };\n if (options.parent !== undefined) {\n body.parent_folder_id = trimRequired(options.parent, \"--parent\");\n }\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/agent-folders\",\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = folderResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { folder } = parsed.data;\n\n console.log(green(\"Folder created!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: folder.id },\n { label: \"Name\", value: folder.name },\n { label: \"Parent\", value: folder.parent_folder_id ?? \"(root)\" },\n { label: \"Created\", value: folder.created_at ?? \"\" },\n ])\n );\n });\n}\n", "import { confirm, isCancel } from \"@clack/prompts\";\n\nimport { CancelCliError, CliError } from \"@/errors.js\";\n\ntype ConfirmOptions = {\n /** Question shown to the user, e.g. `Remove profile \"acme\"?`. */\n message: string;\n /** Caller already collected consent (e.g. via `--yes`). */\n skip: boolean;\n};\n\n/**\n * Prompt for [y/N] confirmation on a destructive action. Skipped when\n * the caller passes `skip: true` (typically from a `--yes` flag).\n *\n * In non-interactive shells (no TTY on stdin) we refuse rather than\n * silently treat piped input as consent. The caller must opt in via\n * `--yes` to proceed without a prompt.\n *\n * Throws instead of calling `process.exit` so the top-level error\n * handler remains the single chokepoint for process termination.\n */\nexport async function confirmDestructive(\n options: ConfirmOptions\n): Promise<void> {\n if (options.skip) {\n return;\n }\n\n if (!process.stdin.isTTY) {\n throw new CliError(\n `${options.message} Pass --yes to confirm without an interactive prompt.`\n );\n }\n\n const answer = await confirm({\n message: options.message,\n initialValue: false,\n });\n\n if (isCancel(answer) || !answer) {\n throw new CancelCliError();\n }\n}\n", "import { type Command } from \"commander\";\n\nimport { deleteFolderResponseSchema } from \"@/api/agent-folder-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { trimRequired } from \"../shared/trim-required.js\";\n\ntype DeleteOptions = {\n force?: boolean;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerAgentFoldersDelete(folders: Command): void {\n folders\n .command(\"delete <id>\")\n .description(\"Delete an agent folder\")\n .option(\n \"--force\",\n \"delete even if the folder contains assignments or subfolders (contained agents move to the root)\"\n )\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function deleteAction(\n this: Command,\n id: string,\n options: DeleteOptions\n ) {\n const folderId = trimRequired(id, \"<id>\");\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Delete folder \"${folderId}\"?`,\n skip: options.yes ?? false,\n });\n\n const searchParams = new URLSearchParams();\n if (options.force === true) {\n searchParams.append(\"force\", \"true\");\n }\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/agent-folders/${encodeURIComponent(folderId)}`,\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = deleteFolderResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n throw new CliError(`Failed to delete folder \"${folderId}\".`);\n }\n\n console.log(green(`Folder \"${folderId}\" deleted.`));\n });\n}\n", "import { shouldColor } from \"./should-color.js\";\n\nconst STYLE = \"\\x1b[4;36m\";\nconst RESET = \"\\x1b[0m\";\n\n/**\n * Style a column header (cyan + underline). Wrap *after* padding \u2014\n * ANSI escape codes count toward `string.length` and would otherwise\n * misalign neighbouring columns.\n */\nexport function tableHeader(text: string): string {\n if (!shouldColor()) {\n return text;\n }\n\n return `${STYLE}${text}${RESET}`;\n}\n", "import { tableHeader } from \"./table-header.js\";\n\nexport type Column<T> = {\n header: string;\n cell: (row: T) => string;\n /**\n * Optional cap on the rendered width of the column. Cells wider than\n * this are truncated with a trailing `\u2026` to keep each row on one line.\n * The header is truncated too so the column never exceeds the cap.\n */\n maxWidth?: number;\n};\n\n/**\n * Renders a fixed-width ASCII table. Columns auto-size to the widest\n * cell (including the header) but never exceed `maxWidth` when set.\n * Headers are styled via `tableHeader` (cyan + underline) when stdout\n * is a TTY; in non-TTY contexts the styling is a no-op so piped output\n * stays clean.\n */\nexport function renderTable<T>(\n columns: readonly Column<T>[],\n rows: readonly T[]\n): string {\n if (columns.length === 0) {\n return \"\";\n }\n\n const cells = rows.map((row) => columns.map((col) => col.cell(row)));\n const widths = columns.map((col, i) => {\n const contentWidth = Math.max(\n col.header.length,\n ...cells.map((row) => row[i].length)\n );\n return col.maxWidth ? Math.min(col.maxWidth, contentWidth) : contentWidth;\n });\n\n const headerLine = columns\n .map((col, i) =>\n tableHeader(pad(truncate(col.header, widths[i]), widths[i]))\n )\n .join(\" \");\n const bodyLines = cells.map((row) =>\n row.map((cell, i) => pad(truncate(cell, widths[i]), widths[i])).join(\" \")\n );\n\n return [headerLine, ...bodyLines].join(\"\\n\");\n}\n\nfunction pad(value: string, width: number): string {\n if (value.length >= width) {\n return value;\n }\n\n return value + \" \".repeat(width - value.length);\n}\n\nfunction truncate(value: string, width: number): string {\n if (value.length <= width) {\n return value;\n }\n\n if (width <= 1) {\n return \"\u2026\".slice(0, width);\n }\n\n return `${value.slice(0, width - 1)}\u2026`;\n}\n", "import { type Command } from \"commander\";\n\nimport {\n listAgentFoldersResponseSchema,\n type PublicAgentFolder,\n} from \"@/api/agent-folder-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: PublicAgentFolder) => row.id },\n { header: \"NAME\", cell: (row: PublicAgentFolder) => row.name },\n {\n header: \"PARENT\",\n cell: (row: PublicAgentFolder) => row.parent_folder_id ?? \"(root)\",\n },\n {\n header: \"AGENTS\",\n cell: (row: PublicAgentFolder) =>\n row.agent_count === undefined || row.agent_count === null\n ? \"\"\n : String(row.agent_count),\n },\n {\n header: \"SUBFOLDERS\",\n cell: (row: PublicAgentFolder) =>\n row.subfolder_count === undefined || row.subfolder_count === null\n ? \"\"\n : String(row.subfolder_count),\n },\n] as const;\n\nexport function registerAgentFoldersList(folders: Command): void {\n folders\n .command(\"list\", { isDefault: true })\n .description(\"List all agent folders for your team\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/agent-folders\",\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listAgentFoldersResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.folders.length === 0) {\n console.log(\"No folders found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, parsed.data.folders));\n console.log(`Showing ${parsed.data.folders.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { moveAgentsResponseSchema } from \"@/api/agent-folder-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { trimRequired } from \"../shared/trim-required.js\";\n\ntype MoveAgentsOptions = {\n agent: readonly string[];\n folder?: string;\n toRoot?: boolean;\n json?: boolean;\n};\n\ntype RequestBody = {\n agent_ids: readonly string[];\n folder_id: string | null;\n};\n\nfunction collect(\n value: string,\n previous: readonly string[] = []\n): readonly string[] {\n return [...previous, value];\n}\n\nfunction resolveFolderId(options: MoveAgentsOptions): string | null {\n if (options.folder !== undefined && options.toRoot === true) {\n throw new CliError(\"Pass either --folder or --to-root, not both.\");\n }\n\n if (options.toRoot === true) {\n return null;\n }\n\n if (options.folder !== undefined) {\n return trimRequired(options.folder, \"--folder\");\n }\n\n throw new CliError(\n \"Provide --folder <id> to move agents into a folder, or --to-root to move them to the root level.\"\n );\n}\n\nexport function registerAgentFoldersMoveAgents(folders: Command): void {\n folders\n .command(\"move-agents\")\n .description(\"Move one or more agents into a folder, or to the root level\")\n .requiredOption(\n \"--agent <id>\",\n \"agent ID to move (repeat for multiple)\",\n collect,\n [] as readonly string[]\n )\n .option(\"--folder <id>\", \"destination folder ID\")\n .option(\"--to-root\", \"move the agents to the root level\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function moveAgentsAction(\n this: Command,\n options: MoveAgentsOptions\n ) {\n if (options.agent.length === 0) {\n throw new CliError(\"Provide at least one --agent <id>.\");\n }\n\n const agentIds = options.agent.map((id) => trimRequired(id, \"--agent\"));\n if (new Set(agentIds).size !== agentIds.length) {\n throw new CliError(\"--agent values must be unique.\");\n }\n\n const folderId = resolveFolderId(options);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const body: RequestBody = {\n agent_ids: agentIds,\n folder_id: folderId,\n };\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/agent-folders/move-agents\",\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = moveAgentsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n throw new CliError(\"Failed to move agents.\");\n }\n\n const target =\n folderId === null ? \"the root level\" : `folder ${folderId}`;\n console.log(\n green(`Moved ${parsed.data.moved_count} agent(s) to ${target}.`)\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { folderResponseSchema } from \"@/api/agent-folder-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { trimRequired } from \"../shared/trim-required.js\";\n\ntype UpdateOptions = {\n name?: string;\n parent?: string;\n moveToRoot?: boolean;\n json?: boolean;\n};\n\ntype RequestBody = {\n name?: string;\n parent_folder_id?: string | null;\n};\n\nfunction buildBody(options: UpdateOptions): RequestBody {\n const body: RequestBody = {};\n\n if (options.name !== undefined) {\n body.name = trimRequired(options.name, \"--name\");\n }\n\n if (options.parent !== undefined && options.moveToRoot === true) {\n throw new CliError(\"Pass either --parent or --move-to-root, not both.\");\n }\n\n if (options.parent !== undefined) {\n body.parent_folder_id = trimRequired(options.parent, \"--parent\");\n } else if (options.moveToRoot === true) {\n body.parent_folder_id = null;\n }\n\n if (Object.keys(body).length === 0) {\n throw new CliError(\n \"Provide at least one field to update (e.g. --name, --parent, --move-to-root).\"\n );\n }\n\n return body;\n}\n\nexport function registerAgentFoldersUpdate(folders: Command): void {\n folders\n .command(\"update <id>\")\n .description(\"Rename an agent folder or move it to a new parent\")\n .option(\"--name <name>\", \"new folder name\")\n .option(\"--parent <id>\", \"new parent folder ID\")\n .option(\"--move-to-root\", \"move the folder to the root level\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function updateAction(\n this: Command,\n id: string,\n options: UpdateOptions\n ) {\n const folderId = trimRequired(id, \"<id>\");\n const body = buildBody(options);\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"PATCH\",\n path: `/v1/agent-folders/${encodeURIComponent(folderId)}`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = folderResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { folder } = parsed.data;\n\n console.log(green(\"Folder updated!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: folder.id },\n { label: \"Name\", value: folder.name },\n { label: \"Parent\", value: folder.parent_folder_id ?? \"(root)\" },\n { label: \"Updated\", value: folder.updated_at ?? \"\" },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerAgentFoldersCreate } from \"./create.js\";\nimport { registerAgentFoldersDelete } from \"./delete.js\";\nimport { registerAgentFoldersList } from \"./list.js\";\nimport { registerAgentFoldersMoveAgents } from \"./move-agents.js\";\nimport { registerAgentFoldersUpdate } from \"./update.js\";\n\nexport function registerAgentFolders(program: Command): void {\n const folders = program\n .command(\"agent-folders\")\n .description(\"Manage agent folders in the Duvo public API\");\n\n registerAgentFoldersList(folders);\n registerAgentFoldersCreate(folders);\n registerAgentFoldersUpdate(folders);\n registerAgentFoldersDelete(folders);\n registerAgentFoldersMoveAgents(folders);\n}\n", "import { readFile } from \"node:fs/promises\";\n\nimport { confirm, isCancel, text } from \"@clack/prompts\";\nimport { AGENT_CONFIG_VERSION, DEFAULT_AGENT_CONFIG } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport {\n type BuildConfig,\n buildConfigSchema,\n createAgentResponseSchema,\n DEFAULT_BUILD_CONFIG,\n DEFAULT_BUILD_NAME,\n DEFAULT_NEW_AGENT_NAME,\n} from \"@/api/agent-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CancelCliError, CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype CreateOptions = {\n name?: string;\n config?: string;\n input?: string;\n build?: boolean;\n json?: boolean;\n};\n\ntype BuildBody = {\n name: string;\n config: BuildConfig;\n};\n\nexport function registerAgentsCreate(agents: Command): void {\n agents\n .command(\"create\")\n .description(\"Create a new agent\")\n .option(\"--name <name>\", \"human-readable agent name\")\n .option(\n \"--input <text>\",\n \"initial agent instructions (merged into the default build config)\"\n )\n .option(\n \"--config <path>\",\n \"path to a JSON file with the full build config (overrides --input)\"\n )\n .option(\"--no-build\", \"create the agent without an initial build\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function createAction(this: Command, options: CreateOptions) {\n const resolved = await requireAuthenticatedConfig(this);\n\n const name = await resolveName(options.name);\n\n const body: { name: string; build?: BuildBody } = { name };\n if (options.build !== false) {\n const config = await resolveBuildConfig(options);\n if (config) {\n body.build = {\n name: DEFAULT_BUILD_NAME,\n config,\n };\n }\n }\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/agents\",\n apiKey: resolved.apiKey,\n apiBaseUrl: resolved.apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = createAgentResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { agent, build } = parsed.data;\n\n const entries = [\n { label: \"ID\", value: agent.id },\n { label: \"Name\", value: agent.name },\n { label: \"Created\", value: agent.created_at ?? \"\" },\n ];\n if (build) {\n entries.push({ label: \"Build\", value: `${build.id} (${build.name})` });\n }\n\n console.log(green(\"Agent created!\"));\n console.log();\n console.log(renderKeyValue(entries));\n });\n}\n\nfunction isInteractiveTerminal(): boolean {\n return process.stdin.isTTY === true && process.stdout.isTTY === true;\n}\n\nasync function resolveName(flag: string | undefined): Promise<string> {\n if (flag !== undefined) {\n const trimmed = flag.trim();\n if (trimmed.length === 0) {\n throw new CliError(\"--name must not be empty\");\n }\n\n return trimmed;\n }\n\n if (!isInteractiveTerminal()) {\n return DEFAULT_NEW_AGENT_NAME;\n }\n\n const answer = await text({\n message: \"Agent name\",\n placeholder: DEFAULT_NEW_AGENT_NAME,\n defaultValue: DEFAULT_NEW_AGENT_NAME,\n validate: (value) => {\n if (value && value.trim().length === 0) {\n return \"Agent name must not be blank.\";\n }\n\n return undefined;\n },\n });\n if (isCancel(answer)) {\n throw new CancelCliError(\"Create cancelled.\");\n }\n\n const trimmed = answer.trim();\n return trimmed.length === 0 ? DEFAULT_NEW_AGENT_NAME : trimmed;\n}\n\nasync function resolveBuildConfig(\n options: Pick<CreateOptions, \"config\" | \"input\">\n): Promise<BuildConfig | undefined> {\n if (options.config !== undefined) {\n const trimmed = options.config.trim();\n if (trimmed.length === 0) {\n throw new CliError(\"--config must be a non-empty file path\");\n }\n\n return readConfigFromFile(trimmed);\n }\n\n if (options.input !== undefined) {\n return buildConfigWithInput(options.input);\n }\n\n if (!isInteractiveTerminal()) {\n return DEFAULT_BUILD_CONFIG;\n }\n\n const hasCustomConfig = await confirm({\n message: \"Do you have your own build config?\",\n initialValue: false,\n });\n if (isCancel(hasCustomConfig)) {\n throw new CancelCliError(\"Create cancelled.\");\n }\n\n if (hasCustomConfig) {\n const path = await text({\n message: \"Path to build config JSON\",\n validate: (value) => {\n if (!value || value.trim().length === 0) {\n return \"A file path is required.\";\n }\n\n return undefined;\n },\n });\n if (isCancel(path)) {\n throw new CancelCliError(\"Create cancelled.\");\n }\n\n return readConfigFromFile(path.trim());\n }\n\n const input = await text({\n message: \"Initial instructions for the agent (leave empty for the default)\",\n defaultValue: \"\",\n });\n if (isCancel(input)) {\n throw new CancelCliError(\"Create cancelled.\");\n }\n\n const trimmed = input.trim();\n if (trimmed.length === 0) {\n return DEFAULT_BUILD_CONFIG;\n }\n\n return buildConfigWithInput(trimmed);\n}\n\nfunction buildConfigWithInput(input: string): BuildConfig {\n const trimmed = input.trim();\n if (trimmed.length === 0) {\n return DEFAULT_BUILD_CONFIG;\n }\n\n return {\n version: AGENT_CONFIG_VERSION,\n data: {\n ...DEFAULT_AGENT_CONFIG,\n input: [\n {\n role: \"system\",\n content: [{ type: \"input_text\", text: trimmed }],\n },\n ],\n },\n };\n}\n\nasync function readConfigFromFile(path: string): Promise<BuildConfig> {\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Could not read config file \"${path}\": ${message}`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Config file \"${path}\" is not valid JSON: ${message}`);\n }\n\n const result = buildConfigSchema.safeParse(parsed);\n if (!result.success) {\n throw new CliError(\n `Config file \"${path}\" does not match expected build config shape (version \"${AGENT_CONFIG_VERSION}\"): ${result.error.message}`\n );\n }\n\n return result.data;\n}\n", "export const ANALYTICS_EVENTS = [\n \"agent_builder_ai_config_edit_failed\",\n \"agent_builder_ai_config_edit_started\",\n \"agent_builder_ai_config_edit_succeeded\",\n \"agent_builder_generate_clicked\",\n \"agent_builder_start_from_scratch_clicked\",\n \"agent_builder_build_config_completed\",\n \"agent_builder_build_config_failed\",\n \"agent_builder_file_removed\",\n \"agent_builder_files_updated\",\n \"agent_builder_instructions_edited\",\n \"agent_builder_instructions_updated\",\n \"agent_builder_skill_removed\",\n \"agent_builder_skills_updated\",\n \"agent_builder_loaded\",\n \"agent_builder_memory_saved\",\n \"agent_builder_memory_toggled\",\n \"agent_builder_model_changed\",\n \"agent_builder_model_selector_expanded\",\n \"opus46_tooltip_dismissed\",\n \"opus46_tooltip_shown\",\n \"agent_builder_name_updated\",\n \"agent_builder_plugin_added\",\n \"agent_builder_plugin_removed\",\n \"agent_builder_sub_assignment_added\",\n \"agent_builder_sub_assignment_removed\",\n \"agent_builder_prompt_starter_clicked\",\n \"agent_builder_prompt_submitted\",\n \"agent_builder_voice_prompt_started\",\n \"agent_builder_voice_prompt_submitted\",\n \"agent_builder_voice_prompt_failed\",\n \"agent_builder_voice_prompt_cancelled\",\n \"agent_builder_slack_toggle_failed\",\n \"agent_builder_slack_toggled\",\n \"agent_case_trigger_updated\",\n \"agent_builder_tab_changed\",\n \"agent_builder_tool_actions_updated\",\n \"agent_builder_tool_added\",\n \"agent_builder_tool_removed\",\n \"agent_builder_tools_batch_updated\",\n \"agent_builder_new_revision_created\",\n \"agent_builder_revision_changed\",\n \"agent_builder_browsing_model_changed\",\n \"agent_builder_sop_login_hint_dismissed\",\n \"agent_builder_sop_login_hint_add_clicked\",\n \"agent_builder_sop_login_hint_shown\",\n \"agent_builder_sop_team_member_mentioned\",\n \"agent_builder_sop_mention_copied\",\n \"agent_builder_sop_mention_cut\",\n \"agent_builder_sop_mention_pasted\",\n \"agent_builder_build_promoted\",\n \"agent_builder_draft_accepted\",\n \"agent_builder_draft_declined\",\n \"agent_builder_draft_deleted\",\n \"agent_browser_preview_minimized\",\n \"agent_browser_preview_shown\",\n \"agent_desktop_preview_expanded\",\n \"agent_desktop_preview_minimized\",\n \"agent_desktop_preview_shown\",\n \"agent_chat_collapsed\",\n \"agent_chat_expanded\",\n \"agent_connection_removed\",\n \"agent_created\",\n \"agent_created_from_template\",\n \"agent_duplicated\",\n \"agent_created_on_signup\",\n \"agent_evaluate_run\",\n \"agent_execution_completed\",\n \"agent_execution_failed\",\n \"agent_execution_files_attached\",\n \"agent_execution_file_removed\",\n \"agent_execution_interrupted\",\n \"agent_execution_message_received\",\n \"agent_execution_processing_failed\",\n \"agent_execution_reset\",\n \"agent_execution_rerun\",\n \"agent_execution_started\",\n \"agent_test_clicked\",\n \"agent_test_generate_assignment_clicked\",\n \"agent_test_with_trigger_message\",\n \"agent_builder_test_case_selected\",\n \"agent_feedback_submitted\",\n \"agent_follow_up_started\",\n \"agent_builder_follow_up_questions_shown\",\n \"agent_builder_follow_up_questions_submitted\",\n \"agent_handover_approved\",\n \"agent_handover_pending_approval\",\n \"agent_handover_rejected\",\n \"agent_learn_from_run\",\n \"agent_run_detail_access_denied\",\n \"agent_run_detail_failed\",\n \"agent_run_detail_loaded\",\n \"agent_run_detail_missing\",\n \"agent_run_detail_integration_instances_loaded\",\n \"agent_run_selected\",\n \"agent_runs_list_failed\",\n \"agent_runs_list_loaded\",\n \"agent_schedule_due\",\n \"agent_schedule_load_failed\",\n \"agent_schedule_loaded\",\n \"agent_schedule_modal_opened\",\n \"agent_schedule_nl_convert_failed\",\n \"agent_schedule_nl_converted\",\n \"agent_schedule_run_created\",\n \"agent_schedule_run_skipped\",\n \"agent_schedule_saved\",\n \"agent_schedule_suggestion_accepted\",\n \"agent_schedule_suggestion_dismissed\",\n \"agent_schedule_update_failed\",\n \"agent_schedule_updated\",\n \"agent_schedule_deleted\",\n \"agent_schedule_added_from_modal\",\n \"agent_trigger_modal_opened\",\n \"agent_template_selected\",\n \"agent_template_used\",\n \"auth_error_viewed\",\n \"auth_login_attempt\",\n \"auth_login_post_check\",\n \"auth_login_result\",\n \"auth_logout\",\n \"auth_password_change_attempt\",\n \"auth_password_change_result\",\n \"auth_password_reset_requested\",\n \"auth_password_reset_result\",\n \"auth_provider_clicked\",\n \"auth_provider_result\",\n \"auth_signup_attempt\",\n \"auth_signup_result\",\n \"billing_checkout_created\",\n \"billing_checkout_failed\",\n \"billing_free_subscription_created\",\n \"billing_details_viewed\",\n \"billing_manage_subscription_clicked\",\n \"billing_subscribe_initiated\",\n \"billing_subscribe_failed\",\n \"billing_subscribe_redirected\",\n \"billing_subscription_created\",\n \"billing_subscription_updated\",\n \"billing_subscription_deleted\",\n \"billing_trial_will_end\",\n \"billing_upgrade_section_viewed\",\n \"clarity_capture_deleted\",\n \"clarity_capture_resumed\",\n \"clarity_captures_sheet_opened\",\n \"clarity_capture_viewed\",\n \"clarity_extra_capture_request_assigned\",\n \"clarity_extra_capture_request_unassigned\",\n \"clarity_contributors_updated\",\n \"clarity_create_assignment_clicked\",\n \"clarity_process_created\",\n \"clarity_process_deleted\",\n \"clarity_process_duplicated\",\n \"clarity_process_name_suggestion_clicked\",\n \"clarity_process_generate_completed\",\n \"clarity_process_generate_failed\",\n \"clarity_process_generate_started\",\n \"clarity_process_interview_paused\",\n \"clarity_process_interview_resumed\",\n \"clarity_process_interview_save_failed\",\n \"clarity_process_interview_saved\",\n \"clarity_process_interview_started\",\n \"clarity_process_interview_stopped\",\n \"clarity_process_interview_transcript_downloaded\",\n \"clarity_process_diagram_downloaded\",\n \"clarity_process_custom_prompt_saved\",\n \"clarity_process_phone_interview_initiated\",\n \"clarity_process_phone_interview_completed\",\n \"clarity_process_phone_interview_failed\",\n \"clarity_process_marked_complete\",\n \"clarity_process_renamed\",\n \"admin_clarity_analysis_edit_started\",\n \"admin_clarity_analysis_copied\",\n \"admin_clarity_analysis_overwritten\",\n \"admin_clarity_analysis_overwrite_failed\",\n \"clarity_process_video_analysis_completed\",\n \"clarity_process_video_analysis_failed\",\n \"clarity_process_video_analysis_started\",\n \"clarity_process_video_removed\",\n \"clarity_process_video_selected\",\n \"clarity_process_video_upload_completed\",\n \"clarity_process_video_upload_failed\",\n \"clarity_process_video_upload_started\",\n \"clarity_process_document_removed\",\n \"clarity_process_document_selected\",\n \"clarity_process_document_upload_completed\",\n \"clarity_process_document_upload_failed\",\n \"clarity_process_document_upload_started\",\n \"clarity_team_settings_updated\",\n \"clarity_transformation_guidance_cloned\",\n \"clarity_transformation_guidance_clone_failed\",\n \"clarity_transformation_guidance_saved\",\n \"clarity_transformation_guidance_save_failed\",\n \"clarity_transformation_regenerate_started\",\n \"clarity_transformation_regenerate_failed\",\n \"clarity_transformation_regenerate_finished\",\n \"clarity_transformation_proposal_viewed\",\n \"clarity_transformation_proposal_accepted\",\n \"clarity_transformation_proposal_rejected\",\n \"clarity_session_created\",\n \"clarity_v2_current_process_saved\",\n \"clarity_v2_transformation_proposal_saved\",\n \"clarity_v2_session_created\",\n \"clarity_v2_session_completed\",\n \"clarity_v2_director_decision\",\n \"clarity_v2_doc_generated\",\n \"clarity_v2_onboarding_shown\",\n \"clarity_v2_onboarding_dismissed\",\n \"clarity_v2_onboarding_replayed\",\n \"clarity_v2_mic_muted\",\n \"clarity_v2_mic_unmuted\",\n \"clarity_v2_session_resumed\",\n \"clarity_v2_language_selected\",\n \"clarity_v2_pip_opened\",\n \"clarity_v2_pip_closed\",\n \"clarity_v2_edit_mode_entered\",\n \"clarity_v2_upgrade_started\",\n \"clarity_v2_upgrade_succeeded\",\n \"clarity_v2_upgrade_failed\",\n \"clarity_video_removed\",\n \"clarity_video_selected\",\n \"clarity_video_upload_completed\",\n \"clarity_video_upload_failed\",\n \"clarity_video_upload_started\",\n \"clarity_voice_interview_started\",\n \"clarity_voice_interview_stopped\",\n \"clarity_voice_transcript_saved\",\n \"clarity_process_share_link_copied\",\n \"clarity_process_sharing_disabled\",\n \"clarity_process_sharing_enabled\",\n \"clarity_ontology_extraction_started\",\n \"clarity_ontology_extraction_completed\",\n \"clarity_ontology_extraction_failed\",\n \"clarity_ontology_merge_completed\",\n \"clarity_ontology_merge_failed\",\n \"clarity_portfolio_intelligence_started\",\n \"clarity_portfolio_intelligence_completed\",\n \"clarity_portfolio_intelligence_failed\",\n \"clarity_portfolio_intelligence_viewed\",\n \"clarity_portfolio_message_sent\",\n \"clarity_library_filter_changed\",\n \"clarity_library_sort_changed\",\n \"clarity_overview_created\",\n \"clarity_overview_deleted\",\n \"browser_login_attached_to_build\",\n \"browser_login_detached_from_build\",\n \"credential_attached_to_build\",\n \"credential_copied\",\n \"credential_created\",\n \"credential_create_failed\",\n \"credential_deleted\",\n \"credential_delete_failed\",\n \"credential_detached_from_build\",\n \"credential_edit_clicked\",\n \"credential_import_failed\",\n \"credential_import_succeeded\",\n \"credential_shared_with_team\",\n \"credential_updated\",\n \"credential_update_failed\",\n \"credential_viewed\",\n \"human_in_loop_bulk_delete_all\",\n \"human_in_loop_bulk_delete_responded\",\n \"human_in_loop_bulk_mark_responded\",\n \"human_in_loop_request_deleted\",\n \"human_in_loop_request_responded\",\n \"human_in_loop_request_responded_structured\",\n \"human_in_loop_request_responded_via_slack\",\n \"human_in_loop_request_responded_via_slack_dm\",\n \"human_in_loop_request_selected\",\n \"human_in_loop_run_failed\",\n \"human_in_loop_run_loaded\",\n \"human_in_loop_tab_changed\",\n \"human_in_loop_viewed\",\n \"impersonation_executed\",\n \"impersonation_execute_failed\",\n \"custom_connection_create_failed\",\n \"custom_connection_create_requested\",\n \"custom_connection_create_succeeded\",\n \"custom_connection_delete_failed\",\n \"custom_connection_delete_requested\",\n \"custom_connection_delete_succeeded\",\n \"custom_connection_instance_modal_opened\",\n \"custom_connection_oauth_initiated\",\n \"integration_connect_failed\",\n \"integration_connect_requested\",\n \"integration_connect_succeeded\",\n \"integration_connected\",\n \"integration_disconnected\",\n \"integration_latency\",\n \"integration_beta_access_requested\",\n \"integration_requested\",\n \"integration_update_failed\",\n \"integration_update_requested\",\n \"integration_update_succeeded\",\n \"integrations_custom_mcp_modal_opened\",\n \"integrations_mcp_test_failed\",\n \"integrations_mcp_test_started\",\n \"integrations_mcp_test_succeeded\",\n \"integrations_search_updated\",\n \"integrations_tab_changed\",\n \"team_files_file_delete_failed\",\n \"team_files_file_deleted\",\n \"team_files_file_downloaded\",\n \"team_files_file_dropped\",\n \"team_files_file_rename_failed\",\n \"team_files_file_renamed\",\n \"team_files_file_upload_failed\",\n \"team_files_file_uploaded\",\n \"team_files_files_list_failed\",\n \"team_files_files_listed\",\n \"team_files_search_changed\",\n \"team_files_sort_changed\",\n \"team_files_upload_button_clicked\",\n \"team_files_upload_completed\",\n \"team_files_upload_dialog_opened\",\n \"team_files_upload_file_removed\",\n \"team_files_upload_files_added\",\n \"team_files_upload_results_cleared\",\n \"team_files_upload_started\",\n \"team_files_viewed\",\n \"onboarding_connection_connect_clicked\",\n \"onboarding_connections_completed\",\n \"onboarding_connections_viewed\",\n \"onboarding_org_created_from_discovery\",\n \"onboarding_org_join_requested\",\n \"onboarding_org_setup_completed\",\n \"organization_discovery_banner_dismissed\",\n \"organization_discovery_join_requested\",\n \"organization_logo_removed\",\n \"organization_logo_remove_failed\",\n \"organization_logo_uploaded\",\n \"organization_logo_upload_failed\",\n \"onboarding_plans_success\",\n \"onboarding_plans_viewed\",\n \"onboarding_team_name_entered\",\n \"onboarding_team_name_submitted\",\n \"onboarding_team_name_viewed\",\n \"onboarding_welcome_get_started_clicked\",\n \"onboarding_welcome_viewed\",\n \"profile_email_digest_disabled\",\n \"profile_email_digest_enabled\",\n \"profile_email_digest_time_updated\",\n \"profile_name_updated\",\n \"profile_teams_notifications_enabled\",\n \"profile_teams_notifications_disabled\",\n \"profile_eval_notifications_enabled\",\n \"profile_eval_notifications_disabled\",\n \"process_analysis_cancel_failed\",\n \"process_analysis_cancel_requested\",\n \"process_analysis_create_requested\",\n \"process_analysis_detail_viewed\",\n \"process_analysis_execution_completed\",\n \"process_analysis_execution_error\",\n \"process_analysis_execution_failed\",\n \"process_analysis_execution_fetch_failed\",\n \"process_analysis_execution_started\",\n \"process_analysis_list_refresh_failed\",\n \"process_analysis_list_refreshed\",\n \"process_analysis_list_viewed\",\n \"process_analysis_mining_failed\",\n \"process_analysis_mining_started\",\n \"process_analysis_selected\",\n \"process_analysis_stream_completed\",\n \"process_analysis_stream_error\",\n \"process_analysis_stream_opened\",\n \"skill_editor_opened\",\n \"skill_viewer_opened\",\n \"skill_file_save_completed\",\n \"skill_file_save_started\",\n \"skill_browser_opened\",\n \"skill_recording_completed\",\n \"skill_recording_error\",\n \"skill_recording_no_events\",\n \"skill_recording_started\",\n \"skill_recording_stopped\",\n \"skill_upload_completed\",\n \"skill_create_completed\",\n \"skill_create_started\",\n \"skill_creator_opened\",\n \"skill_ai_generate_started\",\n \"skill_ai_generate_completed\",\n \"skill_upload_dialog_opened\",\n \"skill_upload_file_added\",\n \"skill_upload_started\",\n \"file_editor_opened\",\n \"file_save_completed\",\n \"file_save_started\",\n \"slack_user_connect_clicked\",\n \"slack_user_unlink_failed\",\n \"slack_user_unlinked\",\n \"solution_request_failed\",\n \"solution_request_opened\",\n \"solution_request_submitted\",\n \"solution_selected\",\n \"custom_solution_request_failed\",\n \"custom_solution_request_opened\",\n \"custom_solution_request_submitted\",\n \"team_created\",\n \"team_deleted\",\n \"team_switched\",\n \"team_member_invite_deleted\",\n \"team_member_invite_failed\",\n \"team_member_invite_resent\",\n \"team_member_invited\",\n \"team_invite_role_updated\",\n \"team_members_bulk_invited\",\n \"team_members_bulk_invite_failed\",\n \"team_member_removed\",\n \"team_member_role_updated\",\n \"team_logo_removed\",\n \"team_logo_remove_failed\",\n \"team_logo_uploaded\",\n \"team_logo_upload_failed\",\n \"team_access_mode_updated\",\n \"team_browser_location_override_updated\",\n \"team_join_request_approved\",\n \"team_join_request_denied\",\n \"org_team_join_request_approved\",\n \"org_team_join_request_denied\",\n \"team_name_update_failed\",\n \"team_name_updated\",\n \"team_settings_cancel_edit\",\n \"team_settings_viewed\",\n \"team_invitation_created\",\n \"team_invitation_accepted\",\n \"team_invitation_accept_failed\",\n \"team_invitation_declined\",\n \"team_invitation_decline_failed\",\n \"team_invitation_email_sent\",\n \"team_invitation_email_failed\",\n \"team_invite_link_copied\",\n \"team_invite_link_created\",\n \"team_invite_link_deleted\",\n \"team_invite_link_regenerated\",\n \"organization_invitation_created\",\n \"organization_invitation_accepted\",\n \"organization_invitation_declined\",\n \"organization_invitation_email_sent\",\n \"organization_invitation_email_failed\",\n \"organization_invitation_copied\",\n \"organization_invite_link_accepted\",\n \"organization_invite_link_copied\",\n \"organization_invite_link_created\",\n \"organization_invite_link_deleted\",\n \"organization_invite_link_regenerated\",\n \"organization_member_role_updated\",\n \"admin_org_member_added\",\n \"team_bulk_invite_completed\",\n \"team_bulk_invite_failed\",\n \"settings_section_viewed\",\n \"team_slack_add_button_clicked\",\n \"team_slack_install_clicked\",\n \"team_slack_install_completed\",\n \"team_slack_install_failed\",\n \"team_slack_install_started\",\n \"team_slack_organization_disconnect_failed\",\n \"team_slack_organization_disconnected\",\n \"team_slack_settings_modal_opened\",\n \"team_slack_settings_save_failed\",\n \"team_slack_settings_saved\",\n \"team_ms_teams_install_clicked\",\n \"team_ms_teams_connect_clicked\",\n \"team_ms_teams_organization_disconnected\",\n \"team_ms_teams_settings_saved\",\n \"ms_teams_user_unlinked\",\n \"case_list_viewed\",\n \"case_list_filtered\",\n \"case_filter_applied\",\n \"case_filter_removed\",\n \"case_list_searched\",\n \"case_list_sorted\",\n \"case_detail_viewed\",\n \"case_job_opened\",\n \"case_job_assignment_opened\",\n \"case_job_hitl_respond_clicked\",\n \"case_stats_loaded\",\n \"case_created\",\n \"case_deleted\",\n \"case_retried\",\n \"case_delegated\",\n \"case_status_updated\",\n \"case_needs_input_badge_clicked\",\n \"case_awaiting_approval_badge_clicked\",\n \"case_approval_responded\",\n \"case_approval_resolved\",\n \"cases_bulk_deleted\",\n \"cases_bulk_retried\",\n \"cases_bulk_delegated\",\n \"cases_bulk_status_updated\",\n \"case_queue_cleared\",\n \"case_queue_created\",\n \"case_queue_deleted\",\n \"case_queue_exported\",\n \"case_queue_imported\",\n \"case_queue_description_updated\",\n \"case_queue_moved\",\n \"case_queue_renamed\",\n \"case_queue_switched\",\n \"case_queue_stats_period_changed\",\n \"case_attribute_assigned\",\n \"case_attribute_unassigned\",\n \"case_attribute_created\",\n \"case_attribute_deleted\",\n \"case_attribute_renamed\",\n \"case_attribute_color_changed\",\n \"case_attribute_values_updated\",\n \"case_label_assigned\",\n \"case_label_unassigned\",\n \"case_label_created\",\n \"case_label_deleted\",\n \"case_label_renamed\",\n \"workflow_builder_plan_started\",\n \"workflow_builder_refinement_submitted\",\n \"job_list_viewed\",\n \"job_list_filtered\",\n \"job_list_searched\",\n \"job_list_sorted\",\n \"clarity_overview_capture_deleted\",\n \"clarity_overview_capture_viewed\",\n \"clarity_overview_document_removed\",\n \"clarity_overview_document_selected\",\n \"clarity_overview_document_upload_completed\",\n \"clarity_overview_document_upload_failed\",\n \"clarity_overview_document_upload_started\",\n \"clarity_overview_filter_applied\",\n \"clarity_overview_filter_cleared\",\n \"clarity_overview_generate_failed\",\n \"clarity_overview_generate_started\",\n \"clarity_overview_interview_paused\",\n \"clarity_overview_interview_resumed\",\n \"clarity_overview_interview_save_failed\",\n \"clarity_overview_interview_saved\",\n \"clarity_overview_interview_started\",\n \"clarity_overview_interview_stopped\",\n \"clarity_overview_interview_transcript_downloaded\",\n \"clarity_overview_process_selected\",\n \"clarity_overview_video_analysis_completed\",\n \"clarity_overview_video_analysis_failed\",\n \"clarity_overview_video_analysis_started\",\n \"clarity_overview_video_removed\",\n \"clarity_overview_video_selected\",\n \"clarity_overview_video_upload_completed\",\n \"clarity_overview_video_upload_failed\",\n \"clarity_overview_video_upload_started\",\n \"clarity_automation_created\",\n \"clarity_automation_agent_assigned\",\n \"clarity_automation_activated\",\n \"clarity_automation_run_started\",\n \"clarity_automation_run_completed\",\n \"clarity_automation_run_failed\",\n \"clarity_flow_version_created\",\n \"clarity_flow_version_edited\",\n \"clarity_flow_version_compared\",\n \"linear_trigger_enabled\",\n \"linear_trigger_disabled\",\n \"linear_trigger_updated\",\n \"slack_mention_trigger_disabled\",\n \"slack_mention_trigger_enabled\",\n \"slack_trigger_created\",\n \"slack_trigger_deleted\",\n \"slack_trigger_fired\",\n \"slack_trigger_updated\",\n \"teams_mention_trigger_disabled\",\n \"teams_mention_trigger_enabled\",\n \"job_issue_alerts_toggled\",\n \"job_issue_alerts_rubrics_changed\",\n \"job_issue_alert_email_sent\",\n \"assignment_list_sorted\",\n] as const;\n\nexport type AnalyticsEventName = (typeof ANALYTICS_EVENTS)[number];\n", "import { z } from \"zod\";\n\nexport const customerPortalResponseSchema = z.object({\n url: z.string(),\n});\n\nexport type CustomerPortalResponse = z.infer<\n typeof customerPortalResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport { BasePlan, PlanFeature, RunCountingMode } from \"./plan-versions\";\n\n/**\n * Resource types that have plan limits\n */\nexport type LimitedResource = \"assignment\" | \"agent_run\";\n\n/**\n * Result of checking if a resource can be created\n */\nexport interface CanCreateResult {\n allowed: boolean;\n current: number;\n limit: number | \"unlimited\";\n upgradeRequired: boolean;\n}\n\n/**\n * All entitlements for a team\n */\nexport interface PlanEntitlements {\n planVersionId: string;\n planName: string;\n basePlan: BasePlan;\n features: readonly PlanFeature[];\n limits: {\n maxAgents: number | \"unlimited\";\n maxAgentRunsPerMonth: number | \"unlimited\";\n runCountingMode: RunCountingMode;\n };\n usage: {\n currentAssignments: number;\n currentMonthAgentRuns: number;\n };\n subscription: {\n status: \"active\" | \"trialing\" | \"canceled\" | \"past_due\";\n trialEndsAt: Date | null;\n currentPeriodEnd: Date | null;\n };\n canCreateTeams: boolean;\n}\n\n/**\n * EntitlementService API\n */\nexport interface EntitlementService {\n hasFeature(teamId: string, feature: PlanFeature): Promise<boolean>;\n getLimit(\n teamId: string,\n limit: \"maxAgents\" | \"maxAgentRunsPerMonth\"\n ): Promise<number | \"unlimited\">;\n canCreate(\n teamId: string,\n resource: LimitedResource\n ): Promise<CanCreateResult>;\n getTeamEntitlements(teamId: string): Promise<PlanEntitlements>;\n}\n\nconst limitSchema = z.union([z.number(), z.literal(\"unlimited\")]);\n\nexport const entitlementsResponseSchema = z.object({\n planVersionId: z.string(),\n planName: z.string(),\n basePlan: z.enum([\"free\", \"pro\", \"enterprise\"]),\n features: z.array(z.string()),\n limits: z.object({\n maxAgents: limitSchema,\n maxAgentRunsPerMonth: limitSchema,\n runCountingMode: z.enum([\"monthly\", \"lifetime\"]),\n }),\n usage: z.object({\n currentAssignments: z.number(),\n currentMonthAgentRuns: z.number(),\n }),\n subscription: z.object({\n status: z.enum([\"active\", \"trialing\", \"canceled\", \"past_due\"]),\n trialEndsAt: z.coerce.date().nullable(),\n currentPeriodEnd: z.coerce.date().nullable(),\n }),\n canCreateTeams: z.boolean(),\n});\n\nexport type EntitlementsResponse = z.infer<typeof entitlementsResponseSchema>;\n", "import { z } from \"zod\";\n\nexport const invoiceSchema = z.object({\n id: z.string(),\n number: z.string().nullable(),\n status: z.enum([\"draft\", \"open\", \"paid\", \"uncollectible\", \"void\"]),\n amountDue: z.number(),\n amountPaid: z.number(),\n currency: z.string(),\n createdAt: z.string(),\n paidAt: z.string().nullable(),\n hostedInvoiceUrl: z.string().nullable(),\n invoicePdf: z.string().nullable(),\n});\n\nexport type Invoice = z.infer<typeof invoiceSchema>;\n\nexport const invoicesResponseSchema = z.object({\n invoices: z.array(invoiceSchema),\n hasMore: z.boolean(),\n nextCursor: z.string().nullable(),\n});\n\nexport type InvoicesResponse = z.infer<typeof invoicesResponseSchema>;\n", "/**\n * Plan features that can be enabled per plan\n */\nexport const PLAN_FEATURE = {\n API_ACCESS: \"api_access\",\n BROWSER_AUTOMATION: \"browser_automation\",\n ADVANCED_INTEGRATIONS: \"advanced_integrations\",\n CUSTOM_MCP_SERVERS: \"custom_mcp_servers\",\n CASE_QUEUE: \"case_queue\",\n CLARITY: \"clarity\",\n CLARITY_OVERVIEW: \"clarity_overview\",\n SSO: \"sso\",\n AUDIT_LOGS: \"audit_logs\",\n PRIORITY_SUPPORT: \"priority_support\",\n CAN_CREATE_TEAMS: \"can_create_teams\",\n LEARNINGS: \"learnings\",\n BROWSING_SKILL_RECORDING: \"browsing_skill_recording\",\n WORKFLOW_BUILDER: \"workflow_builder\",\n AGENTIC_MEMORY: \"agentic_memory\",\n} as const;\n\nexport type PlanFeature = (typeof PLAN_FEATURE)[keyof typeof PLAN_FEATURE];\n\n/**\n * Base plan types\n */\nexport type BasePlan = \"pro\" | \"enterprise\" | \"free\";\n\n/**\n * How agent runs are counted against plan limits\n * - \"monthly\": Resets each billing period (default for paid plans)\n * - \"lifetime\": Counts all runs ever, never resets (used for free tier)\n */\nexport type RunCountingMode = \"monthly\" | \"lifetime\";\n\n/**\n * Plan version definition\n */\nexport interface PlanVersionDefinition {\n /** Display name for the plan */\n name: string;\n /** Base plan slug */\n basePlan: BasePlan;\n /** Maximum number of agents */\n maxAgents: number | \"unlimited\";\n /** Maximum agent runs per month (or total for lifetime mode) */\n maxAgentRunsPerMonth: number | \"unlimited\";\n /** How runs are counted: \"monthly\" resets each period, \"lifetime\" counts all-time */\n runCountingMode: RunCountingMode;\n /** Maximum concurrent agent runs */\n maxConcurrentRuns: number | \"unlimited\";\n /** Enabled features for this plan version */\n features: readonly PlanFeature[];\n /** Whether this version is currently available for new subscriptions */\n isActive: boolean;\n /** Monthly price in cents (for display purposes, actual billing via Stripe) */\n monthlyPriceCents: number;\n /** Stripe price ID for this plan version (if applicable) */\n stripePriceId?: string;\n}\n\n/**\n * Versioned plan definitions\n *\n * Format: {basePlan}_v{version}\n *\n * When changing plan features:\n * 1. Create a new version (e.g., pro_v2)\n * 2. Set isActive: false on the old version\n * 3. Set isActive: true on the new version\n * 4. Existing subscribers keep their version (grandfathered)\n */\nexport const PLAN_VERSIONS = {\n free_v1: {\n name: \"Pro Trial Plan\",\n basePlan: \"free\",\n maxAgents: 1,\n maxAgentRunsPerMonth: 100,\n runCountingMode: \"lifetime\",\n maxConcurrentRuns: 1,\n features: [],\n isActive: true,\n monthlyPriceCents: 0,\n },\n pro_v1: {\n name: \"Pro\",\n basePlan: \"pro\",\n maxAgents: \"unlimited\",\n maxAgentRunsPerMonth: 500,\n runCountingMode: \"monthly\",\n maxConcurrentRuns: 1,\n features: [\n PLAN_FEATURE.BROWSER_AUTOMATION,\n PLAN_FEATURE.ADVANCED_INTEGRATIONS,\n PLAN_FEATURE.CUSTOM_MCP_SERVERS,\n PLAN_FEATURE.BROWSING_SKILL_RECORDING,\n PLAN_FEATURE.AGENTIC_MEMORY,\n ],\n isActive: true,\n monthlyPriceCents: 19900, // $199/month\n },\n\n enterprise_v1: {\n name: \"Enterprise\",\n basePlan: \"enterprise\",\n maxAgents: \"unlimited\",\n maxAgentRunsPerMonth: \"unlimited\",\n runCountingMode: \"monthly\",\n maxConcurrentRuns: \"unlimited\",\n features: [\n PLAN_FEATURE.API_ACCESS,\n PLAN_FEATURE.BROWSER_AUTOMATION,\n PLAN_FEATURE.ADVANCED_INTEGRATIONS,\n PLAN_FEATURE.CUSTOM_MCP_SERVERS,\n PLAN_FEATURE.CASE_QUEUE,\n PLAN_FEATURE.CLARITY,\n PLAN_FEATURE.CLARITY_OVERVIEW,\n PLAN_FEATURE.SSO,\n PLAN_FEATURE.AUDIT_LOGS,\n PLAN_FEATURE.PRIORITY_SUPPORT,\n PLAN_FEATURE.CAN_CREATE_TEAMS,\n PLAN_FEATURE.LEARNINGS,\n PLAN_FEATURE.BROWSING_SKILL_RECORDING,\n PLAN_FEATURE.WORKFLOW_BUILDER,\n PLAN_FEATURE.AGENTIC_MEMORY,\n ],\n isActive: true,\n monthlyPriceCents: 0, // Custom pricing\n },\n} as const satisfies Record<string, PlanVersionDefinition>;\n\nexport type PlanVersionId = keyof typeof PLAN_VERSIONS;\n\nexport const FREE_PLAN_VERSION_ID = \"free_v1\";\nexport const PRO_PLAN_VERSION_ID = \"pro_v1\";\nexport const ENTERPRISE_PLAN_VERSION_ID = \"enterprise_v1\";\n\nexport type BillingEnvironment =\n | \"development\"\n | \"staging\"\n | \"production\"\n | \"test\";\n\nconst STRIPE_PRICE_IDS: Record<\n BillingEnvironment,\n Partial<Record<PlanVersionId, string>>\n> = {\n development: {\n pro_v1: \"price_1SsNA0G2suWmkoit1EDZ1yIp\", // Test mode\n free_v1: \"price_1SzK5cG2suWmkoit6MBgzq1O\", // Test mode\n },\n test: {\n pro_v1: \"price_TEST_PRO_V1\",\n free_v1: \"price_TEST_FREE_V1\",\n },\n staging: {\n pro_v1: \"price_1Suwy95poyNfxXdjeBEG4ZUR\", // Stripe Staging Sandbox\n free_v1: \"price_1T03AQ5poyNfxXdj3vGmHt6f\", // Stripe Staging Sandbox\n },\n production: {\n pro_v1: \"price_1SuYr7G2suWmkoitumMHF23S\", // Live mode\n free_v1: \"price_1SzvwvG2suWmkoityHM6SDMp\", // Live mode\n },\n};\n\n/**\n * Get the Stripe price ID for a plan version in the given environment\n */\nexport function getStripePriceId(\n planVersionId: PlanVersionId,\n environment: BillingEnvironment\n): string | null {\n const prices = STRIPE_PRICE_IDS[environment];\n return prices[planVersionId] ?? null;\n}\n\n/**\n * Get plan version definition by ID\n */\nexport function getPlanVersion(\n planVersionId: string\n): PlanVersionDefinition | null {\n return (\n (PLAN_VERSIONS as Record<string, PlanVersionDefinition>)[planVersionId] ??\n null\n );\n}\n\n/**\n * Get the current active version for a base plan\n */\nexport function getCurrentPlanVersion(\n basePlan: BasePlan\n): PlanVersionId | null {\n const entry = Object.entries(PLAN_VERSIONS).find(\n ([, def]) => def.basePlan === basePlan && def.isActive\n );\n return entry ? (entry[0] as PlanVersionId) : null;\n}\n\n/**\n * Check if a plan version has a specific feature\n */\nexport function planHasFeature(\n planVersionId: string,\n feature: PlanFeature\n): boolean {\n const plan = getPlanVersion(planVersionId);\n if (!plan) {\n return false;\n }\n\n return plan.features.includes(feature);\n}\n\n/**\n * Get a limit value from a plan version\n */\nexport function getPlanLimit(\n planVersionId: string,\n limit: \"maxAgents\" | \"maxAgentRunsPerMonth\" | \"maxConcurrentRuns\"\n): number | \"unlimited\" {\n const plan = getPlanVersion(planVersionId);\n if (!plan) {\n return 0;\n }\n\n return plan[limit];\n}\n\n/**\n * Get the run counting mode for a plan version\n */\nexport function getRunCountingMode(planVersionId: string): RunCountingMode {\n const plan = getPlanVersion(planVersionId);\n if (!plan) {\n return \"monthly\";\n }\n\n return plan.runCountingMode;\n}\n\n/**\n * Check if a value is within the plan limit\n */\nexport function isWithinPlanLimit(\n planVersionId: string,\n limit: \"maxAgents\" | \"maxAgentRunsPerMonth\" | \"maxConcurrentRuns\",\n currentValue: number\n): boolean {\n const planLimit = getPlanLimit(planVersionId, limit);\n if (planLimit === \"unlimited\") {\n return true;\n }\n\n return currentValue < planLimit;\n}\n", "import { type BasePlan, PLAN_FEATURE, type PlanFeature } from \"./plan-versions\";\n\n/**\n * Human-readable labels for plan features\n */\nexport const PLAN_FEATURE_LABELS: Record<PlanFeature, string> = {\n [PLAN_FEATURE.API_ACCESS]: \"API Access\",\n [PLAN_FEATURE.BROWSER_AUTOMATION]: \"Browser Automation\",\n [PLAN_FEATURE.ADVANCED_INTEGRATIONS]: \"Advanced Integrations\",\n [PLAN_FEATURE.CUSTOM_MCP_SERVERS]: \"Custom MCP Servers\",\n [PLAN_FEATURE.CASE_QUEUE]: \"Case Queue\",\n [PLAN_FEATURE.CLARITY]: \"Clarity\",\n [PLAN_FEATURE.CLARITY_OVERVIEW]: \"Clarity Overview\",\n [PLAN_FEATURE.SSO]: \"Single Sign-On (SSO)\",\n [PLAN_FEATURE.AUDIT_LOGS]: \"Audit Logs\",\n [PLAN_FEATURE.PRIORITY_SUPPORT]: \"Priority Support\",\n [PLAN_FEATURE.CAN_CREATE_TEAMS]: \"Create Teams\",\n [PLAN_FEATURE.LEARNINGS]: \"Learnings\",\n [PLAN_FEATURE.BROWSING_SKILL_RECORDING]: \"Browsing Skill Recording\",\n [PLAN_FEATURE.WORKFLOW_BUILDER]: \"Workflow Builder\",\n [PLAN_FEATURE.AGENTIC_MEMORY]: \"Agentic Memory\",\n};\n\n/**\n * Get the display label for a plan feature\n */\nexport function getFeatureLabel(feature: PlanFeature): string {\n return PLAN_FEATURE_LABELS[feature];\n}\n\n/**\n * Format a price in cents to a display string\n */\nexport function formatPrice(priceCents: number, basePlan?: BasePlan): string {\n if (priceCents === 0 && basePlan === \"free\") {\n return \"Free\";\n }\n\n if (priceCents === 0) {\n return \"Custom pricing\";\n }\n\n return `$${(priceCents / 100).toLocaleString()}/month`;\n}\n\n/**\n * Format a limit value for display\n */\nexport function formatLimit(value: number | \"unlimited\"): string {\n if (value === \"unlimited\") {\n return \"Unlimited\";\n }\n\n return value.toLocaleString();\n}\n", "import { z } from \"zod\";\n\nexport const subscriptionDetailsSchema = z.object({\n planName: z.string(),\n price: z.number(),\n currency: z.string(),\n interval: z.enum([\"month\", \"year\"]),\n status: z.string(),\n currentPeriodEnd: z.string(),\n cancelAtPeriodEnd: z.boolean(),\n});\n\nexport type SubscriptionDetails = z.infer<typeof subscriptionDetailsSchema>;\n\nexport const subscriptionDetailsResponseSchema = z.object({\n subscription: subscriptionDetailsSchema.nullable(),\n});\n\nexport type SubscriptionDetailsResponse = z.infer<\n typeof subscriptionDetailsResponseSchema\n>;\n", "import { z } from \"zod\";\n\nexport const subscriptionStatusSchema = z.object({\n hasActiveSubscription: z.boolean(),\n isEnterprise: z.boolean(),\n planVersionId: z.string().nullable(),\n status: z.string().nullable(),\n canCreateTeams: z.boolean(),\n});\n\nexport type SubscriptionStatus = z.infer<typeof subscriptionStatusSchema>;\n", "import { z } from \"zod\";\n\nimport { type AgentRunSource, agentRunSourceSchema } from \"../types/agent-run\";\n\n/**\n * Usage period information\n */\nexport const usagePeriodSchema = z.object({\n start: z.coerce.date(),\n end: z.coerce.date(),\n});\n\nexport type UsagePeriod = z.infer<typeof usagePeriodSchema>;\n\n/**\n * Resource usage with limit information\n */\nexport const resourceUsageSchema = z.object({\n used: z.number(),\n limit: z.union([z.number(), z.literal(\"unlimited\")]),\n remaining: z.union([z.number(), z.literal(\"unlimited\")]),\n});\n\nexport type ResourceUsage = z.infer<typeof resourceUsageSchema>;\n\n/**\n * Resource usage without remaining (for seats/assignments that don't have monthly limits)\n */\nexport const resourceCountSchema = z.object({\n used: z.number(),\n limit: z.union([z.number(), z.literal(\"unlimited\")]),\n});\n\nexport type ResourceCount = z.infer<typeof resourceCountSchema>;\n\n/**\n * Team-level usage data\n */\nexport const teamUsageSchema = z.object({\n teamId: z.guid(),\n period: usagePeriodSchema,\n agentRuns: resourceUsageSchema,\n assignments: resourceCountSchema,\n concurrency: resourceCountSchema,\n});\n\nexport type TeamUsage = z.infer<typeof teamUsageSchema>;\n\n/**\n * Usage breakdown by source\n */\nexport const usageBySourceSchema = z.partialRecord(\n agentRunSourceSchema,\n z.number()\n);\n\nexport type UsageBySource = Partial<Record<AgentRunSource, number>>;\n\n/**\n * User-level usage data within a team\n */\nexport const userUsageSchema = z.object({\n userId: z.guid(),\n teamId: z.guid(),\n period: usagePeriodSchema,\n totalRuns: z.number(),\n assignmentsUsed: z.array(z.guid()),\n bySource: usageBySourceSchema,\n});\n\nexport type UserUsage = z.infer<typeof userUsageSchema>;\n\n/**\n * Reasons why execution may not be allowed\n */\nexport const executionBlockedReasonSchema = z.enum([\n \"limit_exceeded\",\n \"concurrent_limit_exceeded\",\n \"no_subscription\",\n \"subscription_inactive\",\n]);\n\nexport type ExecutionBlockedReason = z.infer<\n typeof executionBlockedReasonSchema\n>;\n\n/**\n * Result of checking if an agent run can be executed\n */\nexport const canExecuteResultSchema = z.object({\n allowed: z.boolean(),\n reason: executionBlockedReasonSchema.optional(),\n usage: z.object({\n current: z.number(),\n limit: z.union([z.number(), z.literal(\"unlimited\")]),\n remaining: z.union([z.number(), z.literal(\"unlimited\")]),\n periodEnd: z.coerce.date(),\n }),\n});\n\nexport type CanExecuteResult = z.infer<typeof canExecuteResultSchema>;\n\n/**\n * Result of checking if a concurrent agent run can be executed\n */\nexport const canExecuteConcurrentResultSchema = z.object({\n allowed: z.boolean(),\n reason: executionBlockedReasonSchema.optional(),\n usage: z.object({\n current: z.number(),\n limit: z.union([z.number(), z.literal(\"unlimited\")]),\n remaining: z.union([z.number(), z.literal(\"unlimited\")]),\n }),\n});\n\nexport type CanExecuteConcurrentResult = z.infer<\n typeof canExecuteConcurrentResultSchema\n>;\n\n/**\n * UsageService interface for checking and tracking usage\n */\nexport interface UsageService {\n /**\n * Get current usage for a team including all resource types\n */\n getCurrentUsage(teamId: string): Promise<TeamUsage>;\n\n /**\n * Get usage for a specific user within a team\n */\n getUserUsage(\n teamId: string,\n userId: string,\n startDate?: Date\n ): Promise<UserUsage>;\n\n /**\n * Check if a team can execute an agent run (pre-execution check for monthly limits)\n */\n canExecuteRun(teamId: string): Promise<CanExecuteResult>;\n\n /**\n * Check if a team can execute a concurrent agent run (pre-execution check for concurrent limits)\n */\n canExecuteConcurrentRun(teamId: string): Promise<CanExecuteConcurrentResult>;\n}\n", "import { z } from \"zod\";\n\nimport { agentMessageSchema } from \"../schemas/automation-message\";\nimport { evalSummarySchema } from \"../schemas/run-evaluation\";\n\nexport const DISPATCH_MAX_RETRIES = 100;\n\n/**\n * Agent run status values\n */\nexport const AGENT_RUN_STATUSES = [\n \"not_started\", // Legacy status (pre-dispatcher)\n \"pending\", // Queued, waiting for dispatch\n \"starting\", // Dispatched by dispatcher, webhook fired, awaiting ack from cc-server\n \"running\", // Acknowledged by cc-server, actively executing\n \"waiting\", // Paused waiting for human input (e.g., AskUserQuestion)\n // Terminal states\n \"completed\", // Finished successfully\n \"failed\", // Finished with error\n \"interrupted\", // User interrupted\n] as const;\n\nexport const ACTIVE_AGENT_RUN_STATUSES = [\n \"not_started\",\n \"pending\",\n \"starting\",\n \"running\",\n \"waiting\",\n] as const satisfies AgentRunStatus[];\n\nexport const TERMINAL_AGENT_RUN_STATUSES = [\n \"completed\",\n \"failed\",\n \"interrupted\",\n] as const satisfies AgentRunStatus[];\n\nexport type AgentRunStatus = (typeof AGENT_RUN_STATUSES)[number];\n\ntype TerminalAgentRunStatus = (typeof TERMINAL_AGENT_RUN_STATUSES)[number];\ntype ActiveAgentRunStatus = (typeof ACTIVE_AGENT_RUN_STATUSES)[number];\n\n/**\n * Type-level check: TERMINAL + ACTIVE must cover all AGENT_RUN_STATUSES with no overlap.\n * If a status is missing or duplicated, these assertions will fail to compile.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-expressions\n(function _agentRunStatusChecks() {\n type AllStatuses = TerminalAgentRunStatus | ActiveAgentRunStatus;\n\n /** Fails if any status is missing from TERMINAL or ACTIVE. */\n const _complete: [AgentRunStatus] extends [AllStatuses] ? true : never = true;\n\n /** Fails if TERMINAL and ACTIVE have any overlap. */\n const _noOverlap: [TerminalAgentRunStatus & ActiveAgentRunStatus] extends [\n never,\n ]\n ? true\n : never = true;\n\n return [_complete, _noOverlap];\n});\n\nexport const agentRunStatusSchema = z.enum(AGENT_RUN_STATUSES);\n\n/**\n * Agent run sources - where the agent run was initiated from\n */\nexport const AGENT_RUN_SOURCES = [\n \"app\",\n \"scheduling\",\n \"slack\",\n \"teams\",\n \"api\",\n \"case_trigger\",\n \"handover\",\n \"postpone\",\n \"delegate\",\n \"trigger\",\n] as const;\n\n/**\n * Type representing the source of an agent run\n */\nexport type AgentRunSource = (typeof AGENT_RUN_SOURCES)[number];\n\n/**\n * Zod schema for validating agent run sources\n */\nexport const agentRunSourceSchema = z.enum(AGENT_RUN_SOURCES);\n\n/**\n * Agent invocation initiators - internal classification of how/why a run was started.\n * Some initiators map from sources, others are set directly (e.g., \"url-upload\", \"builder\").\n */\nexport const AGENT_INVOCATION_INITIATORS = [\n \"api\",\n \"builder\",\n \"case-queue\",\n \"clarity\",\n \"handover\",\n \"schedule\",\n \"slack\",\n \"teams\",\n \"trigger\",\n \"url-upload\",\n \"user-trigger\",\n \"workflow-builder\",\n] as const;\n\nexport type AgentInvocationInitiator =\n (typeof AGENT_INVOCATION_INITIATORS)[number];\n\nexport const agentInvocationInitiatorSchema = z.enum(\n AGENT_INVOCATION_INITIATORS\n);\n\nconst SOURCE_TO_INITIATOR: Record<AgentRunSource, AgentInvocationInitiator> = {\n app: \"user-trigger\",\n scheduling: \"schedule\",\n slack: \"slack\",\n teams: \"teams\",\n api: \"api\",\n case_trigger: \"case-queue\",\n handover: \"handover\",\n postpone: \"case-queue\",\n delegate: \"case-queue\",\n trigger: \"trigger\",\n};\n\n/**\n * Map a source value to its corresponding initiator.\n * Validates with Zod and falls back to \"user-trigger\" for invalid sources.\n */\nexport function mapSourceToInitiator(\n source: string | null | undefined\n): AgentInvocationInitiator {\n const parsed = agentRunSourceSchema.safeParse(source);\n if (!parsed.success) {\n return \"user-trigger\";\n }\n\n return SOURCE_TO_INITIATOR[parsed.data];\n}\n\n/**\n * Schema for a single agent run\n */\nexport const agentRunSchema = z.object({\n id: z.guid(),\n created_at: z.coerce.date(),\n updated_at: z.coerce.date(),\n agent_id: z.guid(),\n build_id: z.guid(),\n started_at: z.coerce.date().nullable(),\n completed_at: z.coerce.date().nullable(),\n last_session_id: z.string().nullable(),\n user_id: z.guid().nullable(),\n source: z.string().nullable(),\n bb_session_id: z.string().nullable(),\n computer_session_id: z.string().nullable().optional(),\n status: agentRunStatusSchema.optional(),\n /** Case queue item ID for case-bound runs (set by claim_case or pre-bound at start) */\n case_queue_item_id: z.guid().nullable().optional(),\n // API run and webhook status fields (for runs started via public API)\n is_api_run: z.boolean().optional(),\n has_webhook: z.boolean().optional(),\n latest_webhook_triggered_at: z.string().nullable().optional(),\n latest_webhook_status_code: z.number().nullable().optional(),\n latest_webhook_error: z.string().nullable().optional(),\n eval_summaries: evalSummarySchema.nullable().optional(),\n user_name: z.string().nullable().optional(),\n user_email: z.string().nullable().optional(),\n submitted_prompt_count: z.number().int().min(0).optional(),\n});\n\n/**\n * Type inferred from agentRunSchema\n */\nexport type AgentRun = z.infer<typeof agentRunSchema>;\n\n/**\n * Response schema for the agent runs list endpoint\n */\nexport const agentRunsListResponseSchema = z.object({\n data: z.array(agentRunSchema),\n total: z.number(),\n learningSourceRunId: z.guid().nullable(),\n});\n\n/**\n * Type inferred from agentRunsListResponseSchema\n */\nexport type AgentRunsListResponse = z.infer<typeof agentRunsListResponseSchema>;\n\n/**\n * Schema for integration instance metadata in agent run detail\n */\nexport const integrationInstanceMetadataSchema = z.object({\n instanceId: z.string(),\n name: z.string(),\n integrationType: z.string(),\n iconUrl: z.string().nullish(),\n});\n\nexport type IntegrationInstanceMetadata = z.infer<\n typeof integrationInstanceMetadataSchema\n>;\n\n/**\n * Schema for conversation pagination metadata\n */\nexport const conversationPaginationSchema = z.object({\n total: z.number(),\n included: z.number(),\n hasMore: z.boolean(),\n});\n\nexport type ConversationPagination = z.infer<\n typeof conversationPaginationSchema\n>;\n\n/**\n * Handover status values for the handover info object\n */\nexport const handoverStatusSchema = z.enum([\n \"pending\",\n \"evaluating\",\n \"pending_approval\",\n \"approved\",\n \"rejected\",\n]);\n\nexport type HandoverStatus = z.infer<typeof handoverStatusSchema>;\n\n/**\n * Schema for handover info attached to an agent run\n */\nexport const handoverInfoSchema = z.object({\n targetAgentId: z.guid(),\n targetAgentName: z.string(),\n status: handoverStatusSchema,\n targetRunId: z.guid().nullable(),\n targetBuildId: z.guid().nullable(),\n rejectionReason: z.string().nullable(),\n});\n\nexport type HandoverInfo = z.infer<typeof handoverInfoSchema>;\n\n/**\n * Slim view of a sub-assignment that was frozen into the run config at\n * creation time. Used by the message renderer to map the `subagent_type`\n * slug Claude reports back to a human-readable assignment name and an\n * agent ID for click-through.\n *\n * Shipped as a separate slim shape so we never expose the sub-assignment's\n * full SOP/prompt or redacted MCP server map to the frontend.\n */\nexport const runSubAgentRefSchema = z.object({\n agentId: z.guid(),\n slug: z\n .string()\n .describe(\n \"Stable kebab-case slug Claude Code uses as the subagent name (matches `subagent_type` on Agent tool calls)\"\n ),\n displayName: z.string(),\n});\n\nexport type RunSubAgentRef = z.infer<typeof runSubAgentRefSchema>;\n\n/**\n * Schema for agent run detail (includes conversation)\n */\nconst agentRunDetailSchemaData = z.object({\n id: z.guid(),\n created_at: z.coerce.date(),\n updated_at: z.coerce.date(),\n agent_id: z.guid(),\n build_id: z.guid(),\n started_at: z.coerce.date().nullable(),\n completed_at: z.coerce.date().nullable(),\n last_session_id: z.string().nullable(),\n user_id: z.guid().nullable(),\n source: z.string().nullable(),\n bb_session_id: z.string().nullable(),\n computer_session_id: z.string().nullable().optional(),\n sandbox_id: z.string().nullable(),\n status: agentRunStatusSchema.optional(),\n conversation: agentMessageSchema.array().optional(),\n conversationPagination: conversationPaginationSchema.optional(),\n integrationInstances: integrationInstanceMetadataSchema.array().optional(),\n subAgents: runSubAgentRefSchema.array().optional(),\n /** Case queue item ID for case-triggered runs */\n case_queue_item_id: z.guid().nullable().optional(),\n handover: handoverInfoSchema.nullable().optional(),\n eval_summaries: evalSummarySchema.nullable().optional(),\n user_name: z.string().nullable().optional(),\n user_email: z.string().nullable().optional(),\n submitted_prompt_count: z.number().int().min(0).optional(),\n});\n\nexport const agentRunDetailSchema = z.object({\n data: agentRunDetailSchemaData.nullable(),\n});\n\n/**\n * Type inferred from agentRunDetailSchema\n */\nexport type AgentRunDetail = z.infer<typeof agentRunDetailSchema>;\n", "import { z } from \"zod\";\n\nexport const agentRuntimeSchema = z.union([\n z.literal(\"responses\"),\n z.literal(\"terminal-agent\"),\n]);\n\nconst agentMessageRoleSchema = z.union([\n z.literal(\"user\"),\n z.literal(\"assistant\"),\n z.literal(\"system\"),\n]);\n\nconst agentMessageTypeSchema = z.union([\n z.literal(\"text\"),\n z.literal(\"tool_call\"),\n z.literal(\"tool_result\"),\n z.literal(\"system\"),\n z.literal(\"thinking\"),\n]);\n\nconst duvoMessageTypeSchema = z.union([\n z.literal(\"agent_run_created\"),\n z.literal(\"session_started\"),\n z.literal(\"session_completed\"),\n z.literal(\"session_interrupted\"),\n z.literal(\"session_error\"),\n z.literal(\"browser_session_created\"),\n]);\n\nconst duvoBaseSystemMessageSchema = z.object({\n id: z.string(),\n runtime: agentRuntimeSchema,\n timestamp: z.string(),\n role: z.literal(\"duvo\"),\n type: duvoMessageTypeSchema,\n});\n\nconst duvoSystemSessionStartedMessageSchema = duvoBaseSystemMessageSchema.and(\n z.object({\n type: z.literal(\"session_started\"),\n })\n);\n\nconst duvoSystemSessionCompletedMessageSchema = duvoBaseSystemMessageSchema.and(\n z.object({\n type: z.literal(\"session_completed\"),\n })\n);\n\nconst duvoSystemSessionInterruptedMessageSchema =\n duvoBaseSystemMessageSchema.and(\n z.object({\n type: z.literal(\"session_interrupted\"),\n })\n );\n\nconst duvoSystemSessionErrorMessageSchema = duvoBaseSystemMessageSchema.and(\n z.object({\n type: z.literal(\"session_error\"),\n error: z.string(),\n })\n);\n\nconst duvoSystemAgentRunCreatedMessageSchema = duvoBaseSystemMessageSchema.and(\n z.object({\n type: z.literal(\"agent_run_created\"),\n agent_run_id: z.string(),\n })\n);\n\nconst duvoSystemBrowserSessionCreatedMessageSchema =\n duvoBaseSystemMessageSchema.and(\n z.object({\n type: z.literal(\"browser_session_created\"),\n browser_session_id: z.string(),\n })\n );\n\nexport const agentRuntimeMessageTypeSchema = z.union([\n agentMessageTypeSchema,\n duvoMessageTypeSchema,\n]);\n\nexport const duvoSystemMessageSchema = z.union([\n duvoSystemSessionStartedMessageSchema,\n duvoSystemSessionCompletedMessageSchema,\n duvoSystemSessionInterruptedMessageSchema,\n duvoSystemAgentRunCreatedMessageSchema,\n duvoSystemBrowserSessionCreatedMessageSchema,\n duvoSystemSessionErrorMessageSchema,\n]);\n\nexport const sdkMessageSchema = z.looseObject({\n session_id: z.string(),\n uuid: z.string(),\n});\n\nexport const pausableToolCategorySchema = z.union([\n z.literal(\"question\"),\n z.literal(\"approval\"),\n z.literal(\"confirmation\"),\n z.literal(\"input\"),\n z.literal(\"credentials\"),\n]);\n\nexport const toolPausedEventSchema = z.object({\n type: z.literal(\"tool_paused\"),\n executionId: z.string(),\n sessionId: z.string().optional(),\n toolName: z.string(),\n toolInput: z.record(z.string(), z.unknown()),\n category: pausableToolCategorySchema,\n behavior: z.union([z.literal(\"canUseTool\"), z.literal(\"interrupt\")]),\n timestamp: z.string().optional(),\n});\n\nexport const responseSchema = z.any();\n\nconst baseMessageSchema = z.object({\n id: z.string(),\n type: agentMessageTypeSchema,\n runtime: agentRuntimeSchema,\n timestamp: z.string(),\n raw_message: z.union([sdkMessageSchema, responseSchema]),\n role: agentMessageRoleSchema,\n});\n\nconst textMessageSchema = baseMessageSchema.and(\n z.object({\n type: z.literal(\"text\"),\n role: z.union([z.literal(\"assistant\"), z.literal(\"user\")]),\n text_content: z.string(),\n metadata: z\n .looseObject({\n isAgentInstruction: z.boolean().optional(),\n })\n .optional(),\n })\n);\n\nconst thinkingMessageSchema = baseMessageSchema.and(\n z.object({\n type: z.literal(\"thinking\"),\n role: z.literal(\"assistant\"),\n text_content: z.string(),\n })\n);\n\nconst toolCallMessageSchema = baseMessageSchema.and(\n z.object({\n type: z.literal(\"tool_call\"),\n role: z.literal(\"assistant\"),\n mcp_server_label: z.string().optional(),\n tool_call: z.object({\n id: z.string(),\n name: z.string(),\n arguments: z.record(z.string(), z.unknown()).optional(),\n }),\n })\n);\n\nconst toolResultMessageSchema = baseMessageSchema.and(\n z.object({\n type: z.literal(\"tool_result\"),\n role: z.literal(\"assistant\"),\n mcp_server_label: z.string().optional(),\n tool_result: z.object({\n tool_call_id: z.string(),\n result: z.unknown().optional(),\n error: z.string().optional(),\n }),\n })\n);\n\nexport const agentMessageSchema = z.union([\n textMessageSchema,\n thinkingMessageSchema,\n toolCallMessageSchema,\n toolResultMessageSchema,\n duvoSystemMessageSchema,\n]);\n", "import { z } from \"zod\";\n\nexport const evaluationDataSchema = z.record(\n z.string(),\n z.union([z.boolean(), z.string(), z.null()])\n);\n\nexport const evaluationOutputSchema = z.object({\n schemaId: z.string().optional(),\n schemaVersion: z.string().optional(),\n data: evaluationDataSchema,\n});\n\nexport const runEvaluationResponseSchema = z.object({\n data: z\n .object({\n id: z.guid(),\n created_at: z.string(),\n run_id: z.guid(),\n source: z.string().nullable(),\n output: evaluationOutputSchema,\n })\n .nullable(),\n});\n\nexport type RunEvaluationResponse = z.infer<typeof runEvaluationResponseSchema>;\n\nexport const evalSummarySchema = z.object({\n passed: z.number(),\n total: z.number(),\n final_comment: z.string().optional(),\n status: z.enum([\"ready\", \"unavailable\", \"in_progress\"]),\n});\n\nexport type EvalSummaryData = z.infer<typeof evalSummarySchema>;\n\nexport const evalFlagCountSchema = z.object({\n flag: z.string(),\n count: z.int(),\n});\n\nexport type EvalFlagCount = z.infer<typeof evalFlagCountSchema>;\n\nexport const evalScoresResponseSchema = z.object({\n total_evaluated: z.int(),\n with_issues: z.int(),\n flag_distribution: z.array(evalFlagCountSchema),\n});\n\nexport type EvalScoresResponse = z.infer<typeof evalScoresResponseSchema>;\n\nexport const evalCountsSchema = z.object({\n total_evaluated: z.int(),\n with_issues: z.int(),\n});\n\nexport type EvalCounts = z.infer<typeof evalCountsSchema>;\n\nexport const evalCountsByAgentResponseSchema = z.object({\n by_agent: z.record(z.string(), evalCountsSchema),\n});\n\nexport type EvalCountsByAgentResponse = z.infer<\n typeof evalCountsByAgentResponseSchema\n>;\n\nexport const summarizeEvalScoresBodySchema = z.object({\n since: z.iso.datetime(),\n});\n\nexport type SummarizeEvalScoresBody = z.infer<\n typeof summarizeEvalScoresBodySchema\n>;\n\nexport const summarizeEvalScoresResponseSchema = z.object({\n data: z.object({\n summary: z.string(),\n run_count: z.int(),\n }),\n});\n\nexport type SummarizeEvalScoresResponse = z.infer<\n typeof summarizeEvalScoresResponseSchema\n>;\n", "import { z } from \"zod\";\n\n/**\n * Zod schema for browsing providers supported by Stagehand\n */\nexport const BrowsingProviderSchema = z.enum([\"google\", \"anthropic\"]);\n\nexport type BrowsingProvider = z.infer<typeof BrowsingProviderSchema>;\n\n/**\n * Platform-wide default models for agent configuration\n */\nexport const PLATFORM_DEFAULT_MODELS = {\n agent: {\n model: \"claude-sonnet-4-6[1m]\",\n },\n browsing: {\n provider: \"google\",\n model: \"gemini-2.5-pro\",\n },\n} as const satisfies {\n agent: { model: ClaudeModelId };\n browsing: { provider: BrowsingProvider; model: BrowsingModelId };\n};\n\ntype ModelMetadata = {\n displayName: string;\n description?: string;\n};\n\n/**\n * Core Claude model IDs (canonical identifiers) \u2014 the set of models selectable\n * in the UI and accepted unchanged by the runtime. Everything else is treated\n * as legacy and resolves to `PLATFORM_DEFAULT_MODELS.agent.model`.\n */\nexport const CLAUDE_MODEL_IDS = [\n \"claude-sonnet-4-6\",\n \"claude-sonnet-4-6[1m]\",\n \"claude-opus-4-6\",\n \"claude-opus-4-6[1m]\",\n \"claude-opus-4-7\",\n \"claude-opus-4-7[1m]\",\n] as const;\n\n/**\n * Tombstone IDs: values that may still appear in historic agent_run.run_config\n * snapshots and therefore need to parse through `ClaudeModelIdSchema`, but are\n * no longer selectable and always resolve to the platform default at runtime.\n */\nconst LEGACY_MODEL_IDS = [\n // Old duvo wrapper aliases\n \"d1-max\",\n \"duvo-1-max\",\n \"duvo-1-max-sonnet-1m\",\n \"duvo-1-max-sonnet-4.5\",\n \"duvo-1-max-sonnet-4.5-1m\",\n \"duvo-1-max-opus\",\n \"duvo-1-max-opus-4.5\",\n // Legacy OpenAI models (never actually ran \u2014 silently fell back to Claude)\n \"gpt-4.1\",\n \"gpt-4o\",\n \"gpt-4o-mini\",\n \"gpt-5\",\n \"gpt-5.1\",\n // Retired canonical Claude model IDs\n \"claude-sonnet-4-20250514\",\n \"claude-sonnet-4-20250514[1m]\",\n \"claude-sonnet-4-5-20250929\",\n \"claude-sonnet-4-5-20250929[1m]\",\n \"claude-opus-4-1-20250805\",\n \"claude-opus-4-5-20251101\",\n] as const;\n\n/**\n * Zod schema for Claude model IDs (includes legacy model IDs for backward compatibility)\n */\nexport const ClaudeModelIdSchema = z.enum([\n ...CLAUDE_MODEL_IDS,\n ...LEGACY_MODEL_IDS,\n]);\n\nexport type ClaudeModelId = z.infer<typeof ClaudeModelIdSchema>;\n\n/**\n * Core Claude model ID type (excludes legacy IDs)\n */\nexport type CoreClaudeModelId = (typeof CLAUDE_MODEL_IDS)[number];\n\n/**\n * Available main agent models \u2014 shown in the UI model picker.\n */\nexport const AVAILABLE_AGENT_MODELS: Record<CoreClaudeModelId, ModelMetadata> =\n {\n \"claude-sonnet-4-6\": {\n displayName: \"Claude Sonnet 4.6\",\n },\n \"claude-sonnet-4-6[1m]\": {\n displayName: \"Claude Sonnet 4.6\",\n description: \"Fast and capable for everyday tasks\",\n },\n \"claude-opus-4-6\": {\n displayName: \"Claude Opus 4.6\",\n description: \"Advanced model for complex work\",\n },\n \"claude-opus-4-6[1m]\": {\n displayName: \"Claude Opus 4.6\",\n description: \"Advanced model for complex work\",\n },\n \"claude-opus-4-7\": {\n displayName: \"Claude Opus 4.7\",\n description: \"Our most capable model \\u2014 best for complex work\",\n },\n \"claude-opus-4-7[1m]\": {\n displayName: \"Claude Opus 4.7\",\n description: \"Our most capable model \\u2014 best for complex work\",\n },\n } as const;\n\nexport type BrowsingModelMetadata = {\n displayName: string;\n provider: BrowsingProvider;\n};\n\n/**\n * Zod schema for browsing model IDs\n */\nexport const BrowsingModelIdSchema = z.enum([\n \"gemini-2.5-pro\",\n \"gemini-2.5-flash\",\n \"gemini-3-pro-preview\",\n \"claude-haiku-4-5\",\n \"claude-sonnet-4-5\",\n \"claude-opus-4-1\",\n]);\n\nexport type BrowsingModelId = z.infer<typeof BrowsingModelIdSchema>;\n\nexport const EVALUATION_MODEL: CoreClaudeModelId = \"claude-sonnet-4-6[1m]\";\n\nexport const INPUT_SAFETY_MODEL = \"claude-haiku-4-5-20251001\";\n\n/**\n * Target that retired/legacy model IDs resolve to at runtime. A stored\n * `build.config` model string that isn't in `CLAUDE_MODEL_IDS` (legacy aliases,\n * retired canonical IDs, OpenAI stubs, null/garbage) maps to this ID.\n *\n * Kept separate from `PLATFORM_DEFAULT_MODELS.agent.model` so legacy routing\n * can diverge from new-Assignment defaults if product ever wants to pin them\n * apart (e.g. route legacy traffic to a cheaper tier while keeping new\n * Assignments on the latest flagship).\n */\nexport const LEGACY_DEFAULT_MODEL: CoreClaudeModelId = \"claude-sonnet-4-6[1m]\";\n\n/**\n * A model ID as it might appear from any source: a current canonical string,\n * a legacy alias, a retired canonical, `null` (Postgres NULL \u2192 JS null on\n * reads), `undefined` (optional chaining / missing JSON keys), or an empty\n * string. Both `mapModelToClaudeModel` and `isLegacyModelId` accept this\n * shape so callers don't have to normalize `undefined \u2192 null` at the boundary.\n */\nexport type MaybeStoredModelId = string | null | undefined;\n\n/**\n * Resolve any stored model ID (current, legacy alias, or retired canonical) to\n * a currently-runnable canonical Claude model. Anything not in `CLAUDE_MODEL_IDS`\n * routes to `LEGACY_DEFAULT_MODEL` \u2014 single source of truth for legacy routing.\n */\nexport function mapModelToClaudeModel(\n model: MaybeStoredModelId\n): CoreClaudeModelId {\n if (model && CLAUDE_MODEL_IDS.includes(model as CoreClaudeModelId)) {\n return model as CoreClaudeModelId;\n }\n\n return LEGACY_DEFAULT_MODEL;\n}\n\n/**\n * Returns true when a stored model ID is a legacy alias or retired canonical\n * ID \u2014 anything not in the currently-selectable `CLAUDE_MODEL_IDS`. Useful for\n * UI affordances (e.g. showing a \"legacy model, will be routed\" indicator).\n * Null / undefined / empty string \u2192 false (no stored model, not a legacy value).\n */\nexport function isLegacyModelId(model: MaybeStoredModelId): boolean {\n return (\n model != null &&\n model !== \"\" &&\n !CLAUDE_MODEL_IDS.includes(model as CoreClaudeModelId)\n );\n}\n", "import {\n type BrowserProviderType,\n type StoredAgentConfigV2,\n} from \"../types/agent-config\";\nimport type { EditableAgentConfig } from \"../utils/normalize-agent-config\";\nimport { PLATFORM_DEFAULT_MODELS } from \"./models\";\n\nexport const AGENT_CONFIG_VERSION: StoredAgentConfigV2[\"version\"] = \"v2\";\n\n/**\n * Default browser provider for NEW agent runs.\n */\nexport const DEFAULT_BROWSER_PROVIDER: BrowserProviderType = \"browserbase\";\n\n/**\n * Legacy default browser provider for backward compatibility.\n * Used when agent_run.run_config is null (pre-run_config runs)\n * or when browserProvider is not specified in the config.\n */\nexport const LEGACY_DEFAULT_BROWSER_PROVIDER: BrowserProviderType =\n \"browserbase\";\n\nexport const DEFAULT_AGENT_NAME = \"New Assignment\";\n\n/**\n * Maximum SOP (Standard Operating Procedure) size in bytes.\n * Larger SOPs cause 413 errors when dispatching to cc-server.\n */\nexport const MAX_SOP_SIZE_BYTES = 512 * 1024; // 0.5MB\n\n/**\n * Maximum number of sub-assignments a parent assignment can declare.\n * Bounds breadth/fan-out at delegation time; large fan-outs balloon the\n * cc-server payload and the parent's prompt cache cost.\n */\nexport const MAX_SUB_AGENTS = 16;\n\n/**\n * Maximum aggregate size, in bytes, of all sub-assignment prompts plus\n * descriptions plus names in a single run config. Each sub ships its own\n * SOP in the cc-server payload, so this caps the request body even when\n * the parent task itself is well under MAX_SOP_SIZE_BYTES.\n */\nexport const MAX_SUB_AGENTS_TOTAL_BYTES = 512 * 1024; // 0.5MB\n\nexport const DEFAULT_AGENT_CONFIG: EditableAgentConfig = {\n models: {\n agent: {\n model: PLATFORM_DEFAULT_MODELS.agent.model,\n },\n browsing: {\n provider: PLATFORM_DEFAULT_MODELS.browsing.provider,\n model: PLATFORM_DEFAULT_MODELS.browsing.model,\n },\n },\n input: [],\n files: [], // Context files\n skills: [], // Attached skill IDs\n subAgents: [], // Sub-assignment agent IDs\n options: {\n browserProvider: DEFAULT_BROWSER_PROVIDER,\n },\n};\n", "export const BROWSER_VIEWPORT_WIDTH = 1536;\nexport const BROWSER_VIEWPORT_HEIGHT = 864;\n\nexport const BROWSER_RECORDING_VIEWPORT_WIDTH = 1920;\nexport const BROWSER_RECORDING_VIEWPORT_HEIGHT = 1080;\n\nexport const BROWSER_SCREENSHOT_WIDTH = 1280;\nexport const BROWSER_SCREENSHOT_HEIGHT = 720;\n", "export const BUILD_STATUS = {\n DRAFT: \"draft\",\n LIVE: \"live\",\n HISTORIC: \"historic\",\n} as const;\n\nexport type BuildStatus = (typeof BUILD_STATUS)[keyof typeof BUILD_STATUS];\n", "// Case queue item status constants\nexport const CASE_QUEUE_ITEM_STATUS = {\n PENDING: \"pending\",\n CLAIMED: \"claimed\",\n COMPLETED: \"completed\",\n FAILED: \"failed\",\n} as const;\n\nexport type CaseQueueItemStatus =\n (typeof CASE_QUEUE_ITEM_STATUS)[keyof typeof CASE_QUEUE_ITEM_STATUS];\n\n/**\n * Statuses from which a case can be retried. A case in any of these states\n * will be reset to `pending` by the retry flow; any active runs attached to\n * a claimed case are interrupted first. `pending` is the only status excluded\n * \u2014 there is nothing to retry.\n */\nexport const RETRYABLE_CASE_STATUSES = [\n CASE_QUEUE_ITEM_STATUS.COMPLETED,\n CASE_QUEUE_ITEM_STATUS.FAILED,\n CASE_QUEUE_ITEM_STATUS.CLAIMED,\n] as const satisfies readonly CaseQueueItemStatus[];\n\nexport function isRetryableCaseStatus(status: CaseQueueItemStatus): boolean {\n return (RETRYABLE_CASE_STATUSES as readonly CaseQueueItemStatus[]).includes(\n status\n );\n}\n", "export const E2B_SANDBOX_TIMEOUT_MS = 43_200_000; // 12 hour timeout\n", "/**\n * Central evaluation rubric catalog shared across backend and frontend.\n *\n * This is the ever-growing catalog of every rubric that has ever been used.\n * Never remove entries \u2014 the admin dashboard needs them to display\n * historical evaluation data.\n */\n\n/**\n * High-level cause classification for evaluation rubrics.\n *\n * Each class needs different treatment when a spike is detected:\n *\n * - `sop_gap` \u2014 The user's instructions are missing, ambiguous, or under-specified.\n * Fix: the user improves their SOP (e.g. adds explicit defaults, clarifies scope).\n *\n * - `agent_misbehavior` \u2014 The agent acted incorrectly despite clear instructions.\n * Fix: auto-correct via learnings (e.g. the agent skipped tasks, hallucinated, or\n * ignored stated constraints).\n *\n * - `platform_issue` \u2014 Our infrastructure or tooling failed.\n * Fix: we fix the underlying platform problem (e.g. broken integrations, flaky\n * browser automation, expired credentials).\n *\n * - `user_access_gap` \u2014 The agent cannot make progress until a human admin on\n * the customer side provisions access (e.g. grants a role in the target system,\n * enables a feature for the account, adds the agent user to a group).\n * Fix: a customer-side administrator grants the missing access in the external\n * system. Distinct from `sop_gap` (which is about instructions) and from\n * `platform_issue` (which is something we fix on our side).\n */\nexport type EvaluationRubricCause =\n | \"sop_gap\"\n | \"agent_misbehavior\"\n | \"platform_issue\"\n | \"user_access_gap\";\n\nexport interface EvaluationRubricDefinition {\n label: string;\n description: string;\n nullable: boolean;\n cause: EvaluationRubricCause;\n is_recommended: boolean;\n}\n\nexport const EVALUATION_RUBRIC_CATALOG = {\n skipped_known_items: {\n label: \"Skipped known items\",\n description:\n \"Did the agent fail to complete one or more explicitly enumerated tasks or items from the original instructions while presenting the task as completed?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: true,\n },\n skipped_discovered_items: {\n label: \"Skipped discovered items\",\n description:\n \"Did the agent fail to process all relevant items discovered during task execution (e.g. files, rows, documents) while presenting the task as completed?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n unrequested_activities: {\n label: \"Unrequested activities\",\n description:\n \"Did the agent spend a significant number of steps on activities that were neither requested by the user nor clearly necessary to unblock required work?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n ignored_constraints: {\n label: \"Ignored constraints\",\n description:\n 'Did the agent explicitly ignore or contradict a clearly stated instruction or constraint (e.g. required format, required steps, \"do not do X\") and still present the task as completed?',\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n format_compliance_failure: {\n label: \"Format compliance failure\",\n description:\n \"Did the agent fail to produce the required output format, structure, or schema (e.g. template, JSON shape, table columns), even if the underlying content was otherwise correct?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: true,\n },\n priority_inversion: {\n label: \"Priority inversion\",\n description:\n \"Did the agent focus on lower-priority or secondary work first and fail to complete critical required tasks as a result?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n unsure_missing_required_step: {\n label: \"Unsure: missing required step\",\n description:\n \"Did the agent explicitly state uncertainty because it could not perform or identify a core, required step defined in the instructions?\",\n nullable: false,\n cause: \"sop_gap\",\n is_recommended: true,\n },\n unsure_missing_instructions: {\n label: \"Unsure: missing instructions\",\n description:\n \"Did the agent explicitly state uncertainty because necessary instructions were missing or ambiguous and not knowable at task start?\",\n nullable: false,\n cause: \"sop_gap\",\n is_recommended: true,\n },\n integration_or_tool_missing: {\n label: \"Integration or tool missing\",\n description:\n \"Did the agent fail to complete required work because a necessary tool or integration was missing or not configured, including cases where the agent explicitly stated uncertainty because the required tool or capability did not exist?\",\n nullable: false,\n cause: \"platform_issue\",\n is_recommended: false,\n },\n integration_or_tool_failure: {\n label: \"Integration or tool failure\",\n description:\n \"Did the agent fail to complete required work because a necessary tool or integration was inaccessible or failed at runtime (e.g. permission or authentication errors, expired credentials, resource not found, execution failure)? IMPORTANT: Do NOT include rate-limit errors here \u2014 any occurrence of HTTP 429, 'too many requests', 'rate limit', 'retry after', 'throttled', or quota-exceeded errors must be evaluated under `rate_limit_hit` instead, even if other non-rate-limit failures also occurred in the same run.\",\n nullable: false,\n cause: \"platform_issue\",\n is_recommended: false,\n },\n rate_limit_hit: {\n label: \"Rate limit hit\",\n description:\n \"Did an external tool or integration return rate-limit errors (HTTP 429, 'too many requests', 'rate limit', 'retry after', 'throttled', quota exceeded) that materially impacted the agent's execution \u2014 whether by causing it to abandon or skip work, wait or retry for extended periods, or significantly degrade throughput? Set to true if rate-limit errors appeared and caused any meaningful disruption, even if the agent eventually completed the task.\",\n nullable: false,\n cause: \"platform_issue\",\n is_recommended: false,\n },\n uncaught_tool_failure: {\n label: \"Uncaught tool failure\",\n description:\n \"Did a tool or execution step fail, but the agent proceeded as if it had succeeded or failed to acknowledge and recover from the failure?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n missed_human_approval: {\n label: \"Missed human approval\",\n description:\n \"Did the agent require human approval to proceed but fail to invoke the HITL (human-in-the-loop) tool?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: true,\n },\n overreach_without_consent: {\n label: \"Overreach without consent\",\n description:\n \"Did the agent take or attempt an action that should reasonably require explicit user or human approval without asking first?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: true,\n },\n missed_user_question: {\n label: \"Missed user question\",\n description:\n \"Did the agent require additional information from the user to continue but fail to ask a question using the AskUserQuestion tool?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n unused_provided_artifact: {\n label: \"Unused provided artifact\",\n description:\n \"Was the agent provided with a file or artifact necessary for the task but failed to use it?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n unused_skill: {\n label: \"Unused skill\",\n description:\n \"Was a skill available that provides capabilities required by the task, but the agent failed to read or invoke it?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n hallucinated_facts: {\n label: \"Hallucinated facts\",\n description:\n \"Did the agent invent facts, data, claims, or details not supported by provided inputs, artifacts, or tool outputs?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: true,\n },\n wrong_assumptions: {\n label: \"Wrong assumptions\",\n description:\n \"Did the agent make a key unstated assumption (e.g. units, definitions, defaults, scope) that materially affected the result without flagging or validating it?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n over_refusal: {\n label: \"Over-refusal\",\n description:\n \"Did the agent unnecessarily refuse or decline a request that was allowed and feasible, or fail to provide partial help when it reasonably could have?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n user_said_wrong: {\n label: \"User said wrong\",\n description:\n \"Did the user explicitly state that the agent's output was wrong, incorrect, off-topic, or low-quality?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: true,\n },\n user_asked_to_continue: {\n label: \"User asked to continue\",\n description:\n \"Did the user explicitly ask the agent to continue or finish remaining work that was still feasible without restarting?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n user_said_incomplete: {\n label: \"User said incomplete\",\n description:\n \"Did the user explicitly state that the final output was incomplete in a way that would require restarting or major rework to fix?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: true,\n },\n browser_repetitive_actions: {\n label: \"Browser repetitive actions\",\n description:\n \"Did the agent perform repetitive browser actions without making meaningful progress (e.g., scrolling up/down multiple times in sequence, taking multiple similar screenshots or snapshots, clicking or extracting from the same elements 3+ times, or repeatedly using the same tool with similar parameters without success)?\",\n nullable: true,\n cause: \"platform_issue\",\n is_recommended: false,\n },\n browser_auth_failure: {\n label: \"Browser auth failure\",\n description:\n \"When browser authentication was required, did the agent fail to properly use available credential tools (list_credentials, fill_username, fill_password, fill_otp), attempt to manually type credentials in an insecure way, or give up on login flows without exhausting available authentication methods?\",\n nullable: true,\n cause: \"platform_issue\",\n is_recommended: false,\n },\n browser_authentication_issues: {\n label: \"Browser authentication issues\",\n description:\n \"When browser authentication was required, did the agent struggle with the login process \u2014 for example, retrying credential entry multiple times, cycling through authentication methods inefficiently, taking an excessive number of steps to complete login, failing to handle TOTP or multi-factor prompts smoothly, or encountering and recovering from repeated auth-related errors \u2014 even if it eventually succeeded?\",\n nullable: true,\n cause: \"platform_issue\",\n is_recommended: false,\n },\n browser_inappropriate_tools: {\n label: \"Browser inappropriate tools\",\n description:\n \"Did the agent repeatedly use inappropriate browser tools for the task at hand (e.g., using only screenshots when element inspection tools would be better, performing actions without first identifying target elements, using data extraction tools repeatedly when they're failing instead of trying different approaches), or fail to adapt its browsing strategy after multiple consecutive failures?\",\n nullable: true,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n browser_permission_wall: {\n label: \"Browser permission wall\",\n description:\n \"After the agent successfully authenticated to a browser-based target site, did the site block a required action because the authenticated account lacks a specific role, permission, or entitlement (e.g., 'Access denied. Required role: X', 'insufficient privileges', '403 Forbidden', 'you do not have permission to perform this action', 'this feature is not enabled for your account')? Set to true ONLY when login itself succeeded and the block appears at a post-login authorization layer; do NOT set true for login/credential failures, missing credentials that the agent could have requested via the request_credentials tool, or generic tool errors unrelated to authorization. This signals that a customer-side administrator must provision additional access on the target system \u2014 it is not a platform defect, not an agent mistake, and cannot be fixed in-run.\",\n nullable: true,\n cause: \"user_access_gap\",\n is_recommended: false,\n },\n browser_network_access_blocked: {\n label: \"Browser network access blocked\",\n description:\n \"Did the agent fail to reach a browser target because the network layer itself was blocked \u2014 i.e., navigation or connection never completed and no login form could be shown (e.g., 'ERR_CONNECTION_TIMED_OUT', 'ERR_NAME_NOT_RESOLVED', 'ERR_TUNNEL_CONNECTION_FAILED', 'this site can't be reached', 'DNS_PROBE_FINISHED_NXDOMAIN', explicit 'You must be connected to VPN' landing pages, or the target resolves only from a corporate network)? Set to true when the failure occurs at navigation/connection time BEFORE any authentication attempt. Do NOT set true for: post-login authorization errors (use browser_permission_wall), rate limits (use rate_limit_hit), login/credential failures, or transient single-request failures that the agent recovered from. This signals that a customer-side administrator must grant network access to the agent's egress \u2014 by allowlisting our IPs, providing VPN access, or exposing the target via a reachable URL.\",\n nullable: true,\n cause: \"user_access_gap\",\n is_recommended: false,\n },\n} as const satisfies Record<string, EvaluationRubricDefinition>;\n\nexport type EvaluationRubricKey = keyof typeof EVALUATION_RUBRIC_CATALOG;\n\nexport const ALL_EVALUATION_RUBRIC_KEYS = Object.keys(\n EVALUATION_RUBRIC_CATALOG\n) as EvaluationRubricKey[];\n\n/**\n * Field on `run_evaluations.output.data` that holds the judge's free-text\n * summary. Excluded when iterating over rubric flags.\n */\nexport const EVALUATION_FINAL_COMMENT_KEY = \"final_comment\";\n\nexport function isEvaluationRubricKey(\n value: string\n): value is EvaluationRubricKey {\n return Object.prototype.hasOwnProperty.call(EVALUATION_RUBRIC_CATALOG, value);\n}\n\nexport const ALL_EVALUATION_RUBRIC_CAUSES = [\n \"sop_gap\",\n \"agent_misbehavior\",\n \"platform_issue\",\n \"user_access_gap\",\n] as const;\n\nexport const EVALUATION_RUBRIC_KEYS_BY_CAUSE: Readonly<\n Record<EvaluationRubricCause, readonly EvaluationRubricKey[]>\n> = (() => {\n const mutable: Record<EvaluationRubricCause, EvaluationRubricKey[]> = {\n sop_gap: [],\n agent_misbehavior: [],\n platform_issue: [],\n user_access_gap: [],\n } satisfies Record<EvaluationRubricCause, EvaluationRubricKey[]>;\n\n for (const key of ALL_EVALUATION_RUBRIC_KEYS) {\n mutable[EVALUATION_RUBRIC_CATALOG[key].cause].push(key);\n }\n\n return mutable;\n})();\n", "/**\n * Human request types for the Activity Inbox feature.\n * - approval: Traditional HITL request requiring user approval\n * - question: AskUserQuestion tool request for clarification\n * - credentials: Agent needs login credentials for a website\n */\nexport const HUMAN_REQUEST_TYPE = {\n APPROVAL: \"approval\",\n QUESTION: \"question\",\n CREDENTIALS: \"credentials\",\n} as const;\n\nexport type HumanRequestType =\n (typeof HUMAN_REQUEST_TYPE)[keyof typeof HUMAN_REQUEST_TYPE];\n", "const SENSITIVE_FIELD_KEYWORDS = [\n \"password\",\n \"passphrase\",\n \"secret\",\n \"token\",\n \"key\",\n \"credential\",\n \"authorization\",\n \"service-account\",\n] as const;\n\nexport function isSensitiveFieldName(fieldName: string): boolean {\n const lower = fieldName.toLowerCase();\n return SENSITIVE_FIELD_KEYWORDS.some((keyword) => lower.includes(keyword));\n}\n\nexport { SENSITIVE_FIELD_KEYWORDS };\n", "/**\n * Duvo platform plugins that are pre-installed in E2B sandbox images.\n * These plugins are distinct from:\n * - Anthropic built-in plugins (from github.com/anthropics/claude-code/plugins/)\n * - GitHub custom plugins (downloaded at runtime from user-specified URLs)\n */\nexport const DUVO_PLATFORM_PLUGINS = [\"browsing\", \"default-skills\"] as const;\n\nexport type DuvoPlatformPlugin = (typeof DUVO_PLATFORM_PLUGINS)[number];\n\nexport const DUVO_PLATFORM_PLUGIN_DESCRIPTIONS: Record<\n DuvoPlatformPlugin,\n string\n> = {\n browsing: \"Enables the assignment to browse the web.\",\n \"default-skills\":\n \"Bundles Duvo's default skills (docx, pdf, pptx, google-sheets, snowflake) so the assignment can read and produce common document formats.\",\n};\n\nexport function isDuvoPlatformPlugin(name: string): name is DuvoPlatformPlugin {\n return (DUVO_PLATFORM_PLUGINS as readonly string[]).includes(name);\n}\n\n// Skill UUIDs now delivered via the default-skills plugin baked into the\n// E2B sandbox image. Soft-deleted from the DB \u2014 used to filter stale\n// references in old build configs.\nexport const PLUGIN_BACKED_DEFAULT_SKILL_IDS = new Set([\n \"a7f3d8e2-9b4c-4e6a-8c3f-1d2e5f7a9b3c\", // docx\n \"b8e4c9f1-3a5d-4b7e-9d2c-6f8a1c3e5d7b\", // pdf\n \"c9d5b8a2-4f6e-4c8a-8e3d-7b9c2d4f6a8e\", // pptx\n \"d8f6e7a3-5b7c-4d9a-9e4f-8c7b3f2a6d5e\", // google-sheets\n \"bad3cc47-8180-4fca-99bd-a51b543c6d87\", // snowflake\n]);\n", "/**\n * Available solution categories for retail solutions\n */\nexport const SOLUTION_CATEGORIES = [\n \"category-merchandising\",\n \"vendor-trade\",\n \"supply-chain\",\n \"finance-ops\",\n \"commercial-marketing\",\n] as const;\n\n/**\n * Solution category type derived from available categories\n */\nexport type SolutionCategory = (typeof SOLUTION_CATEGORIES)[number];\n\n/**\n * Map of solution category slugs to human-readable display labels\n */\nexport const SOLUTION_CATEGORY_LABELS: Record<SolutionCategory, string> = {\n \"category-merchandising\": \"Category & Merchandising\",\n \"vendor-trade\": \"Vendor & Trade\",\n \"supply-chain\": \"Supply Chain\",\n \"finance-ops\": \"Finance Ops\",\n \"commercial-marketing\": \"Commercial & Marketing\",\n} as const;\n\n/**\n * Format solution category slug into display label\n */\nexport const formatSolutionCategoryLabel = (\n category: SolutionCategory\n): string => {\n return SOLUTION_CATEGORY_LABELS[category] || category;\n};\n", "export const LINEAR_TRIGGER_TYPE = \"linear_event\" as const;\n\nexport const LINEAR_EVENT_TYPES = [\n \"new_issue\",\n \"issue_state_changed\",\n \"issue_assigned\",\n \"new_comment\",\n] as const;\n\nexport type LinearEventType = (typeof LINEAR_EVENT_TYPES)[number];\n", "export const COOKIE_NAMES = {\n IMPERSONATION: \"impersonation\",\n OTP_IMPORT_GUIDE_DISMISSED: \"otp_import_guide_dismissed\",\n LAST_VISITED_QUEUE_ID: \"duvo_last_visited_queue_id\",\n POST_LOGOUT_REDIRECT: \"post_logout_redirect\",\n} as const;\n\nexport type CookieName = (typeof COOKIE_NAMES)[keyof typeof COOKIE_NAMES];\n", "import { z } from \"zod\";\n\nexport const CLARITY_SCREENSHARE_SESSION_STATUSES = [\n \"active\",\n \"completing\",\n \"completed\",\n] as const;\n\nexport type ClarityScreenshareSessionStatus =\n (typeof CLARITY_SCREENSHARE_SESSION_STATUSES)[number];\n\nexport const CLARITY_SCREENSHARE_COVERAGE_AREAS = [\n \"processIdentity\",\n \"stepsAndFlow\",\n \"inputsAndResources\",\n \"toolsAndSystems\",\n \"outputsAndRecords\",\n \"timingAndControls\",\n \"exceptionsAndFailureModes\",\n \"painPoints\",\n] as const;\n\nexport type ClarityScreenshareCoverageArea =\n (typeof CLARITY_SCREENSHARE_COVERAGE_AREAS)[number];\n\nexport const CLARITY_SCREENSHARE_AREA_STATUSES = [\n \"not_started\",\n \"partial\",\n \"covered\",\n] as const;\n\nexport type ClarityScreenshareAreaStatus =\n (typeof CLARITY_SCREENSHARE_AREA_STATUSES)[number];\n\nexport const CLARITY_SCREENSHARE_DECISIONS = [\n \"suggestion\",\n \"context\",\n \"close\",\n \"silence\",\n] as const;\n\nexport type ClarityScreenshareDecision =\n (typeof CLARITY_SCREENSHARE_DECISIONS)[number];\n\n// --- Coverage ---\n\nconst areaStatusSchema = z.enum(CLARITY_SCREENSHARE_AREA_STATUSES);\n\nconst processIdentityExtractedSchema = z.object({\n processName: z.string().nullable(),\n owner: z.string().nullable(),\n trigger: z.string().nullable(),\n finalOutput: z.string().nullable(),\n recentInstance: z.string().nullable(),\n});\n\nconst stepsAndFlowExtractedSchema = z.object({\n majorPhases: z.array(z.object({ name: z.string(), description: z.string() })),\n handoffs: z.array(\n z.object({\n from: z.string(),\n to: z.string(),\n description: z.string(),\n })\n ),\n});\n\nconst inputsAndResourcesExtractedSchema = z.object({\n inputs: z.array(\n z.object({\n step: z.string(),\n items: z.array(z.string()),\n source: z.string(),\n })\n ),\n missingOrLateInputs: z.array(z.string()),\n phaseOwners: z.array(\n z.object({ phase: z.string(), role: z.string(), team: z.string() })\n ),\n totalPeopleInvolved: z.string().nullable(),\n});\n\nconst toolsAndSystemsExtractedSchema = z.object({\n toolsPerStep: z.array(\n z.object({ step: z.string(), tools: z.array(z.string()) })\n ),\n manualReentry: z.array(z.string()),\n});\n\nconst outputsAndRecordsExtractedSchema = z.object({\n outputsPerStage: z.array(\n z.object({ stage: z.string(), artifacts: z.array(z.string()) })\n ),\n systemOfRecord: z.string().nullable(),\n scattered: z.boolean().nullable(),\n});\n\nconst timingAndControlsExtractedSchema = z.object({\n cycleTimePerStep: z.array(\n z.object({ step: z.string(), duration: z.string() })\n ),\n waitingPoints: z.array(z.string()),\n approvalsAndChecks: z.array(\n z.object({ description: z.string(), whereRecorded: z.string() })\n ),\n overallCycleTime: z.string().nullable(),\n});\n\nconst exceptionsAndFailureModesExtractedSchema = z.object({\n exceptions: z.array(\n z.object({\n description: z.string(),\n percentageAffected: z.string(),\n additionalTime: z.string(),\n })\n ),\n});\n\nconst painPointsExtractedSchema = z.object({\n painPoints: z.array(\n z.object({ description: z.string(), estimatedMonthlyCost: z.string() })\n ),\n topBottlenecks: z.array(\n z.object({ description: z.string(), timeImpact: z.string() })\n ),\n});\n\nconst areaSchema = <T extends z.ZodType>(extractedSchema: T) =>\n z.object({\n status: areaStatusSchema,\n extracted: extractedSchema,\n });\n\nexport const clarityScreenshareCoverageSchema = z.object({\n startedAt: z.number(),\n roundNumber: z.number(),\n elapsedSeconds: z.number(),\n timeTargetSeconds: z.number(),\n processName: z.string(),\n areas: z.object({\n processIdentity: areaSchema(processIdentityExtractedSchema),\n stepsAndFlow: areaSchema(stepsAndFlowExtractedSchema),\n inputsAndResources: areaSchema(inputsAndResourcesExtractedSchema),\n toolsAndSystems: areaSchema(toolsAndSystemsExtractedSchema),\n outputsAndRecords: areaSchema(outputsAndRecordsExtractedSchema),\n timingAndControls: areaSchema(timingAndControlsExtractedSchema),\n exceptionsAndFailureModes: areaSchema(\n exceptionsAndFailureModesExtractedSchema\n ),\n painPoints: areaSchema(painPointsExtractedSchema),\n }),\n gaps: z.array(z.string()),\n});\n\nexport type ClarityScreenshareCoverage = z.infer<\n typeof clarityScreenshareCoverageSchema\n>;\n\nexport function createInitialCoverage(\n processName: string\n): ClarityScreenshareCoverage {\n return {\n startedAt: 0,\n roundNumber: 0,\n elapsedSeconds: 0,\n timeTargetSeconds: 600,\n processName,\n areas: {\n processIdentity: {\n status: \"not_started\",\n extracted: {\n processName: null,\n owner: null,\n trigger: null,\n finalOutput: null,\n recentInstance: null,\n },\n },\n stepsAndFlow: {\n status: \"not_started\",\n extracted: { majorPhases: [], handoffs: [] },\n },\n inputsAndResources: {\n status: \"not_started\",\n extracted: {\n inputs: [],\n missingOrLateInputs: [],\n phaseOwners: [],\n totalPeopleInvolved: null,\n },\n },\n toolsAndSystems: {\n status: \"not_started\",\n extracted: { toolsPerStep: [], manualReentry: [] },\n },\n outputsAndRecords: {\n status: \"not_started\",\n extracted: {\n outputsPerStage: [],\n systemOfRecord: null,\n scattered: null,\n },\n },\n timingAndControls: {\n status: \"not_started\",\n extracted: {\n cycleTimePerStep: [],\n waitingPoints: [],\n approvalsAndChecks: [],\n overallCycleTime: null,\n },\n },\n exceptionsAndFailureModes: {\n status: \"not_started\",\n extracted: { exceptions: [] },\n },\n painPoints: {\n status: \"not_started\",\n extracted: { painPoints: [], topBottlenecks: [] },\n },\n },\n gaps: [\n \"Process identity: name, owner, trigger, output, recent instance\",\n \"Steps and flow: major phases, handoffs\",\n \"Inputs and resources: inputs per step, missing/late, phase owners, headcount\",\n \"Tools and systems: tools per step, manual re-entry\",\n \"Outputs and records: artifacts per stage, system of record\",\n \"Timing and controls: SLAs, waiting points, approvals\",\n \"Exceptions and failure modes: common exceptions, % affected, resolution time\",\n \"Pain points: top 3 time sinks, estimated monthly cost\",\n ],\n };\n}\n\n// --- Transcript ---\n\nexport const clarityScreenshareTranscriptEntrySchema = z.object({\n id: z.string(),\n timestamp: z.number(),\n role: z.enum([\"user\", \"assistant\", \"interviewer\"]),\n text: z.string(),\n});\n\nexport type ClarityScreenshareTranscriptEntry = z.infer<\n typeof clarityScreenshareTranscriptEntrySchema\n>;\n\n// --- Frame ---\n\nexport const clarityScreenshareFrameSchema = z.object({\n base64: z.string(),\n timestamp: z.number(),\n});\n\nexport type ClarityScreenshareFrame = z.infer<\n typeof clarityScreenshareFrameSchema\n>;\n\n// --- Screenshare language ---\n\nexport const screenshareLanguageSchema = z.enum([\n \"cs\",\n \"de\",\n \"en\",\n \"es\",\n \"fr\",\n \"pl\",\n]);\n\nexport type ScreenshareLanguage = z.infer<typeof screenshareLanguageSchema>;\n\n// --- Turn submission (FE -> BE) ---\n\nexport const clarityScreenshareTurnBodySchema = z.object({\n transcript: z.array(clarityScreenshareTranscriptEntrySchema),\n images: z.array(clarityScreenshareFrameSchema),\n coverage: clarityScreenshareCoverageSchema,\n turnNumber: z.number(),\n elapsedSeconds: z.number(),\n language: screenshareLanguageSchema,\n});\n\nexport type ClarityScreenshareTurnBody = z.infer<\n typeof clarityScreenshareTurnBodySchema\n>;\n\n// --- Turn response (BE -> FE) ---\n\nexport const clarityScreenshareTurnResponseSchema = z.object({\n decision: z.enum(CLARITY_SCREENSHARE_DECISIONS),\n text: z.string().nullable(),\n coverage: clarityScreenshareCoverageSchema,\n turnNumber: z.number(),\n});\n\nexport type ClarityScreenshareTurnResponse = z.infer<\n typeof clarityScreenshareTurnResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport {\n clarityCaptureSchema,\n clarityProcessStatusSchema,\n generationProgressSchema,\n} from \"../types/clarity\";\nimport {\n postprocessClarityCurrentProcessDataSchema,\n postprocessClarityStepBaseSchema,\n postprocessClarityTransformationProposalDataSchema,\n} from \"./process-data\";\nimport { refineStepGraph } from \"./validators\";\n\n/**\n * Wire-format current-process snapshot for the v2 read model. Wrapper fields\n * are snake_case per the public-API guide; the nested `data` payload is an\n * LLM-produced BPMN graph that stays camelCase as a documented opaque\n * payload \u2014 converting the inner schema would touch every prompt and\n * postprocess agent.\n */\nexport const clarityCurrentProcessSnapshotApiSchema = z.object({\n id: z.guid().describe(\"Snapshot id\"),\n data: postprocessClarityCurrentProcessDataSchema.describe(\n \"Opaque BPMN payload describing the captured process. Field names inside `data` are camelCase by design.\"\n ),\n created_at: z.string().describe(\"ISO 8601 creation timestamp\"),\n updated_at: z.string().describe(\"ISO 8601 last-update timestamp\"),\n});\n\nexport const clarityTransformationProposalSnapshotApiSchema = z.object({\n id: z.guid().describe(\"Proposal id\"),\n data: postprocessClarityTransformationProposalDataSchema.describe(\n \"Opaque BPMN payload for the proposed transformed process. Field names inside `data` are camelCase by design.\"\n ),\n created_at: z.string().describe(\"ISO 8601 creation timestamp\"),\n updated_at: z.string().describe(\"ISO 8601 last-update timestamp\"),\n});\n\nexport const clarityV2ProcessReadModelSchema = z.object({\n process: z.object({\n id: z.guid().describe(\"Clarity process id\"),\n team_id: z.guid().describe(\"Owning team id\"),\n user_id: z.guid().describe(\"Creator user id\"),\n name: z.string().describe(\"Process name\"),\n status: clarityProcessStatusSchema.describe(\"Lifecycle status\"),\n version: z.number().int().describe(\"Schema version (always 2 here)\"),\n generation_error: z\n .string()\n .nullable()\n .describe(\"Error message from the most recent failed generation, if any\"),\n generation_progress: generationProgressSchema\n .nullable()\n .describe(\n \"Live progress checklist while a generation is in flight; null otherwise. Field names inside the payload are camelCase, matching the legacy v1 generation-progress shape.\"\n ),\n custom_prompt: z\n .string()\n .nullable()\n .describe(\"User-supplied custom prompt that steers generation\"),\n created_at: z.string().describe(\"ISO 8601 creation timestamp\"),\n updated_at: z.string().describe(\"ISO 8601 last-update timestamp\"),\n }),\n current_process: clarityCurrentProcessSnapshotApiSchema\n .nullable()\n .describe(\"Latest current-process snapshot, if generation has run\"),\n transformation_proposal: clarityTransformationProposalSnapshotApiSchema\n .nullable()\n .describe(\"Latest transformation proposal, if generation has run\"),\n captures: z\n .array(clarityCaptureSchema)\n .describe(\n \"All captures (videos, interviews, documents) attached to this process. Field names follow the legacy v1 capture wire format (camelCase) so existing capture consumers keep working unchanged.\"\n ),\n});\n\nexport type ClarityV2ProcessReadModel = z.infer<\n typeof clarityV2ProcessReadModelSchema\n>;\n\nexport const EXTRA_CAPTURE_REQUEST_PRIORITIES = [\n \"low\",\n \"medium\",\n \"high\",\n] as const;\n\nexport const EXTRA_CAPTURE_REQUEST_STATUSES = [\n \"requested\",\n \"captured\",\n \"resolved\",\n] as const;\n\n/**\n * Wire-format shape of one row from `clarity_proposal_extra_capture_request`.\n * Callers key by `id` to look up which steps still need a capture\n * (`status === \"requested\"`) versus which have already been filled in by a\n * prior capture (`status === \"captured\" | \"resolved\"`).\n *\n * `requested_user_id` is the team member assigned to fulfil the capture\n * (set by an admin/manager via the assign route). When non-null, only that\n * user should see the \"Add capture\" button; everyone else sees the assignee.\n */\nexport const clarityProposalExtraCaptureRequestSchema = z.object({\n id: z.guid().describe(\"Extra-capture-request id\"),\n proposal_id: z\n .guid()\n .describe(\"The transformation proposal this request belongs to\"),\n step_id: z.string().describe(\"Step id within the proposal's BPMN graph\"),\n capture_id: z\n .guid()\n .nullable()\n .describe(\"Capture that fulfilled this request, once one is created\"),\n requested_user_id: z\n .guid()\n .nullable()\n .describe(\"Assigned team member, if any\"),\n status: z\n .enum(EXTRA_CAPTURE_REQUEST_STATUSES)\n .describe(\"Lifecycle status of the request\"),\n gap: z.string().describe(\"Plain-language gap blocking automation\"),\n suggested_prompt: z\n .string()\n .nullable()\n .describe(\"LLM-produced suggested capture prompt\"),\n priority: z\n .enum(EXTRA_CAPTURE_REQUEST_PRIORITIES)\n .describe(\"Priority of fulfilling this request\"),\n created_at: z.string().describe(\"ISO 8601 creation timestamp\"),\n updated_at: z.string().describe(\"ISO 8601 last-update timestamp\"),\n});\n\nexport type ClarityProposalExtraCaptureRequest = z.infer<\n typeof clarityProposalExtraCaptureRequestSchema\n>;\n\n/**\n * Response shape for the per-proposal extra-capture-request list endpoint.\n * Includes pagination metadata as required by the public-API guide.\n */\nexport const clarityProposalExtraCaptureRequestListResponseSchema = z.object({\n requests: z.array(clarityProposalExtraCaptureRequestSchema),\n total: z.number().int().describe(\"Total matching rows across all pages\"),\n limit: z.number().int().describe(\"Page size that was applied\"),\n offset: z.number().int().describe(\"Offset that was applied\"),\n});\n\nexport type ClarityProposalExtraCaptureRequestListResponse = z.infer<\n typeof clarityProposalExtraCaptureRequestListResponseSchema\n>;\n\n/**\n * Body for the assign route. `user_id` is the team member to assign; pass\n * `null` to clear the existing assignment.\n */\nexport const assignClarityProposalExtraCaptureRequestRequestSchema = z.object({\n user_id: z\n .guid()\n .nullable()\n .describe(\"Team member to assign, or null to unassign\"),\n});\n\n/**\n * Body for the save-current-process route. Persists a user-edited steps array\n * as a new `clarity_current_process` snapshot. `baselineSnapshotId` is the id\n * of the snapshot the draft was forked from; the route rejects with 409 when\n * a newer snapshot has been written meanwhile so the user does not silently\n * overwrite a fresh pipeline run.\n *\n * `steps` is validated against the same graph rules the pipeline applies via\n * `refineStepGraph`, so the FE cannot bypass invariants by going through this\n * route.\n */\nexport const saveClarityV2CurrentProcessBodySchema = z.object({\n steps: z\n .array(postprocessClarityStepBaseSchema)\n .min(1)\n .superRefine(refineStepGraph),\n baselineSnapshotId: z.guid(),\n});\n\n/**\n * Body for the save-transformation-proposal route. Persists a user-edited\n * steps array as a new `clarity_transformation_proposal` snapshot anchored to\n * the given `clarityCurrentProcessId`. `baselineSnapshotId` references the\n * proposal snapshot the draft was forked from; the route returns 409 when a\n * newer proposal has landed meanwhile.\n */\nexport const saveClarityV2TransformationProposalBodySchema = z.object({\n steps: z\n .array(postprocessClarityStepBaseSchema)\n .min(1)\n .superRefine(refineStepGraph),\n baselineSnapshotId: z.guid(),\n clarityCurrentProcessId: z.guid(),\n});\n\n/**\n * Response for both save routes. Reuses the public read-model API schemas so\n * the FE can drop the response straight into its query cache without\n * reshaping snake_case \u2194 camelCase keys on every save.\n */\nexport const saveClarityV2CurrentProcessResponseSchema = z.object({\n snapshot: clarityCurrentProcessSnapshotApiSchema,\n});\n\nexport type SaveClarityV2CurrentProcessResponse = z.infer<\n typeof saveClarityV2CurrentProcessResponseSchema\n>;\n\nexport const saveClarityV2TransformationProposalResponseSchema = z.object({\n snapshot: clarityTransformationProposalSnapshotApiSchema,\n});\n\nexport type SaveClarityV2TransformationProposalResponse = z.infer<\n typeof saveClarityV2TransformationProposalResponseSchema\n>;\n\n/**\n * Body for the postprocess route. Re-runs the postprocessing agents on an\n * existing snapshot identified by the discriminated `type`. Used to recover\n * when an agent silently failed and a tab is left without data.\n */\nexport const postprocessClarityV2SnapshotBodySchema = z.discriminatedUnion(\n \"type\",\n [\n z.object({\n type: z.literal(\"current_process\"),\n current_process_id: z\n .guid()\n .describe(\n \"ID of the `clarity_current_process` snapshot to re-postprocess.\"\n ),\n }),\n z.object({\n type: z.literal(\"transformation_proposal\"),\n transformation_proposal_id: z\n .guid()\n .describe(\n \"ID of the `clarity_transformation_proposal` snapshot to re-postprocess.\"\n ),\n }),\n ]\n);\n\nexport type PostprocessClarityV2SnapshotBody = z.infer<\n typeof postprocessClarityV2SnapshotBodySchema\n>;\n\n/**\n * Discriminator value for the 409 returned by the v2 save routes when the\n * baseline snapshot id no longer matches the latest snapshot. Exported so\n * routes, the FE banner, and tests reference the same literal.\n */\nexport const CLARITY_V2_STALE_BASELINE_CODE = \"stale_baseline\" as const;\n\n/**\n * 409 body returned when the baseline snapshot id no longer matches the\n * latest snapshot for the process. The FE uses `latestSnapshotId` to render\n * the stale-baseline banner (\"a newer version was generated\") with a refresh\n * button that loads the new snapshot.\n */\nexport const clarityV2StaleBaselineErrorSchema = z.object({\n code: z.literal(CLARITY_V2_STALE_BASELINE_CODE),\n latestSnapshotId: z.guid(),\n});\n\nexport type ClarityV2StaleBaselineError = z.infer<\n typeof clarityV2StaleBaselineErrorSchema\n>;\n", "import { z } from \"zod\";\n\nexport const CLARITY_PROCESS_STATUSES = [\n \"draft\",\n \"collecting\",\n \"generating\",\n \"review\",\n \"complete\",\n \"generation_failed\",\n] as const;\n\nexport type ClarityProcessStatus = (typeof CLARITY_PROCESS_STATUSES)[number];\n\nexport const clarityProcessStatusSchema = z.enum(CLARITY_PROCESS_STATUSES);\n\nexport const CLARITY_CAPTURE_STATUSES = [\n \"pending\",\n \"recording\",\n \"processing\",\n \"complete\",\n \"failed\",\n] as const;\n\nexport type ClarityCaptureStatus = (typeof CLARITY_CAPTURE_STATUSES)[number];\n\nexport const clarityCaptureStatusSchema = z.enum(CLARITY_CAPTURE_STATUSES);\n\nexport const CLARITY_CAPTURE_TYPES = [\n \"video\",\n \"interview\",\n \"document\",\n \"screenshare\",\n] as const;\n\nexport type ClarityCaptureType = (typeof CLARITY_CAPTURE_TYPES)[number];\n\nexport const clarityCaptureTypeSchema = z.enum(CLARITY_CAPTURE_TYPES);\n\nexport const conversationMessageSchema = z.object({\n source: z.enum([\"ai\", \"user\", \"interviewer\"]),\n message: z.string().min(1),\n timestamp: z.number().optional(),\n});\n\nexport type ConversationMessage = z.infer<typeof conversationMessageSchema>;\n\nexport type ClarityStep = {\n title: string;\n /** Legacy markdown blob. Retained so old analyses still render. Prefer the structured fields below for new data. */\n description?: string;\n action?: string;\n role?: string;\n system?: string;\n input?: string;\n output?: string;\n condition?: string;\n exception?: string;\n handling?: string;\n order?: number;\n};\n\nexport const CLARITY_STEP_STRUCTURED_FIELDS = [\n \"action\",\n \"role\",\n \"system\",\n \"input\",\n \"output\",\n \"condition\",\n \"exception\",\n \"handling\",\n] as const;\n\nexport type ClarityStepStructuredField =\n (typeof CLARITY_STEP_STRUCTURED_FIELDS)[number];\n\nfunction hasNonEmptyStepValue(value: string | undefined): boolean {\n return (value ?? \"\").trim().length > 0;\n}\n\nfunction hasClarityStepContent(step: ClarityStep): boolean {\n return (\n hasNonEmptyStepValue(step.description) ||\n CLARITY_STEP_STRUCTURED_FIELDS.some((field) =>\n hasNonEmptyStepValue(step[field])\n )\n );\n}\n\nexport const editableClarityStepSchema = z\n .object({\n title: z.string().min(1),\n description: z.string().optional(),\n action: z.string().optional(),\n role: z.string().optional(),\n system: z.string().optional(),\n input: z.string().optional(),\n output: z.string().optional(),\n condition: z.string().optional(),\n exception: z.string().optional(),\n handling: z.string().optional(),\n order: z.int().positive().optional(),\n })\n .superRefine((step, ctx) => {\n if (hasClarityStepContent(step)) {\n return;\n }\n\n ctx.addIssue({\n code: \"custom\",\n message:\n \"Step must include a description or at least one structured field with content\",\n });\n });\n\nexport const clarityStepSchema = z.object({\n title: z.string().min(1),\n description: z.string().min(1),\n action: z.string().optional(),\n role: z.string().optional(),\n system: z.string().optional(),\n input: z.string().optional(),\n output: z.string().optional(),\n condition: z.string().optional(),\n exception: z.string().optional(),\n handling: z.string().optional(),\n order: z.int().positive().optional(),\n});\n\nexport const CLARITY_STEP_TARGETS = [\"current\", \"proposed\"] as const;\nexport type ClarityStepTarget = (typeof CLARITY_STEP_TARGETS)[number];\nexport const clarityStepTargetSchema = z.enum(CLARITY_STEP_TARGETS);\n\nexport const updateClarityStepsSchema = z.object({\n target: clarityStepTargetSchema,\n steps: z.array(editableClarityStepSchema).min(1),\n});\n\nexport type UpdateClarityStepsBody = z.infer<typeof updateClarityStepsSchema>;\n\nexport const resetClarityStepsSchema = z.object({\n target: clarityStepTargetSchema,\n});\n\nexport type ResetClarityStepsBody = z.infer<typeof resetClarityStepsSchema>;\n\n/**\n * ClarityInsight represents a unified finding that combines\n * what were previously separate \"gaps\" and \"opportunities\".\n * Each insight captures an issue and its recommendation.\n * Array position conveys priority (first = highest impact).\n */\nexport type ClarityInsight = {\n title: string;\n issue: string;\n recommendation: string;\n};\n\nexport const clarityInsightSchema = z.object({\n title: z.string().min(1),\n issue: z.string().min(1),\n recommendation: z.string().min(1),\n});\n\n/**\n * A single phase in the process transformation roadmap.\n * Describes the transition from current state to proposed state.\n */\nexport type TransformationPhase = {\n title: string;\n currentState: string;\n proposedState: string;\n /** Required for new generations; optional for backward compatibility with old data */\n rationale?: string;\n};\n\nexport const transformationPhaseSchema = z.object({\n title: z.string().min(1),\n currentState: z.string().min(1),\n proposedState: z.string().min(1),\n rationale: z.string().min(1).optional(),\n});\n\n/**\n * ProcessTransformation proposes a complete redesign of the process,\n * questioning fundamental assumptions rather than just patching issues.\n * Think: \"If we designed this from scratch today, what would it look like?\"\n */\nexport type ProcessTransformation = {\n /** 2-3 sentence \"north star\" description of the ideal end state */\n visionStatement: string;\n /** Brief summary of how the process works today */\n currentProcessSummary: string;\n /** Brief summary of the proposed redesigned process */\n proposedProcessSummary: string;\n /** Legacy phased implementation roadmap. Replaced by top-level proposedProcessFlow + proposedSteps. */\n phases?: TransformationPhase[];\n /** Process-specific key metrics + money impact with calculation basis. Null if no team context. */\n projectedImpact: string | null;\n};\n\nexport const processTransformationSchema = z.object({\n visionStatement: z.string().min(1),\n currentProcessSummary: z.string().min(1),\n proposedProcessSummary: z.string().min(1),\n phases: z.array(transformationPhaseSchema).min(1).max(4).optional(),\n projectedImpact: z.string().nullable().default(null),\n});\n\n// Risk & resilience types for process vulnerability analysis\nexport const RESILIENCE_RATINGS = [\n \"fragile\",\n \"brittle\",\n \"moderate\",\n \"resilient\",\n] as const;\n\nexport type ResilienceRating = (typeof RESILIENCE_RATINGS)[number];\n\nexport type ProcessVulnerability = {\n title: string;\n description: string;\n};\n\nexport const processVulnerabilitySchema = z.object({\n title: z.string().min(1),\n description: z.string().min(1),\n});\n\nexport type ProcessRiskResilience = {\n resilienceRating: ResilienceRating;\n resilienceNarrative: string;\n vulnerabilities: ProcessVulnerability[];\n};\n\nexport const processRiskResilienceSchema = z.object({\n resilienceRating: z.enum(RESILIENCE_RATINGS),\n resilienceNarrative: z.string().min(1),\n vulnerabilities: z.array(processVulnerabilitySchema).min(1).max(10),\n});\n\n// BPMN-aligned node types (Level 1)\nexport const PROCESS_FLOW_NODE_TYPES = [\"event\", \"task\", \"gateway\"] as const;\n\nexport const PROCESS_FLOW_EVENT_SUBTYPES = [\n \"start\",\n \"end\",\n \"timer\",\n \"message\",\n \"escalation\",\n] as const;\n\nexport const PROCESS_FLOW_TASK_SUBTYPES = [\n \"user\",\n \"service\",\n \"send\",\n \"receive\",\n \"manual\",\n \"businessRule\",\n \"script\",\n] as const;\n\nexport const PROCESS_FLOW_GATEWAY_SUBTYPES = [\n \"exclusive\",\n \"parallel\",\n \"inclusive\",\n] as const;\n\n// Legacy types for backward compat with existing stored analyses\nexport const PROCESS_FLOW_LEGACY_NODE_TYPES = [\n \"step\",\n \"decision\",\n \"inform\",\n \"escalation\",\n \"wait\",\n] as const;\n\nexport type ProcessFlowNodeType = (typeof PROCESS_FLOW_NODE_TYPES)[number];\nexport type ProcessFlowLegacyNodeType =\n (typeof PROCESS_FLOW_LEGACY_NODE_TYPES)[number];\nexport type ProcessFlowEventSubtype =\n (typeof PROCESS_FLOW_EVENT_SUBTYPES)[number];\nexport type ProcessFlowTaskSubtype =\n (typeof PROCESS_FLOW_TASK_SUBTYPES)[number];\nexport type ProcessFlowGatewaySubtype =\n (typeof PROCESS_FLOW_GATEWAY_SUBTYPES)[number];\n\nexport const processFlowNodeSchema = z.object({\n id: z.string(),\n type: z.enum([...PROCESS_FLOW_NODE_TYPES, ...PROCESS_FLOW_LEGACY_NODE_TYPES]),\n subtype: z\n .enum([\n ...PROCESS_FLOW_EVENT_SUBTYPES,\n ...PROCESS_FLOW_TASK_SUBTYPES,\n ...PROCESS_FLOW_GATEWAY_SUBTYPES,\n ])\n .optional(),\n label: z.string(),\n performer: z.string().optional(),\n description: z.string().optional(),\n});\nexport type ProcessFlowNode = z.infer<typeof processFlowNodeSchema>;\n\nexport const processFlowEdgeSchema = z.object({\n source: z.string(),\n target: z.string(),\n label: z.string().optional(),\n isDefault: z.boolean().optional(),\n});\nexport type ProcessFlowEdge = z.infer<typeof processFlowEdgeSchema>;\n\nexport const processFlowSchema = z.object({\n nodes: z.array(processFlowNodeSchema),\n edges: z.array(processFlowEdgeSchema),\n});\nexport type ProcessFlow = z.infer<typeof processFlowSchema>;\n\nexport const CLARITY_STEPS_SOURCES = [\"ai\", \"human\"] as const;\nexport type ClarityStepsSource = (typeof CLARITY_STEPS_SOURCES)[number];\n\nexport type ClarityAnalysis = {\n summary: string | null;\n steps: ClarityStep[] | null;\n /** Tracks whether current steps were last set by AI or a human edit. Null/undefined for legacy analyses. */\n stepsSource?: ClarityStepsSource | null;\n /** Top 5 highest-priority insights ordered by business impact */\n insights: ClarityInsight[] | null;\n /** Visual flow representation of the current process. Null for legacy analyses. */\n processFlow: ProcessFlow | null;\n /** Financial impact narrative estimating costs of inefficiencies. Null if team context not provided. */\n financialImpactNarrative: string | null;\n /** Full process transformation proposal - redesign from scratch. Null for legacy analyses. */\n transformation: ProcessTransformation | null;\n /** BPMN 2.0 process flow for the proposed/transformed process. Null for legacy analyses. */\n proposedProcessFlow: ProcessFlow | null;\n /** Ordered steps describing the proposed process. Null for legacy analyses. */\n proposedSteps: ClarityStep[] | null;\n /** Tracks whether proposed steps were last set by AI or a human edit. Null/undefined for legacy analyses. */\n proposedStepsSource?: ClarityStepsSource | null;\n /** Risk & resilience analysis - vulnerabilities. Null for legacy analyses or trivial processes. */\n riskResilience: ProcessRiskResilience | null;\n generated_at: string;\n};\n\nexport const clarityAnalysisSchema = z.object({\n summary: z.string().min(1).nullable(),\n steps: z.array(editableClarityStepSchema).nullable(),\n stepsSource: z.enum(CLARITY_STEPS_SOURCES).nullable().optional(),\n insights: z.array(clarityInsightSchema).max(5).nullable(),\n processFlow: processFlowSchema.nullable(),\n financialImpactNarrative: z.string().nullable(),\n transformation: processTransformationSchema.nullable(),\n proposedProcessFlow: processFlowSchema.nullable().default(null),\n proposedSteps: z.array(editableClarityStepSchema).nullable().default(null),\n proposedStepsSource: z.enum(CLARITY_STEPS_SOURCES).nullable().optional(),\n riskResilience: processRiskResilienceSchema.nullable().default(null),\n generated_at: z.string(),\n});\n\nexport const clarityAnalysisResponseSchema = z.object({\n summary: z.string().min(1).nullable(),\n steps: z.array(clarityStepSchema).nullable(),\n stepsSource: z.enum(CLARITY_STEPS_SOURCES).nullable().optional(),\n insights: z.array(clarityInsightSchema).max(5).nullable(),\n processFlow: processFlowSchema.nullable(),\n financialImpactNarrative: z.string().nullable(),\n transformation: processTransformationSchema.nullable(),\n proposedProcessFlow: processFlowSchema.nullable().default(null),\n proposedSteps: z.array(clarityStepSchema).nullable().default(null),\n proposedStepsSource: z.enum(CLARITY_STEPS_SOURCES).nullable().optional(),\n riskResilience: processRiskResilienceSchema.nullable().default(null),\n generated_at: z.string(),\n});\n\nexport type ClarityAnalysisResponse = z.infer<\n typeof clarityAnalysisResponseSchema\n>;\n\nexport const teamClaritySettingsSchema = z.object({\n teamId: z.guid(),\n teamSize: z.int().positive(),\n averageHourlyRate: z.number().positive(),\n currency: z.enum([\"USD\"]),\n emailReportsEnabled: z.boolean(),\n emailReportIncludeSummary: z.boolean(),\n emailReportIncludeCaptures: z.boolean(),\n updatedAt: z.coerce.date(),\n updatedBy: z.guid().nullable(),\n companyName: z.string().nullable().optional(),\n industry: z.string().nullable().optional(),\n annualRevenue: z.number().nullable().optional(),\n isUserConfigured: z.boolean(),\n});\n\nexport type TeamClaritySettings = z.infer<typeof teamClaritySettingsSchema>;\n\nexport const DEFAULT_TEAM_CLARITY_SETTINGS = {\n teamSize: 5,\n averageHourlyRate: 75,\n currency: \"USD\" as const,\n emailReportsEnabled: true,\n emailReportIncludeSummary: true,\n emailReportIncludeCaptures: false,\n companyName: null,\n industry: null,\n annualRevenue: null,\n};\n\nexport const clarityCaptureSchema = z.object({\n id: z.guid(),\n processId: z.guid(),\n userId: z.guid(),\n userName: z.string().optional(),\n type: clarityCaptureTypeSchema,\n videoUrl: z.string().nullable(),\n videoTranscript: z.string().nullable(),\n transcript: z.array(conversationMessageSchema).nullable(),\n status: clarityCaptureStatusSchema,\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n});\n\nexport type ClarityCapture = z.infer<typeof clarityCaptureSchema>;\n\n/**\n * Narrow architecture version. Applied at the repository boundary; wire\n * schemas stay `z.number().int()` so the OpenAPI contract doesn't break.\n */\nexport const clarityProcessVersionSchema = z.union([\n z.literal(1),\n z.literal(2),\n]);\n\nexport type ClarityProcessVersion = z.infer<typeof clarityProcessVersionSchema>;\n\nexport const clarityProcessSchema = z.object({\n id: z.guid(),\n teamId: z.guid(),\n userId: z.guid(),\n name: z.string(),\n status: clarityProcessStatusSchema,\n /** 1 = legacy, 2 = v2. */\n version: z.number().int(),\n analysis: clarityAnalysisResponseSchema.nullable(),\n generationError: z.string().nullable(),\n customPrompt: z.string().nullable().optional(),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n});\n\nexport type ClarityProcess = z.infer<typeof clarityProcessSchema>;\n\nexport const clarityProcessListItemSchema = z.object({\n id: z.guid(),\n teamId: z.guid().optional(),\n teamName: z.string().optional(),\n name: z.string(),\n status: clarityProcessStatusSchema,\n version: z.number().int(),\n captureCount: z.number(),\n captureCounts: z\n .object({\n video: z.number(),\n interview: z.number(),\n document: z.number(),\n })\n .optional(),\n insightsCount: z.number(),\n hasAnalysis: z.boolean(),\n pendingInvitationCount: z.number().optional(),\n summary: z.string().nullable().optional(),\n vulnerabilityCount: z.number().optional(),\n contributors: z\n .array(z.object({ userId: z.string(), userName: z.string() }))\n .optional(),\n createdAt: z.coerce.date(),\n createdByName: z.string().optional(),\n});\n\nexport type ClarityProcessListItem = z.infer<\n typeof clarityProcessListItemSchema\n>;\n\n// Generation progress types for async clarity\n\nconst GENERATION_STEP_STATUSES = [\n \"pending\",\n \"in_progress\",\n \"complete\",\n] as const;\n\nexport type GenerationStepStatus = (typeof GENERATION_STEP_STATUSES)[number];\n\nexport const generationStepStatusSchema = z.enum(GENERATION_STEP_STATUSES);\n\nexport const generationStepProgressSchema = z.object({\n key: z.string(),\n label: z.string(),\n status: generationStepStatusSchema,\n order: z.number(),\n count: z.number().optional(),\n});\n\nexport type GenerationStepProgress = z.infer<\n typeof generationStepProgressSchema\n>;\n\nexport const generationProgressSchema = z.object({\n steps: z.array(generationStepProgressSchema),\n});\n\nexport type GenerationProgress = z.infer<typeof generationProgressSchema>;\n\nexport const usedGuidanceMessageSchema = z.object({\n content: z.string(),\n author: z.string().nullable(),\n date: z.string().nullable(),\n});\n\nexport type UsedGuidanceMessage = z.infer<typeof usedGuidanceMessageSchema>;\n\nexport const clarityProcessDetailSchema = clarityProcessSchema.extend({\n captures: z.array(clarityCaptureSchema),\n createdByName: z.string().optional(),\n creatorUserId: z.guid(),\n generationProgress: generationProgressSchema.nullable(),\n transformationGuidance: z.string().nullable(),\n transformationGuidanceAuthor: z.string().nullable(),\n transformationGuidanceDate: z.string().nullable(),\n usedGuidanceMessages: z.array(usedGuidanceMessageSchema),\n});\n\nexport type ClarityProcessDetail = z.infer<typeof clarityProcessDetailSchema>;\n\nexport type ClarityProcessClient = Omit<\n ClarityProcessDetail,\n \"teamId\" | \"userId\"\n>;\n\nexport const createClarityProcessSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n});\n\nexport type CreateClarityProcess = z.infer<typeof createClarityProcessSchema>;\n\nexport const updateClarityProcessSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n customPrompt: z.string().max(5000).nullable().optional(),\n});\n\nexport type UpdateClarityProcess = z.infer<typeof updateClarityProcessSchema>;\n\nexport const saveClarityCaptureInterviewSchema = z.object({\n captureId: z.guid().optional(),\n extraCaptureRequestId: z.guid().optional(),\n transcript: z.array(conversationMessageSchema).min(1),\n});\n\nexport const startClarityCaptureInterviewQuerySchema = z.object({\n extraCaptureRequestId: z.guid().optional(),\n});\n\nexport type StartClarityCaptureInterviewQuery = z.infer<\n typeof startClarityCaptureInterviewQuerySchema\n>;\n\nexport type SaveClarityCaptureInterview = z.infer<\n typeof saveClarityCaptureInterviewSchema\n>;\n\nexport const INTERVIEW_LANGUAGES = [\n \"en\",\n \"cs\",\n \"de\",\n \"es\",\n \"fr\",\n \"pl\",\n] as const;\n\nexport type InterviewLanguage = (typeof INTERVIEW_LANGUAGES)[number];\n\nexport const initiateClarityPhoneInterviewSchema = z.object({\n phoneNumber: z.string().regex(/^\\+\\d{7,15}$/, \"Must be E.164 format\"),\n language: z.enum(INTERVIEW_LANGUAGES).optional().default(\"en\"),\n extraCaptureRequestId: z.guid().optional(),\n});\n\nexport type InitiateClarityPhoneInterview = z.infer<\n typeof initiateClarityPhoneInterviewSchema\n>;\n\nexport const initiateClarityPhoneInterviewResponseSchema = z.object({\n captureId: z.string().uuid(),\n status: z.literal(\"calling\"),\n});\n\nexport type InitiateClarityPhoneInterviewResponse = z.infer<\n typeof initiateClarityPhoneInterviewResponseSchema\n>;\n\n// Public sharing types\n\n/**\n * Public view of a clarity process (limited data for unauthenticated access).\n * Excludes team info, user info, and captures.\n */\nexport const publicClarityProcessSchema = z.object({\n id: z.guid(),\n name: z.string(),\n status: clarityProcessStatusSchema,\n analysis: clarityAnalysisResponseSchema.nullable(),\n createdAt: z.coerce.date(),\n});\n\nexport type PublicClarityProcess = z.infer<typeof publicClarityProcessSchema>;\n\n/**\n * Sharing status for a clarity process.\n */\nexport const claritySharingStatusSchema = z.object({\n shareEnabled: z.boolean(),\n shareToken: z.string().nullable(),\n shareUrl: z.string().nullable(),\n});\n\nexport type ClaritySharingStatus = z.infer<typeof claritySharingStatusSchema>;\n\n// Portfolio Intelligence types\n\nexport const PORTFOLIO_INTELLIGENCE_STATUSES = [\n \"idle\",\n \"generating\",\n \"complete\",\n \"generation_failed\",\n] as const;\n\nexport type PortfolioIntelligenceStatus =\n (typeof PORTFOLIO_INTELLIGENCE_STATUSES)[number];\n\nexport const portfolioIntelligenceStatusSchema = z.enum(\n PORTFOLIO_INTELLIGENCE_STATUSES\n);\n\nexport const RECOMMENDATION_CATEGORIES = [\n \"automation\",\n \"process-redesign\",\n \"governance\",\n \"tooling\",\n] as const;\n\nexport type RecommendationCategory = (typeof RECOMMENDATION_CATEGORIES)[number];\n\nexport const RECOMMENDATION_PRIORITIES = [\"P1\", \"P2\", \"P3\"] as const;\n\nexport type RecommendationPriority = (typeof RECOMMENDATION_PRIORITIES)[number];\n\nexport const RECOMMENDATION_EFFORTS = [\n \"Low (days)\",\n \"Medium (weeks)\",\n \"High (months)\",\n] as const;\n\nexport type RecommendationEffort = (typeof RECOMMENDATION_EFFORTS)[number];\n\nexport const portfolioRecommendationSchema = z.object({\n title: z.string().min(1),\n category: z.enum(RECOMMENDATION_CATEGORIES),\n priority: z.enum(RECOMMENDATION_PRIORITIES).optional().default(\"P2\"),\n rationale: z.string().min(1),\n impact: z.string().min(1),\n effort: z.enum(RECOMMENDATION_EFFORTS),\n processIds: z.array(z.guid()).min(1),\n});\n\nexport type PortfolioRecommendation = z.infer<\n typeof portfolioRecommendationSchema\n>;\n\nexport const portfolioAnalysisSchema = z.object({\n executiveSummary: z.string().min(1),\n recommendations: z.array(portfolioRecommendationSchema).min(1),\n aggregateFinancialImpact: z.string().nullable(),\n generatedAt: z.string(),\n});\n\nexport type PortfolioAnalysis = z.infer<typeof portfolioAnalysisSchema>;\n\nexport const portfolioIntelligenceResponseSchema = z.object({\n id: z.guid(),\n status: portfolioIntelligenceStatusSchema,\n generationError: z.string().nullable(),\n analysis: portfolioAnalysisSchema.nullable(),\n generatedAt: z.string().nullable(),\n processCount: z.number(),\n completedProcessCount: z.number(),\n generationProgress: generationProgressSchema.nullable(),\n});\n\nexport type PortfolioIntelligenceResponse = z.infer<\n typeof portfolioIntelligenceResponseSchema\n>;\n\nexport const PORTFOLIO_MIN_PROCESSES_REQUIRED = 2;\n", "import { z } from \"zod\";\n\nimport {\n PROCESS_FLOW_EVENT_SUBTYPES,\n PROCESS_FLOW_GATEWAY_SUBTYPES,\n PROCESS_FLOW_NODE_TYPES,\n PROCESS_FLOW_TASK_SUBTYPES,\n} from \"../types/clarity\";\nimport { refineStepGraph } from \"./validators\";\n\nexport const CLARITY_V2_SNAPSHOT_VERSION = 1;\n\nconst stepSourceSchema = z.object({\n attribution: z\n .string()\n .min(1)\n .describe(\n 'Human-readable source label identifying who or what the evidence comes from. Examples: \"Anna (sales interview)\", \"Onboarding SOP \u00A73.2\", \"Slack #ops 2024-06-12\"'\n ),\n excerpt: z\n .string()\n .min(1)\n .describe(\n 'Verbatim supporting text quoted from the capture, document, or transcript. Example: \"We always wait for finance to sign off before sending the invoice.\"'\n ),\n});\n\nconst stepEdgeSchema = z.object({\n stepId: z\n .string()\n .min(1)\n .describe(\n 'Id of the step this edge points to. Must match an existing step.id in the same steps array. Example: \"step-review-invoice\"'\n ),\n label: z\n .string()\n .nullable()\n .describe(\n 'Human-readable label shown on the BPMN edge. For gateways, the outcome answer; for default flows, \"Otherwise\". Examples: \"Approved\", \"> $5k\", \"Otherwise\"'\n ),\n isDefault: z\n .boolean()\n .describe(\n \"True on exactly one outgoing edge of an exclusive or inclusive gateway, marking the fallback taken when no other condition matches. False on all other edges.\"\n ),\n});\n\nexport const clarityStepBaseSchema = z.object({\n id: z\n .string()\n .min(1)\n .describe(\n 'Stable identifier for the step. Referenced by targetSteps[].stepId and by postprocessing agents annotating specific steps. Example: \"step-review-invoice\"'\n ),\n\n nodeType: z\n .enum(PROCESS_FLOW_NODE_TYPES)\n .describe(\n 'BPMN top-level category. \"event\" for things that happen (start/end/timer/message/escalation), \"task\" for work performed, \"gateway\" for branching decisions.'\n ),\n nodeSubtype: z\n .enum([\n ...PROCESS_FLOW_EVENT_SUBTYPES,\n ...PROCESS_FLOW_TASK_SUBTYPES,\n ...PROCESS_FLOW_GATEWAY_SUBTYPES,\n ])\n .describe(\n 'Specific BPMN element. Events: \"start\", \"end\", \"timer\", \"message\", \"escalation\". Tasks: \"user\", \"service\", \"send\", \"receive\", \"manual\", \"businessRule\", \"script\". Gateways: \"exclusive\", \"parallel\", \"inclusive\".'\n ),\n\n targetSteps: z\n .array(stepEdgeSchema)\n .describe(\n \"Outgoing BPMN edges from this step. Empty array only on end events. Exclusive and inclusive gateways must have \u22652 entries with exactly one isDefault: true.\"\n ),\n\n title: z\n .string()\n .min(1)\n .describe(\n 'Short action-oriented heading, 2-5 words. Used as the step\\'s name in lists and BPMN node labels. Example: \"Review invoice\"'\n ),\n description: z\n .string()\n .min(1)\n .describe(\n 'Full prose paragraph describing what happens in this step in natural language. Used for documentation reconstruction. Example: \"Finance reviews the invoice in NetSuite, checking line item accuracy and matching against the purchase order before flagging for approval.\"'\n ),\n action: z\n .string()\n .min(1)\n .nullable()\n .describe(\n 'Verb-led one-liner summarizing the concrete action performed. Example: \"Reviews invoice line items in NetSuite against the purchase order.\"'\n ),\n rationale: z\n .string()\n .min(1)\n .describe(\n 'Why this step exists in the process \u2014 its purpose or business reason. Used by downstream agents to assess whether the step is essential or removable. Example: \"Catches mispriced line items before they reach the customer and prevents downstream credit notes.\"'\n ),\n role: z\n .string()\n .min(1)\n .nullable()\n .describe(\n 'Performer of this step \u2014 the specific job title, team, or system. Use \"Duvo\" for automated actions and \"System\" for system-triggered steps. Examples: \"Finance Analyst\", \"Sales Operations\", \"Duvo\", \"System\"'\n ),\n sources: z\n .array(stepSourceSchema)\n .min(1)\n .describe(\n \"Evidence supporting this step's existence and details. At least one source is required \u2014 every step must trace back to something in the captures.\"\n ),\n\n system: z\n .string()\n .nullable()\n .describe(\n 'System, tool, or application used to perform this step. Null when the step is purely manual or is a decision/event with no associated tool. Examples: \"NetSuite\", \"Gmail\", \"Excel\", null'\n ),\n input: z\n .string()\n .nullable()\n .describe(\n 'Information or artifacts required to start this step. Null on start events or steps with no preconditions. Example: \"Invoice PDF and matching purchase order number\"'\n ),\n output: z\n .string()\n .nullable()\n .describe(\n 'What this step produces or updates. Null on pure waits or events that emit nothing. Example: \"Approved invoice record in NetSuite with reviewer signature\"'\n ),\n condition: z\n .string()\n .nullable()\n .describe(\n 'Decision criteria or precondition that gates this step. Null when the step is unconditional. For gateway nodes, this is the question being evaluated. Example: \"Only when invoice total exceeds $10,000\"'\n ),\n exception: z\n .string()\n .nullable()\n .describe(\n 'Known exceptions, errors, or failure modes observed in the captures for this step. Null when none were mentioned. Example: \"Customer disputes line items or PO number does not match\"'\n ),\n handling: z\n .string()\n .nullable()\n .describe(\n 'How exceptions or escalations are handled \u2014 escalation path, fallback action, or retry strategy. Null when no exception or no handling described. Example: \"Escalate to AP manager via email and pause processing until resolved\"'\n ),\n assumptions: z\n .array(z.string())\n .nullable()\n .describe(\n 'Assumptions the LLM made when extracting this step that were not directly stated in captures. Null if none. Used by verification agents to flag risky inferences. Example: [\"Invoices are reviewed within 24 hours of receipt\"]'\n ),\n openQuestions: z\n .array(z.string())\n .nullable()\n .describe(\n 'Specific gaps in understanding that a follow-up capture should address. Null if none. Drives the next interview or document request. Example: [\"Is there a backup approver when the AP manager is out of office?\"]'\n ),\n confidence: z\n .enum([\"low\", \"medium\", \"high\"])\n .describe(\n 'Confidence in the accuracy of this step given evidence quality and completeness. \"high\" = directly stated by multiple sources, \"medium\" = stated by one source or inferred from strong signals, \"low\" = inferred with significant assumptions.'\n ),\n});\n\nexport type ClarityStepBase = z.infer<typeof clarityStepBaseSchema>;\n\n/* ===========================================================================\n * Postprocessing-agent extension chain\n * ---------------------------------------------------------------------------\n *\n * Postprocessing agents enrich snapshots after the pipeline writes them. Each\n * agent owns a small, optional slice of the snapshot. The schemas below are\n * the registry: every agent that touches the snapshot data shape MUST\n *\n * 1. declare its own slice schema (per-step or root-level) in this file,\n * 2. chain it onto the relevant `postprocess<Kind>Schema.extend(...)` call,\n *\n * so the canonical postprocess schemas always reflect every registered agent.\n *\n * Hard rules for any registered slice schema:\n *\n * - Every field MUST be optional (`.optional()`). Pipeline output predates\n * all agents, so snapshots must be valid before any agent has run.\n * - `undefined` = \"agent has not yet run\". `null` = \"agent ran, no output\".\n * - An agent owns its fields exclusively. Never reuse a field across two\n * agents and never let one agent write into another agent's slice.\n *\n * The slice schemas live here (and not next to each agent) so the postprocess\n * schemas can be assembled in one place. The agent runtime imports the\n * postprocess schemas; the agent files themselves only need to re-export the\n * slice schema for prompt-time validation of their own LLM output.\n * ========================================================================= */\n\n/* --- Per-step agent slice schemas ----------------------------------------- */\nexport const extraCaptureNeededValueSchema = z.object({\n id: z\n .guid()\n .describe(\n \"Id of the `clarity_proposal_extra_capture_request` row this slot points at. Created server-side by the agent after the LLM call; the LLM never produces this value.\"\n ),\n gap: z\n .string()\n .min(1)\n .describe(\n 'Plain-language description of what about this step is unknown or under-specified, blocking automation. One short sentence. Example: \"We don\\'t know which fields the AP analyst copies from the invoice into NetSuite.\"'\n ),\n proposal: z\n .string()\n .min(1)\n .nullable()\n .optional()\n .describe(\n 'What the new capture should include in order to resolve the gap \u2014 concrete actions, screens, or decisions the user should walk through. Optional: omit when no specific proposal can be inferred. Example: \"Walk through reviewing one invoice in NetSuite end-to-end while narrating each field you check.\"'\n ),\n});\n\nexport type ExtraCaptureNeededValue = z.infer<\n typeof extraCaptureNeededValueSchema\n>;\n\n/**\n * Slice schema owned by the `extra-capture-needed` agent. Adds an optional\n * per-step `extraCaptureNeeded` field on transformation-proposal steps that\n * cannot be automated without an additional deep-dive capture.\n *\n * - `undefined`: the agent has not yet run for this step.\n * - `null`: the agent ran and the step is automation-ready (no extra needed).\n * - `{ id, gap, proposal? }`: the agent flagged this step. The same value is\n * mirrored into a `clarity_proposal_extra_capture_request` row by the\n * agent so the L3 \u2192 L4 capture loop can pick it up.\n */\nexport const extraCaptureNeededAgentStepSchema = z.object({\n extraCaptureNeeded: extraCaptureNeededValueSchema.nullable().optional(),\n});\n\nexport const STEP_READINESS_LEVELS = [\"low\", \"medium\", \"high\"] as const;\n\nexport type StepReadinessLevel = (typeof STEP_READINESS_LEVELS)[number];\n\nexport const bpmnStepReadinessAgentStepSchema = z.object({\n readiness: z\n .enum(STEP_READINESS_LEVELS)\n .nullable()\n .optional()\n .describe(\n 'Automation-readiness rating for this step. \"high\" = fully automatable today, \"medium\" = partially automatable or needs minor changes, \"low\" = blocked by manual review, judgement, or missing data.'\n ),\n readinessRationale: z\n .string()\n .nullable()\n .optional()\n .describe(\n 'One-sentence justification for the readiness rating, citing the specific signals that drove the choice. Example: \"Requires human judgement on edge cases that are not documented in the captures.\"'\n ),\n});\n\nexport const postprocessClarityStepBaseSchema = clarityStepBaseSchema\n .extend(extraCaptureNeededAgentStepSchema.shape)\n .extend(bpmnStepReadinessAgentStepSchema.shape)\n .extend({});\n\nexport type PostprocessClarityStepBase = z.infer<\n typeof postprocessClarityStepBaseSchema\n>;\n\nconst clarityCurrentProcessDataObjectSchema = z.object({\n version: z\n .number()\n .int()\n .describe(\n \"Schema version for the current process data payload. Increment on breaking changes to the data shape so consumers can branch on the version field.\"\n ),\n steps: z\n .array(postprocessClarityStepBaseSchema)\n .describe(\n \"Ordered steps describing how the process works today, extracted from captures. Array position is the canonical order; BPMN topology is encoded by each step's targetSteps[] edges.\"\n )\n .superRefine(refineStepGraph),\n});\n\nexport const processSummaryAgentCurrentProcessSchema = z.object({\n summary: z\n .string()\n .min(1)\n .nullable()\n .optional()\n .describe(\n 'One short paragraph (3-5 sentences) describing the captured process at a glance. Surfaced at the top of the current-process tab so reviewers can orient themselves before scanning the steps. Example: \"Customers order beer at the bar; the bartender greets them, picks an option matching their preference, pours and garnishes the glass, then rings the order through the POS before serving.\"'\n ),\n});\n\nexport type ProcessSummaryAgentCurrentProcess = z.infer<\n typeof processSummaryAgentCurrentProcessSchema\n>;\n\nexport const swotAnalysisSchema = z.object({\n strengths: z\n .array(z.string().min(1))\n .describe(\n 'Internal advantages of the current process \u2014 capabilities, resources, or design choices that work in its favour today. Phrase each as a short, evidence-backed statement. Example: \"Bartenders know regulars by name, which keeps service personal during peak hours.\"'\n ),\n weaknesses: z\n .array(z.string().min(1))\n .describe(\n 'Internal limitations of the current process \u2014 gaps, inefficiencies, or fragile assumptions visible in how it runs today. Phrase each as a short, evidence-backed statement. Example: \"Manual pour times balloon during rushes because there is only one tap.\"'\n ),\n opportunities: z\n .array(z.string().min(1))\n .describe(\n 'External openings the current process could exploit \u2014 adjacent automations, scale effects, or unmet needs surfaced by the captures. Example: \"POS data could feed dynamic pricing for slow hours.\"'\n ),\n threats: z\n .array(z.string().min(1))\n .describe(\n 'External risks that could degrade the current process \u2014 regulatory, operational, technological, or human factors visible in the captures. Example: \"New ID-check legislation will require staff to interrupt every order.\"'\n ),\n});\n\nexport type SwotAnalysis = z.infer<typeof swotAnalysisSchema>;\n\nexport const swotAnalysisAgentCurrentProcessSchema = z.object({\n swot: swotAnalysisSchema\n .nullable()\n .optional()\n .describe(\n \"SWOT analysis produced by the swot-analysis postprocessing agent. `undefined` = agent has not yet run; `null` = agent ran and produced no analysis.\"\n ),\n});\n\n/**\n * Current-process data as stored on disk after agents have written. This is\n * the schema repositories use for `parse` / `safeParse` and the schema the\n * read model exposes to the frontend.\n */\nexport const postprocessClarityCurrentProcessDataSchema =\n clarityCurrentProcessDataObjectSchema\n .extend(swotAnalysisAgentCurrentProcessSchema.shape)\n .extend(processSummaryAgentCurrentProcessSchema.shape)\n .extend({});\n\nexport type PostprocessClarityCurrentProcessData = z.infer<\n typeof postprocessClarityCurrentProcessDataSchema\n>;\n\n/* --- Transformation-proposal data ----------------------------------------- */\n\nconst clarityTransformationProposalDataObjectSchema = z.object({\n version: z\n .number()\n .int()\n .describe(\n \"Schema version for the transformation proposal data payload. Increment on breaking changes to the data shape so consumers can branch on the version field.\"\n ),\n steps: z\n .array(postprocessClarityStepBaseSchema)\n .describe(\n \"Ordered steps describing the proposed redesigned process. Same shape as the current process steps; BPMN topology is encoded by each step's targetSteps[] edges.\"\n )\n .superRefine(refineStepGraph),\n});\n\nexport const proposalSummaryAgentTransformationProposalSchema = z.object({\n summary: z\n .string()\n .min(1)\n .nullable()\n .optional()\n .describe(\n 'One short paragraph (3-5 sentences) describing the proposed transformed process at a glance. Surfaced at the top of the transformation-proposal tab so reviewers can orient themselves before scanning the steps. Example: \"Customers self-order on a tablet at the bar; a smart tap auto-pours the chosen beer into a labelled glass, which the customer collects from the pickup counter once payment clears.\"'\n ),\n});\n\nexport type ProposalSummaryAgentTransformationProposal = z.infer<\n typeof proposalSummaryAgentTransformationProposalSchema\n>;\n\nexport const postprocessClarityTransformationProposalDataSchema =\n clarityTransformationProposalDataObjectSchema\n .extend(proposalSummaryAgentTransformationProposalSchema.shape)\n .extend({});\n\nexport type PostprocessClarityTransformationProposalData = z.infer<\n typeof postprocessClarityTransformationProposalDataSchema\n>;\n\n/**\n * Snapshot of how a Clarity v2 process runs today. Returned by\n * `ClarityCurrentProcessRepository`. This is the internal in-memory shape\n * (camelCase). The wire-format API schema lives in `./api-schema.ts` and\n * snake_cases wrapper fields at the route boundary.\n *\n * `data` uses the postprocess schema so agent extensions surface in reads.\n */\nexport const clarityCurrentProcessSnapshotSchema = z.object({\n id: z.guid(),\n processId: z.guid(),\n data: postprocessClarityCurrentProcessDataSchema,\n createdAt: z.iso.datetime(),\n updatedAt: z.iso.datetime(),\n});\n\nexport type ClarityCurrentProcessSnapshot = z.infer<\n typeof clarityCurrentProcessSnapshotSchema\n>;\n\nexport const clarityTransformationProposalSnapshotSchema = z.object({\n id: z.guid(),\n processId: z.guid(),\n clarityCurrentProcessId: z.guid(),\n data: postprocessClarityTransformationProposalDataSchema,\n createdAt: z.iso.datetime(),\n updatedAt: z.iso.datetime(),\n});\n\nexport type ClarityTransformationProposalSnapshot = z.infer<\n typeof clarityTransformationProposalSnapshotSchema\n>;\n", "import type { z } from \"zod\";\n\nimport type { ClarityStepBase } from \"./process-data\";\n\n/**\n * Graph-level invariants that the per-step Zod schema cannot express:\n * unique step ids, exactly one start, at least one end, every targetSteps[]\n * edge resolves to an existing step, end events have no outgoing edges,\n * exclusive and inclusive gateways have at least two outgoing edges with\n * exactly one default. Mirrors the rules the prompt asks the LLM to\n * follow; validating server-side prevents an off-spec hallucination from\n * being persisted as a snapshot.\n */\nexport function refineStepGraph(\n steps: ClarityStepBase[],\n ctx: z.RefinementCtx\n): void {\n const idToIndex = new Map<string, number>();\n\n steps.forEach((step, index) => {\n if (idToIndex.has(step.id)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"steps\", index, \"id\"],\n message: `Duplicate step id \"${step.id}\"`,\n });\n } else {\n idToIndex.set(step.id, index);\n }\n });\n\n const startSteps = steps.filter(\n (s) => s.nodeType === \"event\" && s.nodeSubtype === \"start\"\n );\n if (startSteps.length !== 1) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"steps\"],\n message: `Exactly one event/start node is required (found ${startSteps.length})`,\n });\n }\n\n const endSteps = steps.filter(\n (s) => s.nodeType === \"event\" && s.nodeSubtype === \"end\"\n );\n if (endSteps.length === 0) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"steps\"],\n message: \"At least one event/end node is required\",\n });\n }\n\n steps.forEach((step, index) => {\n step.targetSteps.forEach((edge, edgeIndex) => {\n if (!idToIndex.has(edge.stepId)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"steps\", index, \"targetSteps\", edgeIndex, \"stepId\"],\n message: `targetSteps[].stepId \"${edge.stepId}\" does not match any step.id`,\n });\n }\n });\n\n const isEndEvent = step.nodeType === \"event\" && step.nodeSubtype === \"end\";\n if (isEndEvent && step.targetSteps.length > 0) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"steps\", index, \"targetSteps\"],\n message: \"End events must have no outgoing edges\",\n });\n }\n\n const isBranchingGateway =\n step.nodeType === \"gateway\" &&\n (step.nodeSubtype === \"exclusive\" || step.nodeSubtype === \"inclusive\");\n\n if (isBranchingGateway) {\n if (step.targetSteps.length < 2) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"steps\", index, \"targetSteps\"],\n message: `${step.nodeSubtype} gateway must have at least 2 outgoing edges`,\n });\n }\n\n const defaultCount = step.targetSteps.filter((e) => e.isDefault).length;\n if (defaultCount !== 1) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"steps\", index, \"targetSteps\"],\n message: `${step.nodeSubtype} gateway must have exactly one outgoing edge with isDefault: true (found ${defaultCount})`,\n });\n }\n }\n });\n}\n", "export function stringifyError(err: unknown): string {\n if (err instanceof Error) {\n if (err.message) {\n return err.message;\n }\n\n // The error has no message \u2014 try to extract meaning from its own\n // enumerable properties (e.g. Puppeteer / network errors that omit message).\n try {\n const ownProps = JSON.stringify(err, Object.getOwnPropertyNames(err));\n if (ownProps && ownProps !== \"{}\" && ownProps !== \"null\") {\n return ownProps;\n }\n } catch {\n // ignore serialization errors and fall through\n }\n\n return String(err);\n }\n\n try {\n return JSON.stringify(err) ?? String(err);\n } catch {\n return String(err);\n }\n}\n", "import { stringifyError } from \"./stringify-error\";\n\nexport type SeverityLevel =\n | \"fatal\"\n | \"error\"\n | \"warning\"\n | \"log\"\n | \"info\"\n | \"debug\"\n | \"critical\";\n\nexport type SentryLike = {\n captureException(err: unknown): void;\n withScope(cb: (scope: ScopeLike) => void): void;\n};\n\ntype ScopeLike = {\n setExtras(extras: Record<string, unknown>): void;\n setLevel(level: SeverityLevel): void;\n setTag(key: string, value: string): void;\n};\n\n// Keys that should be set as tags (searchable in Sentry) rather than just extras\nconst SEARCHABLE_KEYS = [\n \"agentRunId\",\n \"runId\",\n \"buildId\",\n \"sandboxId\",\n \"agentId\",\n \"teamId\",\n \"userId\",\n \"sessionId\",\n] as const;\n\nexport function makeSentryReporter(sentry: SentryLike) {\n return function reportToSentry(\n error: unknown,\n severity: SeverityLevel = \"error\",\n extras: Record<string, unknown> = {}\n ) {\n const errorWithStack =\n error instanceof Error && error.stack\n ? error\n : new Error(stringifyError(error));\n\n if (severity === \"warning\") {\n console.warn(errorWithStack, extras);\n } else {\n console.error(errorWithStack, extras);\n }\n\n try {\n sentry.withScope((scope) => {\n // Set searchable tags for key identifiers\n // These make errors searchable by agent_run_id, build_id, etc. in Sentry Issues\n for (const key of SEARCHABLE_KEYS) {\n const value = extras[key];\n if (value !== undefined && value !== null) {\n // Convert camelCase to snake_case for Sentry tag naming convention\n const tagKey = key.replace(/([A-Z])/g, \"_$1\").toLowerCase();\n scope.setTag(tagKey, String(value));\n }\n }\n\n scope.setExtras(extras);\n scope.setLevel(severity);\n sentry.captureException(errorWithStack);\n });\n } catch {\n try {\n sentry.captureException(errorWithStack);\n } catch {\n console.error(errorWithStack);\n }\n }\n };\n}\n", "export const ORG_ROLE = {\n EXECUTIVE: \"organization:executive\",\n OWNER: \"organization:owner\",\n ADMIN: \"organization:admin\",\n MEMBER: \"organization:member\",\n} as const;\n\nexport type OrgRole = (typeof ORG_ROLE)[keyof typeof ORG_ROLE];\n\nexport const ORG_ROLE_CONFIG: Record<OrgRole, { parentRole: OrgRole | null }> =\n {\n [ORG_ROLE.EXECUTIVE]: { parentRole: null },\n [ORG_ROLE.OWNER]: { parentRole: ORG_ROLE.EXECUTIVE },\n [ORG_ROLE.ADMIN]: { parentRole: ORG_ROLE.OWNER },\n [ORG_ROLE.MEMBER]: { parentRole: ORG_ROLE.ADMIN },\n };\n\nexport const ORG_ROLES = {\n EXECUTIVE_ONLY: [ORG_ROLE.EXECUTIVE] as const,\n OWNER_AND_ABOVE: [ORG_ROLE.EXECUTIVE, ORG_ROLE.OWNER] as const,\n ADMIN_AND_ABOVE: [\n ORG_ROLE.EXECUTIVE,\n ORG_ROLE.OWNER,\n ORG_ROLE.ADMIN,\n ] as const,\n ALL: [\n ORG_ROLE.EXECUTIVE,\n ORG_ROLE.OWNER,\n ORG_ROLE.ADMIN,\n ORG_ROLE.MEMBER,\n ] as const,\n} as const;\n\nexport function isValidOrgRole(role: string): role is OrgRole {\n return Object.values(ORG_ROLE).includes(role as OrgRole);\n}\n\nexport function hasMinimumOrgRole(\n userRole: string,\n minimumRole: OrgRole\n): boolean {\n if (!isValidOrgRole(userRole)) {\n return false;\n }\n let current: OrgRole | null = minimumRole;\n while (current) {\n if (current === userRole) {\n return true;\n }\n current = ORG_ROLE_CONFIG[current].parentRole;\n }\n return false;\n}\n\nexport function canAssignOrgRole(\n callerRole: string,\n targetRole: string\n): boolean {\n if (!isValidOrgRole(callerRole) || !isValidOrgRole(targetRole)) {\n return false;\n }\n return hasMinimumOrgRole(callerRole, targetRole);\n}\n", "export const TEAM_ROLE = {\n OWNER: \"team:owner\",\n SUPERADMIN: \"team:superadmin\",\n ADMIN: \"team:admin\",\n MANAGER: \"team:manager\",\n BUILDER: \"team:builder\",\n MEMBER: \"team:member\",\n CLARITY_MEMBER: \"team:clarity-member\",\n} as const;\n\nexport type TeamRole = (typeof TEAM_ROLE)[keyof typeof TEAM_ROLE];\n\nexport const TEAM_ROLE_CONFIG = {\n [TEAM_ROLE.OWNER]: {\n displayName: \"Owner\",\n parentRole: null,\n },\n [TEAM_ROLE.SUPERADMIN]: {\n displayName: \"Administrator\",\n parentRole: TEAM_ROLE.OWNER,\n },\n [TEAM_ROLE.ADMIN]: {\n displayName: \"Manager\",\n parentRole: TEAM_ROLE.SUPERADMIN,\n },\n [TEAM_ROLE.MANAGER]: {\n displayName: \"Manager\",\n parentRole: TEAM_ROLE.ADMIN,\n },\n [TEAM_ROLE.BUILDER]: {\n displayName: \"Builder\",\n parentRole: TEAM_ROLE.MANAGER,\n },\n [TEAM_ROLE.MEMBER]: {\n displayName: \"Member\",\n parentRole: TEAM_ROLE.BUILDER,\n },\n [TEAM_ROLE.CLARITY_MEMBER]: {\n displayName: \"Clarity Member\",\n parentRole: TEAM_ROLE.MEMBER,\n },\n} as const;\n\nexport const TEAM_ROLES = {\n OWNER_ONLY: [TEAM_ROLE.OWNER] as const,\n SUPERADMIN_AND_ABOVE: [TEAM_ROLE.OWNER, TEAM_ROLE.SUPERADMIN] as const,\n ADMIN_AND_ABOVE: [\n TEAM_ROLE.OWNER,\n TEAM_ROLE.SUPERADMIN,\n TEAM_ROLE.ADMIN,\n ] as const,\n MANAGER_AND_ABOVE: [\n TEAM_ROLE.OWNER,\n TEAM_ROLE.SUPERADMIN,\n TEAM_ROLE.ADMIN,\n TEAM_ROLE.MANAGER,\n ] as const,\n BUILDER_AND_ABOVE: [\n TEAM_ROLE.OWNER,\n TEAM_ROLE.SUPERADMIN,\n TEAM_ROLE.ADMIN,\n TEAM_ROLE.MANAGER,\n TEAM_ROLE.BUILDER,\n ] as const,\n MEMBER_AND_ABOVE: [\n TEAM_ROLE.OWNER,\n TEAM_ROLE.SUPERADMIN,\n TEAM_ROLE.ADMIN,\n TEAM_ROLE.MANAGER,\n TEAM_ROLE.BUILDER,\n TEAM_ROLE.MEMBER,\n ] as const,\n ALL: [\n TEAM_ROLE.OWNER,\n TEAM_ROLE.SUPERADMIN,\n TEAM_ROLE.ADMIN,\n TEAM_ROLE.MANAGER,\n TEAM_ROLE.BUILDER,\n TEAM_ROLE.MEMBER,\n TEAM_ROLE.CLARITY_MEMBER,\n ] as const,\n} as const;\n\nexport function hasMinimumRole(\n userRole: string,\n minimumRole: TeamRole\n): boolean {\n if (!isValidTeamRole(userRole)) {\n return false;\n }\n\n let current: TeamRole | null = minimumRole;\n while (current) {\n if (current === userRole) {\n return true;\n }\n current = TEAM_ROLE_CONFIG[current].parentRole;\n }\n return false;\n}\n\nexport function isValidTeamRole(role: string): role is TeamRole {\n return Object.values(TEAM_ROLE).includes(role as TeamRole);\n}\n", "import { z } from \"zod\";\n\nexport const apiKeySchema = z.object({\n id: z.guid(),\n name: z.string(),\n key_prefix: z.string(),\n user_id: z.guid(),\n user_name: z.string().nullable(),\n user_email: z.string().nullable(),\n last_used_at: z.string().nullable(),\n expires_at: z.string().nullable(),\n revoked_at: z.string().nullable(),\n created_at: z.string(),\n});\n\nexport type ApiKey = z.infer<typeof apiKeySchema>;\n\nexport const apiKeyListResponseSchema = z.object({\n apiKeys: z.array(apiKeySchema),\n});\n\nexport type ApiKeyListResponse = z.infer<typeof apiKeyListResponseSchema>;\n\nexport const createApiKeyBodySchema = z.object({\n name: z.string().trim().min(1).max(100),\n expires_in_days: z.int().min(1).max(365).optional(),\n});\n\nexport type CreateApiKeyBody = z.infer<typeof createApiKeyBodySchema>;\n\nexport const createApiKeyResponseSchema = z.object({\n id: z.guid(),\n name: z.string(),\n key: z.string(),\n key_prefix: z.string(),\n expires_at: z.string().nullable(),\n created_at: z.string(),\n});\n\nexport type CreateApiKeyResponse = z.infer<typeof createApiKeyResponseSchema>;\n\nexport const deleteApiKeyParamsSchema = z.object({\n keyId: z.guid(),\n});\n\nexport const deleteApiKeyResponseSchema = z.object({\n success: z.boolean(),\n});\n\nexport type DeleteApiKeyResponse = z.infer<typeof deleteApiKeyResponseSchema>;\n", "import { z } from \"zod\";\n\nexport const askUserQuestionOptionSchema = z.object({\n label: z.string(),\n description: z.string().optional().default(\"\"),\n});\n\nexport const askUserQuestionSchema = z.object({\n question: z.string(),\n header: z.string().optional().default(\"\"),\n options: z.array(askUserQuestionOptionSchema).optional().default([]),\n multiSelect: z.boolean().optional().default(false),\n});\n\nexport const askUserQuestionInputSchema = z.object({\n questions: z.array(askUserQuestionSchema).min(1),\n});\n\nexport type AskUserQuestionOption = z.infer<typeof askUserQuestionOptionSchema>;\nexport type AskUserQuestion = z.infer<typeof askUserQuestionSchema>;\nexport type AskUserQuestionInput = z.infer<typeof askUserQuestionInputSchema>;\n\nexport function parseAskUserQuestionInput(\n raw: unknown\n): AskUserQuestionInput | null {\n if (!raw || typeof raw !== \"object\") {\n return null;\n }\n\n const obj = raw as Record<string, unknown>;\n if (!Array.isArray(obj.questions)) {\n return null;\n }\n\n const validQuestions = obj.questions\n .map((q: unknown) => askUserQuestionSchema.safeParse(q))\n .filter((r) => r.success)\n .map((r) => r.data);\n\n if (validQuestions.length === 0) {\n return null;\n }\n\n return { questions: validQuestions } satisfies AskUserQuestionInput;\n}\n", "import { z } from \"zod\";\n\nexport const browserReplayScreenshotSchema = z.object({\n id: z.guid(),\n agent_run_id: z.guid(),\n tool_execution_id: z.string(),\n tool_name: z.string(),\n timing: z.string(),\n created_at: z.coerce.date(),\n signedUrl: z.string().nullable(),\n});\n\nexport const toolExecutionPairSchema = z.object({\n executionId: z.string(),\n toolName: z.string(),\n beforeScreenshot: browserReplayScreenshotSchema.nullable(),\n afterScreenshot: browserReplayScreenshotSchema.nullable(),\n});\n\nexport const screenshotsTimelineResponseSchema = z.object({\n toolExecutions: z.array(toolExecutionPairSchema),\n});\n\nexport type BrowserReplayScreenshot = z.infer<\n typeof browserReplayScreenshotSchema\n>;\n\nexport type ToolExecutionPair = z.infer<typeof toolExecutionPairSchema>;\n\nexport type ScreenshotsTimelineResponse = z.infer<\n typeof screenshotsTimelineResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport {\n clarityScreenshareTranscriptEntrySchema,\n clarityScreenshareTurnBodySchema,\n} from \"../clarity-screenshare/types\";\nimport {\n clarityCaptureSchema,\n clarityProcessStatusSchema,\n conversationMessageSchema,\n} from \"../types/clarity\";\n\nexport const voiceConfigSchema = z.object({\n method: z.literal(\"openAiRTC\"),\n rtcUrl: z.string(),\n clientSecretToken: z.string(),\n});\n\nexport type VoiceConfig = z.infer<typeof voiceConfigSchema>;\n\nexport const getClarityScreenshareSessionResponseSchema = z.object({\n sessionId: z.guid(),\n name: z.string(),\n status: clarityProcessStatusSchema,\n messages: z.array(conversationMessageSchema),\n lastError: z.string().nullable(),\n lastFrameBase64Data: z.string().nullable(),\n});\n\nexport type GetClarityScreenshareSessionResponse = z.infer<\n typeof getClarityScreenshareSessionResponseSchema\n>;\n\n/**\n * Per-interview guidance derived from a `clarity_proposal_extra_capture_request`\n * row when the capture is started to fulfil that request. The voice agent uses\n * `gap` and `suggestedPrompt` to focus the interview on the missing information\n * rather than re-walking the full process. Null when the capture has no linked\n * extra-capture-request.\n */\nexport const screenshareExtraCaptureGuidanceSchema = z.object({\n gap: z.string(),\n suggestedPrompt: z.string().nullable(),\n});\n\nexport type ScreenshareExtraCaptureGuidance = z.infer<\n typeof screenshareExtraCaptureGuidanceSchema\n>;\n\nexport const startScreenshareCaptureResponseSchema =\n clarityCaptureSchema.extend({\n createdAt: z.string(),\n updatedAt: z.string(),\n openaiToken: z.string(),\n openaiTokenExpiresAt: z.string(),\n /**\n * Process-level guidance authored by the process owner via the \"Process\n * guidance\" dialog (`clarity_process.custom_prompt`). Applies to every\n * interview on this process. Null when the owner has not set guidance.\n */\n processGuidance: z.string().nullable(),\n extraCaptureGuidance: screenshareExtraCaptureGuidanceSchema.nullable(),\n });\n\nexport type StartScreenshareCaptureResponse = z.infer<\n typeof startScreenshareCaptureResponseSchema\n>;\n\nexport const MAX_SCREENSHARE_FRAMES_PER_CAPTURE = 300;\n\nexport const screenshareUploadUrlsBodySchema = z.object({\n screenshareStartTime: z.int().nonnegative(),\n frameTimestamps: z\n .array(z.int().nonnegative())\n .max(MAX_SCREENSHARE_FRAMES_PER_CAPTURE),\n});\n\nexport type ScreenshareUploadUrlsBody = z.infer<\n typeof screenshareUploadUrlsBodySchema\n>;\n\nexport const screenshareFrameUploadSchema = z.object({\n timestamp: z.int().nonnegative(),\n url: z.string(),\n gcsPath: z.string(),\n});\n\nexport type ScreenshareFrameUpload = z.infer<\n typeof screenshareFrameUploadSchema\n>;\n\nexport const screenshareUploadUrlsResponseSchema = z.object({\n videoUploadUrl: z.string(),\n videoGcsPath: z.string(),\n frameUploadUrls: z.array(screenshareFrameUploadSchema),\n expiresAt: z.string(),\n});\n\nexport type ScreenshareUploadUrlsResponse = z.infer<\n typeof screenshareUploadUrlsResponseSchema\n>;\n\nexport const completeScreenshareCaptureBodySchema =\n screenshareUploadUrlsBodySchema.extend({\n transcript: z.array(conversationMessageSchema).min(1),\n });\n\nexport type CompleteScreenshareCaptureBody = z.infer<\n typeof completeScreenshareCaptureBodySchema\n>;\n\nexport const completeScreenshareCaptureResponseSchema =\n clarityCaptureSchema.extend({\n createdAt: z.string(),\n updatedAt: z.string(),\n });\n\nexport type CompleteScreenshareCaptureResponse = z.infer<\n typeof completeScreenshareCaptureResponseSchema\n>;\n\nexport const autoSaveScreenshareCaptureBodySchema =\n clarityScreenshareTurnBodySchema.pick({ images: true }).extend({\n transcript: z.array(\n clarityScreenshareTranscriptEntrySchema.extend({\n role: z.enum([\"user\", \"assistant\", \"interviewer\"]),\n })\n ),\n });\n\nexport type AutoSaveScreenshareCaptureBody = z.infer<\n typeof autoSaveScreenshareCaptureBodySchema\n>;\n", "import { z } from \"zod\";\n\nexport const errorSchema = z.object({\n error: z.string(),\n});\n", "import { z } from \"zod\";\n\nexport const HUMAN_REQUEST_MIN_OPTIONS = 2;\nexport const HUMAN_REQUEST_MAX_OPTIONS = 6;\nconst HUMAN_REQUEST_OPTION_LABEL_MAX = 80;\nconst HUMAN_REQUEST_OPTION_DESCRIPTION_MAX = 200;\nconst HUMAN_REQUEST_FREE_TEXT_MAX = 1000;\n\nexport const humanRequestOptionSchema = z.object({\n label: z.string().min(1).max(HUMAN_REQUEST_OPTION_LABEL_MAX),\n description: z.string().max(HUMAN_REQUEST_OPTION_DESCRIPTION_MAX).optional(),\n});\n\nexport const humanRequestOptionsSchema = z\n .array(humanRequestOptionSchema)\n .min(HUMAN_REQUEST_MIN_OPTIONS)\n .max(HUMAN_REQUEST_MAX_OPTIONS);\n\nexport const humanRequestResponseSchema = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"free_text\"),\n text: z.string().min(1).max(HUMAN_REQUEST_FREE_TEXT_MAX),\n }),\n z.object({\n kind: z.literal(\"single_select\"),\n optionLabel: z.string().min(1).max(HUMAN_REQUEST_OPTION_LABEL_MAX),\n }),\n z.object({\n kind: z.literal(\"multi_select\"),\n optionLabels: z\n .array(z.string().min(1).max(HUMAN_REQUEST_OPTION_LABEL_MAX))\n .min(1)\n .max(HUMAN_REQUEST_MAX_OPTIONS),\n }),\n z.object({\n kind: z.literal(\"approval\"),\n approved: z.boolean(),\n }),\n]);\n\nexport type HumanRequestOption = z.infer<typeof humanRequestOptionSchema>;\nexport type HumanRequestOptions = z.infer<typeof humanRequestOptionsSchema>;\nexport type HumanRequestResponse = z.infer<typeof humanRequestResponseSchema>;\n\nexport function formatHumanRequestResponseForDisplay(\n response: HumanRequestResponse\n): string {\n switch (response.kind) {\n case \"free_text\": {\n return response.text;\n }\n case \"single_select\": {\n return response.optionLabel;\n }\n case \"multi_select\": {\n return response.optionLabels.join(\", \");\n }\n case \"approval\": {\n return response.approved ? \"Approved\" : \"Rejected\";\n }\n }\n}\n", "import { z } from \"zod\";\n\nexport const logoUploadUrlBodySchema = z.object({\n fileName: z.string().min(1),\n contentType: z.string().min(1),\n});\nexport type LogoUploadUrlBody = z.infer<typeof logoUploadUrlBodySchema>;\n\nexport const logoUploadUrlResponseSchema = z.object({\n signedUrl: z.string(),\n expiresAt: z.string(),\n});\nexport type LogoUploadUrlResponse = z.infer<typeof logoUploadUrlResponseSchema>;\n\nexport const logoUrlResponseSchema = z.object({\n url: z.string(),\n expiresAt: z.string(),\n});\nexport type LogoUrlResponse = z.infer<typeof logoUrlResponseSchema>;\n", "import { z } from \"zod\";\n\nexport const successSchema = z.object({\n success: z.boolean(),\n});\n\nexport type SuccessResponse = z.infer<typeof successSchema>;\n", "import { z } from \"zod\";\n\nimport { ORG_ROLES } from \"../organization-roles\";\nimport { DISCOVERY_MODES } from \"./organization\";\n\nexport const adminOrgSummarySchema = z.object({\n id: z.guid(),\n name: z.string(),\n discoveryMode: z.string(),\n enterpriseBillingEnabled: z.boolean(),\n createdAt: z.string().nullable(),\n deletedAt: z.string().nullable(),\n teamCount: z.number().int().nonnegative(),\n memberCount: z.number().int().nonnegative(),\n domainCount: z.number().int().nonnegative(),\n});\nexport type AdminOrgSummary = z.infer<typeof adminOrgSummarySchema>;\n\nexport const adminOrgListResponseSchema = z.object({\n organizations: z.array(adminOrgSummarySchema),\n total: z.number().int().nonnegative(),\n});\nexport type AdminOrgListResponse = z.infer<typeof adminOrgListResponseSchema>;\n\nexport const ADMIN_ORG_SORT_FIELDS = [\n \"name\",\n \"teamCount\",\n \"memberCount\",\n \"domainCount\",\n \"createdAt\",\n] as const;\nexport type AdminOrgSortField = (typeof ADMIN_ORG_SORT_FIELDS)[number];\n\nexport const adminOrgListQuerySchema = z.object({\n q: z.string().trim().optional(),\n limit: z.coerce.number().int().min(1).max(100).prefault(25),\n offset: z.coerce.number().int().min(0).prefault(0),\n includeDeleted: z\n .enum([\"true\", \"false\"])\n .prefault(\"false\")\n .transform((v) => v === \"true\"),\n sortBy: z.enum(ADMIN_ORG_SORT_FIELDS).prefault(\"createdAt\"),\n sortDir: z.enum([\"asc\", \"desc\"]).prefault(\"desc\"),\n discoveryMode: z.enum(DISCOVERY_MODES).optional(),\n});\nexport type AdminOrgListQuery = z.infer<typeof adminOrgListQuerySchema>;\n\nexport const adminOrgTeamSchema = z.object({\n id: z.guid(),\n name: z.string(),\n createdAt: z.string().nullable(),\n discoveryMode: z.string().nullable(),\n memberCount: z.number().int().nonnegative(),\n pendingInvitationCount: z.number().int().nonnegative(),\n pendingJoinRequestCount: z.number().int().nonnegative(),\n});\nexport type AdminOrgTeam = z.infer<typeof adminOrgTeamSchema>;\n\nexport const adminOrgMemberSchema = z.object({\n userId: z.guid(),\n name: z.string().nullable(),\n email: z.string(),\n role: z.string(),\n});\nexport type AdminOrgMember = z.infer<typeof adminOrgMemberSchema>;\n\nexport const adminOrgDomainSchema = z.object({\n id: z.guid(),\n domain: z.string(),\n createdAt: z.string().nullable(),\n});\nexport type AdminOrgDomain = z.infer<typeof adminOrgDomainSchema>;\n\nexport const adminOrgDetailResponseSchema = z.object({\n organization: adminOrgSummarySchema,\n teams: z.array(adminOrgTeamSchema),\n members: z.array(adminOrgMemberSchema),\n membersTotal: z.number().int().nonnegative(),\n membersTruncated: z.boolean(),\n domains: z.array(adminOrgDomainSchema),\n});\nexport type AdminOrgDetailResponse = z.infer<\n typeof adminOrgDetailResponseSchema\n>;\n\nexport const adminOrgCreateRequestSchema = z.object({\n name: z.string().trim().min(1).max(200),\n discoveryMode: z.enum(DISCOVERY_MODES).optional(),\n});\nexport type AdminOrgCreateRequest = z.infer<typeof adminOrgCreateRequestSchema>;\n\nexport const adminOrgUpdateRequestSchema = z\n .object({\n name: z.string().trim().min(1).max(200).optional(),\n discoveryMode: z.enum(DISCOVERY_MODES).optional(),\n enterpriseBillingEnabled: z.boolean().optional(),\n })\n .refine(\n (val) => Object.values(val).some((v) => v !== undefined),\n \"At least one field must be provided\"\n );\nexport type AdminOrgUpdateRequest = z.infer<typeof adminOrgUpdateRequestSchema>;\n\nexport const adminOrgMutationResponseSchema = z.object({\n organization: adminOrgSummarySchema,\n});\nexport type AdminOrgMutationResponse = z.infer<\n typeof adminOrgMutationResponseSchema\n>;\n\nexport const adminOrgAddDomainRequestSchema = z.object({\n domain: z\n .string()\n .trim()\n .toLowerCase()\n .min(3)\n .max(253)\n .regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/),\n});\nexport type AdminOrgAddDomainRequest = z.infer<\n typeof adminOrgAddDomainRequestSchema\n>;\n\nexport const adminOrgAddDomainResponseSchema = z.object({\n domain: adminOrgDomainSchema,\n});\nexport type AdminOrgAddDomainResponse = z.infer<\n typeof adminOrgAddDomainResponseSchema\n>;\n\nexport const adminOrgAssignTeamRequestSchema = z.object({\n teamId: z.guid(),\n});\nexport type AdminOrgAssignTeamRequest = z.infer<\n typeof adminOrgAssignTeamRequestSchema\n>;\n\nexport const adminOrgAddMemberRequestSchema = z.object({\n userId: z.guid(),\n role: z.enum(ORG_ROLES.ALL),\n});\nexport type AdminOrgAddMemberRequest = z.infer<\n typeof adminOrgAddMemberRequestSchema\n>;\n\nexport const adminOrgAddMemberResponseSchema = z.object({\n member: adminOrgMemberSchema,\n});\nexport type AdminOrgAddMemberResponse = z.infer<\n typeof adminOrgAddMemberResponseSchema\n>;\n\nexport const adminOrgSuccessResponseSchema = z.object({\n success: z.literal(true),\n});\nexport type AdminOrgSuccessResponse = z.infer<\n typeof adminOrgSuccessResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport { ORG_ROLES } from \"../organization-roles\";\n\nconst orgRoleEnum = z.enum(ORG_ROLES.ALL);\n\nexport const organizationApiSchema = z.object({\n id: z.guid(),\n name: z.string(),\n discoveryMode: z.string(),\n createdAt: z.string(),\n});\nexport type OrganizationApi = z.infer<typeof organizationApiSchema>;\n\nexport const orgMemberApiSchema = z.object({\n id: z.guid(),\n name: z.string().nullable(),\n email: z.email(),\n role: z.string(),\n teams: z\n .array(\n z.object({\n teamId: z.guid(),\n teamName: z.string(),\n teamRole: z.string(),\n })\n )\n .default([]),\n});\nexport type OrgMemberApi = z.infer<typeof orgMemberApiSchema>;\n\nexport const organizationDomainApiSchema = z.object({\n id: z.guid(),\n domain: z.string(),\n createdAt: z.string(),\n});\nexport type OrganizationDomainApi = z.infer<typeof organizationDomainApiSchema>;\n\nconst joinRequestStatusSchema = z.enum([\"pending\", \"approved\", \"denied\"]);\n\nexport const orgJoinRequestApiSchema = z.object({\n id: z.guid(),\n organizationId: z.guid(),\n userId: z.guid(),\n userName: z.string().nullable().optional(),\n userEmail: z.email().optional(),\n status: joinRequestStatusSchema,\n createdAt: z.string(),\n resolvedAt: z.string().nullable(),\n resolvedBy: z.guid().nullable(),\n});\nexport type OrgJoinRequestApi = z.infer<typeof orgJoinRequestApiSchema>;\n\nexport const teamJoinRequestApiSchema = z.object({\n id: z.guid(),\n teamId: z.guid(),\n userId: z.guid(),\n userName: z.string().nullable().optional(),\n userEmail: z.email().optional(),\n status: joinRequestStatusSchema,\n createdAt: z.string(),\n resolvedAt: z.string().nullable(),\n resolvedBy: z.guid().nullable(),\n});\nexport type TeamJoinRequestApi = z.infer<typeof teamJoinRequestApiSchema>;\n\nexport const createOrganizationRequestSchema = z.object({\n name: z.string().min(1),\n});\nexport type CreateOrganizationRequest = z.infer<\n typeof createOrganizationRequestSchema\n>;\n\nexport const DISCOVERY_MODES = [\"request\", \"auto\"] as const;\nexport type DiscoveryMode = (typeof DISCOVERY_MODES)[number];\n\nexport const discoveryModeSchema = z.enum(DISCOVERY_MODES);\n\nexport const updateOrganizationRequestSchema = z.object({\n name: z.string().min(1).optional(),\n discoveryMode: discoveryModeSchema.optional(),\n});\nexport type UpdateOrganizationRequest = z.infer<\n typeof updateOrganizationRequestSchema\n>;\n\nexport const inviteOrgMemberRequestSchema = z.object({\n email: z.email(),\n role: z.enum([\n \"organization:executive\",\n \"organization:owner\",\n \"organization:admin\",\n \"organization:member\",\n ]),\n frontendUrl: z.url().optional(),\n teamId: z.guid().optional(),\n});\nexport type InviteOrgMemberRequest = z.infer<\n typeof inviteOrgMemberRequestSchema\n>;\n\nexport const inviteOrgMemberResponseSchema = z.object({\n success: z.boolean(),\n invitationId: z.guid(),\n emailSent: z.boolean(),\n});\nexport type InviteOrgMemberResponse = z.infer<\n typeof inviteOrgMemberResponseSchema\n>;\n\nexport const updateOrgMemberRoleRequestSchema = z.object({\n role: z.enum([\n \"organization:executive\",\n \"organization:owner\",\n \"organization:admin\",\n \"organization:member\",\n ]),\n});\nexport type UpdateOrgMemberRoleRequest = z.infer<\n typeof updateOrgMemberRoleRequestSchema\n>;\n\nexport const addOrgDomainRequestSchema = z.object({\n domain: z\n .string()\n .min(3)\n .regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/),\n});\nexport type AddOrgDomainRequest = z.infer<typeof addOrgDomainRequestSchema>;\n\nexport const resolveJoinRequestSchema = z.object({\n status: z.enum([\"approved\", \"denied\"]),\n});\nexport type ResolveJoinRequest = z.infer<typeof resolveJoinRequestSchema>;\n\nexport const discoverOrganizationResponseSchema = z.object({\n found: z.boolean(),\n organization: organizationApiSchema.nullable(),\n});\nexport type DiscoverOrganizationResponse = z.infer<\n typeof discoverOrganizationResponseSchema\n>;\n\nexport const listOrgMembersResponseSchema = z.object({\n members: z.array(orgMemberApiSchema),\n});\nexport type ListOrgMembersResponse = z.infer<\n typeof listOrgMembersResponseSchema\n>;\n\nexport const listOrgDomainsResponseSchema = z.object({\n domains: z.array(organizationDomainApiSchema),\n});\nexport type ListOrgDomainsResponse = z.infer<\n typeof listOrgDomainsResponseSchema\n>;\n\nexport const listOrgJoinRequestsResponseSchema = z.object({\n requests: z.array(orgJoinRequestApiSchema),\n});\nexport type ListOrgJoinRequestsResponse = z.infer<\n typeof listOrgJoinRequestsResponseSchema\n>;\n\nexport const listTeamJoinRequestsResponseSchema = z.object({\n requests: z.array(teamJoinRequestApiSchema),\n});\nexport type ListTeamJoinRequestsResponse = z.infer<\n typeof listTeamJoinRequestsResponseSchema\n>;\n\nexport const teamJoinRequestWithTeamApiSchema = teamJoinRequestApiSchema.extend(\n {\n teamName: z.string(),\n }\n);\nexport type TeamJoinRequestWithTeamApi = z.infer<\n typeof teamJoinRequestWithTeamApiSchema\n>;\n\nexport const listOrgTeamJoinRequestsResponseSchema = z.object({\n requests: z.array(teamJoinRequestWithTeamApiSchema),\n total: z.number().int().nonnegative(),\n});\nexport type ListOrgTeamJoinRequestsResponse = z.infer<\n typeof listOrgTeamJoinRequestsResponseSchema\n>;\n\nexport const userOrganizationResponseSchema = z.object({\n organization: organizationApiSchema.nullable(),\n role: z.string().nullable(),\n});\nexport type UserOrganizationResponse = z.infer<\n typeof userOrganizationResponseSchema\n>;\n\nexport const orgMembershipApiSchema = z.object({\n organization: organizationApiSchema,\n role: z.string(),\n memberCount: z.number(),\n});\nexport type OrgMembershipApi = z.infer<typeof orgMembershipApiSchema>;\n\nexport const userOrganizationsResponseSchema = z.object({\n memberships: z.array(orgMembershipApiSchema),\n});\nexport type UserOrganizationsResponse = z.infer<\n typeof userOrganizationsResponseSchema\n>;\n\nexport const createOrgTeamRequestSchema = z.object({\n name: z.string().min(1),\n});\nexport type CreateOrgTeamRequest = z.infer<typeof createOrgTeamRequestSchema>;\n\nexport const orgInvitationApiSchema = z.object({\n id: z.guid(),\n email: z.email(),\n role: z.string(),\n teamId: z.guid().nullable().optional(),\n createdAt: z.string(),\n invitedByName: z.string().nullable().optional(),\n});\nexport type OrgInvitationApi = z.infer<typeof orgInvitationApiSchema>;\n\nexport const listOrgInvitationsResponseSchema = z.object({\n invitations: z.array(orgInvitationApiSchema),\n});\nexport type ListOrgInvitationsResponse = z.infer<\n typeof listOrgInvitationsResponseSchema\n>;\n\nexport const orgInvitationDetailApiSchema = z.object({\n id: z.guid(),\n email: z.email(),\n role: orgRoleEnum,\n createdAt: z.string(),\n resolvedAt: z.string().nullable(),\n invitedByName: z.string().nullable(),\n invitedByEmail: z.email().nullable(),\n organization: z.object({\n id: z.guid(),\n name: z.string(),\n }),\n});\nexport type OrgInvitationDetailApi = z.infer<\n typeof orgInvitationDetailApiSchema\n>;\n\nexport const acceptOrgInvitationResponseSchema = z.object({\n success: z.boolean(),\n orgId: z.guid(),\n});\nexport type AcceptOrgInvitationResponse = z.infer<\n typeof acceptOrgInvitationResponseSchema\n>;\n\nexport const createOrganizationInviteLinkRequestSchema = z.object({\n frontendUrl: z.url(),\n});\nexport type CreateOrganizationInviteLinkRequest = z.infer<\n typeof createOrganizationInviteLinkRequestSchema\n>;\n\nexport const getOrganizationInviteLinkQuerySchema = z.object({\n frontendUrl: z.url(),\n});\nexport type GetOrganizationInviteLinkQuery = z.infer<\n typeof getOrganizationInviteLinkQuerySchema\n>;\n\nexport const organizationInviteLinkCreatorSchema = z.object({\n id: z.guid(),\n name: z.string().nullable(),\n email: z.email(),\n});\n\nexport const organizationInviteLinkSchema = z.object({\n id: z.guid(),\n url: z.url().optional(),\n createdAt: z.string(),\n createdBy: organizationInviteLinkCreatorSchema,\n});\nexport type OrganizationInviteLink = z.infer<\n typeof organizationInviteLinkSchema\n>;\n\nexport const getOrganizationInviteLinkResponseSchema = z.object({\n hasLink: z.boolean(),\n link: organizationInviteLinkSchema.optional(),\n});\nexport type GetOrganizationInviteLinkResponse = z.infer<\n typeof getOrganizationInviteLinkResponseSchema\n>;\n\nexport const createOrganizationInviteLinkResponseSchema =\n organizationInviteLinkSchema;\nexport type CreateOrganizationInviteLinkResponse = z.infer<\n typeof createOrganizationInviteLinkResponseSchema\n>;\n\nexport const orgJoinLinkInfoResponseSchema = z.object({\n valid: z.boolean(),\n orgName: z.string().optional(),\n orgId: z.guid().optional(),\n reason: z.enum([\"invalid\", \"expired\"]).optional(),\n});\nexport type OrgJoinLinkInfoResponse = z.infer<\n typeof orgJoinLinkInfoResponseSchema\n>;\n\nexport const acceptOrgJoinLinkResponseSchema = z.object({\n success: z.boolean(),\n orgId: z.guid(),\n});\nexport type AcceptOrgJoinLinkResponse = z.infer<\n typeof acceptOrgJoinLinkResponseSchema\n>;\n\nexport const pendingCountsResponseSchema = z.object({\n joinRequests: z.number(),\n invitations: z.number(),\n});\nexport type PendingCountsResponse = z.infer<typeof pendingCountsResponseSchema>;\n", "import { z } from \"zod\";\n\nimport { StoredAgentConfigSchema } from \"./agent-config\";\n\n/**\n * Zod schemas for agent API responses\n * These schemas are used for both backend validation and frontend type inference\n */\n\n/**\n * Schedule frequency enum schema\n */\nexport const scheduleFrequencySchema = z.enum([\n \"every_5_minutes\",\n \"every_15_minutes\",\n \"hourly\",\n \"daily\",\n \"workday\",\n \"weekly\",\n \"monthly\",\n \"custom\",\n]);\n\n/**\n * Schedule day enum schema\n */\nexport const scheduleDaySchema = z.enum([\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n \"sunday\",\n]);\n\n/**\n * Schedule as returned over the wire.\n *\n * Frequency-dependent fields are nullable on this shape; the per-frequency\n * required-fields contract is:\n *\n * - `cron` set iff `frequency === \"custom\"`.\n * - `time` required for `daily`, `workday`, `weekly`, `monthly`.\n * - `day` required for `weekly`; `day_of_month` required for `monthly`.\n *\n * Writes are validated by `scheduleUpsertRequestSchema.superRefine`; cron\n * evaluation is in `shouldRunSchedule`.\n */\nexport const scheduleApiSchema = z.object({\n id: z.string(),\n build_id: z.string(),\n agent_id: z.string(),\n user_id: z.string(),\n enabled: z.boolean(),\n frequency: scheduleFrequencySchema,\n time: z.string().nullable(),\n timezone: z.string(),\n day: z.string().nullable(),\n day_of_month: z.number().nullable(),\n /** Cron expression. Set iff `frequency === \"custom\"`; null otherwise. */\n cron: z.string().nullable(),\n /** Who authored the schedule. `\"user\"` for user-driven upserts; `null` on legacy rows. */\n source: z.string().nullable(),\n /** Optional prompt appended to the run when the schedule fires. */\n task: z.string().nullable(),\n /** `false` for one-shot schedules, which are retired after the first fire. `null` is treated as recurring. */\n recurring: z.boolean().nullable(),\n created_at: z.string(),\n updated_at: z.string(),\n /** Populated only by the all-users admin endpoint; undefined on per-user responses. */\n user_name: z.string().nullable().optional(),\n /** Populated only by the all-users admin endpoint; undefined on per-user responses. */\n user_email: z.string().nullable().optional(),\n});\n\nexport const integrationConfigApiSchema = z.object({\n id: z.string(),\n integration_id: z.string(),\n integration_type: z.string(),\n integration_name: z.string(),\n created_at: z.string(),\n icon_url: z.string().nullish(),\n is_connected: z.boolean().optional(),\n});\n\n/**\n * Per-user blocker entry for the all-users schedule view (superadmin).\n * Lists missing integration connections for one schedule owner so the UI\n * can flag whether that user can edit or run their own schedules.\n */\nexport const userScheduleBlockersSchema = z.object({\n user_id: z.string(),\n missing_integrations: z.array(\n z.object({\n integration_id: z.string().nullable(),\n integration_type: z.string(),\n })\n ),\n});\n\nconst FREQUENCIES_REQUIRING_TIME = [\n \"daily\",\n \"workday\",\n \"weekly\",\n \"monthly\",\n] as const;\n\n/** Maximum schedules one `(agent_id, user_id)` pair can own. Enforced on create. */\nexport const MAX_SCHEDULES_PER_AGENT = 5;\n\n/**\n * Schedule upsert request schema\n */\nexport const scheduleUpsertRequestSchema = z\n .object({\n agent_id: z.string(),\n enabled: z.boolean(),\n frequency: scheduleFrequencySchema,\n time: z.string().nullable().optional(),\n timezone: z.string(),\n day: scheduleDaySchema.nullable().optional(),\n day_of_month: z.int().min(1).max(31).nullable().optional(),\n cron: z.string().nullable().optional(),\n recurring: z.boolean().nullable().optional(),\n })\n .superRefine((data, ctx) => {\n // Only validate required fields when schedule is enabled\n if (!data.enabled) {\n return;\n }\n\n if (data.frequency === \"custom\" && !data.cron) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Cron expression is required for custom schedules\",\n path: [\"cron\"],\n });\n }\n\n if (data.frequency === \"weekly\" && !data.day) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Day of week is required for weekly schedules\",\n path: [\"day\"],\n });\n }\n\n if (data.frequency === \"monthly\" && data.day_of_month == null) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Day of month is required for monthly schedules\",\n path: [\"day_of_month\"],\n });\n }\n\n if (\n FREQUENCIES_REQUIRING_TIME.includes(\n data.frequency as (typeof FREQUENCIES_REQUIRING_TIME)[number]\n ) &&\n !data.time\n ) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Time is required for this schedule frequency\",\n path: [\"time\"],\n });\n }\n });\n\n/**\n * Build schema for API responses (with ISO string dates).\n *\n * `agent_id` mirrors `copilot_id` for public consumers that pre-date\n * the rename; keep both populated in every response.\n */\nexport const buildApiSchema = z.strictObject({\n id: z.guid(),\n copilot_id: z.guid(),\n agent_id: z.guid(),\n name: z.string(),\n config: StoredAgentConfigSchema.nullable(),\n status: z.string().nullable(),\n revision_number: z.number().nullable(),\n parent_build_id: z.string().nullable(),\n created_by: z.string().nullable(),\n created_by_name: z.string().nullable().optional(),\n created_at: z.string().nullable(),\n updated_at: z.string().nullable(),\n schedules: z.array(scheduleApiSchema).optional(),\n});\n\n/**\n * Schema for a conflicting agent in case trigger conflict detection\n */\nexport const conflictingAgentSchema = z.object({\n id: z.string(),\n name: z.string(),\n});\n\nexport type ConflictingAgent = z.infer<typeof conflictingAgentSchema>;\n\n/**\n * Agent schema for API responses (with ISO string dates)\n */\nexport const agentApiSchema = z.object({\n id: z.guid(),\n name: z.string(),\n slack_enabled: z.boolean().nullable(),\n microsoft_teams_enabled: z.boolean().nullable(),\n agentic_memory_enabled: z.boolean().nullable(),\n team_id: z.string().nullable(),\n thread_id: z.string().nullable(),\n folder_id: z.string().nullable().optional(),\n created_at: z.string().nullable(),\n updated_at: z.string().nullable(),\n last_run_at: z.string().nullable(),\n created_by: z\n .object({\n id: z.string(),\n name: z.string().nullable(),\n email: z.string(),\n })\n .nullable()\n .optional(),\n updated_by: z\n .object({\n id: z.string(),\n name: z.string().nullable(),\n email: z.string(),\n })\n .nullable()\n .optional(),\n latest_build: buildApiSchema.nullable(),\n integration_configs: z.array(integrationConfigApiSchema),\n user_triggers: z\n .object({\n slack_mention: z.boolean(),\n slack_channel: z.boolean(),\n teams_mention: z.boolean(),\n })\n .optional(),\n case_trigger_enabled: z.boolean().optional(),\n case_trigger_has_conflict: z.boolean().optional(),\n case_trigger_conflicting_agents: z.array(conflictingAgentSchema).optional(),\n case_queue_name: z.string().nullable().optional(),\n});\n\n/**\n * Paginated list of agents for the GET /v1/agents response.\n */\nexport const agentsListApiSchema = z.object({\n agents: z.array(agentApiSchema),\n total: z.int(),\n limit: z.int(),\n offset: z.int(),\n});\n\n/**\n * Wrapper for single-agent responses (GET /v1/agents/:agent_id).\n */\nexport const agentResponseApiSchema = z.object({\n agent: agentApiSchema,\n});\n\n/**\n * Response for POST /v1/agents.\n *\n * When an inline `build` is supplied in the request body, the first build\n * is returned alongside the agent. Otherwise `build` is omitted.\n */\nexport const createAgentResponseApiSchema = z.object({\n agent: agentApiSchema,\n build: buildApiSchema.optional(),\n});\n\n/**\n * Agent run schema for API responses (with ISO string dates)\n */\nexport const agentRunApiSchema = z.object({\n id: z.string(),\n agent_id: z.string(),\n build_id: z.string(),\n status: z.string(),\n user_id: z.string().nullable(),\n source: z.string().nullable(),\n sandbox_id: z.string().nullable(),\n bb_session_id: z.string().nullable(),\n last_session_id: z.string().nullable(),\n created_at: z.string(),\n updated_at: z.string(),\n started_at: z.string().nullable(),\n completed_at: z.string().nullable(),\n});\n\n/**\n * Agent with runs schema - used when including run statistics\n */\nexport const agentWithRunsApiSchema = z.object({\n id: z.string(),\n name: z.string(),\n slack_enabled: z.boolean().nullable(),\n team_id: z.string().nullable(),\n thread_id: z.string().nullable(),\n created_at: z.string().nullable(),\n updated_at: z.string().nullable(),\n agent_run: z.array(agentRunApiSchema),\n});\n\n/**\n * Array of agents with runs schema for list endpoints\n */\nexport const agentsWithRunsListApiSchema = z.array(agentWithRunsApiSchema);\n\n/**\n * Active run counts grouped by agent\n */\nexport const activeRunCountByAgentApiSchema = z.object({\n agent: z.object({\n id: z.string(),\n name: z.string(),\n }),\n run_count: z.int(),\n});\n\nexport const activeRunsListApiSchema = z.array(activeRunCountByAgentApiSchema);\n\n/**\n * Schema for an agent's per-build integration slot row.\n * Returned by GET /v1/agents/:agent_id/builds/:build_id/integrations.\n */\nexport const buildIntegrationConfigSchema = z.object({\n id: z.guid(),\n integration_id: z.guid().nullable(),\n custom_integration_id: z.guid().nullable(),\n integration_type: z.string(),\n integration_name: z.string(),\n created_at: z.string(),\n});\n\nexport const listBuildIntegrationsResponseSchema = z.object({\n integrations: z.array(buildIntegrationConfigSchema),\n});\n\n/**\n * Schema for a queue summary linked to a build integration slot. Used by\n * GET /v1/agents/:agent_id/builds/:build_id/integrations/:integration_id/queues.\n */\nexport const buildIntegrationCaseQueueSchema = z.object({\n id: z.guid(),\n name: z.string(),\n});\n\nexport const buildIntegrationQueuesResponseSchema = z.object({\n queues: z.array(buildIntegrationCaseQueueSchema),\n});\n\n/**\n * TypeScript types for API responses\n * Inferred from Zod schemas to ensure they stay in sync\n */\nexport type ScheduleFrequency = z.infer<typeof scheduleFrequencySchema>;\nexport type ScheduleDay = z.infer<typeof scheduleDaySchema>;\nexport type ScheduleApi = z.infer<typeof scheduleApiSchema>;\nexport type UserScheduleBlockers = z.infer<typeof userScheduleBlockersSchema>;\nexport type ScheduleUpsertRequest = z.infer<typeof scheduleUpsertRequestSchema>;\nexport type BuildApi = z.infer<typeof buildApiSchema>;\nexport type IntegrationConfigApi = z.infer<typeof integrationConfigApiSchema>;\nexport type BuildIntegrationConfig = z.infer<\n typeof buildIntegrationConfigSchema\n>;\nexport type ListBuildIntegrationsResponse = z.infer<\n typeof listBuildIntegrationsResponseSchema\n>;\nexport type BuildIntegrationCaseQueue = z.infer<\n typeof buildIntegrationCaseQueueSchema\n>;\nexport type BuildIntegrationQueuesResponse = z.infer<\n typeof buildIntegrationQueuesResponseSchema\n>;\nexport type AgentApi = z.infer<typeof agentApiSchema>;\nexport type AgentsListApi = z.infer<typeof agentsListApiSchema>;\nexport type AgentResponseApi = z.infer<typeof agentResponseApiSchema>;\nexport type CreateAgentResponseApi = z.infer<\n typeof createAgentResponseApiSchema\n>;\nexport type AgentRunApi = z.infer<typeof agentRunApiSchema>;\nexport type AgentWithRunsApi = z.infer<typeof agentWithRunsApiSchema>;\nexport type AgentsWithRunsListApi = z.infer<typeof agentsWithRunsListApiSchema>;\nexport type ActiveRunCountByAgentApi = z.infer<\n typeof activeRunCountByAgentApiSchema\n>;\nexport type ActiveRunsListApi = z.infer<typeof activeRunsListApiSchema>;\n", "import type {\n ResponseIncludable,\n Tool,\n} from \"openai/resources/responses/responses\";\nimport { z } from \"zod\";\n\nimport {\n BrowsingModelIdSchema,\n BrowsingProviderSchema,\n ClaudeModelIdSchema,\n} from \"../constants/models\";\n\n// Schema for MCP tool approval filter\nconst McpToolApprovalFilterSchema = z.object({\n always: z\n .object({\n tool_names: z.array(z.string()).nullable().optional(),\n })\n .nullable()\n .optional(),\n never: z\n .object({\n tool_names: z.array(z.string()).nullable().optional(),\n })\n .nullable()\n .optional(),\n});\n\n// Schema for MCP allowed tools filter\nconst McpAllowedToolsFilterSchema = z.object({\n tool_names: z.array(z.string()).nullable().optional(),\n});\n\n// Schema for MCP tool definition\nexport const McpToolSchema = z.object({\n type: z.literal(\"mcp\"),\n server_label: z.string(),\n server_url: z.string(),\n allowed_tools: z\n .union([z.array(z.string()), McpAllowedToolsFilterSchema])\n .nullable()\n .optional(),\n headers: z.record(z.string(), z.string()).nullable().optional(),\n require_approval: z\n .union([\n z.literal(\"always\"),\n z.literal(\"never\"),\n McpToolApprovalFilterSchema,\n ])\n .nullable()\n .optional(),\n});\n\nexport type McpTool = z.infer<typeof McpToolSchema>;\n\n// Schema for input text content\nexport const InputTextSchema = z.object({\n type: z.literal(\"input_text\"),\n text: z.string(),\n});\n\nexport type InputText = z.infer<typeof InputTextSchema>;\n\n// Schema for input image content\nexport const InputImageSchema = z.object({\n type: z.literal(\"input_image\"),\n detail: z.enum([\"low\", \"high\", \"auto\"]).nullable().optional(),\n file_id: z.string().nullable().optional(),\n url: z.string().nullable().optional(),\n});\n\nexport type InputImage = z.infer<typeof InputImageSchema>;\n\n// Schema for input file content\nexport const InputFileSchema = z.object({\n type: z.literal(\"input_file\"),\n file_id: z.string(),\n});\n\nexport type InputFile = z.infer<typeof InputFileSchema>;\n\n// Union of all input content types\nexport const InputContentSchema = z.union([\n InputTextSchema,\n InputImageSchema,\n InputFileSchema,\n]);\n\nexport type InputContent = z.infer<typeof InputContentSchema>;\n\n// Schema for input messages\nexport const InputMessageSchema = z.object({\n role: z.enum([\"system\", \"user\", \"assistant\"]),\n content: z.union([z.string(), z.array(InputContentSchema)]),\n type: z.literal(\"message\").nullable().optional(),\n});\n\nexport type InputMessage = z.infer<typeof InputMessageSchema>;\n\n// Schema for OpenAI Responses API parameters (matches route.ts)\nexport const OpenAIResponseParamsSchema = z.object({\n // Required fields\n input: z.array(InputMessageSchema).describe(\"Instructions payload\"),\n model: z.string(),\n\n // Optional fields that OpenAI accepts\n background: z.boolean().nullable().optional(),\n include: z\n .array(z.string())\n .nullable()\n .optional()\n .transform((val) => val?.map((item) => item as ResponseIncludable)),\n instructions: z.string().nullable().optional(),\n max_output_tokens: z.number().positive().nullable().optional(),\n metadata: z.record(z.string(), z.string()).nullable().optional(),\n parallel_tool_calls: z.boolean().nullable().optional(),\n previous_response_id: z.string().nullable().optional(),\n reasoning: z.boolean().nullable().optional(),\n service_tier: z.enum([\"auto\", \"default\", \"flex\"]).nullable().optional(),\n store: z.boolean().nullable().optional(),\n stream: z.boolean().transform(() => true), // Always stream\n temperature: z.number().min(0).max(2).nullable().optional(),\n text: z\n .object({\n format: z\n .union([\n z.object({ type: z.literal(\"text\") }),\n z.object({ type: z.literal(\"json_object\") }),\n ])\n .nullable()\n .optional(),\n })\n .nullable()\n .optional(),\n tool_choice: z\n .union([\n z.string(),\n z.object({\n type: z.enum([\"tool\"]),\n name: z.string(),\n }),\n ])\n .nullable()\n .optional(),\n tools: z\n .array(McpToolSchema)\n .nullable()\n .optional()\n .transform((val) => val?.map((item) => item as Tool.Mcp)),\n top_p: z.number().min(0).max(1).nullable().optional(),\n truncation: z.enum([\"auto\", \"disabled\"]).nullable().optional(),\n user: z.string().nullable().optional(),\n});\n\nexport type OpenAIResponseParams = z.infer<typeof OpenAIResponseParamsSchema>;\n\n// Schema for incoming request (includes our custom conversation fields)\nexport const RequestParamsSchema = OpenAIResponseParamsSchema.extend({\n // Custom conversation handling fields\n messages: z\n .array(\n z.object({\n role: z.enum([\"user\", \"assistant\", \"system\"]),\n content: z.string(),\n })\n )\n .nullable()\n .optional(),\n conversationContext: z\n .array(\n z.object({\n role: z.enum([\"user\", \"assistant\", \"system\"]),\n content: z.string(),\n })\n )\n .nullable()\n .optional(),\n systemPrompt: z.string().nullable().optional(),\n});\n\n// v1 Schema (Legacy - OpenAI-based)\nexport const AgentConfigSchemaV1 = OpenAIResponseParamsSchema.pick({\n model: true,\n temperature: true,\n max_output_tokens: true,\n top_p: true,\n store: true,\n tools: true,\n input: true,\n text: true,\n}).extend({\n files: z.array(z.string()).nullable().optional().default([]),\n skills: z.array(z.string()).nullable().optional().default([]),\n input: z.union([z.string(), z.array(InputMessageSchema)]),\n});\n\nexport type AgentConfigV1 = z.infer<typeof AgentConfigSchemaV1>;\n\nexport const StoredAgentConfigSchemaV1 = z.object({\n version: z.literal(\"v1\"),\n data: AgentConfigSchemaV1,\n});\n\nexport type StoredAgentConfigV1 = z.infer<typeof StoredAgentConfigSchemaV1>;\n\n/**\n * Browser infrastructure provider types (where browser sessions run).\n */\nexport const BrowserProviderTypeSchema = z.enum([\"browserbase\", \"browser-use\"]);\nexport type BrowserProviderType = z.infer<typeof BrowserProviderTypeSchema>;\n\nexport const BenchmarkExpectedOutcomeSchema = z.object({\n description: z\n .string()\n .describe(\"Human-readable description of the expected outcome\"),\n criteria: z\n .string()\n .describe(\"Pass/fail criteria used to evaluate the outcome\"),\n});\n\nexport type BenchmarkExpectedOutcome = z.infer<\n typeof BenchmarkExpectedOutcomeSchema\n>;\n\n/**\n * Runtime options schema for agent execution.\n * Uses passthrough() to allow additional unknown keys for future extensibility.\n */\nexport const RuntimeOptionsSchema = z.looseObject({\n browserProvider: BrowserProviderTypeSchema.optional().describe(\n \"Browser infrastructure provider\"\n ),\n evaluationSchemaId: z\n .string()\n .optional()\n .describe(\"ID of the evaluation schema to apply to runs of this agent\"),\n benchmarkExpectedOutcomes: z\n .array(BenchmarkExpectedOutcomeSchema)\n .optional()\n .describe(\"Expected outcomes used when running benchmark scenarios\"),\n});\n\nexport type RuntimeOptions = z.infer<typeof RuntimeOptionsSchema>;\n\n// v2 Schema - nested models object matching PLATFORM_DEFAULT_MODELS structure\nexport const AgentConfigSchemaV2 = z.object({\n models: z\n .object({\n agent: z\n .object({\n model: ClaudeModelIdSchema.describe(\n \"Claude model identifier used for the primary agent loop\"\n ),\n })\n .describe(\"Primary Claude agent model configuration\"),\n browsing: z\n .object({\n provider: BrowsingProviderSchema.describe(\n \"Provider backing the browsing/computer-use model\"\n ),\n model: BrowsingModelIdSchema.describe(\n \"Model identifier for the browsing provider\"\n ),\n })\n .describe(\"Browsing/computer-use model configuration\"),\n })\n .describe(\"Model configuration for each capability the agent uses\"),\n\n // Core fields\n input: z\n .union([z.string(), z.array(InputMessageSchema)])\n .describe(\n \"Initial agent instructions \u2014 either a single system prompt string or a list of structured messages\"\n ),\n files: z\n .array(z.string())\n .nullable()\n .optional()\n .default([])\n .describe(\"IDs of team files that should be available to the agent\"),\n skills: z\n .array(z.string())\n .nullable()\n .optional()\n .default([])\n .describe(\n \"IDs of skills (team or system) that should be available to the agent\"\n ),\n // Plugins can be:\n // - Built-in plugin name: \"code-review\", \"commit-commands\"\n // - GitHub URL: \"https://github.com/owner/repo\"\n plugins: z\n .array(z.string())\n .nullable()\n .optional()\n .default([])\n .describe(\n 'Plugins to load \u2014 either a built-in plugin name (e.g. \"code-review\") or a GitHub URL (e.g. \"https://github.com/owner/repo\")'\n ),\n subAgents: z\n .array(z.uuid())\n .nullable()\n .optional()\n .default([])\n .describe(\n \"IDs of other assignments (agents in the same team) to expose to this assignment as Claude Code subagents. Each sub-assignment runs with its own SOP and connections; the parent can delegate to them via the Agent tool.\"\n ),\n\n // Runtime options (extensible)\n options: RuntimeOptionsSchema.optional().describe(\n \"Optional runtime options controlling how the agent executes\"\n ),\n});\n\nexport type AgentConfigV2 = z.infer<typeof AgentConfigSchemaV2>;\n\nexport const StoredAgentConfigSchemaV2 = z.object({\n version: z\n .literal(\"v2\")\n .describe(\n 'Schema version discriminator \u2014 must be \"v2\" for the current schema'\n ),\n data: AgentConfigSchemaV2.describe(\"Agent configuration payload\"),\n});\n\nexport type StoredAgentConfigV2 = z.infer<typeof StoredAgentConfigSchemaV2>;\n\nexport const AgentConfigSchema = AgentConfigSchemaV2;\nexport type AgentConfig = AgentConfigV2;\n\nexport const StoredAgentConfigSchema = z.union([\n StoredAgentConfigSchemaV1,\n StoredAgentConfigSchemaV2,\n]);\n\nexport type StoredAgentConfig = StoredAgentConfigV1 | StoredAgentConfigV2;\n\nexport const EditConfigParamsSchema = z.object({\n buildId: z.guid(),\n});\n\nexport type EditConfigParams = z.infer<typeof EditConfigParamsSchema>;\n\nexport const EditConfigBodySchema = z.object({\n prompt: z.union([z.string(), z.array(z.string())]),\n runId: z.guid().optional().describe(\"Optional run ID for context\"),\n conversation: z\n .array(z.object({ source: z.enum([\"ai\", \"user\"]), message: z.string() }))\n .optional()\n .describe(\"Optional voice conversation transcript\"),\n processId: z.guid().optional().describe(\"Optional process ID for context\"),\n insightIndex: z\n .number()\n .min(0)\n .optional()\n .describe(\"Optional insight index for context\"),\n previousBuildId: z\n .guid()\n .optional()\n .describe(\"Previous build ID for sandbox reuse\"),\n});\n\nexport type EditConfigBody = z.infer<typeof EditConfigBodySchema>;\n", "import { z } from \"zod\";\n\nexport const feedbackSentimentSchema = z.enum([\"positive\", \"negative\"]);\n\nexport type FeedbackSentiment = z.infer<typeof feedbackSentimentSchema>;\n\n/**\n * Maximum length for feedback comments in characters.\n */\nexport const MAX_FEEDBACK_COMMENT_LENGTH = 2000;\n\nexport const feedbackDataSchema = z.object({\n id: z.guid(),\n agent_id: z.guid(),\n build_id: z.guid(),\n run_id: z.guid(),\n user_id: z.guid(),\n sentiment: feedbackSentimentSchema,\n comment: z.string().max(MAX_FEEDBACK_COMMENT_LENGTH).nullable(),\n session_id: z.string().nullable(),\n created_at: z.string(),\n updated_at: z.string(),\n});\n\nexport type FeedbackData = z.infer<typeof feedbackDataSchema>;\n", "import { z } from \"zod\";\n\nexport const agentFolderResponseSchema = z.object({\n id: z.string(),\n name: z.string(),\n team_id: z.string(),\n parent_folder_id: z.string().nullable(),\n created_at: z.string(),\n updated_at: z.string(),\n agent_count: z.number(),\n subfolder_count: z.number(),\n});\n\nexport const agentFoldersListResponseSchema = z.array(\n agentFolderResponseSchema\n);\n\nexport const createAgentFolderRequestSchema = z.object({\n name: z.string().min(1).max(100),\n parent_folder_id: z.guid().nullable().optional(),\n});\n\nexport const updateAgentFolderRequestSchema = z.object({\n name: z.string().min(1).max(100).optional(),\n parent_folder_id: z.guid().nullable().optional(),\n});\n\nexport const moveAgentsRequestSchema = z.object({\n agent_ids: z.array(z.guid()).min(1),\n folder_id: z.guid().nullable(),\n});\n\nexport type AgentFolderResponse = z.infer<typeof agentFolderResponseSchema>;\nexport type AgentFoldersListResponse = z.infer<\n typeof agentFoldersListResponseSchema\n>;\nexport type CreateAgentFolderRequest = z.infer<\n typeof createAgentFolderRequestSchema\n>;\nexport type UpdateAgentFolderRequest = z.infer<\n typeof updateAgentFolderRequestSchema\n>;\nexport type MoveAgentsRequest = z.infer<typeof moveAgentsRequestSchema>;\n", "import { z } from \"zod\";\n\n/**\n * Zod schema for validating agent learning entities\n */\nexport const learningSchema = z.object({\n id: z.string(),\n content: z.string(),\n sourceRunId: z.string().nullable(),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\n\n/**\n * Type representing an agent learning entity\n */\nexport type Learning = z.infer<typeof learningSchema>;\n\n/**\n * Zod schema for API responses containing a learning entity\n */\nexport const getLearningsResponseSchema = z.object({\n learning: learningSchema.nullable(),\n});\n", "import { z } from \"zod\";\n\n// Page schema - all fields required (Browserbase provides full page data)\nexport const browserPageSchema = z.object({\n id: z.string().describe(\"Page ID\"),\n url: z.url().describe(\"Page URL\"),\n faviconUrl: z.string().describe(\"Page favicon URL\"),\n title: z.string().describe(\"Page title\"),\n debuggerUrl: z.url().describe(\"Page-specific debugger URL\"),\n debuggerFullscreenUrl: z\n .url()\n .describe(\"Page-specific full-screen debugger URL\"),\n});\n\n// Alias for backwards compatibility\nexport const browserbasePageSchema = browserPageSchema;\n\n// Session info response - includes session-level URLs + optional pages\n// Browser Use provides session-level URLs only, Browserbase provides both\nexport const browserSessionInfoSchema = z.object({\n // Session-level URLs (Browser Use provides these, Browserbase also has them)\n wsUrl: z.url().nullable(),\n liveUrl: z.url().nullable(),\n\n // Page-level data (Browserbase provides these, Browser Use returns empty array)\n pages: z.array(browserPageSchema),\n});\n\n// Zod schema for Browserbase debug API response\nexport const browserbaseDebugResponseSchema = z.object({\n debuggerFullscreenUrl: z.url().describe(\"Session full-screen debugger URL\"),\n debuggerUrl: z.url().describe(\"Session debugger URL\"),\n pages: z.array(browserPageSchema).describe(\"List of pages in the session\"),\n wsUrl: z.url().describe(\"WebSocket URL for the session\"),\n});\n\n// Zod schema for Browserbase session creation response\nexport const browserbaseSessionCreateResponseSchema = z.object({\n id: z.string().describe(\"Session ID\"),\n createdAt: z.iso.datetime().describe(\"Session creation timestamp\"),\n updatedAt: z.iso.datetime().describe(\"Session last update timestamp\"),\n projectId: z.string().describe(\"Project ID\"),\n startedAt: z.iso.datetime().describe(\"Session start timestamp\"),\n endedAt: z.iso.datetime().optional().describe(\"Session end timestamp\"),\n expiresAt: z.iso.datetime().describe(\"Session expiration timestamp\"),\n status: z.string().describe(\"Session status\"),\n proxyBytes: z.number().describe(\"Proxy bytes used\"),\n avgCpuUsage: z.number().describe(\"Average CPU usage\"),\n memoryUsage: z.number().describe(\"Memory usage\"),\n keepAlive: z.boolean().describe(\"Keep alive flag\"),\n contextId: z.string().describe(\"Context ID\"),\n region: z.string().describe(\"Region\"),\n userMetadata: z.record(z.string(), z.unknown()).describe(\"User metadata\"),\n connectUrl: z.string().describe(\"Connect URL\"),\n seleniumRemoteUrl: z.string().describe(\"Selenium remote URL\"),\n signingKey: z.string().describe(\"Signing key\"),\n});\n\n// TypeScript types derived from schemas\nexport type BrowserPage = z.infer<typeof browserPageSchema>;\nexport type BrowserbasePage = BrowserPage; // Alias for backwards compatibility\nexport type BrowserSessionInfo = z.infer<typeof browserSessionInfoSchema>;\nexport type BrowserbaseDebugResponse = z.infer<\n typeof browserbaseDebugResponseSchema\n>;\nexport type BrowserbaseSessionCreateResponse = z.infer<\n typeof browserbaseSessionCreateResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport { askUserQuestionInputSchema } from \"../schemas/ask-user-question\";\nimport { buildApiSchema } from \"./agent-api\";\nimport { StoredAgentConfigSchema } from \"./agent-config\";\n\n/**\n * Zod schemas for build API requests and responses\n * These schemas are used for both backend validation and frontend type inference\n */\n\n/**\n * Schema for get build params\n */\nexport const getBuildParamsSchema = z.object({\n buildId: z.guid(),\n});\n\n/**\n * Schema for list builds params\n */\nexport const listBuildsParamsSchema = z.object({\n copilotId: z.guid(),\n});\n\n/**\n * Schema for updating a build\n */\nexport const updateBuildBodySchema = z.object({\n config: z.record(z.string(), z.any()).describe(\"Build configuration object\"),\n handoverTargetIds: z\n .array(z.guid())\n .optional()\n .describe(\"Agent IDs that this agent can hand over work to\"),\n});\n\n/**\n * Schema for creating a new build\n */\nexport const createBuildBodySchema = z.object({\n copilot_id: z.guid().describe(\"Agent ID\"),\n name: z.string().describe(\"Build name\"),\n config: z\n .record(z.string(), z.any())\n .optional()\n .describe(\"Build configuration object\"),\n handoverTargetIds: z\n .array(z.guid())\n .optional()\n .describe(\"Agent IDs that this agent can hand over work to\"),\n source_build_id: z\n .guid()\n .optional()\n .describe(\"Build ID to copy integrations and case queue links from\"),\n});\n\n/**\n * TypeScript type for create build request body\n */\nexport type CreateBuildBody = z.infer<typeof createBuildBodySchema>;\n\n/**\n * Schema for build API response\n */\nexport const buildResponseSchema = z.object({\n build_id: z.string().describe(\"Build ID\"),\n name: z.string().describe(\"Build name\"),\n config: z\n .record(z.string(), z.any())\n .nullable()\n .describe(\"Build configuration\"),\n copilot_id: z.string().describe(\"Associated copilot ID\"),\n status: z.string().describe(\"Build status\"),\n created_at: z.coerce.date().describe(\"Creation timestamp\"),\n updated_at: z.coerce.date().nullable().describe(\"Last update timestamp\"),\n revision_number: z.number().nullable().describe(\"Revision number\"),\n parent_build_id: z.string().nullable().describe(\"Parent build ID\"),\n created_by: z.string().nullable().describe(\"User who created this build\"),\n created_by_name: z\n .string()\n .nullable()\n .optional()\n .describe(\"Display name of the user who created this build\"),\n});\n\n/**\n * Schema for list of builds response\n */\nexport const listBuildsResponseSchema = z.array(buildResponseSchema);\n\n/**\n * TypeScript types for build responses\n */\nexport type BuildResponse = z.infer<typeof buildResponseSchema>;\n\n/**\n * Wrapper for single-build responses (GET /v1/agents/:agent_id/builds/:build_id).\n */\nexport const buildResponseApiSchema = z.object({\n build: buildApiSchema,\n});\n\n/**\n * Paginated list of builds for GET /v1/agents/:agent_id/builds.\n */\nexport const buildsListApiSchema = z.object({\n builds: z.array(buildApiSchema),\n total: z.int(),\n limit: z.int(),\n offset: z.int(),\n});\n\n/**\n * Response for POST /v1/agents/:agent_id/builds.\n */\nexport const createBuildResponseApiSchema = z.object({\n build: buildApiSchema,\n agent: z.object({\n id: z.guid(),\n }),\n});\n\nexport type BuildResponseApi = z.infer<typeof buildResponseApiSchema>;\nexport type BuildsListApi = z.infer<typeof buildsListApiSchema>;\nexport type CreateBuildResponseApi = z.infer<\n typeof createBuildResponseApiSchema\n>;\n\nexport const builderRunGenerateResponseSchema = z.object({\n status: z.literal(\"generating\"),\n builderRunId: z.string(),\n buildId: z.string(),\n});\n\nexport type BuilderRunGenerateResponse = z.infer<\n typeof builderRunGenerateResponseSchema\n>;\n\nconst BUILDER_RUN_STATUSES = [\n \"not_started\",\n \"running\",\n \"completed\",\n \"failed\",\n \"cancelled\",\n \"waiting_for_input\",\n \"waiting_for_approve\",\n] as const;\n\nexport type BuilderRunStatusValue = (typeof BUILDER_RUN_STATUSES)[number];\n\nexport const builderRunStatusSchema = z.object({\n id: z.string(),\n status: z.enum(BUILDER_RUN_STATUSES),\n build_id: z.string(),\n started_at: z.string().nullable(),\n completed_at: z.string().nullable(),\n checkpoint_config: StoredAgentConfigSchema.nullable(),\n pending_user_questions: askUserQuestionInputSchema.nullable(),\n schedule_suggested: z.boolean().optional(),\n});\n\nexport type BuilderRunStatus = z.infer<typeof builderRunStatusSchema>;\n", "import { z } from \"zod\";\n\n/**\n * The two terminal decisions an approver can submit. Anything else is rejected\n * by both the route handler and the DB CHECK constraint on\n * `case_approval_request.decision`.\n */\nexport const CASE_APPROVAL_DECISION = {\n APPROVED: \"approved\",\n REJECTED: \"rejected\",\n} as const;\n\nexport type CaseApprovalDecision =\n (typeof CASE_APPROVAL_DECISION)[keyof typeof CASE_APPROVAL_DECISION];\n\nexport const caseApprovalDecisionSchema = z.enum([\n CASE_APPROVAL_DECISION.APPROVED,\n CASE_APPROVAL_DECISION.REJECTED,\n]);\n\n/**\n * Public-safe shape for an open or recently-resolved case approval request.\n * Mirrors `case_approval_request` 1:1 \u2014 including `cancellation_reason`,\n * which is bounded server-side and only set on cancellation paths.\n */\nexport const caseApprovalRequestSchema = z.object({\n id: z.string().uuid(),\n case_queue_item_id: z.string().uuid(),\n agent_run_id: z.string().uuid(),\n team_id: z.string().uuid(),\n approver_user_id: z.string().uuid(),\n title: z.string(),\n prompt: z.string(),\n created_at: z.string(),\n resolved_at: z.string().nullable(),\n resolved_by_user_id: z.string().uuid().nullable(),\n decision: caseApprovalDecisionSchema.nullable(),\n cancelled_at: z.string().nullable(),\n cancellation_reason: z.string().nullable(),\n});\n\nexport type CaseApprovalRequest = z.infer<typeof caseApprovalRequestSchema>;\n\n/**\n * One row in the case-detail Approvals section: covers both unresolved and\n * resolved/cancelled requests. The approver and resolver profiles are joined\n * server-side so the UI can render names without a follow-up fetch.\n */\nexport const caseApprovalListItemSchema = z.object({\n id: z.string().uuid(),\n agent_run_id: z.string().uuid(),\n title: z.string(),\n prompt: z.string(),\n created_at: z.string(),\n\n approver_user_id: z.string().uuid(),\n approver_name: z.string().nullable(),\n approver_email: z.string().nullable(),\n\n decision: caseApprovalDecisionSchema.nullable(),\n resolved_at: z.string().nullable(),\n resolved_by_user_id: z.string().uuid().nullable(),\n resolved_by_name: z.string().nullable(),\n resolved_by_email: z.string().nullable(),\n\n cancelled_at: z.string().nullable(),\n cancellation_reason: z.string().nullable(),\n});\n\nexport type CaseApprovalListItem = z.infer<typeof caseApprovalListItemSchema>;\n\nexport const createCaseApprovalRequestBodySchema = z.object({\n agentRunId: z.string().uuid(),\n approverUserId: z.string().uuid(),\n title: z.string().trim().min(1).max(200),\n prompt: z.string().trim().min(1).max(2000),\n});\n\nexport type CreateCaseApprovalRequestBody = z.infer<\n typeof createCaseApprovalRequestBodySchema\n>;\n\nexport const createCaseApprovalRequestResponseSchema = z.object({\n id: z.string().uuid(),\n created_at: z.string(),\n});\n\nexport type CreateCaseApprovalRequestResponse = z.infer<\n typeof createCaseApprovalRequestResponseSchema\n>;\n\nexport const respondCaseApprovalRequestBodySchema = z.object({\n decision: caseApprovalDecisionSchema,\n});\n\nexport type RespondCaseApprovalRequestBody = z.infer<\n typeof respondCaseApprovalRequestBodySchema\n>;\n\nexport const respondCaseApprovalRequestResponseSchema = z.object({\n id: z.string().uuid(),\n resolved_at: z.string(),\n resolved_by_user_id: z.string().uuid(),\n decision: caseApprovalDecisionSchema,\n});\n\nexport type RespondCaseApprovalRequestResponse = z.infer<\n typeof respondCaseApprovalRequestResponseSchema\n>;\n\n/**\n * Tool input/output for the agent-callable `request_case_approval`. The agent\n * picks `approverUserId` from the candidate set surfaced in the system\n * prompt; the backend rejects anything outside the candidate set.\n */\nexport const requestCaseApprovalToolInputSchema = z.object({\n approverUserId: z.string().uuid(),\n title: z.string().trim().min(1).max(200),\n prompt: z.string().trim().min(1).max(2000),\n});\n\nexport type RequestCaseApprovalToolInput = z.infer<\n typeof requestCaseApprovalToolInputSchema\n>;\n\nexport const requestCaseApprovalToolOutputSchema = z.object({\n status: caseApprovalDecisionSchema,\n resolvedByUserId: z.string().uuid(),\n});\n\nexport type RequestCaseApprovalToolOutput = z.infer<\n typeof requestCaseApprovalToolOutputSchema\n>;\n", "import { z } from \"zod\";\n\nexport const filterValueSchema = z.object({\n value: z.string().min(1),\n name: z.string().min(1),\n});\n\nexport type FilterValue = z.infer<typeof filterValueSchema>;\n\nexport const filterCategorySchema = z.object({\n key: z.string(),\n name: z.string().min(1),\n selectionMode: z.enum([\"single\", \"multi\"]),\n values: z.array(filterValueSchema),\n});\n\nexport type FilterCategory = z.infer<typeof filterCategorySchema>;\n\nexport const caseFiltersResponseSchema = z.object({\n filters: z.array(filterCategorySchema),\n});\n\nexport type CaseFiltersResponse = z.infer<typeof caseFiltersResponseSchema>;\n", "import { z } from \"zod\";\n\nexport const caseQueueFolderResponseSchema = z.object({\n id: z.string(),\n name: z.string(),\n team_id: z.string(),\n parent_folder_id: z.string().nullable(),\n created_at: z.string(),\n updated_at: z.string(),\n});\n\nexport const caseQueueFoldersListResponseSchema = z.object({\n folders: z.array(caseQueueFolderResponseSchema),\n});\n\nexport const createCaseQueueFolderRequestSchema = z.object({\n name: z.string().min(1).max(100),\n parent_folder_id: z.guid().nullable().optional(),\n});\n\nexport const updateCaseQueueFolderRequestSchema = z.object({\n name: z.string().min(1).max(100).optional(),\n parent_folder_id: z.guid().nullable().optional(),\n});\n\nexport const moveQueuesToFolderRequestSchema = z.object({\n queue_ids: z.array(z.guid()).min(1),\n folder_id: z.guid().nullable(),\n});\n\nexport type CaseQueueFolderResponse = z.infer<\n typeof caseQueueFolderResponseSchema\n>;\nexport type CaseQueueFoldersListResponse = z.infer<\n typeof caseQueueFoldersListResponseSchema\n>;\nexport type CreateCaseQueueFolderRequest = z.infer<\n typeof createCaseQueueFolderRequestSchema\n>;\nexport type UpdateCaseQueueFolderRequest = z.infer<\n typeof updateCaseQueueFolderRequestSchema\n>;\nexport type MoveQueuesToFolderRequest = z.infer<\n typeof moveQueuesToFolderRequestSchema\n>;\n", "import { z } from \"zod\";\n\nexport const caseQueueLabelSchema = z.object({\n id: z.guid(),\n key: z.string(), // Empty string key means a simple tag (value-only); non-empty key creates a key-value categorization\n value: z.string().min(1),\n color_hue: z.int().min(0).max(360),\n});\n\nexport type CaseQueueLabel = z.infer<typeof caseQueueLabelSchema>;\n\nexport const caseLabelsListResponseSchema = z.object({\n labels: z.array(caseQueueLabelSchema),\n});\n\nexport type CaseLabelsListResponse = z.infer<\n typeof caseLabelsListResponseSchema\n>;\n\nexport const caseLabelAssignInputSchema = z.object({\n labels: z\n .array(\n z.object({\n key: z.string().optional().default(\"\"),\n value: z.string().min(1),\n })\n )\n .min(1)\n .max(50),\n});\n\nexport type CaseLabelAssignInput = z.infer<typeof caseLabelAssignInputSchema>;\n\nexport const caseLabelAssignResponseSchema = z.object({\n labels: z.array(caseQueueLabelSchema),\n});\n\nexport type CaseLabelAssignResponse = z.infer<\n typeof caseLabelAssignResponseSchema\n>;\n\nexport const caseLabelUpdateInputSchema = z.object({\n // key is a partial-update field: omit to leave the existing key unchanged.\n // Do NOT add `.default(\"\")` \u2014 a missing key must not silently relocate the\n // label into the empty-key (\"Labels\") bucket when the caller only wants to\n // change color or value.\n key: z.string().optional(),\n value: z.string().min(1),\n color_hue: z.int().min(0).max(360).optional(),\n});\n\nexport type CaseLabelRenameInput = z.infer<typeof caseLabelUpdateInputSchema>;\n\nexport const caseLabelUpdateResponseSchema = z.object({\n label: caseQueueLabelSchema,\n});\n\nexport type CaseLabelRenameResponse = z.infer<\n typeof caseLabelUpdateResponseSchema\n>;\n\nexport const caseLabelUnlinkInputSchema = z.object({\n label_ids: z.array(z.guid()).min(1),\n});\n\nexport type CaseLabelUnlinkInput = z.infer<typeof caseLabelUnlinkInputSchema>;\n\nexport const caseLabelUnlinkResponseSchema = z.object({\n success: z.boolean(),\n});\n\nexport type CaseLabelUnlinkResponse = z.infer<\n typeof caseLabelUnlinkResponseSchema\n>;\n\nexport const caseLabelCreateInputSchema = z.object({\n key: z.string().optional().default(\"\"),\n value: z.string().min(1),\n color_hue: z.int().min(0).max(360).optional(),\n});\n\nexport type CaseLabelCreateInput = z.infer<typeof caseLabelCreateInputSchema>;\n\nexport const caseLabelCreateResponseSchema = z.object({\n label: caseQueueLabelSchema.extend({\n case_count: z.int().min(0),\n }),\n});\n\nexport type CaseLabelCreateResponse = z.infer<\n typeof caseLabelCreateResponseSchema\n>;\n\nexport const caseQueueLabelWithCountSchema = caseQueueLabelSchema.extend({\n case_count: z.int().min(0),\n});\n\nexport type CaseQueueLabelWithCount = z.infer<\n typeof caseQueueLabelWithCountSchema\n>;\n\nexport const caseLabelsWithCountsListResponseSchema = z.object({\n labels: z.array(caseQueueLabelWithCountSchema),\n});\n\nexport type CaseLabelsWithCountsListResponse = z.infer<\n typeof caseLabelsWithCountsListResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport { conflictingAgentSchema } from \"./agent-api\";\n\nexport const caseTriggerApiSchema = z.object({\n id: z.string(),\n agent_id: z.string(),\n case_queue_id: z.string(),\n case_queue_name: z.string(),\n user_id: z.string(),\n enabled: z.boolean(),\n concurrency: z.int().positive().nullable(),\n created_at: z.string(),\n updated_at: z.string(),\n creator_display_name: z.string().nullable(),\n can_disable: z.boolean(),\n has_conflict: z.boolean(),\n conflicting_agents: z.array(conflictingAgentSchema),\n});\n\nexport type CaseTriggerApi = z.infer<typeof caseTriggerApiSchema>;\n\nexport const caseTriggerResponseSchema = z.object({\n case_trigger: caseTriggerApiSchema,\n});\n\nexport type CaseTriggerResponse = z.infer<typeof caseTriggerResponseSchema>;\n\nexport const caseTriggersListResponseSchema = z.object({\n case_triggers: z.array(caseTriggerApiSchema),\n});\n\nexport type CaseTriggersListResponse = z.infer<\n typeof caseTriggersListResponseSchema\n>;\n\nexport const deleteCaseTriggerResponseSchema = z.object({\n success: z.literal(true),\n});\n\nexport type DeleteCaseTriggerResponse = z.infer<\n typeof deleteCaseTriggerResponseSchema\n>;\n\nconst integrationConfigMinSchema = z.object({\n id: z.string(),\n integration_id: z.guid().nullable(),\n integration_type: z.string(),\n});\n\nexport const integrationConfigsResponseSchema = z.object({\n integrations: z.array(integrationConfigMinSchema),\n});\n\nconst caseQueueMinSchema = z.object({\n id: z.string(),\n name: z.string(),\n});\n\nexport const caseQueuesForSlotResponseSchema = z.object({\n queues: z.array(caseQueueMinSchema),\n});\n\nexport type IntegrationConfigsResponse = z.infer<\n typeof integrationConfigsResponseSchema\n>;\n\nexport type CaseQueuesForSlotResponse = z.infer<\n typeof caseQueuesForSlotResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport { agentMessageSchema } from \"../schemas/automation-message\";\nimport { evalSummarySchema } from \"../schemas/run-evaluation\";\nimport { agentRunStatusSchema } from \"./agent-run\";\nimport { caseApprovalListItemSchema } from \"./case-approval\";\nimport { caseQueueLabelSchema } from \"./case-queue-labels\";\n\nexport const caseQueueItemSchema = z.object({\n id: z.guid(),\n queue_id: z.guid(),\n title: z.string(),\n data: z.string(),\n status: z.enum([\"pending\", \"claimed\", \"completed\", \"failed\"]),\n claimed_at: z.string().nullable(),\n claimed_by_run_id: z.string().nullable(),\n completed_at: z.string().nullable(),\n /** When the case is scheduled to be re-handled (null if not postponed) */\n postponed_to: z.string().nullable(),\n created_at: z.string(),\n updated_at: z.string(),\n created_by_user_id: z.guid().nullable(),\n created_by_user_name: z.string().nullable(),\n created_by_user_email: z.string().nullable(),\n /** Status of the associated agent run (running, waiting, etc.) - null if no active run */\n agent_run_status: z.string().nullable(),\n /** User ID of the owner of the active agent run - null if no active run */\n agent_run_user_id: z.guid().nullable(),\n /** ID of the pending human request for cases waiting for input */\n pending_human_request_id: z.guid().nullable(),\n /** ID of the open case_approval_request bound to this case, if any. Used to derive the `awaiting_approval` UI state. */\n pending_approval_request_id: z.guid().nullable(),\n /** User ID of the approver named on the open `case_approval_request`. Used to switch the badge to \"Awaiting your approval\" for the named approver. */\n pending_approval_approver_user_id: z.guid().nullable(),\n /** Number of resolved approval requests on this case with `decision = 'approved'`. */\n approval_approved_count: z.int().nonnegative(),\n /** Number of resolved approval requests on this case with `decision = 'rejected'`. */\n approval_rejected_count: z.int().nonnegative(),\n /** Snippet from the data field showing search match context. Only present when search matches data. */\n search_match_data_snippet: z\n .object({\n before: z.string(),\n match: z.string(),\n after: z.string(),\n })\n .optional(),\n labels: z.array(caseQueueLabelSchema),\n});\n\nexport type CaseQueueItem = z.infer<typeof caseQueueItemSchema>;\n\nexport const caseQueueItemEventSchema = z.object({\n id: z.guid(),\n case_queue_item_id: z.guid(),\n agent_run_id: z.guid().nullable(),\n human_request_id: z.guid().nullable(),\n type: z.string(),\n created_at: z.string(),\n agent_id: z.guid().nullable(),\n agent_name: z.string().nullable(),\n /**\n * Owner of the agent run referenced by this event (joined from\n * `agent_run.user_id`). The frontend mirrors the backend\n * `assertCanAccessRun` gate against this id + the viewer's team role to\n * decide whether the row should expose a click affordance.\n */\n user_id: z.guid().nullable(),\n user_name: z.string().nullable(),\n user_email: z.string().nullable(),\n human_request_title: z.string().nullable(),\n});\n\nexport type CaseQueueItemEvent = z.infer<typeof caseQueueItemEventSchema>;\n\nexport const casesListResponseSchema = z.object({\n cases: z.array(caseQueueItemSchema),\n total: z.number(),\n limit: z.int(),\n offset: z.int(),\n});\n\nexport type CasesListResponse = z.infer<typeof casesListResponseSchema>;\n\nexport const caseCreateInputSchema = z.object({\n title: z\n .string()\n .min(1)\n .max(500)\n .describe(\n \"Short title for the case (max 500 characters). Put long context in `data`.\"\n ),\n data: z\n .string()\n .optional()\n .describe(\n \"Additional data for the case. Free-form text or JSON; Assignments receive this on claim.\"\n ),\n labels: z\n .array(\n z.object({\n key: z\n .string()\n .optional()\n .default(\"\")\n .describe(\"Label key (omit for a simple tag).\"),\n value: z.string().min(1).describe(\"Label value (required).\"),\n })\n )\n .max(50)\n .optional()\n .describe(\n \"Optional labels to assign to the case at creation. Labels are created on the queue if they don't already exist.\"\n ),\n});\n\nexport type CaseCreateInput = z.infer<typeof caseCreateInputSchema>;\n\nexport const caseCreateRequestSchema = z\n .object({\n case: caseCreateInputSchema.optional(),\n cases: z.array(caseCreateInputSchema).min(1).max(100).optional(),\n })\n .superRefine((val, ctx) => {\n const hasCase = val.case !== undefined;\n const hasCases = val.cases !== undefined;\n if (hasCase && hasCases) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Provide either `case` or `cases`, not both.\",\n });\n return;\n }\n\n if (!hasCase && !hasCases) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Provide exactly one of `case` or `cases`.\",\n });\n }\n });\n\nexport type CaseCreateRequest = z.infer<typeof caseCreateRequestSchema>;\n\nexport const caseCreateResponseSchema = z.object({\n added_cases: z.array(caseQueueItemSchema),\n});\n\nexport type CaseCreateResponse = z.infer<typeof caseCreateResponseSchema>;\n\nexport const casesStatsSchema = z.object({\n total: z.number(),\n pending: z.number(),\n claimed: z.number(),\n /** Count of claimed cases waiting for human input (run status = waiting) */\n waiting: z.number(),\n /** Count of pending cases that are postponed for later */\n postponed: z.number(),\n completed: z.number(),\n failed: z.number(),\n});\n\nexport const casesStatsResponseSchema = z.object({\n stats: casesStatsSchema,\n});\n\nexport type CasesStatsResponse = z.infer<typeof casesStatsResponseSchema>;\n\nexport const caseDetailResponseSchema = z.object({\n case: caseQueueItemSchema,\n events: z.array(caseQueueItemEventSchema),\n /**\n * Every approval request ever created for this case \u2014 pending, resolved,\n * and cancelled \u2014 ordered by `created_at` ascending. The case-detail\n * Approvals section renders these inline; the unresolved row (if any) is\n * the only one with response affordances and matches\n * `case.pending_approval_request_id`.\n */\n case_approval_requests: z.array(caseApprovalListItemSchema),\n});\n\nexport type CaseDetailResponse = z.infer<typeof caseDetailResponseSchema>;\n\n/**\n * Summary of one Job (agent run) associated with a case, used by the\n * Activity timeline on the case detail page.\n *\n * `claimed_at` is the timestamp of the `claimed` case event that started\n * this run on this case \u2014 the timeline uses it as the Job card's anchor\n * so a single run that claims/releases multiple times renders as multiple\n * cards in correct chronological order.\n */\nexport const caseJobSummarySchema = z.object({\n id: z.string().uuid(),\n case_queue_item_id: z.string().uuid(),\n agent_id: z.string().uuid(),\n agent_name: z.string(),\n status: agentRunStatusSchema,\n source: z.string().nullable(),\n created_at: z.string(),\n started_at: z.string().nullable(),\n completed_at: z.string().nullable(),\n claimed_at: z.string(),\n has_pending_human_request: z.boolean(),\n pending_human_request_title: z.string().nullable(),\n evaluation: evalSummarySchema,\n /**\n * Owner of the agent run (from `agent_run.user_id`). The frontend mirrors\n * the backend `assertCanAccessRun` gate against this id + the viewer's\n * team role to decide whether the card is interactive (live messages,\n * HITL affordances, drawer link).\n */\n user_id: z.guid().nullable(),\n /**\n * Display name of the user who triggered the run, joined from `profiles`.\n * Falls back to `user_email` for the in-card user pill when null.\n */\n user_name: z.string().nullable(),\n user_email: z.string().nullable(),\n});\n\nexport type CaseJobSummary = z.infer<typeof caseJobSummarySchema>;\n\nexport const caseJobsResponseSchema = z.object({\n runs: z.array(caseJobSummarySchema),\n});\n\nexport type CaseJobsResponse = z.infer<typeof caseJobsResponseSchema>;\n\n/**\n * Latest qualifying messages (assistant text + tool calls) for a running\n * Job, streamed into the Activity timeline card body. Newest last so the\n * card reads top-to-bottom.\n */\nexport const caseJobRecentMessagesResponseSchema = z.object({\n messages: z.array(agentMessageSchema),\n});\n\nexport type CaseJobRecentMessagesResponse = z.infer<\n typeof caseJobRecentMessagesResponseSchema\n>;\n\nexport const adjacentCasesResponseSchema = z.object({\n previousId: z.guid().nullable(),\n nextId: z.guid().nullable(),\n position: z.number(),\n total: z.number(),\n});\n\nexport type AdjacentCasesResponse = z.infer<typeof adjacentCasesResponseSchema>;\n\nexport type CaseStatus = \"pending\" | \"claimed\" | \"completed\" | \"failed\";\n\nexport const caseDeleteResponseSchema = z.object({\n success: z.boolean(),\n interruptedRunIds: z.array(z.guid()),\n});\n\nexport type CaseDeleteResponse = z.infer<typeof caseDeleteResponseSchema>;\n\nexport const caseBulkDeleteResponseSchema = z.object({\n deletedCount: z.number(),\n interruptedRunIds: z.array(z.guid()),\n});\n\nexport const caseBulkRetryResponseSchema = z.object({\n retriedCount: z.number(),\n skippedCount: z.number(),\n});\n\nexport type CaseBulkRetryResponse = z.infer<typeof caseBulkRetryResponseSchema>;\n\nexport const caseBulkDelegateResponseSchema = z.object({\n delegatedCount: z.number(),\n skippedCount: z.number(),\n});\n\nexport type CaseBulkDelegateResponse = z.infer<\n typeof caseBulkDelegateResponseSchema\n>;\n\nexport const caseBulkStatusUpdateResponseSchema = z.object({\n updatedCount: z.number(),\n skippedCount: z.number(),\n interruptedRunIds: z.array(z.guid()),\n});\n\nexport type CaseBulkStatusUpdateResponse = z.infer<\n typeof caseBulkStatusUpdateResponseSchema\n>;\n\nexport const deleteQueueResponseSchema = z.object({\n success: z.boolean(),\n deleted_case_count: z.number(),\n interrupted_run_ids: z.array(z.guid()),\n});\n\nexport type DeleteQueueResponse = z.infer<typeof deleteQueueResponseSchema>;\n\nexport type CaseBulkDeleteResponse = z.infer<\n typeof caseBulkDeleteResponseSchema\n>;\n\nexport const caseClearQueueResponseSchema = z.object({\n success: z.boolean(),\n deletedCount: z.number(),\n interruptedRunIds: z.array(z.guid()),\n});\n\nexport type CaseClearQueueResponse = z.infer<\n typeof caseClearQueueResponseSchema\n>;\n\nexport const caseQueueSchema = z.object({\n id: z.guid(),\n name: z.string(),\n description: z.string().nullable(),\n folder_id: z.guid().nullable(),\n created_at: z.string(),\n /**\n * True when at least one case in this queue has ever had a\n * case_approval_request (pending, resolved, or cancelled). The frontend\n * uses this to relabel the \"Needs input\" filter to \"Needs input/approval\"\n * and to show the per-case approvals column.\n */\n has_approvals: z.boolean(),\n});\n\nexport type CaseQueue = z.infer<typeof caseQueueSchema>;\n\nexport const caseQueuesResponseSchema = z.object({\n queues: z.array(caseQueueSchema),\n total: z.number(),\n limit: z.number(),\n offset: z.number(),\n});\n\nexport type CaseQueuesResponse = z.infer<typeof caseQueuesResponseSchema>;\n\nexport const caseGetQueueResponseSchema = z.object({\n queue: caseQueueSchema,\n});\n\nexport type CaseGetQueueResponse = z.infer<typeof caseGetQueueResponseSchema>;\n\nexport const caseCreateQueueResponseSchema = z.object({\n queue: caseQueueSchema,\n});\n\nexport const caseUpdateQueueResponseSchema = z.object({\n queue: caseQueueSchema,\n});\n\nexport type CaseCreateQueueResponse = z.infer<\n typeof caseCreateQueueResponseSchema\n>;\n\nexport const caseQueueAgentProblemSchema = z.enum([\n \"multiple_triggers\",\n \"producer_consumer_mix\",\n]);\n\nexport type CaseQueueAgentProblem = z.infer<typeof caseQueueAgentProblemSchema>;\n\nexport const queueAgentProducerSchema = z.object({\n agent_id: z.guid(),\n agent_name: z.string(),\n case_trigger_enabled: z.boolean(),\n case_trigger_queue_name: z.string().nullable(),\n problems: z.array(caseQueueAgentProblemSchema),\n});\n\nexport const queueAgentConsumerSchema = z.object({\n agent_id: z.guid(),\n agent_name: z.string(),\n case_trigger_enabled: z.boolean(),\n is_handover_target: z.boolean(),\n problems: z.array(caseQueueAgentProblemSchema),\n});\n\nexport const queueAgentsResponseSchema = z.object({\n queue_name: z.string(),\n producers: z.array(queueAgentProducerSchema),\n consumers: z.array(queueAgentConsumerSchema),\n});\n\nexport type QueueAgentProducer = z.infer<typeof queueAgentProducerSchema>;\nexport type QueueAgentConsumer = z.infer<typeof queueAgentConsumerSchema>;\nexport type QueueAgentsResponse = z.infer<typeof queueAgentsResponseSchema>;\n\nexport const exportCasesResponseSchema = z.object({\n version: z.number(),\n queue_name: z.string(),\n exported_at: z.string(),\n cases: z.array(\n z.object({\n title: z.string(),\n data: z.string().optional(),\n })\n ),\n});\n\nexport type ExportCasesResponse = z.infer<typeof exportCasesResponseSchema>;\n\nexport const importCasesResponseSchema = z.object({\n imported_count: z.number(),\n});\n\nexport type ImportCasesResponse = z.infer<typeof importCasesResponseSchema>;\n\nexport const batchQueueStatsResponseSchema = z.object({\n stats: z.record(z.guid(), casesStatsSchema),\n});\n\nexport type BatchQueueStatsResponse = z.infer<\n typeof batchQueueStatsResponseSchema\n>;\n\nexport const batchQueueAgentsResponseSchema = z.object({\n agents: z.record(\n z.guid(),\n z.object({\n producers: z.array(queueAgentProducerSchema),\n consumers: z.array(queueAgentConsumerSchema),\n })\n ),\n});\n\nexport type BatchQueueAgentsResponse = z.infer<\n typeof batchQueueAgentsResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport { conversationMessageSchema } from \"./clarity\";\n\n// === Clarity Overview Status ===\n\nexport const CLARITY_OVERVIEW_STATUSES = [\n \"draft\",\n \"collecting\",\n \"generating\",\n \"review\",\n \"complete\",\n \"generation_failed\",\n] as const;\n\nexport type ClarityOverviewStatus = (typeof CLARITY_OVERVIEW_STATUSES)[number];\nexport const clarityOverviewStatusSchema = z.enum(CLARITY_OVERVIEW_STATUSES);\n\n// === Capture Status & Type ===\n\nexport const CLARITY_OVERVIEW_CAPTURE_STATUSES = [\n \"pending\",\n \"recording\",\n \"processing\",\n \"complete\",\n \"failed\",\n] as const;\n\nexport type ClarityOverviewCaptureStatus =\n (typeof CLARITY_OVERVIEW_CAPTURE_STATUSES)[number];\n\nexport const CLARITY_OVERVIEW_CAPTURE_TYPES = [\n \"video\",\n \"interview\",\n \"document\",\n \"screenshare\",\n] as const;\n\nexport type ClarityOverviewCaptureType =\n (typeof CLARITY_OVERVIEW_CAPTURE_TYPES)[number];\n\n// === Capture Schema ===\n\nexport const clarityOverviewCaptureSchema = z.object({\n id: z.guid(),\n overviewId: z.guid(),\n userId: z.guid(),\n userName: z.string().optional(),\n type: z.enum(CLARITY_OVERVIEW_CAPTURE_TYPES),\n videoUrl: z.string().nullable(),\n videoTranscript: z.string().nullable(),\n transcript: z.array(conversationMessageSchema).nullable(),\n status: z.enum(CLARITY_OVERVIEW_CAPTURE_STATUSES),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n});\n\nexport type ClarityOverviewCapture = z.infer<\n typeof clarityOverviewCaptureSchema\n>;\n\n// === Department Overview Sections ===\n\nconst OverviewKpi = z.object({\n id: z.guid(),\n name: z.string(),\n value: z.string(),\n description: z.string(),\n});\n\nconst OverviewHeadcount = z.object({\n approximate: z.int().nonnegative(),\n notes: z.string().optional(),\n});\n\nconst OverviewTeamMember = z.object({\n id: z.guid(),\n name: z.string(),\n role: z.string(),\n});\n\nconst OverviewTeam = z.object({\n id: z.guid(),\n name: z.string(),\n leadId: z.guid().nullable(),\n description: z.string(),\n memberCount: z.int().nonnegative().optional(),\n people: z.array(OverviewTeamMember),\n});\n\nconst OverviewInsight = z.object({\n id: z.guid(),\n title: z.string(),\n description: z.string(),\n});\n\nconst OverviewHelpNeeded = z.object({\n id: z.guid(),\n title: z.string(),\n description: z.string(),\n fromWhom: z.string(),\n});\n\nconst DepartmentOverview = z.object({\n mission: z.string().nullable(),\n kpis: z.array(OverviewKpi),\n headcount: OverviewHeadcount.nullable(),\n teams: z.array(OverviewTeam),\n worksWell: z.array(OverviewInsight),\n doesNotWorkWell: z.array(OverviewInsight),\n needsHelp: z.array(OverviewHelpNeeded),\n});\n\n// === Enums ===\n\nconst DocumentationStatus = z.enum([\"documented\", \"draft\", \"not_started\"]);\n\nconst VulnerabilitySeverity = z.enum([\"warning\", \"critical\"]);\n\n/**\n * Tags applied to people within a process to indicate their\n * accountability type. Rendered as colored badges in the UI.\n * A person with no tags is a regular participant.\n */\nconst AccountabilityTag = z.enum([\n \"owner\", // Decision-maker, shown with \"owner\" badge\n \"spof\", // Single point of failure \u2014 highlighted as risk\n \"external\", // Outside the org (e.g. Supplier)\n \"notified\", // Receives updates but doesn't act (e.g. Supply Chain)\n]);\n\n// === Systems ===\n\nconst SystemRef = z.object({\n /** Stable identifier for the system, used for deduplication across processes */\n id: z.string(),\n /** Display name as it appears in the UI: \"Product Pantry\", \"Rohlik Admin\", \"Google Sheets\" */\n name: z.string(),\n /** URL to the system's icon/logo. Null if we don't have one \u2014 FE shows a generic fallback */\n iconUrl: z.url().nullable(),\n});\n\n// === People & Roles ===\n\nconst PersonRole = z.object({\n id: z.guid(),\n /** Person's display name: \"Tereza\", \"Kristyna\" */\n name: z.string(),\n /**\n * Their role title within this process, not their org-wide job title.\n * e.g. \"Listing Specialist\", \"Senior Category Manager\"\n */\n role: z.string(),\n /**\n * Accountability tags for this person within THIS process.\n * Same person can be \"owner\" in one process and have no tags in another.\n */\n tags: z.array(AccountabilityTag).default([]),\n /**\n * Full-time equivalent headcount allocated to this role.\n * Optional \u2014 only set when the capture interview surfaced it.\n * e.g. 2.25 FTE for a Listing Specialist team of 3 part-timers.\n */\n fte: z.number().positive().optional(),\n});\n\n// === Vulnerabilities (rendered as \"risks\" on overview cards) ===\n\nconst Vulnerability = z.object({\n id: z.guid(),\n /** Warning = operational concern, Critical = structural/blocking risk */\n severity: VulnerabilitySeverity,\n /**\n * Human-readable description surfaced from the interview.\n * e.g. \"Tereza alone covers fresh listing\"\n * e.g. \"75-95% of obvious approvals still needs human\"\n */\n description: z.string(),\n /**\n * IDs of people directly tied to this vulnerability.\n * Enables FE to highlight affected people in the detail view.\n * e.g. SPOF vulnerability \u2192 [terezaId]\n */\n affectedPersonIds: z.array(z.string()).optional(),\n});\n\n// === Friction Signals ===\n\nconst FrictionSignal = z.object({\n id: z.guid(),\n /**\n * Operational pain point captured during interview.\n * e.g. \"40 unresolved bugs, periodic outages\"\n * These feed into the maturity score (future iteration) as penalties.\n */\n description: z.string(),\n /** Systems where this friction manifests \u2014 used for cross-referencing */\n relatedSystemIds: z.array(z.string()).optional(),\n});\n\n// === Process (full detail \u2014 returned by GET /processes/:id) ===\n\nconst Process = z.object({\n id: z.guid(),\n /** Process name as displayed in card headers: \"Product Listing\", \"Price Proposals\" */\n name: z.string(),\n /**\n * Tracks where this process is in the Clarity documentation pipeline.\n * - \"documented\": fully captured and reviewed\n * - \"draft\": interview done, output not yet validated\n * - \"not_started\": identified but not yet interviewed\n */\n documentationStatus: DocumentationStatus,\n clarityProcessId: z.guid().nullable().optional(),\n\n // --- Content ---\n\n /**\n * Short summary for overview cards (1-2 sentences).\n * e.g. \"End-to-end workflow of listing new products into the catalog...\"\n */\n summary: z.string(),\n /**\n * Rich description shown in the detail panel.\n * May include emphasized metrics (FE handles bold rendering).\n * e.g. \"Listing **660\u2013880 new SKUs every month** from the commercial decision...\"\n */\n description: z.string(),\n /**\n * Authored narrative describing the system flow / toolchain.\n * Comes from the Duvo capture output, not computed.\n * e.g. \"Product Pantry portal \u2192 Rohlik Admin backend \u2192 ChatGPT for description rewrites \u2192 ...\"\n */\n systemNarrative: z.string().optional(),\n /**\n * Authored narrative describing who does what and how accountability flows.\n * e.g. \"Senior CMs decide. Junior CMs configure. The Listing Specialist team finalizes everything.\"\n */\n accountabilityNarrative: z.string().optional(),\n /**\n * Free-text frequency because the real-world cadences are too varied to enumerate.\n * e.g. \"Continuous\", \"Weekly + monthly slowmover\", \"10\u201315 per CM / month\", \"Ad-hoc, no fixed cadence\"\n */\n frequency: z.string(),\n\n // --- Relations ---\n\n people: z.array(PersonRole),\n systems: z.array(SystemRef),\n vulnerabilities: z.array(Vulnerability),\n frictionSignals: z.array(FrictionSignal),\n});\n\n// === API Responses ===\n\n/**\n * GET /api/clarity/overview\n *\n * Returns everything needed to render the overview dashboard:\n * - Aggregate KPIs (processCount, singlePointOfFailureCount) computed on the fly\n * - Slim process cards with just enough data to render the grid\n *\n * The overview intentionally avoids sending full descriptions,\n * narratives, friction signals, and maturity breakdowns \u2014 those\n * are fetched on-demand via the detail endpoint.\n */\nconst ProcessOverviewItem = Process.extend({\n /**\n * Pre-computed count so FE doesn't need to re-count the people array.\n * Displayed as \"5 involved\" on overview cards.\n */\n peopleCount: z.int(),\n\n /**\n * First N systems (typically 4) to render the icon row.\n */\n systemPreviews: z.array(SystemRef),\n\n /**\n * How many systems beyond systemPreviews exist.\n * Rendered as \"+3\" badge after the icon row. 0 means all systems fit.\n */\n systemOverflowCount: z.int().default(0),\n});\n\nconst ClarityOverviewResponse = z.object({\n /** Explicit count for the \"Processes Captured\" KPI tile */\n processCount: z.int(),\n /**\n * Count of processes with at least one SPOF vulnerability.\n * Powers the \"Single point of failure\" KPI tile.\n */\n singlePointOfFailureCount: z.int(),\n processes: z.array(ProcessOverviewItem),\n\n // Department-level overview sections\n mission: z.string().nullable(),\n kpis: z.array(OverviewKpi),\n headcount: OverviewHeadcount.nullable(),\n teams: z.array(OverviewTeam),\n worksWell: z.array(OverviewInsight),\n doesNotWorkWell: z.array(OverviewInsight),\n needsHelp: z.array(OverviewHelpNeeded),\n});\n\n/**\n * GET /api/clarity/processes/:id\n *\n * Returns the full process detail for the side panel / detail view.\n */\nconst ProcessDetailResponse = Process;\n\nexport type ClarityOverviewResponse = z.infer<typeof ClarityOverviewResponse>;\nexport type ProcessDetailResponse = z.infer<typeof ProcessDetailResponse>;\nexport type ProcessOverviewItem = z.infer<typeof ProcessOverviewItem>;\n\n// === Detail Schema ===\n\nexport const clarityOverviewDetailSchema = z.object({\n id: z.guid(),\n teamId: z.guid(),\n userId: z.guid(),\n status: clarityOverviewStatusSchema,\n processCount: z.int(),\n singlePointOfFailureCount: z.int(),\n processes: z.array(ProcessOverviewItem),\n\n // Department-level overview sections\n mission: z.string().nullable(),\n kpis: z.array(OverviewKpi),\n headcount: OverviewHeadcount.nullable(),\n teams: z.array(OverviewTeam),\n worksWell: z.array(OverviewInsight),\n doesNotWorkWell: z.array(OverviewInsight),\n needsHelp: z.array(OverviewHelpNeeded),\n\n generationError: z.string().nullable(),\n captures: z.array(clarityOverviewCaptureSchema),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n});\n\nexport type ClarityOverviewDetail = z.infer<typeof clarityOverviewDetailSchema>;\n\nexport {\n AccountabilityTag,\n ClarityOverviewResponse,\n DepartmentOverview,\n DocumentationStatus,\n FrictionSignal,\n OverviewHeadcount,\n OverviewHelpNeeded,\n OverviewInsight,\n OverviewKpi,\n OverviewTeam,\n OverviewTeamMember,\n PersonRole,\n Process,\n ProcessDetailResponse,\n ProcessOverviewItem,\n SystemRef,\n Vulnerability,\n VulnerabilitySeverity,\n};\n", "import type { IntegrationSlug } from \"./integration\";\n\ntype ComposioAppSpec = {\n slug: IntegrationSlug;\n auth_config?: {\n type: string;\n credentials?: Record<string, string | boolean | number>;\n authScheme?: string;\n };\n};\n\nexport const COMPOSIO_AUTH_CONFIGS: ComposioAppSpec[] = [\n { slug: \"googledocs\" },\n { slug: \"googlesheets\" },\n { slug: \"googlecalendar\" },\n { slug: \"slack\" },\n { slug: \"googledrive\" },\n { slug: \"confluence\" },\n { slug: \"outlook\" },\n {\n slug: \"firecrawl\",\n auth_config: {\n type: \"use_custom_auth\",\n credentials: {},\n authScheme: \"API_KEY\",\n },\n },\n {\n slug: \"shopify\",\n auth_config: {\n type: \"use_custom_auth\",\n credentials: {},\n authScheme: \"API_KEY\",\n },\n },\n { slug: \"zendesk\" },\n { slug: \"intercom\" },\n];\n", "import { z } from \"zod\";\n\n// ============================================================================\n// Credential Preview - returned when listing credentials\n// ============================================================================\n\nexport const credentialPreviewSchema = z.object({\n id: z.guid().describe(\"Credential ID\"),\n domain: z.string().describe(\"Domain for the credential\"),\n username: z.string().nullable().describe(\"Username (if any)\"),\n hasEnabledTOTP: z.boolean().describe(\"Whether TOTP is enabled\"),\n hasPassword: z.boolean().describe(\"Whether a password is stored\"),\n user_id: z\n .string()\n .nullable()\n .describe(\"Owner user id; null when shared with the team\"),\n});\n\nexport type CredentialPreview = z.infer<typeof credentialPreviewSchema>;\n\n// ============================================================================\n// OTP Response - returned when generating a TOTP code\n// ============================================================================\n\nexport const otpResponseSchema = z.object({\n code: z.string().describe(\"The TOTP code\"),\n expiresAt: z.number().describe(\"Expiration timestamp in milliseconds\"),\n});\n\nexport type OtpResponse = z.infer<typeof otpResponseSchema>;\n\n// ============================================================================\n// Encrypted Data - used for storing encrypted passwords/secrets\n// ============================================================================\n\nexport const encryptedDataSchema = z.object({\n encrypted_data: z.string().describe(\"Base64-encoded encrypted data\"),\n key_version: z.string().describe(\"KMS key version or 'base64' for dev\"),\n});\n\nexport type EncryptedData = z.infer<typeof encryptedDataSchema>;\n\n// ============================================================================\n// Credential Detail - returned when fetching full credential details\n// ============================================================================\n\nexport const credentialDetailSchema = z.object({\n domain: z.string().describe(\"Domain for the credential\"),\n username: z.string().nullable().describe(\"Username (if any)\"),\n password: encryptedDataSchema.nullable().describe(\"Encrypted password data\"),\n});\n\nexport type CredentialDetail = z.infer<typeof credentialDetailSchema>;\n\n// ============================================================================\n// API Response types for credential endpoints\n// ============================================================================\n\n/**\n * Raw API response item from the credentials list endpoint.\n * Used for typing the JSON response before mapping to CredentialPreview.\n */\nexport type CredentialPreviewApiResponse = {\n id: string;\n domain: string;\n username: string | null;\n hasEnabledTOTP: boolean;\n hasPassword: boolean;\n user_id: string | null;\n};\n", "/**\n * Feature flag catalogue.\n *\n * Each entry maps an enum key to its database key, default value, and description.\n * The description should explain the flag's purpose and what it affects.\n *\n * Please keep this sorted alphabetically for easy scanning.\n */\n\ninterface FeatureFlagEntry {\n key: string;\n defaultValue: FeatureFlagValue;\n description: string;\n}\n\nexport const FEATURE_FLAG_CATALOGUE = {\n AGENTIC_MEMORY_TEAM_WIDE: {\n key: \"agentic_memory_team_wide\",\n defaultValue: false,\n description:\n \"Enables team-wide agentic memory. When active, newly created agents default to persistent memory and existing agents can also be enabled for persistent memory across runs.\",\n },\n AGENT_SELF_SCHEDULING: {\n key: \"agent_self_scheduling\",\n defaultValue: false,\n description:\n \"Injects the always-on scheduling MCP into agent runs so the agent can call CronCreate/CronList/CronUpdate/CronDelete to manage its own schedules. When off, the scheduling MCP is not injected and the agent cannot create or modify schedules from inside a run; user-created schedules and the cron dispatcher are unaffected.\",\n },\n BUILDER_ADVANCED_CONFIG: {\n key: \"builder_advanced_config\",\n defaultValue: false,\n description:\n \"Shows the Advanced configuration editor in the assignment builder, allowing raw JSON editing of the agent configuration.\",\n },\n BUILDER_BROWSER_LOGIN_NUDGE: {\n key: \"builder_browser_login_nudge\",\n defaultValue: false,\n description:\n \"Displays a nudge prompting users to add browser login credentials when their assignment uses browser integration but has no configured logins.\",\n },\n BUILDER_DRAFT_APPROVAL: {\n key: \"builder_draft_approval\",\n defaultValue: false,\n description:\n \"Enables the draft approval flow in the assignment builder. When enabled, AI-generated SOPs pause at waiting_for_approve for user review instead of auto-completing.\",\n },\n BUILDER_PLUGINS: {\n key: \"builder_plugins\",\n defaultValue: false,\n description:\n \"Enables the plugin selector UI in the assignment builder for managing plugins.\",\n },\n SUB_ASSIGNMENTS: {\n key: \"sub_assignments\",\n defaultValue: false,\n description:\n \"Enables the Sub-Assignments selector row in the assignment builder, letting an assignment delegate work to other assignments in the team.\",\n },\n BROWSING_PLUGIN_AUTO_SYNC: {\n key: \"browsing_plugin_auto_sync\",\n defaultValue: false,\n description:\n \"Automatically syncs browser integration connections from AI-generated tool recommendations during assignment generation and editing.\",\n },\n CASE_APPROVAL: {\n key: \"case_approval\",\n defaultValue: false,\n description:\n \"Enables the case approval feature end-to-end: SOP authors can @-mention team members in the assignment SOP textarea (serialized as <DUVO:USER> tags), agents can request human approval on cases via the request_case_approval tool, and approvers see and respond to pending requests on the case. Off-by-default for staged rollout.\",\n },\n CLARITY_ON_DISK_CAPTURES: {\n key: \"clarity_on_disk_captures\",\n defaultValue: false,\n description:\n \"When enabled, the Clarity generation agent receives capture content (transcripts, documents, video transcripts, screenshare frames) as files on the sandbox filesystem and is instructed to read them via a hard checklist, instead of having the content inlined into the prompt.\",\n },\n CLARITY_OVERVIEW: {\n key: \"clarity_overview\",\n defaultValue: false,\n description:\n \"Enables the Clarity Overview executive dashboard showing high-level process KPIs, maturity scores, and drill-down cards across all captured processes.\",\n },\n CLARITY_PROCESS_GUIDANCE: {\n key: \"clarity_process_guidance\",\n defaultValue: false,\n description:\n \"Enables the Process Guidance editor on Clarity processes, letting privileged users add custom context that steers the interview agent and documentation generation.\",\n },\n CLARITY_SCREENSHARE: {\n key: \"clarity_screenshare\",\n defaultValue: false,\n description:\n \"Enables the Clarity guided session flow (screen capture + voice + live preview). When on, the /clarity landing page routes Get Started / Document Process into the session flow at /clarity/start.\",\n },\n CLARITY_V2: {\n key: \"clarity_v2\",\n defaultValue: false,\n description:\n \"Enables the Clarity v2 architecture: typed snapshot tables (clarity_current_process, clarity_transformation_proposal), the P1-P4 pipelines, the v2 read model, and the v2 process page (/clarity/v2/[id]) with end-to-end use of /v1/clarity-v2/* endpoints.\",\n },\n DYNAMIC_BUILDER_ISLAND: {\n key: \"dynamic_builder_island\",\n defaultValue: false,\n description:\n \"Enables dynamic island-style UI in the assignment builder for contextual actions and status.\",\n },\n COMPUTER_USE: {\n key: \"computer_use\",\n defaultValue: false,\n description:\n \"Grants a team access to the Daytona-backed Computer Use beta. Tile is visible to all teams; when off, the tile shows a Request Access flow. When on, the tile enables the Duvo-managed Windows sandbox.\",\n },\n COMPUTER_USE_RDP: {\n key: \"computer_use_rdp\",\n defaultValue: true,\n description:\n \"Grants a team access to the Windows Remote Desktop beta. Default-on day-one (no known scaling limit); flip off to hide the Enable form and show a Request Access flow on the tile's detail page.\",\n },\n TEAM_ONTOLOGY: {\n key: \"team_ontology\",\n defaultValue: false,\n description:\n \"Enables ontology extraction during Clarity process generation, capturing structured domain knowledge (entities, relationships, business rules) into a team-wide knowledge base.\",\n },\n LEARNINGS: {\n key: \"learnings\",\n defaultValue: false,\n description:\n \"Enables the learnings feature, allowing users to record and reference learnings from assignment runs for continuous improvement.\",\n },\n LEARNINGS_UI: {\n key: \"learnings_ui\",\n defaultValue: false,\n description:\n \"Shows the Learnings, Automatic rating, and User feedback sections in the Evaluations tab.\",\n },\n MINUTE_SCHEDULING: {\n key: \"minute_scheduling\",\n defaultValue: false,\n description:\n \"Enables minute-level granularity for scheduling assignments, allowing sub-hour scheduling intervals for case queue postponement.\",\n },\n NEW_ORG_ONBOARDING: {\n key: \"new_org_onboarding\",\n defaultValue: false,\n description:\n \"Gates the entire organizations feature. When disabled, org UI is hidden and org API routes return 404 so the feature appears not to exist. When enabled, users can create organizations, invite members, manage teams under orgs, and go through the org-based onboarding flow.\",\n },\n PORTFOLIO_INTELLIGENCE: {\n key: \"portfolio_intelligence\",\n defaultValue: false,\n description:\n \"Enables portfolio intelligence analysis in the Clarity sidebar, providing cross-process insights and recommendations.\",\n },\n VISUAL_EDITING: {\n key: \"visual_editing\",\n defaultValue: false,\n description:\n \"Enables visual editing of Clarity process flow diagrams, including the Edit Diagram button, the edit toolbar (add/delete nodes, auto-layout), inline node/edge renaming, and right-click context menus.\",\n },\n} as const satisfies Record<string, FeatureFlagEntry>;\n\ntype FeatureFlagCatalogue = typeof FEATURE_FLAG_CATALOGUE;\n\n/**\n * Feature flag keys.\n * Derived from the catalogue \u2014 maps enum keys to database flag keys.\n */\nexport const FEATURE_FLAGS: {\n [K in keyof FeatureFlagCatalogue]: FeatureFlagCatalogue[K][\"key\"];\n} = Object.fromEntries(\n Object.entries(FEATURE_FLAG_CATALOGUE).map(([enumKey, entry]) => [\n enumKey,\n entry.key,\n ])\n) as { [K in keyof FeatureFlagCatalogue]: FeatureFlagCatalogue[K][\"key\"] };\n\nexport type FeatureFlagKey = (typeof FEATURE_FLAGS)[keyof typeof FEATURE_FLAGS];\n\n/**\n * Feature flag value type.\n * - boolean: for \"on\"/\"off\" flags (coerced to true/false)\n * - string: for variant flags with custom values\n */\nexport type FeatureFlagValue = boolean | string;\n\n/**\n * Default values for feature flags.\n * Derived from the catalogue.\n * Used as fallback when no database override exists or when the user is not logged in.\n */\nexport const FEATURE_FLAG_DEFAULTS: Record<FeatureFlagKey, FeatureFlagValue> =\n Object.fromEntries(\n Object.values(FEATURE_FLAG_CATALOGUE).map((entry) => [\n entry.key,\n entry.defaultValue,\n ])\n ) as Record<FeatureFlagKey, FeatureFlagValue>;\n\n/**\n * Descriptions for feature flags.\n * Derived from the catalogue. Keyed by database flag key.\n */\nexport const FEATURE_FLAG_DESCRIPTIONS: Record<FeatureFlagKey, string> =\n Object.fromEntries(\n Object.values(FEATURE_FLAG_CATALOGUE).map((entry) => [\n entry.key,\n entry.description,\n ])\n ) as Record<FeatureFlagKey, string>;\n\n/**\n * Type for feature flag values from the API.\n * Values are booleans (for on/off), strings (for variants), or undefined if not set.\n */\nexport type FeatureFlags = Record<string, FeatureFlagValue | undefined>;\n\n/**\n * Coerce a raw flag value to its appropriate type.\n * - \"on\" or \"true\" \u2192 true\n * - \"off\" or \"false\" \u2192 false\n * - other strings \u2192 kept as-is\n * - undefined \u2192 undefined\n */\nexport function coerceFlagValue(\n value: string | undefined\n): FeatureFlagValue | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (value === \"on\" || value === \"true\") {\n return true;\n }\n\n if (value === \"off\" || value === \"false\") {\n return false;\n }\n\n return value;\n}\n", "import { z } from \"zod\";\n\n/**\n * Zod schemas for the team files public API.\n * Used by the CLI; the backend routes still define their own (matching) inline\n * schemas. Importing from this file keeps the CLI in sync with the backend.\n */\n\nexport const teamFileItemSchema = z.object({\n id: z.string(),\n name: z.string(),\n path: z.string(),\n created_at: z.string().optional(),\n updated_at: z.string().optional(),\n metadata: z\n .object({\n mimetype: z.string().optional(),\n size: z.number().optional(),\n })\n .nullable()\n .optional(),\n});\n\nexport type TeamFileItem = z.infer<typeof teamFileItemSchema>;\n\nexport const listTeamFilesResponseSchema = z.object({\n files: z.array(teamFileItemSchema),\n});\n\nexport type ListTeamFilesResponse = z.infer<typeof listTeamFilesResponseSchema>;\n\nexport const createTeamFileUploadUrlBodySchema = z.object({\n fileName: z.string().min(1),\n contentType: z.string().min(1),\n});\n\nexport type CreateTeamFileUploadUrlBody = z.infer<\n typeof createTeamFileUploadUrlBodySchema\n>;\n\nexport const createTeamFileUploadUrlResponseSchema = z.object({\n signedUrl: z.url(),\n expiresAt: z.iso.datetime(),\n filePath: z.string(),\n});\n\nexport type CreateTeamFileUploadUrlResponse = z.infer<\n typeof createTeamFileUploadUrlResponseSchema\n>;\n\nexport const renameTeamFileBodySchema = z.object({\n relativePath: z.string().min(1),\n newFilenameOnly: z.string().min(1),\n});\n\nexport type RenameTeamFileBody = z.infer<typeof renameTeamFileBodySchema>;\n\nexport const teamFileSuccessResponseSchema = z.object({\n success: z.boolean(),\n});\n\nexport type TeamFileSuccessResponse = z.infer<\n typeof teamFileSuccessResponseSchema\n>;\n\nexport const teamFileDownloadUrlResponseSchema = z.object({\n url: z.url(),\n expiresAt: z.iso.datetime(),\n});\n\nexport type TeamFileDownloadUrlResponse = z.infer<\n typeof teamFileDownloadUrlResponseSchema\n>;\n\nexport const teamFileContentResponseSchema = z.object({\n content: z.string(),\n path: z.string(),\n contentType: z.string().optional(),\n});\n\nexport type TeamFileContentResponse = z.infer<\n typeof teamFileContentResponseSchema\n>;\n\nexport const updateTeamFileContentBodySchema = z.object({\n content: z.string(),\n});\n\nexport type UpdateTeamFileContentBody = z.infer<\n typeof updateTeamFileContentBodySchema\n>;\n", "import { z } from \"zod\";\n\nexport const globalAdminApiSchema = z.object({\n id: z.guid(),\n email: z.string(),\n userId: z.guid(),\n userName: z.string().nullable(),\n addedByUserId: z.guid().nullable(),\n createdAt: z.string(),\n});\nexport type GlobalAdminApi = z.infer<typeof globalAdminApiSchema>;\n\nexport const globalAdminListResponseSchema = z.object({\n admins: z.array(globalAdminApiSchema),\n});\nexport type GlobalAdminListResponse = z.infer<\n typeof globalAdminListResponseSchema\n>;\n\nexport const globalAdminSearchResponseSchema = z.object({\n users: z.array(\n z.object({\n id: z.guid(),\n name: z.string().nullable(),\n email: z.string(),\n createdAt: z.string().nullable(),\n })\n ),\n});\nexport type GlobalAdminSearchResponse = z.infer<\n typeof globalAdminSearchResponseSchema\n>;\n\nexport const globalAdminCreateRequestSchema = z.object({\n userId: z.guid(),\n});\nexport type GlobalAdminCreateRequest = z.infer<\n typeof globalAdminCreateRequestSchema\n>;\n\nexport const globalAdminCreateResponseSchema = z.object({\n admin: globalAdminApiSchema,\n});\nexport type GlobalAdminCreateResponse = z.infer<\n typeof globalAdminCreateResponseSchema\n>;\n\nexport const globalAdminDeleteResponseSchema = z.object({\n success: z.literal(true),\n});\nexport type GlobalAdminDeleteResponse = z.infer<\n typeof globalAdminDeleteResponseSchema\n>;\n\nexport const adminAccessCheckResponseSchema = z.object({\n isGlobalAdmin: z.boolean(),\n});\nexport type AdminAccessCheckResponse = z.infer<\n typeof adminAccessCheckResponseSchema\n>;\n", "import { z } from \"zod\";\n\nexport type IntegrationProvider = \"default\" | \"native\" | \"composio\" | \"user\";\nexport type IntegrationClass = \"platform\" | \"partner\" | \"custom\";\n\n/**\n * Integration category values.\n * Backend catalog uses kebab-case values; frontend may use display values for backward compatibility.\n */\nexport type IntegrationCategory =\n // Backend catalog (kebab-case)\n | \"google-workspace\"\n | \"ms-office-365\"\n | \"productivity\"\n | \"data-warehouses\"\n | \"duvo-platform\"\n | \"business-intelligence\"\n | \"custom\"\n // Frontend display values (legacy)\n | \"Google Workspace\"\n | \"MS Office 365\"\n | \"Productivity\"\n | \"Business Intelligence\"\n | \"Data Warehouses and Databases\"\n | \"Duvo Business Connections\"\n | \"ERP and Internal systems\";\n\n/**\n * MCP transport protocol types\n * Used to indicate how an MCP server communicates (computed field, not stored in database)\n */\nexport const TransportTypeSchema = z.enum([\"stdio\", \"sse\", \"http\"]);\nexport type TransportType = z.infer<typeof TransportTypeSchema>;\n\nexport const INTEGRATION_SLUGS = [\n \"googlecalendar\",\n \"google-calendar\",\n \"gmail\",\n \"slack\",\n \"googledocs\",\n \"googlesheets\",\n \"googledrive\",\n \"firecrawl\",\n \"exa\",\n \"exa-search\",\n \"exa-company-search\",\n \"exa-people-search\",\n \"deep-research\",\n \"system\",\n \"browser-agent\", // Deprecated: 368 teams still have catalog rows in the integration table\n \"browser-agent-devtools\",\n \"notion\",\n \"linear\",\n \"confluence\",\n \"custom_mcp\",\n \"user_mcp\",\n \"snowflake\",\n \"sharepoint\",\n \"teams\",\n \"onedrive\",\n \"bigquery\",\n \"databricks\",\n \"netsuite\",\n \"outlook\",\n \"microsoft-calendar\",\n \"excel\",\n \"word\",\n \"saps4hana\",\n \"md365\",\n \"businesscentral\",\n \"oraclefusion\",\n \"workday\",\n \"coupa\",\n \"msteams\",\n \"human-in-the-loop\",\n \"email-attachments-reader\",\n \"document-processor\",\n \"google-docs\",\n \"google-sheets\",\n \"google-drive\",\n \"outbound-call\",\n \"case-queue-producer\",\n \"case-queue-consumer\",\n \"handover\",\n \"shopify\",\n \"hubspot\",\n \"zendesk\",\n \"intercom\",\n \"powerbi\",\n \"salesforce\",\n \"pipedrive\",\n \"tableau\",\n \"image-generation\",\n \"forecasting\",\n \"supabase\",\n \"attio\",\n \"amplitude\",\n \"websets\",\n \"firecrawl-platform\",\n \"duvo-computer-use\",\n \"duvo-computer-use-rdp\",\n \"eu-commodity-prices\",\n \"asana\",\n \"ssh\",\n \"scheduling\",\n \"github\",\n \"linear-native\",\n \"notion-native\",\n \"granola\",\n] as const;\n\nexport const IntegrationSlugSchema = z.enum(INTEGRATION_SLUGS);\nexport type IntegrationSlug = z.infer<typeof IntegrationSlugSchema>;\n\nexport function isIntegrationSlug(value: string): value is IntegrationSlug {\n return (INTEGRATION_SLUGS as readonly string[]).includes(value);\n}\n\nexport interface Integration {\n slug: IntegrationSlug; // Used for MCP url backfilling, values must be in sync with the backend\n integrationName: string;\n icon: string;\n provider: IntegrationProvider;\n requires_instance?: boolean;\n integration_class?: IntegrationClass;\n description?: string;\n category?: IntegrationCategory;\n oauth_provider_id?: string | null;\n}\n\nexport const DEPRECATED_INTEGRATION_SLUGS: Set<IntegrationSlug> = new Set([\n \"browser-agent\",\n \"email-attachments-reader\",\n \"exa\",\n \"firecrawl\",\n \"linear\",\n \"notion\",\n]);\n\nexport interface IntegrationView extends Integration {\n id: string;\n name: string;\n}\n\nexport type CaseQueueIntegrationType =\n | \"case-queue-producer\"\n | \"case-queue-consumer\";\n\nexport const CASE_QUEUE_INTEGRATION_TYPES: readonly CaseQueueIntegrationType[] =\n [\"case-queue-producer\", \"case-queue-consumer\"];\n\nexport function isCaseQueueIntegrationType(\n type: string\n): type is CaseQueueIntegrationType {\n return type === \"case-queue-producer\" || type === \"case-queue-consumer\";\n}\n\n/**\n * Shared response schema for integration API objects.\n * Used by both backend routes and frontend API clients.\n *\n * Note on computed fields:\n * - server_url: Required in database, but optional in response for stdio MCP servers\n * - transport_type: NOT stored in database, computed from PRIVATE_MCP_SERVERS config\n * Only present for MCP-type integrations (undefined for OAuth/Composio integrations)\n */\nexport const integrationResponseSchema = z.object({\n id: z.string(),\n name: z.string(),\n type: z.string(),\n provider: z.string(),\n user_id: z.string().nullable(),\n team_id: z.string(),\n server_url: z.string().optional(),\n transport_type: TransportTypeSchema.optional(),\n auth_method: z.string().nullable().optional(),\n composio_mcp_id: z.string().nullable().default(null),\n custom_integration_id: z.string().nullable().optional(),\n icon_url: z.string().nullable().optional(),\n oauth_provider: z.string().nullable().optional(),\n oauth_scopes: z.array(z.string()).nullable().optional(),\n hasHeaders: z.boolean().optional(),\n hasOauthTokens: z.boolean().optional(),\n /**\n * For connection rows (user instances), this is the FK to the team-level\n * integration this connection was created against. Null on catalog rows\n * (where `id` already represents the integration itself) and on\n * custom-integration-backed connections.\n */\n integration_id: z.string().nullable().optional(),\n created_at: z.iso.datetime(),\n updated_at: z.iso.datetime(),\n});\n\nexport type IntegrationApiResponse = z.infer<typeof integrationResponseSchema>;\n\nexport const integrationsListResponseSchema = z.object({\n integrations: z.array(integrationResponseSchema),\n pagination: z\n .object({\n page: z.number(),\n pageSize: z.number(),\n count: z.number(),\n totalPages: z.number(),\n })\n .optional(),\n});\n\nexport const integrationsListRequestQuerySchema = z.object({\n type: z.string().optional(),\n page: z.number().optional(),\n pageSize: z.number().optional(),\n userScope: z.boolean().optional(),\n});\nexport type IntegrationsListRequestQuery = z.infer<\n typeof integrationsListRequestQuerySchema\n>;\n\nexport type IntegrationsListResponse = z.infer<\n typeof integrationsListResponseSchema\n>;\n\nexport const connectIntegrationResponseSchema = z.object({\n integration_id: z.string(),\n mcp_url: z.string(),\n});\n\nexport type ConnectIntegrationResponse = z.infer<\n typeof connectIntegrationResponseSchema\n>;\n\nexport const testIntegrationResponseSchema = z.object({\n success: z.boolean(),\n tools: z\n .array(\n z.object({\n name: z.string(),\n description: z.string().optional(),\n inputSchema: z.any().optional(),\n })\n )\n .optional(),\n error: z.string().optional(),\n});\n\nexport type TestIntegrationResponse = z.infer<\n typeof testIntegrationResponseSchema\n>;\n\nexport const integrationCredentialsResponseSchema = z.object({\n id: z.guid(),\n headers: z.record(z.string(), z.string()),\n});\n\nexport type IntegrationCredentialsResponse = z.infer<\n typeof integrationCredentialsResponseSchema\n>;\n\nexport const deleteIntegrationResponseSchema = z.object({\n success: z.boolean(),\n message: z.string(),\n});\n\nexport type DeleteIntegrationResponse = z.infer<\n typeof deleteIntegrationResponseSchema\n>;\n\nexport const checkDcrSupportResponseSchema = z.object({\n supportsDcr: z.boolean(),\n authorizationEndpoint: z.string().optional(),\n scopes: z.array(z.string()).optional(),\n});\n\nexport type CheckDcrSupportResponse = z.infer<\n typeof checkDcrSupportResponseSchema\n>;\n\nexport const createCustomIntegrationRequestSchema = z\n .object({\n name: z.string().min(1, \"Name is required\"),\n auth_method: z.enum([\"url\", \"apikey\", \"headers\", \"oauth\"]),\n server_url: z.url(\"Must be a valid URL\"),\n oauth_client_id: z.string().min(1).optional(),\n oauth_client_secret: z.string().min(1).optional(),\n })\n .refine(\n (data) => {\n const hasClientId = !!data.oauth_client_id;\n const hasClientSecret = !!data.oauth_client_secret;\n return hasClientId === hasClientSecret;\n },\n {\n error:\n \"Both OAuth Client ID and Client Secret are required, or leave both empty for automatic registration\",\n }\n );\n\nexport type CreateCustomIntegrationRequest = z.infer<\n typeof createCustomIntegrationRequestSchema\n>;\n\n// Schema for creating a new integration\nexport const createIntegrationRequestSchema = z.object({\n name: z.string().min(1, \"Name is required\"),\n server_url: z.url(\"Must be a valid URL\").optional(),\n type: z.string().default(\"custom_mcp\"),\n provider: z.literal(\"user\"),\n auth_method: z.enum([\"url\", \"apikey\", \"headers\", \"oauth\"]),\n custom_integration_id: z.guid().optional(),\n headers: z\n .object({\n plaintext: z.record(z.string(), z.string()).optional(),\n secret: z.record(z.string(), z.string()).optional(),\n })\n .optional(),\n composio_mcp_id: z.string().optional(),\n});\n\nexport type CreateIntegrationRequest = z.infer<\n typeof createIntegrationRequestSchema\n>;\n\n// Schema for updating an integration - all fields optional\nexport const updateIntegrationRequestSchema = z.object({\n name: z.string().min(1).optional(),\n server_url: z.url().optional(),\n auth_method: z.enum([\"url\", \"oauth\", \"apikey\", \"headers\"]).optional(),\n headers: z\n .object({\n plaintext: z.record(z.string(), z.string()).optional(),\n secret: z.record(z.string(), z.string()).optional(),\n })\n .nullable()\n .optional(),\n composio_mcp_id: z.string().nullable().optional(),\n});\n\nexport type UpdateIntegrationRequest = z.infer<\n typeof updateIntegrationRequestSchema\n>;\n\nexport const testIntegrationRequestSchema = z.object({\n server_url: z.url().describe(\"MCP server URL to test\"),\n headers: z\n .record(z.string(), z.string())\n .optional()\n .describe(\"Optional HTTP headers for authentication\"),\n});\n\nexport type TestIntegrationRequest = z.infer<\n typeof testIntegrationRequestSchema\n>;\n", "import { z } from \"zod\";\n\nimport { evalSummarySchema } from \"../schemas/run-evaluation\";\nimport { agentRunStatusSchema } from \"./agent-run\";\n\nexport const JOB_LIST_SORT_COLUMNS = [\"created_at\"] as const;\n\nexport type JobListSortColumn = (typeof JOB_LIST_SORT_COLUMNS)[number];\n\nexport const jobListSortColumnSchema = z.enum(JOB_LIST_SORT_COLUMNS);\n\nexport const jobListItemSchema = z.object({\n id: z.guid(),\n created_at: z.coerce.date(),\n updated_at: z.coerce.date(),\n started_at: z.coerce.date().nullable(),\n completed_at: z.coerce.date().nullable(),\n status: agentRunStatusSchema,\n source: z.string().nullable(),\n title: z.string(),\n run_number: z.number(),\n // Assignment info\n agent_id: z.guid(),\n agent_name: z.string(),\n build_id: z.guid(),\n // User info\n user_id: z.guid().nullable(),\n // Case info\n case_queue_item_id: z.guid().nullable(),\n case_queue_id: z.guid().nullable(),\n case_queue_name: z.string().nullable(),\n case_title: z.string().nullable(),\n postponed_to: z.coerce.date().nullable(),\n submitted_prompt_count: z.number().int().min(0),\n eval_summaries: evalSummarySchema.nullable().optional(),\n});\n\nexport type JobListItem = z.infer<typeof jobListItemSchema>;\n\nexport const jobListResponseSchema = z.object({\n data: z.array(jobListItemSchema),\n total: z.number(),\n});\n\nexport type JobListResponse = z.infer<typeof jobListResponseSchema>;\n\nexport const jobFilterOptionsSchema = z.object({\n agents: z.array(\n z.object({\n id: z.string(),\n name: z.string(),\n folder_id: z.string().nullable(),\n })\n ),\n folders: z.array(\n z.object({\n id: z.string(),\n name: z.string(),\n parent_folder_id: z.string().nullable(),\n })\n ),\n users: z.array(\n z.object({\n id: z.string(),\n name: z.string().nullable(),\n email: z.string(),\n })\n ),\n caseQueues: z.array(z.object({ id: z.string(), name: z.string() })),\n});\n\nexport type JobFilterOptions = z.infer<typeof jobFilterOptionsSchema>;\n", "/**\n * MCP Workflow types for browser automation.\n * Represents recorded user workflows as sequences of MCP tool calls\n * that can be replayed by AI agents.\n */\n\nimport { z } from \"zod\";\n\n/**\n * Single step in an MCP workflow - represents one tool call.\n */\nexport const mcpStepSchema = z.object({\n tool: z.string().describe(\"MCP tool name (e.g., click, fill, navigate_page)\"),\n params: z\n .record(z.string(), z.unknown())\n .describe(\"Tool-specific parameters\"),\n fallbackSelectors: z\n .array(z.string())\n .optional()\n .describe(\"Alternative CSS selectors if primary fails\"),\n description: z\n .string()\n .optional()\n .describe(\"Human-readable step description\"),\n screenshot: z\n .string()\n .optional()\n .describe(\"Base64 screenshot at this step for visual context\"),\n snapshot: z\n .string()\n .optional()\n .describe(\"DOM snapshot in accessibility tree format at this step\"),\n framePath: z\n .array(z.number())\n .optional()\n .describe(\n \"Index-based path to the target iframe (e.g., [0] for first child iframe, [1, 0] for nested)\"\n ),\n});\n\nexport type McpStep = z.infer<typeof mcpStepSchema>;\n\n/**\n * MCP Workflow format - represents a recorded user workflow\n * as a sequence of MCP tool calls.\n */\nexport const mcpWorkflowSchema = z.object({\n name: z.string(),\n startUrl: z.string(),\n viewport: z.object({\n width: z.number(),\n height: z.number(),\n }),\n steps: z.array(mcpStepSchema),\n});\n\nexport type McpWorkflow = z.infer<typeof mcpWorkflowSchema>;\n\n/**\n * JSON Schema representation of the MCP workflow schema.\n * Auto-generated from Zod schemas to stay in sync.\n */\nexport const MCP_WORKFLOW_JSON_SCHEMA = z.toJSONSchema(mcpWorkflowSchema, {\n reused: \"inline\",\n});\n\n/**\n * Documentation string for the MCP workflow schema.\n * Used in generated skill files to document the workflow format.\n */\nexport const MCP_WORKFLOW_SCHEMA_DOCS = JSON.stringify(\n MCP_WORKFLOW_JSON_SCHEMA,\n null,\n 2\n);\n", "import { z } from \"zod\";\n\n/**\n * Zod schemas for the plugins public API.\n * Used by both backend validation and CLI/frontend type inference.\n */\n\nexport const catalogPluginSchema = z.object({\n name: z.string().describe(\"Identifier to pass in the build's plugins array.\"),\n type: z\n .enum([\"duvo-platform\", \"github\"])\n .describe(\n \"Plugin source. 'duvo-platform' plugins are pre-baked into the Duvo runtime; 'github' plugins are downloaded from a user-supplied repository URL at run time.\"\n ),\n description: z.string(),\n});\n\nexport type CatalogPlugin = z.infer<typeof catalogPluginSchema>;\n\nexport const pluginCatalogResponseSchema = z.object({\n plugins: z.array(catalogPluginSchema),\n});\n\nexport type PluginCatalogResponse = z.infer<typeof pluginCatalogResponseSchema>;\n", "import { z } from \"zod\";\n\nexport const publicProfileSchema = z.object({\n id: z.guid(),\n name: z.string().nullable(),\n email: z.email(),\n teamId: z.guid().nullable(),\n});\nexport type PublicProfile = z.infer<typeof publicProfileSchema>;\n\nexport const publicProfileResponseSchema = z.object({\n profile: publicProfileSchema,\n});\nexport type PublicProfileResponse = z.infer<typeof publicProfileResponseSchema>;\n", "/**\n * Types for headless workflow recording in Browserbase sessions.\n * Used by both the Chrome extension and backend API.\n */\n\nimport { z } from \"zod\";\n\n/**\n * Cookie name used to pass recording configuration to the extension.\n * The extension reads this cookie on initialization to determine if\n * it should run in headless mode with auto-start recording.\n */\nexport const RECORDING_CONFIG_COOKIE_NAME = \"__duvo_recording_config\";\n\n/**\n * Configuration passed to the extension via cookie for headless recording.\n */\nexport interface HeadlessRecordingConfig {\n /** Recording session ID (UUID) - used for API calls */\n sessionId: string;\n /** Browserbase session ID */\n browserbaseSessionId: string;\n /** Agent ID this recording is for */\n agentId: string;\n /** Team ID owning the agent */\n teamId: string;\n /** User ID who initiated the recording */\n userId: string;\n /** Optional name for the generated skill */\n skillName?: string;\n /** Optional description for the generated skill */\n skillDescription?: string;\n /** Backend streaming endpoint URL (e.g., https://api.duvo.ai/v1/recordings) */\n streamEndpoint: string;\n /** JWT or API key for authentication */\n authToken: string;\n}\n\n/**\n * Recording session status values.\n */\nexport type RecordingSessionStatus =\n | \"browsing\" // Browser open, not recording yet\n | \"recording\"\n | \"completing\"\n | \"completed\"\n | \"failed\";\n\n/**\n * Batch of recorded events sent from extension to backend.\n */\nexport interface RecordingEventBatch {\n /** Recording session ID */\n sessionId: string;\n /** Sequential batch number (1-indexed) */\n batchNumber: number;\n /** Array of recorded events - uses unknown to avoid circular dependency with extension types */\n events: unknown[];\n /** Timestamp when batch was created (Date.now()) */\n timestamp: number;\n}\n\n/**\n * Metadata about the recording session, sent on completion.\n */\nexport interface RecordingSessionMetadata {\n /** Starting URL of the recording */\n startUrl: string;\n /** Viewport dimensions during recording */\n viewport: {\n width: number;\n height: number;\n };\n /** Browser information */\n browserInfo: {\n name: string;\n version: string;\n userAgent: string;\n };\n}\n\n/**\n * Response from the stream events endpoint.\n */\nexport interface StreamEventsResponse {\n success: boolean;\n eventsReceived: number;\n}\n\n/**\n * Response from the complete recording endpoint.\n */\nexport interface CompleteRecordingResponse {\n success: boolean;\n skillId?: string;\n error?: string;\n}\n\n// =============================================================================\n// Recorded Event Schemas\n// =============================================================================\n\n/**\n * Element selector information captured from the DOM.\n */\nexport const elementSelectorsSchema = z.object({\n css: z.string().optional(),\n cssPath: z.string().optional(),\n xpath: z.string().optional(),\n testId: z.string().optional(),\n ariaSelector: z.string().optional(),\n text: z.string().optional(),\n});\n\nexport type ElementSelectors = z.infer<typeof elementSelectorsSchema>;\n\n/**\n * Element information captured from the DOM.\n */\nexport const elementInfoSchema = z.object({\n uid: z.string().optional(),\n selectors: elementSelectorsSchema,\n tagName: z.string(),\n textContent: z.string().optional(),\n ariaLabel: z.string().optional(),\n computedRole: z.string().optional(),\n attributes: z.record(z.string(), z.string()).optional(),\n framePath: z.array(z.number()).optional(),\n frameUrl: z.string().optional(),\n});\n\nexport type ElementInfo = z.infer<typeof elementInfoSchema>;\n\n/**\n * Base recorded event structure.\n */\nexport const recordedEventSchema = z.looseObject({\n id: z.string(),\n type: z.string(),\n timestamp: z.number(),\n url: z.string(),\n tabId: z.number().optional(),\n frameId: z.number().optional(),\n framePath: z.array(z.number()).optional(),\n element: elementInfoSchema.optional(),\n});\n\nexport type RecordedEvent = z.infer<typeof recordedEventSchema>;\n", "import { z } from \"zod\";\n\nimport { AgentConfigSchema } from \"./agent-config\";\nimport { IntegrationSlugSchema, TransportTypeSchema } from \"./integration\";\n\n/**\n * Redacted MCP server configuration that contains no secrets.\n * Stored in run_config at agent run creation time.\n * Secrets are resolved at execution time using instanceId lookups.\n */\nexport const RedactedMcpServerConfigSchema = z.object({\n type: TransportTypeSchema,\n integrationSlug: IntegrationSlugSchema,\n instanceId: z.string().nullable(),\n});\n\nexport type RedactedMcpServerConfig = z.infer<\n typeof RedactedMcpServerConfigSchema\n>;\n\n/**\n * Schema for thread context messages (e.g., from Slack threads).\n */\nexport const ThreadContextMessageSchema = z.object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string(),\n});\n\nexport type ThreadContextMessage = z.infer<typeof ThreadContextMessageSchema>;\n\n/**\n * Schema for chat platform file references attached to thread messages.\n * Stored in run_config so the runtime can download and upload them to the sandbox.\n *\n * Platform-specific fields:\n * - slack: workspaceId = Slack workspace ID, channelId = Slack channel ID\n * - teams: workspaceId = Teams tenant ID, channelId = Teams channel/conversation ID\n */\nexport const ChatFileReferenceSchema = z.object({\n id: z.string(),\n name: z.string(),\n mimetype: z.string(),\n size: z.number(),\n platform: z.enum([\"slack\", \"teams\"]),\n workspaceId: z.string(),\n channelId: z.string(),\n});\n\nexport type ChatFileReference = z.infer<typeof ChatFileReferenceSchema>;\n\nexport type SlackFileReference = ChatFileReference & { platform: \"slack\" };\nexport type TeamsFileReference = ChatFileReference & { platform: \"teams\" };\n\n/**\n * A sub-assignment resolved at run-creation time.\n *\n * Frozen entry that captures everything needed to run another assignment as\n * a Claude Code subagent: the live build that was current at run creation,\n * a stable slug used as the SDK agent name, the system prompt to give the\n * subagent, and redacted MCP servers (secrets resolved at execution time).\n * Replays consume this directly without re-resolving live builds.\n *\n * NOTE on resource inheritance: a child's `files`, `skills`, and `plugins`\n * are NOT carried on this entry. They are unioned into the parent run's own\n * `files`, `skills`, and `plugins` at config-build time (see\n * `resolveSubAgents` + `buildRunConfig`). Because the sandbox FS is shared\n * and plugins load once at session start, those resources are visible to the\n * parent's main loop and to sibling subagents \u2014 accepted trade-off for\n * letting authors compose existing assignments.\n */\nexport const ResolvedSubAgentSchema = z.object({\n agentId: z.string().uuid(),\n buildId: z.string().uuid(),\n name: z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-z0-9-]+$/)\n .describe(\n \"Stable slug used as the Claude Code subagent name (kebab-case, \u226464 chars)\"\n ),\n description: z\n .string()\n .describe(\n \"Routing description Claude uses to decide when to delegate to this subagent\"\n ),\n prompt: z.string().describe(\"System prompt (SOP) for this subagent\"),\n model: z\n .string()\n .optional()\n .describe(\"Optional Claude model identifier override for this subagent\"),\n mcpServers: z\n .record(z.string(), RedactedMcpServerConfigSchema)\n .default({})\n .describe(\n \"Redacted MCP server configs scoped to this subagent. Secrets resolved at execution time.\"\n ),\n});\n\nexport type ResolvedSubAgent = z.infer<typeof ResolvedSubAgentSchema>;\n\n/**\n * Run configuration data (the actual config payload).\n * Extends AgentConfig with runtime-specific additions (task, mcpServers).\n *\n * Contains all data needed to execute the run, decoupled from build state.\n * MCP server secrets are resolved at execution time using instanceId lookups.\n *\n * NOTE: `subAgents` is overridden here. AgentConfigSchema stores it as a list\n * of agent IDs (the user's selection at edit time); RunConfigSchema replaces\n * those IDs with frozen ResolvedSubAgent entries at run-creation time so\n * downstream execution does not need to re-resolve live builds.\n */\nexport const RunConfigSchema = AgentConfigSchema.extend({\n task: z.string(),\n mcpServers: z.record(z.string(), RedactedMcpServerConfigSchema),\n subAgents: z.array(ResolvedSubAgentSchema).optional().default([]),\n conversationHistory: z.array(ThreadContextMessageSchema).optional(),\n chatFiles: z.array(ChatFileReferenceSchema).optional(),\n /** IANA timezone (e.g. `\"Europe/Prague\"`). Consumers should fall back to UTC when absent. */\n timezone: z.string().optional(),\n});\n\nexport type RunConfig = z.infer<typeof RunConfigSchema>;\n\n/**\n * V0: Empty placeholder for legacy runs (pre-dispatcher).\n * Used for runs created before run_config was implemented.\n */\nexport const StoredRunConfigV0Schema = z.object({\n version: z.literal(\"v0\"),\n});\n\nexport type StoredRunConfigV0 = z.infer<typeof StoredRunConfigV0Schema>;\n\n/**\n * V1: Full frozen run configuration with version wrapper.\n */\nexport const StoredRunConfigV1Schema = z.object({\n version: z.literal(\"v1\"),\n data: RunConfigSchema,\n});\n\nexport type StoredRunConfigV1 = z.infer<typeof StoredRunConfigV1Schema>;\n\n/**\n * Union of all stored run config formats.\n */\nexport const StoredRunConfigSchema = z.union([\n StoredRunConfigV0Schema,\n StoredRunConfigV1Schema,\n]);\n\nexport type StoredRunConfig = z.infer<typeof StoredRunConfigSchema>;\n\n/**\n * Type guard to check if stored config is V0 format.\n */\nexport function isStoredRunConfigV0(\n config: unknown\n): config is StoredRunConfigV0 {\n return StoredRunConfigV0Schema.safeParse(config).success;\n}\n\n/**\n * Type guard to check if stored config is V1 format.\n */\nexport function isStoredRunConfigV1(\n config: unknown\n): config is StoredRunConfigV1 {\n return StoredRunConfigV1Schema.safeParse(config).success;\n}\n\n/**\n * Type guard to check if a value is a RunConfig (the inner data, not the wrapper).\n */\nexport function isRunConfig(config: unknown): config is RunConfig {\n return RunConfigSchema.safeParse(config).success;\n}\n", "import { z } from \"zod\";\n\n/**\n * Zod schemas for the skills public API.\n * Used by the CLI; the backend routes still define their own (matching) inline\n * schemas, but importing from this file keeps the CLI in sync with the backend.\n */\n\nexport const skillApiSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n // System skills have null team_id.\n team_id: z.string().nullable(),\n});\n\nexport type SkillApi = z.infer<typeof skillApiSchema>;\n\nexport const listSkillsResponseSchema = z.object({\n skills: z.array(skillApiSchema),\n});\n\nexport type ListSkillsResponse = z.infer<typeof listSkillsResponseSchema>;\n\nexport const systemSkillSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n});\n\nexport type SystemSkill = z.infer<typeof systemSkillSchema>;\n\nexport const listSystemSkillsResponseSchema = z.object({\n skills: z.array(systemSkillSchema),\n});\n\nexport type ListSystemSkillsResponse = z.infer<\n typeof listSystemSkillsResponseSchema\n>;\n\nexport const skillFileItemSchema = z.object({\n name: z.string(),\n path: z.string(),\n size: z.number().optional(),\n contentType: z.string().optional(),\n updatedAt: z.string().optional(),\n});\n\nexport type SkillFileItem = z.infer<typeof skillFileItemSchema>;\n\nexport const listSkillFilesResponseSchema = z.object({\n files: z.array(skillFileItemSchema),\n});\n\nexport type ListSkillFilesResponse = z.infer<\n typeof listSkillFilesResponseSchema\n>;\n\nexport const getSkillFileContentResponseSchema = z.object({\n content: z.string(),\n path: z.string(),\n contentType: z.string().optional(),\n});\n\nexport type GetSkillFileContentResponse = z.infer<\n typeof getSkillFileContentResponseSchema\n>;\n\nexport const updateSkillFileBodySchema = z.object({\n content: z.string(),\n});\n\nexport type UpdateSkillFileBody = z.infer<typeof updateSkillFileBodySchema>;\n\nexport const updateSkillFileResponseSchema = z.object({\n success: z.boolean(),\n message: z.string(),\n skill: z\n .object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n })\n .optional(),\n});\n\nexport type UpdateSkillFileResponse = z.infer<\n typeof updateSkillFileResponseSchema\n>;\n\nexport const deleteSkillResponseSchema = z.object({\n success: z.boolean(),\n message: z.string(),\n});\n\nexport type DeleteSkillResponse = z.infer<typeof deleteSkillResponseSchema>;\n\nexport const generateSkillBodySchema = z.object({\n prompt: z.string().min(1).max(2000),\n existingContent: z.string().max(20000).optional(),\n});\n\nexport type GenerateSkillBody = z.infer<typeof generateSkillBodySchema>;\n\nexport const generateSkillResponseSchema = z.object({\n content: z.string(),\n});\n\nexport type GenerateSkillResponse = z.infer<typeof generateSkillResponseSchema>;\n", "import { z } from \"zod\";\n\nimport { BrowserProviderTypeSchema } from \"./agent-config\";\nimport { teamInvitationApiSchema } from \"./team-invitation\";\n\nconst teamDiscoveryModeSchema = z.enum([\"request\", \"auto\"]);\nexport type TeamDiscoveryMode = z.infer<typeof teamDiscoveryModeSchema>;\n\nexport const BrowserLocationSchema = z.union([\n z.literal(\"cz\"),\n z.literal(\"de\"),\n z.literal(\"fr\"),\n z.literal(\"gb\"),\n z.literal(\"it\"),\n z.literal(\"pl\"),\n z.literal(\"sk\"),\n]);\nexport type BrowserLocation = z.infer<typeof BrowserLocationSchema>;\n\n// Team member schema\nexport const teamMemberApiSchema = z.object({\n id: z.guid(),\n name: z.string().nullable(),\n email: z.email(),\n role: z.string(),\n inheritedFromOrg: z.boolean().default(false),\n});\nexport type TeamMemberApi = z.infer<typeof teamMemberApiSchema>;\n\n// List members response\nexport const listTeamMembersResponseSchema = z.object({\n members: z.array(teamMemberApiSchema),\n total: z.number().int().nonnegative(),\n limit: z.number().int().positive(),\n offset: z.number().int().nonnegative(),\n});\nexport type ListTeamMembersResponse = z.infer<\n typeof listTeamMembersResponseSchema\n>;\n\n// Update member role request\nexport const updateMemberRoleRequestSchema = z.object({\n role: z.string(),\n});\nexport type UpdateMemberRoleRequest = z.infer<\n typeof updateMemberRoleRequestSchema\n>;\n\n// Remove member response\nexport const removeMemberResponseSchema = z.object({\n success: z.literal(true),\n nextTeamId: z.guid().nullable(),\n planType: z.enum([\"pro\", \"enterprise\"]).nullable(),\n});\nexport type RemoveMemberResponse = z.infer<typeof removeMemberResponseSchema>;\n\n// Get current user role response\nexport const getMemberMeResponseSchema = z.object({\n role: z.string().nullable(),\n});\nexport type GetMemberMeResponse = z.infer<typeof getMemberMeResponseSchema>;\n\n// Add user to team request\nexport const addTeamMemberRequestSchema = z.object({\n userId: z.guid(),\n role: z.string(),\n});\nexport type AddTeamMemberRequest = z.infer<typeof addTeamMemberRequestSchema>;\n\n// Update team request\nexport const updateTeamRequestSchema = z.object({\n name: z.string().min(1).optional(),\n slack_team_id: z.string().optional(),\n discovery_mode: teamDiscoveryModeSchema.optional(),\n});\nexport type UpdateTeamRequest = z.infer<typeof updateTeamRequestSchema>;\n\n// Team response schema\nexport const teamApiSchema = z.object({\n id: z.guid(),\n name: z.string(),\n created_at: z.string(),\n organization_id: z.guid().nullable(),\n slack_team_id: z.string().nullable(),\n discovery_mode: teamDiscoveryModeSchema,\n});\nexport type TeamApi = z.infer<typeof teamApiSchema>;\n\n// Team config schema (versioned envelope)\nexport const TEAM_CONFIG_VERSION = 1;\n\nexport const teamConfigDataSchema = z.object({\n browserProviderOverride: BrowserProviderTypeSchema.nullable().optional(),\n browserLocationOverride: BrowserLocationSchema.nullable().optional(),\n});\nexport type TeamConfigData = z.infer<typeof teamConfigDataSchema>;\n\nexport const teamConfigSchema = z.object({\n version: z.literal(TEAM_CONFIG_VERSION),\n data: teamConfigDataSchema,\n});\nexport type TeamConfig = z.infer<typeof teamConfigSchema>;\n\n// List team invites response\nexport const listTeamInvitesResponseSchema = z.object({\n invitations: z.array(teamInvitationApiSchema),\n});\nexport type ListTeamInvitesResponse = z.infer<\n typeof listTeamInvitesResponseSchema\n>;\n", "import { z } from \"zod\";\n\n// Base invite schema matching the database table\nexport const teamInvitationApiSchema = z.object({\n id: z.string(),\n team_id: z.string(),\n email: z.email(),\n invited_by: z.string(),\n role: z.string(),\n status: z.string(),\n name: z.string().nullable(),\n created_at: z.string(),\n process_id: z.guid().nullable().optional(),\n});\n\nexport type TeamInvitationApi = z.infer<typeof teamInvitationApiSchema>;\n\n// Detailed invite schema with relationships\nexport const teamInvitationDetailApiSchema = z.object({\n id: z.string(),\n team_id: z.string(),\n email: z.email(),\n invited_by: z.string(),\n role: z.string(),\n status: z.string(),\n name: z.string().nullable(),\n created_at: z.string(),\n process_id: z.guid().nullable().optional(),\n team: z.object({\n id: z.string(),\n name: z.string(),\n }),\n invitedBy: z.object({\n id: z.string(),\n name: z.string().nullable(),\n email: z.email(),\n }),\n process: z\n .object({\n id: z.string(),\n name: z.string(),\n })\n .optional(),\n});\n\nexport type TeamInvitationDetailApi = z.infer<\n typeof teamInvitationDetailApiSchema\n>;\n\n// Request schemas for API endpoints\nexport const createTeamInvitationRequestSchema = z.object({\n email: z.email(),\n role: z.string(),\n processId: z.guid().optional(),\n});\n\nexport type CreateTeamInvitationRequest = z.infer<\n typeof createTeamInvitationRequestSchema\n>;\n\nexport const acceptTeamInvitationRequestSchema = z.object({\n name: z.string().optional(),\n});\n\nexport type AcceptTeamInvitationRequest = z.infer<\n typeof acceptTeamInvitationRequestSchema\n>;\n\n// Response schemas\nexport const bulkInviteResponseSchema = z.object({\n succeeded: z.number(),\n skipped: z.number(),\n failed: z.number(),\n});\nexport type BulkInviteResponse = z.infer<typeof bulkInviteResponseSchema>;\n\nexport const createTeamInvitationResponseSchema = teamInvitationDetailApiSchema;\nexport type CreateTeamInvitationResponse = TeamInvitationDetailApi;\n\nexport const getTeamInvitationResponseSchema = teamInvitationDetailApiSchema;\nexport type GetTeamInvitationResponse = TeamInvitationDetailApi;\n", "import { z } from \"zod\";\n\nimport { agentRunSourceSchema } from \"./agent-run\";\n\n// --- Agents-run endpoint schemas ---\n\nexport const teamInsightsCopilotSchema = z.object({\n id: z.guid(),\n name: z.string(),\n teamName: z.string().nullable().optional(),\n created_at: z.string().nullable(),\n updated_at: z.string().nullable(),\n team_id: z.string().nullable(),\n thread_id: z.string().nullable(),\n slack_enabled: z.boolean().nullable(),\n});\n\nexport const teamInsightsUserProfileSchema = z.object({\n id: z.guid(),\n name: z.string().nullable(),\n email: z.string(),\n});\n\nexport const teamInsightsUserUsageSchema = teamInsightsUserProfileSchema.extend(\n {\n runCount: z.number(),\n lastRun: z.string().nullable(),\n }\n);\n\nexport const teamInsightsMetricSourceSchema = z.object({\n source: agentRunSourceSchema,\n runsTotal: z.number(),\n completedRuns: z.number(),\n});\n\nexport const teamInsightsCopilotWithRunsSchema =\n teamInsightsCopilotSchema.extend({\n integrations: z.array(z.string()),\n uniqueUsersCount: z.number(),\n users: z.array(teamInsightsUserUsageSchema),\n totalRuns: z.number(),\n completedRuns: z.number(),\n totalTimeSpentMs: z.number(),\n averageTimeSpentMs: z.number(),\n completedRunsWithTiming: z.number(),\n sources: z.array(teamInsightsMetricSourceSchema),\n });\n\nexport const teamInsightsAgentsRunResponseSchema = z.object({\n data: z.array(teamInsightsCopilotWithRunsSchema),\n total: z.number(),\n});\n\nexport type TeamInsightsAgentsRunResponse = z.infer<\n typeof teamInsightsAgentsRunResponseSchema\n>;\n\n// --- Metrics endpoint schemas ---\n\nexport const teamInsightsMetricsResponseSchema = z.object({\n runsTotal: z.number(),\n completedRuns: z.number(),\n sources: z.array(teamInsightsMetricSourceSchema),\n});\n\nexport type TeamInsightsMetricsResponse = z.infer<\n typeof teamInsightsMetricsResponseSchema\n>;\n\nexport type TeamInsightsMetricSource = z.infer<\n typeof teamInsightsMetricSourceSchema\n>[\"source\"];\n\n// --- Users endpoint schemas ---\n\nexport const teamInsightsUserAgentRunSchema = z.object({\n id: z.guid(),\n created_at: z.string(),\n updated_at: z.string(),\n agent_id: z.guid(),\n agent_name: z.string(),\n build_id: z.guid(),\n source: z.string().nullable(),\n started_at: z.string().nullable(),\n completed_at: z.string().nullable(),\n});\n\nexport const teamInsightsAgentSchema = z.object({\n id: z.guid(),\n name: z.string(),\n teamName: z.string().nullable().optional(),\n runs: z.array(teamInsightsUserAgentRunSchema),\n});\n\nexport const teamInsightsUserWithAgentsAndRunsSchema =\n teamInsightsUserProfileSchema.extend({\n agents: z.array(teamInsightsAgentSchema),\n runs: z.array(teamInsightsUserAgentRunSchema),\n totalRuns: z.number(),\n });\n\nexport const teamInsightsUsersResponseSchema = z.object({\n data: z.array(teamInsightsUserWithAgentsAndRunsSchema),\n total: z.number(),\n});\n\nexport type TeamInsightsUsersResponse = z.infer<\n typeof teamInsightsUsersResponseSchema\n>;\n", "import { z } from \"zod\";\n\n// Request schemas\nexport const createTeamInviteLinkRequestSchema = z.object({\n frontendUrl: z.url(),\n});\n\nexport type CreateTeamInviteLinkRequest = z.infer<\n typeof createTeamInviteLinkRequestSchema\n>;\n\nexport const getTeamInviteLinkQuerySchema = z.object({\n frontendUrl: z.url(),\n});\n\nexport type GetTeamInviteLinkQuery = z.infer<\n typeof getTeamInviteLinkQuerySchema\n>;\n\n// Response schemas\nexport const teamInviteLinkCreatorSchema = z.object({\n id: z.guid(),\n name: z.string().nullable(),\n email: z.email(),\n});\n\nexport const teamInviteLinkSchema = z.object({\n id: z.guid(),\n url: z.url().optional(),\n createdAt: z.string(),\n createdBy: teamInviteLinkCreatorSchema,\n});\n\nexport type TeamInviteLink = z.infer<typeof teamInviteLinkSchema>;\n\nexport const getTeamInviteLinkResponseSchema = z.object({\n hasLink: z.boolean(),\n link: teamInviteLinkSchema.optional(),\n});\n\nexport type GetTeamInviteLinkResponse = z.infer<\n typeof getTeamInviteLinkResponseSchema\n>;\n\nexport const createTeamInviteLinkResponseSchema = teamInviteLinkSchema;\n\nexport type CreateTeamInviteLinkResponse = z.infer<\n typeof createTeamInviteLinkResponseSchema\n>;\n\n// Join link public info (no auth required)\nexport const joinLinkInfoResponseSchema = z.object({\n valid: z.boolean(),\n teamName: z.string().optional(),\n teamId: z.guid().optional(),\n reason: z.enum([\"invalid\", \"expired\"]).optional(),\n});\n\nexport type JoinLinkInfoResponse = z.infer<typeof joinLinkInfoResponseSchema>;\n\n// Accept join link response\nexport const acceptJoinLinkResponseSchema = z.object({\n success: z.boolean(),\n teamId: z.guid(),\n});\n\nexport type AcceptJoinLinkResponse = z.infer<\n typeof acceptJoinLinkResponseSchema\n>;\n", "/**\n * Utilities for the x-agent-run-api-key header.\n *\n * The header format is \"{runId}:{apiKey}\" and is used to authenticate\n * requests from the agent runtime to MCP servers.\n */\n\n/**\n * The header name for agent run API key authentication.\n */\nexport const AGENT_RUN_API_KEY_HEADER = \"x-agent-run-api-key\";\n\n/**\n * Result of parsing the x-agent-run-api-key header.\n */\nexport interface ParsedAgentRunApiKey {\n runId: string;\n apiKey: string;\n}\n\n/**\n * Parses the x-agent-run-api-key header format: \"{runId}:{apiKey}\"\n * Returns null if the header is missing or malformed.\n */\nexport const parseAgentRunApiKeyHeader = (\n agentRunApiKey: string | undefined\n): ParsedAgentRunApiKey | null => {\n if (!agentRunApiKey) {\n return null;\n }\n\n const parts = agentRunApiKey.split(\":\");\n if (parts.length !== 2) {\n return null;\n }\n\n const [runId, apiKey] = parts.map((s) => s.trim());\n if (!runId || !apiKey) {\n return null;\n }\n\n return { runId, apiKey };\n};\n\n/**\n * Builds the x-agent-run-api-key header value from runId and apiKey.\n * Format: \"{runId}:{apiKey}\"\n */\nexport const buildAgentRunApiKeyHeader = (\n runId: string,\n apiKey: string\n): string => {\n return `${runId}:${apiKey}`;\n};\n", "import { z } from \"zod\";\n\nexport type LabelFilters = Record<string, string[]>;\n\nexport const caseFilterStatusSchema = z.enum([\n \"pending\",\n \"claimed\",\n \"completed\",\n \"failed\",\n \"needs_input\",\n \"postponed\",\n]);\n\nexport type CaseFilterStatus = z.infer<typeof caseFilterStatusSchema>;\n\nexport const casesFiltersSchema = z.object({\n status: z.array(caseFilterStatusSchema).optional(),\n created_at_from: z.string().optional(),\n updated_at_from: z.string().optional(),\n labels: z.record(z.string(), z.array(z.string())).optional(),\n});\n\nexport type CasesFilters = z.infer<typeof casesFiltersSchema>;\n\nexport const casesListRequestBodySchema = z.object({\n filters: casesFiltersSchema.default({}),\n limit: z.int().min(1).max(100).default(25),\n offset: z.int().min(0).default(0),\n sort_by: z\n .enum([\"created_at\", \"updated_at\", \"postponed_to\"])\n .default(\"created_at\"),\n sort_order: z.enum([\"asc\", \"desc\"]).default(\"desc\"),\n search: z.string().optional(),\n});\n\nexport type CasesListRequestBody = z.infer<typeof casesListRequestBodySchema>;\n\nexport interface CasesListRequestOptions {\n limit: number;\n offset: number;\n sort_by: \"created_at\" | \"updated_at\" | \"postponed_to\";\n sort_order: \"asc\" | \"desc\";\n search?: string;\n}\n\nfunction toBase64(input: string): string {\n if (typeof btoa === \"function\") {\n return btoa(unescape(encodeURIComponent(input)));\n }\n return Buffer.from(input, \"utf-8\").toString(\"base64\");\n}\n\nfunction fromBase64(input: string): string {\n if (typeof atob === \"function\") {\n return decodeURIComponent(escape(atob(input)));\n }\n return Buffer.from(input, \"base64\").toString(\"utf-8\");\n}\n\nexport function parseLabelsFromUrlParam(\n param: string | null | undefined\n): LabelFilters {\n if (!param) {\n return {};\n }\n try {\n const parsed: unknown = JSON.parse(fromBase64(param));\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return {};\n }\n const result: LabelFilters = {};\n for (const [key, values] of Object.entries(parsed)) {\n if (Array.isArray(values) && values.every((v) => typeof v === \"string\")) {\n result[key] = values as string[];\n }\n }\n return result;\n } catch {\n return {};\n }\n}\n\nexport function serializeLabelsToUrlParam(labels: LabelFilters): string {\n return toBase64(JSON.stringify(labels));\n}\n\n/**\n * All filters serialize into a single `f` URL param as base64-encoded JSON.\n */\nexport const FILTERS_URL_PARAM = \"f\";\n\nexport function serializeCasesFiltersToUrlParam(filters: CasesFilters): string {\n if (isCasesFiltersEmpty(filters)) {\n return \"\";\n }\n return toBase64(JSON.stringify(filters));\n}\n\nexport function parseCasesFiltersFromUrlParam(\n value: string | null | undefined\n): CasesFilters {\n if (!value) {\n return {};\n }\n try {\n const parsed: unknown = JSON.parse(fromBase64(value));\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return {};\n }\n const result = casesFiltersSchema.safeParse(parsed);\n return result.success ? result.data : {};\n } catch {\n return {};\n }\n}\n\nconst LABEL_PREFIX = \"label:\";\n\n/** Read the values for a dropdown category key from typed CasesFilters. */\nexport function getFilterValuesByCategoryKey(\n filters: CasesFilters,\n categoryKey: string\n): string[] {\n if (categoryKey === \"status\") {\n return filters.status ?? [];\n }\n if (categoryKey === \"created_at_from\") {\n return filters.created_at_from ? [filters.created_at_from] : [];\n }\n if (categoryKey === \"updated_at_from\") {\n return filters.updated_at_from ? [filters.updated_at_from] : [];\n }\n if (categoryKey.startsWith(LABEL_PREFIX)) {\n const labelKey = categoryKey.slice(LABEL_PREFIX.length);\n return filters.labels?.[labelKey] ?? [];\n }\n return [];\n}\n\n/** Update a category's values, returning a new CasesFilters. Empty clears. */\nexport function setFilterValuesByCategoryKey(\n filters: CasesFilters,\n categoryKey: string,\n values: string[]\n): CasesFilters {\n if (categoryKey === \"status\") {\n if (values.length === 0) {\n const { status: _, ...rest } = filters;\n return rest;\n }\n const parsed = z.array(caseFilterStatusSchema).safeParse(values);\n if (!parsed.success) {\n return filters;\n }\n return { ...filters, status: parsed.data };\n }\n if (categoryKey === \"created_at_from\") {\n if (values.length === 0 || !values[0]) {\n const { created_at_from: _, ...rest } = filters;\n return rest;\n }\n return { ...filters, created_at_from: values[0] };\n }\n if (categoryKey === \"updated_at_from\") {\n if (values.length === 0 || !values[0]) {\n const { updated_at_from: _, ...rest } = filters;\n return rest;\n }\n return { ...filters, updated_at_from: values[0] };\n }\n if (categoryKey.startsWith(LABEL_PREFIX)) {\n const labelKey = categoryKey.slice(LABEL_PREFIX.length);\n const nextLabels = { ...(filters.labels ?? {}) };\n if (values.length === 0) {\n delete nextLabels[labelKey];\n } else {\n nextLabels[labelKey] = values;\n }\n if (Object.keys(nextLabels).length === 0) {\n const { labels: _, ...rest } = filters;\n return rest;\n }\n return { ...filters, labels: nextLabels };\n }\n return filters;\n}\n\nexport function removeFilterByCategoryKey(\n filters: CasesFilters,\n categoryKey: string\n): CasesFilters {\n return setFilterValuesByCategoryKey(filters, categoryKey, []);\n}\n\nexport function isCasesFiltersEmpty(filters: CasesFilters): boolean {\n return (\n !filters.status?.length &&\n !filters.created_at_from &&\n !filters.updated_at_from &&\n (!filters.labels || Object.keys(filters.labels).length === 0)\n );\n}\n\nexport function countCasesFilters(filters: CasesFilters): number {\n let count = 0;\n if (filters.status?.length) {\n count += 1;\n }\n if (filters.created_at_from) {\n count += 1;\n }\n if (filters.updated_at_from) {\n count += 1;\n }\n if (filters.labels) {\n count += Object.keys(filters.labels).length;\n }\n return count;\n}\n", "import { COMPOSIO_AUTH_CONFIGS } from \"../types/composio\";\nimport { IntegrationSlug } from \"../types/integration\";\n\nexport const getAppSpecBySlug = (slug: string) =>\n COMPOSIO_AUTH_CONFIGS.find((a) => a.slug === (slug as IntegrationSlug));\n", "export function normalizeDomain(value: string): string {\n return (value || \"\")\n .trim()\n .toLowerCase()\n .replace(/^www\\./, \"\");\n}\n\nexport function deriveDomain(input: string): string {\n let value = (input || \"\").trim().toLowerCase();\n if (!value) {\n return value;\n }\n const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\//.test(value);\n if (hasScheme) {\n try {\n const u = new URL(value);\n value = u.hostname;\n } catch {\n // fall back to original value on parse failure\n }\n } else {\n const stopIdx = [\"/\", \"?\", \"#\"].reduce((idx, ch) => {\n const i = value.indexOf(ch);\n return i !== -1 && (idx === -1 || i < idx) ? i : idx;\n }, -1);\n if (stopIdx !== -1) {\n value = value.slice(0, stopIdx);\n }\n const colon = value.indexOf(\":\");\n if (colon > -1) {\n value = value.slice(0, colon);\n }\n }\n return normalizeDomain(value);\n}\n\n/**\n * Server-compatible variant that returns undefined for empty input\n */\nexport function deriveHostnameFromInput(input?: string): string | undefined {\n if (!input) {\n return undefined;\n }\n const value = deriveDomain(input);\n return value ? value : undefined;\n}\n", "// Matches the on-disk `<DUVO:AGENT id=\"...\" name=\"...\">` tag shape produced\n// by the agent-instructions textarea. The escape pair `\\\\.` lets `\\\"` and\n// `\\\\` round-trip through the attribute values.\nconst AGENT_MENTION_REGEX_SOURCE = `<DUVO:AGENT\\\\s+id=\"((?:[^\"\\\\\\\\]|\\\\\\\\.)*)\"\\\\s+name=\"((?:[^\"\\\\\\\\]|\\\\\\\\.)*)\">`;\n\nfunction unescapeAttrValue(value: string): string {\n return value.replace(/\\\\(.)/g, \"$1\");\n}\n\n/**\n * Extracts unique agent IDs referenced by `<DUVO:AGENT>` mentions in SOP\n * text. Used to keep a build's handover target list in sync with the agents\n * mentioned in the SOP \u2014 the source of truth for which agents are valid\n * handover targets.\n */\nexport function extractAgentMentionIds(text: string): string[] {\n if (!text) {\n return [];\n }\n\n const regex = new RegExp(AGENT_MENTION_REGEX_SOURCE, \"g\");\n const ids = new Set<string>();\n for (const match of text.matchAll(regex)) {\n ids.add(unescapeAttrValue(match[1]));\n }\n\n return Array.from(ids);\n}\n", "import type { InputContent } from \"../types/agent-config\";\nimport type { EditableAgentConfig } from \"./normalize-agent-config\";\n\n/**\n * Extracts the system prompt text from an agent config's input field.\n *\n * Handles all input shapes:\n * - A plain string (legacy configs)\n * - An array of messages where the system role message contains the SOP\n * - Content can be a string or an array of typed content blocks\n */\nexport function extractSystemPromptText(\n input: EditableAgentConfig[\"input\"] | undefined | null\n): string {\n if (!input) {\n return \"\";\n }\n\n if (typeof input === \"string\") {\n return input;\n }\n\n if (!Array.isArray(input) || input.length === 0) {\n return \"\";\n }\n\n const systemMessage = input.find((msg) => msg.role === \"system\");\n if (!systemMessage?.content) {\n return \"\";\n }\n\n if (typeof systemMessage.content === \"string\") {\n return systemMessage.content;\n }\n\n if (Array.isArray(systemMessage.content)) {\n const textContent = systemMessage.content.find(\n (c): c is Extract<InputContent, { type: \"input_text\" }> =>\n c.type === \"input_text\"\n );\n return textContent?.text ?? \"\";\n }\n\n return \"\";\n}\n", "export type SentryEnvironment = \"development\" | \"staging\" | \"production\";\n\nconst VALID_ENVIRONMENTS: Record<SentryEnvironment, SentryEnvironment> = {\n development: \"development\",\n staging: \"staging\",\n production: \"production\",\n};\n\nconst ALIAS_MAP: Record<string, SentryEnvironment> = {\n \"vercel-preview\": \"staging\",\n \"vercel-production\": \"production\",\n};\n\nfunction normalize(value: string | undefined | null) {\n return value?.toLowerCase().trim();\n}\n\n/**\n * Restrict Sentry environment values to the canonical trio the team expects.\n * Only the exact names development/staging/production are retained, with\n * vercel-preview mapped to staging and vercel-production mapped to production.\n * The first match is used; fallback is development.\n */\nexport function getSentryEnvironment(\n ...candidates: Array<string | undefined | null>\n): SentryEnvironment {\n for (const candidate of candidates) {\n const normalized = normalize(candidate);\n\n if (!normalized) {\n continue;\n }\n\n if (normalized in ALIAS_MAP) {\n return ALIAS_MAP[normalized];\n }\n\n if (normalized in VALID_ENVIRONMENTS) {\n return VALID_ENVIRONMENTS[normalized as SentryEnvironment];\n }\n }\n\n return \"development\";\n}\n", "import type { InputContent } from \"../types/agent-config\";\nimport type { EditableAgentConfig } from \"./normalize-agent-config\";\n\n/**\n * Checks if an agent config has non-empty instructions (SOP content).\n *\n * Instructions can be:\n * - A non-empty string\n * - An array with a system message containing non-empty text content\n */\nexport function hasInstructions(\n input: EditableAgentConfig[\"input\"] | undefined | null\n): boolean {\n if (!input) {\n return false;\n }\n\n if (typeof input === \"string\") {\n return Boolean(input.trim());\n }\n\n if (!Array.isArray(input) || input.length === 0) {\n return false;\n }\n\n const systemMessage = input.find((msg) => msg.role === \"system\");\n if (!systemMessage?.content) {\n return false;\n }\n\n if (typeof systemMessage.content === \"string\") {\n return Boolean(systemMessage.content.trim());\n }\n\n if (Array.isArray(systemMessage.content)) {\n const textContent = systemMessage.content.find(\n (c): c is Extract<InputContent, { type: \"input_text\" }> =>\n c.type === \"input_text\"\n );\n return Boolean(textContent?.text?.trim());\n }\n\n return false;\n}\n", "import { jsonrepair } from \"jsonrepair\";\nimport type { z, ZodType } from \"zod\";\n\ninterface Logger {\n warn: (obj: Record<string, unknown>, msg: string) => void;\n}\n\nexport function safeParseJson<S extends ZodType>(\n input: string,\n log: Logger,\n schema: S\n): z.output<S> {\n let raw: unknown;\n try {\n raw = JSON.parse(input);\n } catch (parseError) {\n log.warn(\n { error: parseError },\n \"Input contains invalid JSON, attempting repair\"\n );\n try {\n const repaired = jsonrepair(input);\n raw = JSON.parse(repaired);\n } catch (repairError) {\n throw new Error(\n `Failed to parse input even after repair: ${repairError instanceof Error ? repairError.message : String(repairError)}`\n );\n }\n }\n\n return schema.parse(raw);\n}\n", "export const BASE_HUES = [0, 30, 50, 90, 145, 175, 215, 270, 330] as const;\n\nexport type LabelHue = (typeof BASE_HUES)[number];\n\nexport function isLabelHue(value: number): value is LabelHue {\n return (BASE_HUES as readonly number[]).includes(value);\n}\n", "/**\n * MCP Server Label Utilities\n *\n * Unified functions for generating and parsing MCP server labels across\n * backend and frontend. Ensures consistent format for tool identification.\n *\n * Server label formats:\n * - Default integrations: \"{integration_type}\" (e.g., \"browser-agent-devtools\")\n * - Integrations with instances: \"{integration_type}_{instance_id_uuid}\" (e.g., \"gmail_2bf44658-....\", \"custom_mcp_bb92426d-....\")\n */\n\n/**\n * Generates a unique MCP server label for an integration instance.\n *\n * @param integrationType - The integration type slug (e.g., \"gmail\", \"custom_mcp\")\n * @param instanceId - The integration instance UUID (null for default integrations)\n * @returns The generated server label\n *\n * @example\n * // Default integration (no instance)\n * generateMcpServerLabel(\"browser-agent-devtools\", null) // \"browser-agent-devtools\"\n *\n * @example\n * // OAuth integration\n * generateMcpServerLabel(\"gmail\", \"2bf44658-...\") // \"gmail_2bf44658-...\"\n *\n * @example\n * // Custom MCP\n * generateMcpServerLabel(\"custom_mcp\", \"bb92426d-...\") // \"custom_mcp_bb92426d-...\"\n */\nexport function generateMcpServerLabel(\n integrationType: string,\n instanceId: string | null\n): string {\n if (!instanceId) {\n // Default integrations (browser-agent-devtools, exa, etc.) have no instances\n return integrationType;\n }\n\n // Append full instance UUID for unambiguous lookup\n return `${integrationType}_${instanceId}`;\n}\n\nexport interface ParsedMcpServerLabel {\n /** The base integration type slug (e.g., \"custom_mcp\", \"gmail\", \"browser-agent-devtools\") */\n integrationType: string;\n /** The full instance UUID (preferred) or legacy 8-char prefix, or null for default integrations */\n instanceId: string | null;\n}\n\n/**\n * Parses an MCP server label to extract its components.\n *\n * @param serverLabel - The server label to parse\n * @returns Parsed components including integration type and instance ID\n *\n * @example\n * // Default integration\n * parseMcpServerLabel(\"browser-agent-devtools\")\n * // { integrationType: \"browser-agent-devtools\", instanceId: null }\n *\n * @example\n * // OAuth integration\n * parseMcpServerLabel(\"gmail_2bf44658-6dbd-4c39-8ad1-7f4a0d2dcb2a\")\n * // { integrationType: \"gmail\", instanceId: \"2bf44658-6dbd-4c39-8ad1-7f4a0d2dcb2a\" }\n *\n * @example\n * // Custom MCP\n * parseMcpServerLabel(\"custom_mcp_bb92426d-6dbd-4c39-8ad1-7f4a0d2dcb2a\")\n * // { integrationType: \"custom_mcp\", instanceId: \"bb92426d-6dbd-4c39-8ad1-7f4a0d2dcb2a\" }\n */\nexport function parseMcpServerLabel(serverLabel: string): ParsedMcpServerLabel {\n // Prefer full UUIDs (supports optional trailing suffixes like `_1` when names\n // need to be disambiguated by the runtime).\n const uuidPattern =\n /_([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})(?=$|_)/gi;\n let uuidMatch: RegExpExecArray | null = null;\n for (let match = uuidPattern.exec(serverLabel); match; ) {\n uuidMatch = match;\n match = uuidPattern.exec(serverLabel);\n }\n\n if (uuidMatch) {\n const instanceId = uuidMatch[1] ?? null;\n const integrationType = serverLabel.slice(0, uuidMatch.index);\n return { integrationType, instanceId };\n }\n\n // Legacy format: _[8 hex chars] (also supports optional trailing suffixes).\n const legacyPattern = /_([a-f0-9]{8})(?=$|_)/gi;\n let legacyMatch: RegExpExecArray | null = null;\n for (let match = legacyPattern.exec(serverLabel); match; ) {\n legacyMatch = match;\n match = legacyPattern.exec(serverLabel);\n }\n\n if (legacyMatch) {\n const instanceId = legacyMatch[1] ?? null;\n const integrationType = serverLabel.slice(0, legacyMatch.index);\n return { integrationType, instanceId };\n }\n\n // No instance ID suffix - this is a default integration\n return {\n integrationType: serverLabel,\n instanceId: null,\n };\n}\n\n/**\n * Extracts only the integration type slug from a server label.\n * Convenience wrapper around parseMcpServerLabel.\n *\n * @param serverLabel - The server label to parse\n * @returns The integration type slug\n *\n * @example\n * extractIntegrationTypeFromServerLabel(\"gmail_2bf44658-...\") // \"gmail\"\n * extractIntegrationTypeFromServerLabel(\"custom_mcp_bb92426d-...\") // \"custom_mcp\"\n */\nexport function extractIntegrationTypeFromServerLabel(\n serverLabel: string\n): string {\n return parseMcpServerLabel(serverLabel).integrationType;\n}\n", "import {\n type BrowsingModelId,\n type BrowsingProvider,\n CLAUDE_MODEL_IDS,\n type ClaudeModelId,\n type CoreClaudeModelId,\n LEGACY_DEFAULT_MODEL,\n PLATFORM_DEFAULT_MODELS,\n} from \"../constants/models\";\nimport type {\n AgentConfigV1,\n AgentConfigV2,\n RuntimeOptions,\n} from \"../types/agent-config\";\n\ntype InputMessage = Extract<AgentConfigV2[\"input\"], Array<unknown>>[number];\n\n/**\n * Normalized config format for UI editing\n */\nexport interface EditableAgentConfig {\n models: {\n agent: {\n model: ClaudeModelId;\n };\n browsing: {\n provider: BrowsingProvider;\n model: BrowsingModelId;\n };\n };\n input: string | InputMessage[];\n files?: string[];\n skills?: string[];\n plugins?: string[];\n subAgents?: string[];\n options?: RuntimeOptions;\n}\n\nexport function normalizeToEditableConfig(\n config: AgentConfigV1 | AgentConfigV2 | EditableAgentConfig\n): EditableAgentConfig {\n // Check if config has v2 nested models structure\n const hasNestedModels =\n \"models\" in config && config.models?.agent !== undefined;\n\n if (hasNestedModels && config.models) {\n // v2 config with nested structure\n const rawModel = config.models.agent.model;\n const isValidCoreModel =\n !!rawModel && CLAUDE_MODEL_IDS.includes(rawModel as CoreClaudeModelId);\n\n return {\n models: {\n agent: {\n model: isValidCoreModel ? rawModel : LEGACY_DEFAULT_MODEL,\n },\n browsing: {\n provider:\n config.models.browsing?.provider ??\n PLATFORM_DEFAULT_MODELS.browsing.provider,\n model:\n config.models.browsing?.model ??\n PLATFORM_DEFAULT_MODELS.browsing.model,\n },\n },\n input: config.input ?? \"\",\n files: config.files ?? [],\n skills: config.skills ?? [],\n plugins: (\"plugins\" in config ? config.plugins : undefined) ?? [],\n subAgents: (\"subAgents\" in config ? config.subAgents : undefined) ?? [],\n options: config.options,\n };\n }\n\n // v1 config with flat structure \u2014 any stored model (including missing) resolves\n // to LEGACY_DEFAULT_MODEL. Browsing uses platform defaults since v1 never\n // carried a browsing provider/model.\n return {\n models: {\n agent: { model: LEGACY_DEFAULT_MODEL },\n browsing: {\n provider: PLATFORM_DEFAULT_MODELS.browsing.provider,\n model: PLATFORM_DEFAULT_MODELS.browsing.model,\n },\n },\n input: config.input ?? \"\",\n files: config.files ?? [],\n skills: config.skills ?? [],\n plugins: [], // v1 configs don't have plugins\n subAgents: [], // v1 configs don't have subAgents\n };\n}\n\nexport function normalizeForDatabase(\n config: EditableAgentConfig\n): AgentConfigV2 {\n return {\n ...config,\n files: config.files ?? [],\n skills: config.skills ?? [],\n plugins: config.plugins ?? [],\n subAgents: config.subAgents ?? [],\n };\n}\n", "/** Throw this inside a pRetry callback to abort immediately without retrying. */\nexport class AbortError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AbortError\";\n }\n}\n\n/**\n * Retries a promise-returning function with exponential backoff.\n * Throw AbortError to stop retrying immediately.\n *\n * @param fn - The async function to retry\n * @param retries - Maximum number of retry attempts (default: 3)\n * @returns The resolved value of `fn`\n */\nexport async function pRetry<T>(fn: () => Promise<T>, retries = 3): Promise<T> {\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n // eslint-disable-next-line no-await-in-loop\n return await fn();\n } catch (err) {\n if (err instanceof AbortError || attempt === retries) {\n throw err;\n }\n // eslint-disable-next-line no-await-in-loop\n await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 100));\n }\n }\n throw new Error(\"pRetry: unreachable\");\n}\n", "import {\n mapModelToClaudeModel,\n PLATFORM_DEFAULT_MODELS,\n} from \"../constants/models\";\nimport {\n AgentConfigSchema,\n type AgentConfigV2,\n StoredAgentConfigSchemaV1,\n StoredAgentConfigSchemaV2,\n} from \"../types/agent-config\";\n\nexport interface ParseAgentConfigOptions {\n buildId?: string;\n expectedVersion?: string;\n}\n\nexport interface ParseAgentConfigResult {\n config: AgentConfigV2 | null;\n error?: string;\n isLegacyFormat?: boolean;\n versionMismatch?: boolean;\n version?: \"v1\" | \"v2\";\n}\n\nexport function parseAgentConfig(\n configJson: unknown,\n options: ParseAgentConfigOptions = {}\n): ParseAgentConfigResult {\n if (!configJson) {\n return { config: null };\n }\n\n try {\n const parsed =\n typeof configJson === \"string\" ? JSON.parse(configJson) : configJson;\n\n // Check if this is a versioned config\n if (parsed.version && parsed.data) {\n // Try v2 first\n const v2Result = StoredAgentConfigSchemaV2.safeParse(parsed);\n if (v2Result.success) {\n const data = v2Result.data.data;\n\n // v2 always has nested models structure\n // Normalize legacy model IDs (gpt-*, duvo-1-max) to Claude model IDs\n const resolvedConfig: AgentConfigV2 = {\n ...data,\n models: {\n agent: {\n model: mapModelToClaudeModel(data.models.agent.model),\n },\n browsing: {\n provider:\n data.models.browsing.provider ??\n PLATFORM_DEFAULT_MODELS.browsing.provider,\n model:\n data.models.browsing.model ??\n PLATFORM_DEFAULT_MODELS.browsing.model,\n },\n },\n };\n\n // Check version compatibility\n const versionMismatch = options.expectedVersion\n ? v2Result.data.version !== options.expectedVersion\n : undefined;\n\n return {\n config: resolvedConfig,\n version: \"v2\",\n versionMismatch,\n };\n }\n\n // Try v1 and convert to v2 format\n const v1Result = StoredAgentConfigSchemaV1.safeParse(parsed);\n if (v1Result.success) {\n const storedConfig = v1Result.data;\n const v1Data = storedConfig.data;\n\n // Convert v1 flat structure to v2 nested structure\n // Map legacy model IDs (gpt-*, duvo-1-max) to Claude model IDs\n const convertedConfig: AgentConfigV2 = {\n models: {\n agent: {\n model: mapModelToClaudeModel(v1Data.model),\n },\n browsing: {\n provider: PLATFORM_DEFAULT_MODELS.browsing.provider,\n model: PLATFORM_DEFAULT_MODELS.browsing.model,\n },\n },\n input: v1Data.input ?? \"\",\n files: v1Data.files ?? [],\n skills: v1Data.skills ?? [],\n plugins: [],\n subAgents: [],\n };\n\n // Check version compatibility\n const versionMismatch = options.expectedVersion\n ? storedConfig.version !== options.expectedVersion\n : undefined;\n\n return {\n config: convertedConfig,\n version: \"v1\",\n versionMismatch,\n };\n }\n\n // Both failed\n const errorMessage = options.buildId\n ? `Invalid versioned config format for build ${options.buildId}: ${v2Result.error.message}`\n : `Invalid versioned config format: ${v2Result.error.message}`;\n\n return {\n config: null,\n error: errorMessage,\n };\n } else {\n // Legacy format - validate config directly with Zod\n const result = AgentConfigSchema.safeParse(parsed);\n if (!result.success) {\n const errorMessage = options.buildId\n ? `Invalid legacy config format for build ${options.buildId}: ${result.error.message}`\n : `Invalid legacy config format: ${result.error.message}`;\n\n return {\n config: null,\n error: errorMessage,\n isLegacyFormat: true,\n };\n }\n\n return {\n config: result.data,\n isLegacyFormat: true,\n };\n }\n } catch (error) {\n const errorMessage = options.buildId\n ? `Failed to parse config for build ${options.buildId}: ${error}`\n : `Failed to parse config: ${error}`;\n\n return {\n config: null,\n error: errorMessage,\n };\n }\n}\n", "import { LEGACY_DEFAULT_BROWSER_PROVIDER } from \"../constants/agent\";\nimport { BrowserProviderType } from \"../types/agent-config\";\nimport {\n isStoredRunConfigV0,\n isStoredRunConfigV1,\n RunConfig,\n StoredRunConfigSchema,\n StoredRunConfigV1,\n} from \"../types/run-config\";\n\nexport interface ParseRunConfigResult {\n config: RunConfig | null;\n version: \"v0\" | \"v1\" | null;\n error?: string;\n}\n\n/**\n * Parses a stored run config from JSON (string or object).\n * Returns the inner RunConfig for v1, null for v0.\n *\n * Handles:\n * - V1: {version: \"v1\", data: RunConfig} \u2192 returns data\n * - V0: {version: \"v0\"} \u2192 returns null (legacy placeholder)\n * - null/undefined \u2192 returns null\n * - Invalid format \u2192 returns null with error\n */\nexport function parseRunConfig(configJson: unknown): ParseRunConfigResult {\n if (configJson == null) {\n return { config: null, version: null };\n }\n\n try {\n const parsed =\n typeof configJson === \"string\" ? JSON.parse(configJson) : configJson;\n\n const result = StoredRunConfigSchema.safeParse(parsed);\n\n if (result.success) {\n if (isStoredRunConfigV1(result.data)) {\n return { config: result.data.data, version: \"v1\" };\n }\n if (isStoredRunConfigV0(result.data)) {\n return { config: null, version: \"v0\" };\n }\n }\n\n return {\n config: null,\n version: null,\n error: `Invalid run config format: ${result.error?.message ?? \"unknown error\"}`,\n };\n } catch (error) {\n return {\n config: null,\n version: null,\n error: `Failed to parse run config JSON: ${error}`,\n };\n }\n}\n\n/**\n * Convenience function to check if a stored config has dispatchable data.\n * Returns true only for V1 configs (which have the full RunConfig data).\n */\nexport function hasDispatchableRunConfig(configJson: unknown): boolean {\n const { config } = parseRunConfig(configJson);\n return config !== null;\n}\n\n/**\n * Creates a StoredRunConfigV1 wrapper around a RunConfig.\n */\nexport function wrapRunConfig(config: RunConfig): StoredRunConfigV1 {\n return { version: \"v1\", data: config };\n}\n\n/**\n * Extracts browser provider from a parsed RunConfig.\n *\n * Resolution order:\n * 1. config.options.browserProvider (if set)\n * 2. LEGACY_DEFAULT_BROWSER_PROVIDER (browserbase)\n *\n * This ensures backward compatibility for legacy runs that were created\n * before browserProvider was added to the config.\n *\n * @param config - The parsed RunConfig from parseRunConfig()\n * @returns The browser provider type to use for this run\n */\nexport function getBrowserProviderFromRunConfig(\n config: RunConfig | null\n): BrowserProviderType {\n if (config?.options?.browserProvider) {\n return config.options.browserProvider;\n }\n return LEGACY_DEFAULT_BROWSER_PROVIDER;\n}\n", "export class JSONRepairError extends Error {\n position: number\n\n constructor(message: string, position: number) {\n super(`${message} at position ${position}`)\n\n this.position = position\n }\n}\n", "const codeSpace = 0x20 // \" \"\nconst codeNewline = 0xa // \"\\n\"\nconst codeTab = 0x9 // \"\\t\"\nconst codeReturn = 0xd // \"\\r\"\nconst codeNonBreakingSpace = 0xa0\nconst codeEnQuad = 0x2000\nconst codeHairSpace = 0x200a\nconst codeNarrowNoBreakSpace = 0x202f\nconst codeMediumMathematicalSpace = 0x205f\nconst codeIdeographicSpace = 0x3000\n\nexport function isHex(char: string): boolean {\n return /^[0-9A-Fa-f]$/.test(char)\n}\n\nexport function isDigit(char: string): boolean {\n return char >= '0' && char <= '9'\n}\n\nexport function isValidStringCharacter(char: string): boolean {\n // note that the valid range is between \\u{0020} and \\u{10ffff},\n // but in JavaScript it is not possible to create a code point larger than\n // \\u{10ffff}, so there is no need to test for that here.\n return char >= '\\u0020'\n}\n\nexport function isDelimiter(char: string): boolean {\n return ',:[]/{}()\\n+'.includes(char)\n}\n\nexport function isFunctionNameCharStart(char: string) {\n return (\n (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || char === '_' || char === '$'\n )\n}\n\nexport function isFunctionNameChar(char: string) {\n return (\n (char >= 'a' && char <= 'z') ||\n (char >= 'A' && char <= 'Z') ||\n char === '_' ||\n char === '$' ||\n (char >= '0' && char <= '9')\n )\n}\n\n// matches \"https://\" and other schemas\nexport const regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\\/\\/$/\n\n// matches all valid URL characters EXCEPT \"[\", \"]\", and \",\", since that are important JSON delimiters\nexport const regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/\n\nexport function isUnquotedStringDelimiter(char: string): boolean {\n return ',[]/{}\\n+'.includes(char)\n}\n\nexport function isStartOfValue(char: string): boolean {\n return isQuote(char) || regexStartOfValue.test(char)\n}\n\n// alpha, number, minus, or opening bracket or brace\nconst regexStartOfValue = /^[[{\\w-]$/\n\nexport function isControlCharacter(char: string) {\n return char === '\\n' || char === '\\r' || char === '\\t' || char === '\\b' || char === '\\f'\n}\n\nexport interface Text {\n charCodeAt: (index: number) => number\n}\n\n/**\n * Check if the given character is a whitespace character like space, tab, or\n * newline\n */\nexport function isWhitespace(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn\n}\n\n/**\n * Check if the given character is a whitespace character like space or tab,\n * but NOT a newline\n */\nexport function isWhitespaceExceptNewline(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return code === codeSpace || code === codeTab || code === codeReturn\n}\n\n/**\n * Check if the given character is a special whitespace character, some\n * unicode variant\n */\nexport function isSpecialWhitespace(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return (\n code === codeNonBreakingSpace ||\n (code >= codeEnQuad && code <= codeHairSpace) ||\n code === codeNarrowNoBreakSpace ||\n code === codeMediumMathematicalSpace ||\n code === codeIdeographicSpace\n )\n}\n\n/**\n * Test whether the given character is a quote or double quote character.\n * Also tests for special variants of quotes.\n */\nexport function isQuote(char: string): boolean {\n // the first check double quotes, since that occurs most often\n return isDoubleQuoteLike(char) || isSingleQuoteLike(char)\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Also tests for special variants of double quotes.\n */\nexport function isDoubleQuoteLike(char: string): boolean {\n return char === '\"' || char === '\\u201c' || char === '\\u201d'\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Does NOT test for special variants of double quotes.\n */\nexport function isDoubleQuote(char: string): boolean {\n return char === '\"'\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Also tests for special variants of single quotes.\n */\nexport function isSingleQuoteLike(char: string): boolean {\n return (\n char === \"'\" || char === '\\u2018' || char === '\\u2019' || char === '\\u0060' || char === '\\u00b4'\n )\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Does NOT test for special variants of single quotes.\n */\nexport function isSingleQuote(char: string): boolean {\n return char === \"'\"\n}\n\n/**\n * Strip last occurrence of textToStrip from text\n */\nexport function stripLastOccurrence(\n text: string,\n textToStrip: string,\n stripRemainingText = false\n): string {\n const index = text.lastIndexOf(textToStrip)\n return index !== -1\n ? text.substring(0, index) + (stripRemainingText ? '' : text.substring(index + 1))\n : text\n}\n\nexport function insertBeforeLastWhitespace(text: string, textToInsert: string): string {\n let index = text.length\n\n if (!isWhitespace(text, index - 1)) {\n // no trailing whitespaces\n return text + textToInsert\n }\n\n while (isWhitespace(text, index - 1)) {\n index--\n }\n\n return text.substring(0, index) + textToInsert + text.substring(index)\n}\n\nexport function removeAtIndex(text: string, start: number, count: number) {\n return text.substring(0, start) + text.substring(start + count)\n}\n\n/**\n * Test whether a string ends with a newline or comma character and optional whitespace\n */\nexport function endsWithCommaOrNewline(text: string): boolean {\n return /[,\\n][ \\t\\r]*$/.test(text)\n}\n", "import { JSONRepairError } from '../utils/JSONRepairError.js'\nimport {\n endsWithCommaOrNewline,\n insertBeforeLastWhitespace,\n isControlCharacter,\n isDelimiter,\n isDigit,\n isDoubleQuote,\n isDoubleQuoteLike,\n isFunctionNameChar,\n isFunctionNameCharStart,\n isHex,\n isQuote,\n isSingleQuote,\n isSingleQuoteLike,\n isSpecialWhitespace,\n isStartOfValue,\n isUnquotedStringDelimiter,\n isValidStringCharacter,\n isWhitespace,\n isWhitespaceExceptNewline,\n regexUrlChar,\n regexUrlStart,\n removeAtIndex,\n stripLastOccurrence\n} from '../utils/stringUtils.js'\n\nconst controlCharacters: { [key: string]: string } = {\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t'\n}\n\n// map with all escape characters\nconst escapeCharacters: { [key: string]: string } = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t'\n // note that \\u is handled separately in parseString()\n}\n\n/**\n * Repair a string containing an invalid JSON document.\n * For example changes JavaScript notation into JSON notation.\n *\n * Example:\n *\n * try {\n * const json = \"{name: 'John'}\"\n * const repaired = jsonrepair(json)\n * console.log(repaired)\n * // '{\"name\": \"John\"}'\n * } catch (err) {\n * console.error(err)\n * }\n *\n */\nexport function jsonrepair(text: string): string {\n let i = 0 // current index in text\n let output = '' // generated output\n\n parseMarkdownCodeBlock(['```', '[```', '{```'])\n\n const processed = parseValue()\n if (!processed) {\n throwUnexpectedEnd()\n }\n\n parseMarkdownCodeBlock(['```', '```]', '```}'])\n\n const processedComma = parseCharacter(',')\n if (processedComma) {\n parseWhitespaceAndSkipComments()\n }\n\n if (isStartOfValue(text[i]) && endsWithCommaOrNewline(output)) {\n // start of a new value after end of the root level object: looks like\n // newline delimited JSON -> turn into a root level array\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n\n parseNewlineDelimitedJSON()\n } else if (processedComma) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',')\n }\n\n // repair redundant end quotes\n while (text[i] === '}' || text[i] === ']') {\n i++\n parseWhitespaceAndSkipComments()\n }\n\n if (i >= text.length) {\n // reached the end of the document properly\n return output\n }\n\n throwUnexpectedCharacter()\n\n function parseValue(): boolean {\n parseWhitespaceAndSkipComments()\n const processed =\n parseObject() ||\n parseArray() ||\n parseString() ||\n parseNumber() ||\n parseKeywords() ||\n parseUnquotedString(false) ||\n parseRegex()\n parseWhitespaceAndSkipComments()\n\n return processed\n }\n\n function parseWhitespaceAndSkipComments(skipNewline = true): boolean {\n const start = i\n\n let changed = parseWhitespace(skipNewline)\n do {\n changed = parseComment()\n if (changed) {\n changed = parseWhitespace(skipNewline)\n }\n } while (changed)\n\n return i > start\n }\n\n function parseWhitespace(skipNewline: boolean): boolean {\n const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline\n let whitespace = ''\n\n while (true) {\n if (_isWhiteSpace(text, i)) {\n whitespace += text[i]\n i++\n } else if (isSpecialWhitespace(text, i)) {\n // repair special whitespace\n whitespace += ' '\n i++\n } else {\n break\n }\n }\n\n if (whitespace.length > 0) {\n output += whitespace\n return true\n }\n\n return false\n }\n\n function parseComment(): boolean {\n // find a block comment '/* ... */'\n if (text[i] === '/' && text[i + 1] === '*') {\n // repair block comment by skipping it\n while (i < text.length && !atEndOfBlockComment(text, i)) {\n i++\n }\n i += 2\n\n return true\n }\n\n // find a line comment '// ...'\n if (text[i] === '/' && text[i + 1] === '/') {\n // repair line comment by skipping it\n while (i < text.length && text[i] !== '\\n') {\n i++\n }\n\n return true\n }\n\n return false\n }\n\n function parseMarkdownCodeBlock(blocks: string[]): boolean {\n // find and skip over a Markdown fenced code block:\n // ``` ... ```\n // or\n // ```json ... ```\n if (skipMarkdownCodeBlock(blocks)) {\n if (isFunctionNameCharStart(text[i])) {\n // strip the optional language specifier like \"json\"\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++\n }\n }\n\n parseWhitespaceAndSkipComments()\n\n return true\n }\n\n return false\n }\n\n function skipMarkdownCodeBlock(blocks: string[]): boolean {\n parseWhitespace(true)\n\n for (const block of blocks) {\n const end = i + block.length\n if (text.slice(i, end) === block) {\n i = end\n return true\n }\n }\n\n return false\n }\n\n function parseCharacter(char: string): boolean {\n if (text[i] === char) {\n output += text[i]\n i++\n return true\n }\n\n return false\n }\n\n function skipCharacter(char: string): boolean {\n if (text[i] === char) {\n i++\n return true\n }\n\n return false\n }\n\n function skipEscapeCharacter(): boolean {\n return skipCharacter('\\\\')\n }\n\n /**\n * Skip ellipsis like \"[1,2,3,...]\" or \"[1,2,3,...,9]\" or \"[...,7,8,9]\"\n * or a similar construct in objects.\n */\n function skipEllipsis(): boolean {\n parseWhitespaceAndSkipComments()\n\n if (text[i] === '.' && text[i + 1] === '.' && text[i + 2] === '.') {\n // repair: remove the ellipsis (three dots) and optionally a comma\n i += 3\n parseWhitespaceAndSkipComments()\n skipCharacter(',')\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse an object like '{\"key\": \"value\"}'\n */\n function parseObject(): boolean {\n if (text[i] === '{') {\n output += '{'\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: skip leading comma like in {, message: \"hi\"}\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n let initial = true\n while (i < text.length && text[i] !== '}') {\n let processedComma: boolean\n if (!initial) {\n processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n parseWhitespaceAndSkipComments()\n } else {\n processedComma = true\n initial = false\n }\n\n skipEllipsis()\n\n const processedKey = parseString() || parseUnquotedString(true)\n if (!processedKey) {\n if (\n text[i] === '}' ||\n text[i] === '{' ||\n text[i] === ']' ||\n text[i] === '[' ||\n text[i] === undefined\n ) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',')\n } else {\n throwObjectKeyExpected()\n }\n break\n }\n\n parseWhitespaceAndSkipComments()\n const processedColon = parseCharacter(':')\n const truncatedText = i >= text.length\n if (!processedColon) {\n if (isStartOfValue(text[i]) || truncatedText) {\n // repair missing colon\n output = insertBeforeLastWhitespace(output, ':')\n } else {\n throwColonExpected()\n }\n }\n const processedValue = parseValue()\n if (!processedValue) {\n if (processedColon || truncatedText) {\n // repair missing object value\n output += 'null'\n } else {\n throwColonExpected()\n }\n }\n }\n\n if (text[i] === '}') {\n output += '}'\n i++\n } else {\n // repair missing end bracket\n output = insertBeforeLastWhitespace(output, '}')\n }\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse an array like '[\"item1\", \"item2\", ...]'\n */\n function parseArray(): boolean {\n if (text[i] === '[') {\n output += '['\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: skip leading comma like in [,1,2,3]\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n let initial = true\n while (i < text.length && text[i] !== ']') {\n if (!initial) {\n const processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n } else {\n initial = false\n }\n\n skipEllipsis()\n\n const processedValue = parseValue()\n if (!processedValue) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',')\n break\n }\n }\n\n if (text[i] === ']') {\n output += ']'\n i++\n } else {\n // repair missing closing array bracket\n output = insertBeforeLastWhitespace(output, ']')\n }\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse and repair Newline Delimited JSON (NDJSON):\n * multiple JSON objects separated by a newline character\n */\n function parseNewlineDelimitedJSON() {\n // repair NDJSON\n let initial = true\n let processedValue = true\n while (processedValue) {\n if (!initial) {\n // parse optional comma, insert when missing\n const processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair: add missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n } else {\n initial = false\n }\n\n processedValue = parseValue()\n }\n\n if (!processedValue) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',')\n }\n\n // repair: wrap the output inside array brackets\n output = `[\\n${output}\\n]`\n }\n\n /**\n * Parse a string enclosed by double quotes \"...\". Can contain escaped quotes\n * Repair strings enclosed in single quotes or special quotes\n * Repair an escaped string\n *\n * The function can run in two stages:\n * - First, it assumes the string has a valid end quote\n * - If it turns out that the string does not have a valid end quote followed\n * by a delimiter (which should be the case), the function runs again in a\n * more conservative way, stopping the string at the first next delimiter\n * and fixing the string by inserting a quote there, or stopping at a\n * stop index detected in the first iteration.\n */\n function parseString(stopAtDelimiter = false, stopAtIndex = -1): boolean {\n let skipEscapeChars = text[i] === '\\\\'\n if (skipEscapeChars) {\n // repair: remove the first escape character\n i++\n skipEscapeChars = true\n }\n\n if (isQuote(text[i])) {\n // double quotes are correct JSON,\n // single quotes come from JavaScript for example, we assume it will have a correct single end quote too\n // otherwise, we will match any double-quote-like start with a double-quote-like end,\n // or any single-quote-like start with a single-quote-like end\n const isEndQuote = isDoubleQuote(text[i])\n ? isDoubleQuote\n : isSingleQuote(text[i])\n ? isSingleQuote\n : isSingleQuoteLike(text[i])\n ? isSingleQuoteLike\n : isDoubleQuoteLike\n\n const iBefore = i\n const oBefore = output.length\n\n let str = '\"'\n i++\n\n while (true) {\n if (i >= text.length) {\n // end of text, we are missing an end quote\n\n const iPrev = prevNonWhitespaceIndex(i - 1)\n if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) {\n // if the text ends with a delimiter, like [\"hello],\n // so the missing end quote should be inserted before this delimiter\n // retry parsing the string, stopping at the first next delimiter\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(true)\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n return true\n }\n\n if (i === stopAtIndex) {\n // use the stop index detected in the first iteration, and repair end quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n return true\n }\n\n if (isEndQuote(text[i])) {\n // end quote\n // let us check what is before and after the quote to verify whether this is a legit end quote\n const iQuote = i\n const oQuote = str.length\n str += '\"'\n i++\n output += str\n\n parseWhitespaceAndSkipComments(false)\n\n if (\n stopAtDelimiter ||\n i >= text.length ||\n isDelimiter(text[i]) ||\n isQuote(text[i]) ||\n isDigit(text[i])\n ) {\n // The quote is followed by the end of the text, a delimiter,\n // or a next value. So the quote is indeed the end of the string.\n parseConcatenatedString()\n\n return true\n }\n\n const iPrevChar = prevNonWhitespaceIndex(iQuote - 1)\n const prevChar = text.charAt(iPrevChar)\n\n if (prevChar === ',') {\n // A comma followed by a quote, like '{\"a\":\"b,c,\"d\":\"e\"}'.\n // We assume that the quote is a start quote, and that the end quote\n // should have been located right before the comma but is missing.\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(false, iPrevChar)\n }\n\n if (isDelimiter(prevChar)) {\n // This is not the right end quote: it is preceded by a delimiter,\n // and NOT followed by a delimiter. So, there is an end quote missing\n // parse the string again and then stop at the first next delimiter\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(true)\n }\n\n // revert to right after the quote but before any whitespace, and continue parsing the string\n output = output.substring(0, oBefore)\n i = iQuote + 1\n\n // repair unescaped quote\n str = `${str.substring(0, oQuote)}\\\\${str.substring(oQuote)}`\n } else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i])) {\n // we're in the mode to stop the string at the first delimiter\n // because there is an end quote missing\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(iBefore + 1, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n str += text[i]\n i++\n }\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n parseConcatenatedString()\n\n return true\n } else if (text[i] === '\\\\') {\n // handle escaped content like \\n or \\u2605\n const char = text.charAt(i + 1)\n const escapeChar = escapeCharacters[char]\n if (escapeChar !== undefined) {\n str += text.slice(i, i + 2)\n i += 2\n } else if (char === 'u') {\n let j = 2\n while (j < 6 && isHex(text[i + j])) {\n j++\n }\n\n if (j === 6) {\n str += text.slice(i, i + 6)\n i += 6\n } else if (i + j >= text.length) {\n // repair invalid or truncated unicode char at the end of the text\n // by removing the unicode char and ending the string here\n i = text.length\n } else {\n throwInvalidUnicodeCharacter()\n }\n } else {\n // repair invalid escape character: remove it\n str += char\n i += 2\n }\n } else {\n // handle regular characters\n const char = text.charAt(i)\n\n if (char === '\"' && text[i - 1] !== '\\\\') {\n // repair unescaped double quote\n str += `\\\\${char}`\n i++\n } else if (isControlCharacter(char)) {\n // unescaped control character\n str += controlCharacters[char]\n i++\n } else {\n if (!isValidStringCharacter(char)) {\n throwInvalidCharacter(char)\n }\n str += char\n i++\n }\n }\n\n if (skipEscapeChars) {\n // repair: skipped escape character (nothing to do)\n skipEscapeCharacter()\n }\n }\n }\n\n return false\n }\n\n /**\n * Repair concatenated strings like \"hello\" + \"world\", change this into \"helloworld\"\n */\n function parseConcatenatedString(): boolean {\n let processed = false\n\n parseWhitespaceAndSkipComments()\n while (text[i] === '+') {\n processed = true\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: remove the end quote of the first string\n output = stripLastOccurrence(output, '\"', true)\n const start = output.length\n const parsedStr = parseString()\n if (parsedStr) {\n // repair: remove the start quote of the second string\n output = removeAtIndex(output, start, 1)\n } else {\n // repair: remove the + because it is not followed by a string\n output = insertBeforeLastWhitespace(output, '\"')\n }\n }\n\n return processed\n }\n\n /**\n * Parse a number like 2.4 or 2.4e6\n */\n function parseNumber(): boolean {\n const start = i\n if (text[i] === '-') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n }\n\n // Note that in JSON leading zeros like \"00789\" are not allowed.\n // We will allow all leading zeros here though and at the end of parseNumber\n // check against trailing zeros and repair that if needed.\n // Leading zeros can have meaning, so we should not clear them.\n while (isDigit(text[i])) {\n i++\n }\n\n if (text[i] === '.') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n while (isDigit(text[i])) {\n i++\n }\n }\n\n if (text[i] === 'e' || text[i] === 'E') {\n i++\n if (text[i] === '-' || text[i] === '+') {\n i++\n }\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n while (isDigit(text[i])) {\n i++\n }\n }\n\n // if we're not at the end of the number by this point, allow this to be parsed as another type\n if (!atEndOfNumber()) {\n i = start\n return false\n }\n\n if (i > start) {\n // repair a number with leading zeros like \"00789\"\n const num = text.slice(start, i)\n const hasInvalidLeadingZero = /^0\\d/.test(num)\n\n output += hasInvalidLeadingZero ? `\"${num}\"` : num\n return true\n }\n\n return false\n }\n\n /**\n * Parse keywords true, false, null\n * Repair Python keywords True, False, None\n */\n function parseKeywords(): boolean {\n return (\n parseKeyword('true', 'true') ||\n parseKeyword('false', 'false') ||\n parseKeyword('null', 'null') ||\n // repair Python keywords True, False, None\n parseKeyword('True', 'true') ||\n parseKeyword('False', 'false') ||\n parseKeyword('None', 'null')\n )\n }\n\n function parseKeyword(name: string, value: string): boolean {\n if (text.slice(i, i + name.length) === name) {\n output += value\n i += name.length\n return true\n }\n\n return false\n }\n\n /**\n * Repair an unquoted string by adding quotes around it\n * Repair a MongoDB function call like NumberLong(\"2\")\n * Repair a JSONP function call like callback({...});\n */\n function parseUnquotedString(isKey: boolean) {\n // note that the symbol can end with whitespaces: we stop at the next delimiter\n // also, note that we allow strings to contain a slash / in order to support repairing regular expressions\n const start = i\n\n if (isFunctionNameCharStart(text[i])) {\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++\n }\n\n let j = i\n while (isWhitespace(text, j)) {\n j++\n }\n\n if (text[j] === '(') {\n // repair a MongoDB function call like NumberLong(\"2\")\n // repair a JSONP function call like callback({...});\n i = j + 1\n\n parseValue()\n\n if (text[i] === ')') {\n // repair: skip close bracket of function call\n i++\n if (text[i] === ';') {\n // repair: skip semicolon after JSONP call\n i++\n }\n }\n\n return true\n }\n }\n\n while (\n i < text.length &&\n !isUnquotedStringDelimiter(text[i]) &&\n !isQuote(text[i]) &&\n (!isKey || text[i] !== ':')\n ) {\n i++\n }\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(start, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n i++\n }\n }\n\n if (i > start) {\n // repair unquoted string\n // also, repair undefined into null\n\n // first, go back to prevent getting trailing whitespaces in the string\n while (isWhitespace(text, i - 1) && i > 0) {\n i--\n }\n\n const symbol = text.slice(start, i)\n output += symbol === 'undefined' ? 'null' : JSON.stringify(symbol)\n\n if (text[i] === '\"') {\n // we had a missing start quote, but now we encountered the end quote, so we can skip that one\n i++\n }\n\n return true\n }\n }\n\n function parseRegex() {\n if (text[i] === '/') {\n const start = i\n i++\n\n while (i < text.length && (text[i] !== '/' || text[i - 1] === '\\\\')) {\n i++\n }\n i++\n\n output += JSON.stringify(text.substring(start, i))\n\n return true\n }\n }\n\n function prevNonWhitespaceIndex(start: number): number {\n let prev = start\n\n while (prev > 0 && isWhitespace(text, prev)) {\n prev--\n }\n\n return prev\n }\n\n function atEndOfNumber() {\n return i >= text.length || isDelimiter(text[i]) || isWhitespace(text, i)\n }\n\n function repairNumberEndingWithNumericSymbol(start: number) {\n // repair numbers cut off at the end\n // this will only be called when we end after a '.', '-', or 'e' and does not\n // change the number more than it needs to make it valid JSON\n output += `${text.slice(start, i)}0`\n }\n\n function throwInvalidCharacter(char: string) {\n throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i)\n }\n\n function throwUnexpectedCharacter() {\n throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i])}`, i)\n }\n\n function throwUnexpectedEnd() {\n throw new JSONRepairError('Unexpected end of json string', text.length)\n }\n\n function throwObjectKeyExpected() {\n throw new JSONRepairError('Object key expected', i)\n }\n\n function throwColonExpected() {\n throw new JSONRepairError('Colon expected', i)\n }\n\n function throwInvalidUnicodeCharacter() {\n const chars = text.slice(i, i + 6)\n throw new JSONRepairError(`Invalid unicode character \"${chars}\"`, i)\n }\n}\n\nfunction atEndOfBlockComment(text: string, i: number) {\n return text[i] === '*' && text[i + 1] === '/'\n}\n", "import {\n AGENT_CONFIG_VERSION,\n DEFAULT_AGENT_CONFIG,\n DEFAULT_AGENT_NAME,\n StoredAgentConfigSchemaV2,\n} from \"@taskcrew/shared\";\nimport { z } from \"zod\";\n\nconst publicAgentSchema = z.object({\n id: z.string(),\n name: z.string(),\n slack_enabled: z.boolean().nullish(),\n microsoft_teams_enabled: z.boolean().nullish(),\n agentic_memory_enabled: z.boolean().nullish(),\n thread_id: z.string().nullish(),\n created_at: z.string().nullish(),\n updated_at: z.string().nullish(),\n});\n\nexport type PublicAgent = z.infer<typeof publicAgentSchema>;\n\nconst publicBuildSchema = z.object({\n id: z.string(),\n agent_id: z.string(),\n name: z.string(),\n revision_number: z.number().nullish(),\n created_at: z.string().nullish(),\n updated_at: z.string().nullish(),\n});\n\nexport type PublicBuild = z.infer<typeof publicBuildSchema>;\n\nexport const listAgentsResponseSchema = z.object({\n agents: z.array(publicAgentSchema),\n total: z.number().nullish(),\n limit: z.number().nullish(),\n offset: z.number().nullish(),\n});\n\nexport type ListAgentsResponse = z.infer<typeof listAgentsResponseSchema>;\n\nexport const getAgentResponseSchema = z.object({\n agent: publicAgentSchema,\n});\n\nexport type GetAgentResponse = z.infer<typeof getAgentResponseSchema>;\n\nexport const createAgentResponseSchema = z.object({\n agent: publicAgentSchema,\n build: publicBuildSchema.optional(),\n});\n\nexport type CreateAgentResponse = z.infer<typeof createAgentResponseSchema>;\n\nexport const buildConfigSchema = StoredAgentConfigSchemaV2;\n\nexport type BuildConfig = z.input<typeof buildConfigSchema>;\n\nexport const DEFAULT_NEW_AGENT_NAME = DEFAULT_AGENT_NAME;\nexport const DEFAULT_BUILD_NAME = \"Initial build\";\n\nexport const DEFAULT_BUILD_CONFIG: BuildConfig = {\n version: AGENT_CONFIG_VERSION,\n data: DEFAULT_AGENT_CONFIG,\n};\n", "import { type Command } from \"commander\";\n\nimport { getAgentResponseSchema } from \"@/api/agent-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype GetOptions = {\n json?: boolean;\n};\n\nexport function registerAgentsGet(agents: Command): void {\n agents\n .command(\"get <id>\")\n .description(\"Get an agent by ID\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function getAction(\n this: Command,\n id: string,\n options: GetOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/agents/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = getAgentResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { agent } = parsed.data;\n\n console.log(\n renderKeyValue([\n { label: \"ID\", value: agent.id },\n { label: \"Name\", value: agent.name },\n { label: \"Created\", value: agent.created_at ?? \"\" },\n { label: \"Updated\", value: agent.updated_at ?? \"\" },\n ])\n );\n });\n}\n", "import { CliError } from \"@/errors.js\";\n\nconst POSITIVE_INT = /^\\d+$/;\n\ntype ParseLimitOptions = {\n defaultValue: number;\n min: number;\n max: number;\n};\n\nexport function parseLimit(\n raw: string | undefined,\n { defaultValue, min, max }: ParseLimitOptions\n): number {\n if (raw === undefined) {\n return defaultValue;\n }\n\n if (!POSITIVE_INT.test(raw)) {\n throw new CliError(`--limit must be an integer between ${min} and ${max}`);\n }\n\n const n = Number(raw);\n if (n < min || n > max) {\n throw new CliError(`--limit must be an integer between ${min} and ${max}`);\n }\n\n return n;\n}\n\nexport function parseOffset(raw: string | undefined): number {\n if (raw === undefined) {\n return 0;\n }\n\n if (!POSITIVE_INT.test(raw)) {\n throw new CliError(\"--offset must be a non-negative integer\");\n }\n\n return Number(raw);\n}\n", "import { type Command } from \"commander\";\n\nimport {\n listAgentsResponseSchema,\n type PublicAgent,\n} from \"@/api/agent-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { parseLimit, parseOffset } from \"../shared/pagination.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n limit?: string;\n offset?: string;\n json?: boolean;\n};\n\nconst DEFAULT_LIMIT = 20;\nconst MIN_LIMIT = 1;\nconst MAX_LIMIT = 100;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: PublicAgent) => row.id },\n { header: \"NAME\", cell: (row: PublicAgent) => row.name },\n { header: \"CREATED\", cell: (row: PublicAgent) => row.created_at ?? \"\" },\n] as const;\n\nexport function registerAgentsList(agents: Command): void {\n agents\n .command(\"list\", { isDefault: true })\n .description(\"List agents for your team\")\n .option(\"--limit <n>\", `page size (${MIN_LIMIT}-${MAX_LIMIT})`)\n .option(\"--offset <n>\", \"number of agents to skip\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const limit = parseLimit(options.limit, {\n defaultValue: DEFAULT_LIMIT,\n min: MIN_LIMIT,\n max: MAX_LIMIT,\n });\n const offset = parseOffset(options.offset);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", String(limit));\n searchParams.append(\"offset\", String(offset));\n\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/agents\",\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listAgentsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const response = parsed.data;\n\n if (response.agents.length === 0) {\n console.log(\"No agents found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, response.agents));\n const resolvedOffset = response.offset ?? offset;\n const summary =\n response.total === null || response.total === undefined\n ? `Showing ${response.agents.length} \u00B7 offset ${resolvedOffset}`\n : `Showing ${response.agents.length} of ${response.total} \u00B7 offset ${resolvedOffset}`;\n console.log(summary);\n });\n}\n", "import { z } from \"zod\";\n\nconst publicScheduleSchema = z.object({\n id: z.string(),\n build_id: z.string(),\n agent_id: z.string(),\n user_id: z.string(),\n enabled: z.boolean(),\n frequency: z.string(),\n time: z.string().nullish(),\n timezone: z.string(),\n day: z.string().nullish(),\n day_of_month: z.number().nullish(),\n cron: z.string().nullish(),\n source: z.string().nullish(),\n task: z.string().nullish(),\n recurring: z.boolean().nullish(),\n created_at: z.string(),\n updated_at: z.string(),\n});\n\nexport type PublicSchedule = z.infer<typeof publicScheduleSchema>;\n\nexport const listSchedulesResponseSchema = z.object({\n schedules: z.array(publicScheduleSchema),\n});\n\nexport type ListSchedulesResponse = z.infer<typeof listSchedulesResponseSchema>;\n", "import { type Command } from \"commander\";\n\nimport {\n listSchedulesResponseSchema,\n type PublicSchedule,\n} from \"@/api/schedule-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype SchedulesOptions = {\n json?: boolean;\n};\n\nconst TASK_PREVIEW_WIDTH = 40;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: PublicSchedule) => row.id },\n {\n header: \"ENABLED\",\n cell: (row: PublicSchedule) => (row.enabled ? \"yes\" : \"no\"),\n },\n { header: \"FREQUENCY\", cell: (row: PublicSchedule) => row.frequency },\n { header: \"WHEN\", cell: whenCell },\n { header: \"TIMEZONE\", cell: (row: PublicSchedule) => row.timezone },\n {\n header: \"RECURRING\",\n cell: (row: PublicSchedule) => (row.recurring === false ? \"no\" : \"yes\"),\n },\n {\n header: \"TASK\",\n cell: (row: PublicSchedule) =>\n row.task ? row.task.replace(/\\s+/g, \" \").trim() : \"\",\n maxWidth: TASK_PREVIEW_WIDTH,\n },\n] as const;\n\nfunction whenCell(row: PublicSchedule): string {\n if (row.frequency === \"custom\") {\n return row.cron ?? \"\";\n }\n\n if (row.frequency === \"weekly\" && row.day) {\n return `${row.day} ${row.time ?? \"\"}`.trim();\n }\n\n if (\n row.frequency === \"monthly\" &&\n row.day_of_month !== null &&\n row.day_of_month !== undefined\n ) {\n return `day ${row.day_of_month} ${row.time ?? \"\"}`.trim();\n }\n\n return row.time ?? \"\";\n}\n\nexport function registerAgentsSchedules(agents: Command): void {\n agents\n .command(\"schedules <agent-id>\")\n .description(\"List schedules you own for an agent\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function schedulesAction(\n this: Command,\n agentId: string,\n options: SchedulesOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/agents/${encodeURIComponent(agentId)}/schedules`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listSchedulesResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { schedules } = parsed.data;\n\n if (schedules.length === 0) {\n console.log(\"No schedules found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, schedules));\n console.log(`Showing ${schedules.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { getAgentResponseSchema } from \"@/api/agent-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { trimRequired } from \"../shared/trim-required.js\";\n\ntype UpdateOptions = {\n name?: string;\n enableSlack?: boolean;\n disableSlack?: boolean;\n enableMicrosoftTeams?: boolean;\n disableMicrosoftTeams?: boolean;\n enableAgenticMemory?: boolean;\n disableAgenticMemory?: boolean;\n threadId?: string;\n clearThread?: boolean;\n json?: boolean;\n};\n\ntype RequestBody = {\n name?: string;\n slack_enabled?: boolean;\n microsoft_teams_enabled?: boolean;\n agentic_memory_enabled?: boolean;\n thread_id?: string | null;\n};\n\nfunction parseBoolPair(\n enable: boolean | undefined,\n disable: boolean | undefined,\n enableFlag: string,\n disableFlag: string\n): boolean | undefined {\n if (enable === true && disable === true) {\n throw new CliError(\n `Pass either --${enableFlag} or --${disableFlag}, not both.`\n );\n }\n\n if (enable === true) {\n return true;\n }\n\n if (disable === true) {\n return false;\n }\n\n return undefined;\n}\n\nfunction buildBody(options: UpdateOptions): RequestBody {\n const body: RequestBody = {};\n\n if (options.name !== undefined) {\n body.name = trimRequired(options.name, \"--name\");\n }\n\n const slack = parseBoolPair(\n options.enableSlack,\n options.disableSlack,\n \"enable-slack\",\n \"disable-slack\"\n );\n if (slack !== undefined) {\n body.slack_enabled = slack;\n }\n\n const teams = parseBoolPair(\n options.enableMicrosoftTeams,\n options.disableMicrosoftTeams,\n \"enable-microsoft-teams\",\n \"disable-microsoft-teams\"\n );\n if (teams !== undefined) {\n body.microsoft_teams_enabled = teams;\n }\n\n const memory = parseBoolPair(\n options.enableAgenticMemory,\n options.disableAgenticMemory,\n \"enable-agentic-memory\",\n \"disable-agentic-memory\"\n );\n if (memory !== undefined) {\n body.agentic_memory_enabled = memory;\n }\n\n if (options.threadId !== undefined && options.clearThread === true) {\n throw new CliError(\"Pass either --thread-id or --clear-thread, not both.\");\n }\n\n if (options.threadId !== undefined) {\n body.thread_id = trimRequired(options.threadId, \"--thread-id\");\n }\n\n if (options.clearThread === true) {\n body.thread_id = null;\n }\n\n if (Object.keys(body).length === 0) {\n throw new CliError(\n \"Provide at least one field to update (e.g. --name, --enable-slack).\"\n );\n }\n\n return body;\n}\n\nexport function registerAgentsUpdate(agents: Command): void {\n agents\n .command(\"update <id>\")\n .description(\"Update an agent's display name or delivery settings\")\n .option(\"--name <name>\", \"new display name\")\n .option(\"--enable-slack\", \"enable Slack delivery\")\n .option(\"--disable-slack\", \"disable Slack delivery\")\n .option(\"--enable-microsoft-teams\", \"enable Microsoft Teams delivery\")\n .option(\"--disable-microsoft-teams\", \"disable Microsoft Teams delivery\")\n .option(\"--enable-agentic-memory\", \"enable agentic memory\")\n .option(\"--disable-agentic-memory\", \"disable agentic memory\")\n .option(\"--thread-id <id>\", \"associate the agent with a thread\")\n .option(\n \"--clear-thread\",\n \"clear the agent's associated thread (sets thread_id to null)\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function updateAction(\n this: Command,\n id: string,\n options: UpdateOptions\n ) {\n const agentId = trimRequired(id, \"<id>\");\n const body = buildBody(options);\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"PATCH\",\n path: `/v1/agents/${encodeURIComponent(agentId)}`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = getAgentResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { agent } = parsed.data;\n\n console.log(green(\"Agent updated!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: agent.id },\n { label: \"Name\", value: agent.name },\n { label: \"Slack\", value: formatBool(agent.slack_enabled) },\n {\n label: \"Microsoft Teams\",\n value: formatBool(agent.microsoft_teams_enabled),\n },\n {\n label: \"Agentic memory\",\n value: formatBool(agent.agentic_memory_enabled),\n },\n { label: \"Thread\", value: agent.thread_id ?? \"(none)\" },\n { label: \"Created\", value: agent.created_at ?? \"\" },\n { label: \"Updated\", value: agent.updated_at ?? \"\" },\n ])\n );\n });\n}\n\nfunction formatBool(value: boolean | null | undefined): string {\n if (value === true) {\n return \"enabled\";\n }\n\n if (value === false) {\n return \"disabled\";\n }\n\n return \"(unset)\";\n}\n", "import { type Command } from \"commander\";\n\nimport { registerAgentsCreate } from \"./create.js\";\nimport { registerAgentsGet } from \"./get.js\";\nimport { registerAgentsList } from \"./list.js\";\nimport { registerAgentsSchedules } from \"./schedules.js\";\nimport { registerAgentsUpdate } from \"./update.js\";\n\nexport function registerAgents(program: Command): void {\n const agents = program\n .command(\"agents\")\n .description(\"Manage agents in the Duvo public API\");\n\n registerAgentsList(agents);\n registerAgentsGet(agents);\n registerAgentsCreate(agents);\n registerAgentsUpdate(agents);\n registerAgentsSchedules(agents);\n}\n", "import { readFileSync } from \"node:fs\";\n\ntype Field = {\n key: string;\n value: unknown;\n};\n\nconst INTEGER_OR_DECIMAL = /^-?\\d+(\\.\\d+)?$/;\n\n/**\n * Parses a `-f key=value` pair. The value is always kept as a string,\n * matching the `gh api` convention.\n */\nexport function parseStringField(input: string): Field {\n const eq = input.indexOf(\"=\");\n if (eq === -1) {\n throw new Error(\n `Invalid field \"${input}\". Expected \"key=value\" (e.g. -f name=\"Bot\").`\n );\n }\n\n const key = input.slice(0, eq);\n if (key.length === 0) {\n throw new Error(\n `Invalid field \"${input}\". Key cannot be empty (e.g. -f name=\"Bot\").`\n );\n }\n\n return { key, value: input.slice(eq + 1) };\n}\n\n/**\n * Parses a `-F key=value` pair. The value is coerced to a typed value\n * when it matches one of: `null`, `true`, `false`, a number, or\n * `@path/to/file.json` (inlines the file's parsed JSON). Anything else\n * falls through as a string.\n */\nexport function parseTypedField(input: string): Field {\n const eq = input.indexOf(\"=\");\n if (eq === -1) {\n throw new Error(\n `Invalid field \"${input}\". Expected \"key=value\" (e.g. -F count=42).`\n );\n }\n\n const key = input.slice(0, eq);\n if (key.length === 0) {\n throw new Error(\n `Invalid field \"${input}\". Key cannot be empty (e.g. -F count=42).`\n );\n }\n\n const raw = input.slice(eq + 1);\n\n if (raw.startsWith(\"@\")) {\n const path = raw.slice(1);\n return { key, value: readJsonFile(path) };\n }\n\n if (raw === \"null\") {\n return { key, value: null };\n }\n\n if (raw === \"true\") {\n return { key, value: true };\n }\n\n if (raw === \"false\") {\n return { key, value: false };\n }\n\n if (INTEGER_OR_DECIMAL.test(raw)) {\n return { key, value: Number(raw) };\n }\n\n return { key, value: raw };\n}\n\n/**\n * Combines repeated `-f` and `-F` flag values into a single object.\n * String fields (`-f`) are applied first, then typed fields (`-F`), so\n * typed fields win on key collision regardless of CLI argument order.\n * Commander collects the two flags into separate arrays, so the original\n * interleaved order is lost by the time we get here.\n */\nexport function buildFieldObject(\n stringFields: readonly string[] = [],\n typedFields: readonly string[] = []\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const input of stringFields) {\n const { key, value } = parseStringField(input);\n result[key] = value;\n }\n\n for (const input of typedFields) {\n const { key, value } = parseTypedField(input);\n result[key] = value;\n }\n\n return result;\n}\n\nfunction readJsonFile(path: string): unknown {\n let contents: string;\n try {\n contents = readFileSync(path, \"utf8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Cannot read \"${path}\": ${message}`);\n }\n\n try {\n return JSON.parse(contents);\n } catch {\n throw new Error(`File \"${path}\" is not valid JSON.`);\n }\n}\n", "import { readFileSync } from \"node:fs\";\n\nimport { CliError } from \"@/errors.js\";\n\n/**\n * Reads a raw JSON body from a file path or from stdin (when path is\n * `\"-\"`). Returns the parsed JSON value. Throws `CliError` if the input\n * is not valid JSON or the file cannot be read.\n */\nexport function readInputJson(path: string): unknown {\n const contents = path === \"-\" ? readStdin() : readFile(path);\n try {\n return JSON.parse(contents);\n } catch {\n const source = path === \"-\" ? \"stdin\" : `\"${path}\"`;\n throw new CliError(`Input from ${source} is not valid JSON.`);\n }\n}\n\nfunction readFile(path: string): string {\n try {\n return readFileSync(path, \"utf8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Cannot read \"${path}\": ${message}`);\n }\n}\n\nfunction readStdin(): string {\n return readFileSync(0, \"utf8\");\n}\n", "import { printJson } from \"@/output/json.js\";\nimport { type Column, renderTable } from \"@/output/table.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nconst FALLBACK_TERMINAL_WIDTH = 120;\nconst MIN_COLUMN_WIDTH = 8;\nconst COLUMN_GUTTER = 2;\n\n/**\n * Routes the response through the shared output pipeline per GUIDE.md:\n * collections render as a table, single objects as a key/value block,\n * everything else (and `--json`) falls back to pretty JSON. `duvo api`\n * has no schema, so columns and labels come straight from the response\n * keys.\n */\nexport function renderApiResponse(response: unknown, asJson: boolean): void {\n if (asJson) {\n printJson(response);\n return;\n }\n\n if (Array.isArray(response)) {\n if (response.length === 0) {\n console.log(\"No results.\");\n return;\n }\n\n if (response.every(isRecord)) {\n renderTableResponse(response);\n return;\n }\n }\n\n if (isRecord(response)) {\n const entries = Object.entries(response).map(([key, value]) => {\n return { label: key, value: formatScalar(value) };\n });\n console.log(renderKeyValue(entries));\n return;\n }\n\n printJson(response);\n}\n\nfunction renderTableResponse(rows: readonly Record<string, unknown>[]): void {\n const keys = Array.from(new Set(rows.flatMap((row) => Object.keys(row))));\n const maxWidth = perColumnMaxWidth(keys.length);\n const columns: Column<Record<string, unknown>>[] = keys.map((key) => {\n return {\n header: key.toUpperCase(),\n cell: (row) => formatScalar(row[key]),\n maxWidth,\n };\n });\n console.log(renderTable(columns, rows));\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction perColumnMaxWidth(columnCount: number): number {\n if (columnCount === 0) {\n return MIN_COLUMN_WIDTH;\n }\n\n const terminalWidth = process.stdout.columns ?? FALLBACK_TERMINAL_WIDTH;\n const budget = terminalWidth - COLUMN_GUTTER * (columnCount - 1);\n return Math.max(MIN_COLUMN_WIDTH, Math.floor(budget / columnCount));\n}\n\nfunction formatScalar(value: unknown): string {\n if (value === null || value === undefined) {\n return \"\";\n }\n\n if (typeof value === \"string\") {\n return value;\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n\n return JSON.stringify(value);\n}\n", "import { type Command } from \"commander\";\n\nimport { buildFieldObject } from \"@/api/parse-fields.js\";\nimport { readInputJson } from \"@/api/read-input.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\n\nimport { renderApiResponse } from \"./api-render.js\";\nimport {\n type AuthenticatedConfig,\n requireAuthenticatedConfig,\n} from \"./shared/require-auth.js\";\n\ntype ApiOptions = {\n field?: string[];\n rawField?: string[];\n input?: string;\n json?: boolean;\n};\n\ntype RequestData = {\n body: unknown;\n searchParams: URLSearchParams | undefined;\n};\n\nconst METHODS_WITH_BODY = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\nconst VALID_METHODS = new Set([\n \"GET\",\n \"HEAD\",\n \"POST\",\n \"PUT\",\n \"PATCH\",\n \"DELETE\",\n]);\n\nexport function registerApi(program: Command): void {\n program\n .command(\"api <method> <path>\")\n .description(\"Make an authenticated request to the Duvo public API\")\n .option(\n \"-f, --field <key=value>\",\n \"string field; repeat for multiple (body on POST/PUT/PATCH/DELETE, query on GET/HEAD)\",\n collect,\n []\n )\n .option(\n \"-F, --raw-field <key=value>\",\n \"typed field (boolean, number, null, or @file for JSON); repeat for multiple\",\n collect,\n []\n )\n .option(\n \"--input <path>\",\n 'raw JSON body from a file, or \"-\" for stdin (mutually exclusive with -f / -F)'\n )\n .option(\"--json\", \"output raw JSON instead of the formatted view\")\n .action(async function apiAction(\n this: Command,\n method: string,\n path: string,\n options: ApiOptions\n ) {\n const resolved = await requireAuthenticatedConfig(this);\n await runApi({ method, path, options }, resolved);\n });\n}\n\nasync function runApi(\n args: { method: string; path: string; options: ApiOptions },\n resolved: AuthenticatedConfig\n): Promise<void> {\n const method = args.method.toUpperCase();\n if (!VALID_METHODS.has(method)) {\n throw new CliError(\n `Invalid HTTP method \"${args.method}\". Expected one of: ${[...VALID_METHODS].join(\", \")}.`\n );\n }\n\n const { body, searchParams } = prepareRequestData(method, args.options);\n\n const response = await httpRequest({\n method,\n path: args.path,\n apiKey: resolved.apiKey,\n apiBaseUrl: resolved.apiBaseUrl,\n body,\n searchParams,\n });\n\n renderApiResponse(response, args.options.json ?? false);\n}\n\nfunction prepareRequestData(method: string, options: ApiOptions): RequestData {\n const hasFieldArgs =\n (options.field?.length ?? 0) > 0 || (options.rawField?.length ?? 0) > 0;\n\n if (options.input !== undefined && hasFieldArgs) {\n throw new CliError(\"Cannot combine --input with -f / -F flags.\");\n }\n\n if (options.input !== undefined) {\n if (!METHODS_WITH_BODY.has(method)) {\n throw new CliError(\n `--input is only supported for ${[...METHODS_WITH_BODY].join(\", \")} requests.`\n );\n }\n\n return { body: readInputJson(options.input), searchParams: undefined };\n }\n\n if (!hasFieldArgs) {\n return { body: undefined, searchParams: undefined };\n }\n\n const fields = buildFieldObject(options.field, options.rawField);\n if (METHODS_WITH_BODY.has(method)) {\n return { body: fields, searchParams: undefined };\n }\n\n return { body: undefined, searchParams: fieldsToSearchParams(fields) };\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\n/**\n * Encodes typed fields as query string values. Scalars pass through as\n * their string form; objects and arrays are JSON-stringified so an\n * `-F filter=@file.json` round-trips to a usable `?filter=\u2026` rather\n * than `[object Object]`. `null` / `undefined` keys are dropped \u2014 query\n * strings have no native null encoding.\n */\nfunction fieldsToSearchParams(\n fields: Record<string, unknown>\n): URLSearchParams {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(fields)) {\n if (value === null || value === undefined) {\n continue;\n }\n\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n params.append(key, String(value));\n continue;\n }\n\n params.append(key, JSON.stringify(value));\n }\n\n return params;\n}\n", "import { z } from \"zod\";\n\nimport { jsonValueSchema } from \"./json-value.js\";\n\nconst publicBuildSchema = z.object({\n id: z.string(),\n agent_id: z.string(),\n name: z.string(),\n config: jsonValueSchema.nullish(),\n revision_number: z.number().nullish(),\n created_at: z.string().nullish(),\n updated_at: z.string().nullish(),\n});\n\nexport type PublicBuild = z.infer<typeof publicBuildSchema>;\n\nexport const listBuildsResponseSchema = z.object({\n builds: z.array(publicBuildSchema),\n total: z.number().nullish(),\n limit: z.number().nullish(),\n offset: z.number().nullish(),\n});\n\nexport type ListBuildsResponse = z.infer<typeof listBuildsResponseSchema>;\n\nexport const getBuildResponseSchema = z.object({\n build: publicBuildSchema,\n});\n\nexport type GetBuildResponse = z.infer<typeof getBuildResponseSchema>;\n\nexport const createBuildResponseSchema = z.object({\n build: publicBuildSchema,\n agent: z.object({ id: z.string() }),\n});\n\nexport type CreateBuildResponse = z.infer<typeof createBuildResponseSchema>;\n", "import { z } from \"zod\";\n\nexport type JsonPrimitive = boolean | number | string | null;\nexport type JsonArray = JsonValue[];\nexport type JsonObject = { [key: string]: JsonValue | undefined };\nexport type JsonValue = JsonPrimitive | JsonArray | JsonObject;\n\nexport const jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>\n z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(jsonValueSchema),\n z.record(z.string(), jsonValueSchema),\n ])\n);\n", "import { type Command } from \"commander\";\n\nimport { createBuildResponseSchema } from \"@/api/build-schemas.js\";\nimport { type JsonValue, jsonValueSchema } from \"@/api/json-value.js\";\nimport { readInputJson } from \"@/api/read-input.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype CreateOptions = {\n agent: string;\n name: string;\n configFile: string;\n json?: boolean;\n};\n\ntype RequestBody = {\n name: string;\n config: JsonValue;\n};\n\nexport function registerBuildsCreate(builds: Command): void {\n builds\n .command(\"create\")\n .description(\"Create a new build for an existing agent\")\n .requiredOption(\"--agent <id>\", \"ID of the agent this build belongs to\")\n .requiredOption(\"--name <text>\", \"build name\")\n .requiredOption(\n \"--config-file <path>\",\n 'path to a JSON file with the build config, or \"-\" for stdin'\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function createAction(this: Command, options: CreateOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const parsedConfig = jsonValueSchema.safeParse(\n readInputJson(options.configFile)\n );\n if (!parsedConfig.success) {\n throw new CliError(`Invalid config: ${parsedConfig.error.message}`);\n }\n\n const config = parsedConfig.data;\n\n const body: RequestBody = {\n name: options.name,\n config,\n };\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/agents/${encodeURIComponent(options.agent)}/builds`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = createBuildResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { build } = parsed.data;\n\n const revision = String(build.revision_number ?? \"\");\n\n console.log(green(\"Build created!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: build.id },\n { label: \"Agent\", value: build.agent_id },\n { label: \"Name\", value: build.name },\n { label: \"Revision\", value: revision },\n { label: \"Created\", value: build.created_at ?? \"\" },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { getBuildResponseSchema } from \"@/api/build-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype GetOptions = {\n agent: string;\n json?: boolean;\n};\n\nexport function registerBuildsGet(builds: Command): void {\n builds\n .command(\"get <id>\")\n .description(\"Get a build by ID\")\n .requiredOption(\"--agent <id>\", \"ID of the agent this build belongs to\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function getAction(\n this: Command,\n id: string,\n options: GetOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/agents/${encodeURIComponent(options.agent)}/builds/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = getBuildResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { build } = parsed.data;\n\n const revision = String(build.revision_number ?? \"\");\n\n console.log(\n renderKeyValue([\n { label: \"ID\", value: build.id },\n { label: \"Agent\", value: build.agent_id },\n { label: \"Name\", value: build.name },\n { label: \"Revision\", value: revision },\n { label: \"Created\", value: build.created_at ?? \"\" },\n { label: \"Updated\", value: build.updated_at ?? \"\" },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport {\n listBuildsResponseSchema,\n type PublicBuild,\n} from \"@/api/build-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { parseLimit, parseOffset } from \"../shared/pagination.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n agent: string;\n limit?: string;\n offset?: string;\n json?: boolean;\n};\n\nconst DEFAULT_LIMIT = 20;\nconst MIN_LIMIT = 1;\nconst MAX_LIMIT = 100;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: PublicBuild) => row.id },\n { header: \"NAME\", cell: (row: PublicBuild) => row.name },\n {\n header: \"REVISION\",\n cell: (row: PublicBuild) => String(row.revision_number ?? \"\"),\n },\n { header: \"CREATED\", cell: (row: PublicBuild) => row.created_at ?? \"\" },\n] as const;\n\nexport function registerBuildsList(builds: Command): void {\n builds\n .command(\"list\", { isDefault: true })\n .description(\"List builds for an agent\")\n .requiredOption(\"--agent <id>\", \"ID of the agent to list builds for\")\n .option(\"--limit <n>\", `page size (${MIN_LIMIT}-${MAX_LIMIT})`)\n .option(\"--offset <n>\", \"number of builds to skip\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const limit = parseLimit(options.limit, {\n defaultValue: DEFAULT_LIMIT,\n min: MIN_LIMIT,\n max: MAX_LIMIT,\n });\n const offset = parseOffset(options.offset);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", String(limit));\n searchParams.append(\"offset\", String(offset));\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/agents/${encodeURIComponent(options.agent)}/builds`,\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listBuildsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const response = parsed.data;\n\n if (response.builds.length === 0) {\n console.log(\"No builds found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, response.builds));\n const resolvedOffset = response.offset ?? offset;\n const total = response.total ?? null;\n const summary =\n total === null\n ? `Showing ${response.builds.length} \u00B7 offset ${resolvedOffset}`\n : `Showing ${response.builds.length} of ${total} \u00B7 offset ${resolvedOffset}`;\n console.log(summary);\n });\n}\n", "import {\n buildResponseApiSchema,\n extractAgentMentionIds,\n extractSystemPromptText,\n parseAgentConfig,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { type JsonValue, jsonValueSchema } from \"@/api/json-value.js\";\nimport { readInputJson } from \"@/api/read-input.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype UpdateOptions = {\n configFile: string;\n json?: boolean;\n};\n\ntype RequestBody = {\n config: JsonValue;\n handoverTargetIds: string[];\n};\n\nexport function registerBuildsUpdate(builds: Command): void {\n builds\n .command(\"update <build-id>\")\n .description(\n \"Update a build's config (and handover targets, derived from it)\"\n )\n .requiredOption(\n \"--config-file <path>\",\n 'path to a JSON file with the new build config, or \"-\" for stdin'\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function updateAction(\n this: Command,\n buildId: string,\n options: UpdateOptions\n ) {\n const parsedConfig = jsonValueSchema.safeParse(\n readInputJson(options.configFile)\n );\n if (!parsedConfig.success) {\n throw new CliError(`Invalid config: ${parsedConfig.error.message}`);\n }\n\n const body: RequestBody = {\n config: parsedConfig.data,\n handoverTargetIds: deriveHandoverTargetIds(parsedConfig.data),\n };\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"PATCH\",\n path: `/v1/builds/${encodeURIComponent(buildId)}`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = buildResponseApiSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { build } = parsed.data;\n console.log(green(\"Build updated!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: build.id },\n { label: \"Agent\", value: build.agent_id },\n { label: \"Name\", value: build.name },\n {\n label: \"Revision\",\n value: String(build.revision_number ?? \"\"),\n },\n { label: \"Updated\", value: build.updated_at ?? \"\" },\n ])\n );\n });\n}\n\nfunction deriveHandoverTargetIds(config: JsonValue): string[] {\n const { config: parsedConfig } = parseAgentConfig(config);\n const sopText = extractSystemPromptText(parsedConfig?.input);\n return extractAgentMentionIds(sopText);\n}\n", "import { type Command } from \"commander\";\n\nimport { registerBuildsCreate } from \"./create.js\";\nimport { registerBuildsGet } from \"./get.js\";\nimport { registerBuildsList } from \"./list.js\";\nimport { registerBuildsUpdate } from \"./update.js\";\n\nexport function registerBuilds(program: Command): void {\n const builds = program\n .command(\"builds\")\n .description(\"Manage agent builds in the Duvo public API\");\n\n registerBuildsList(builds);\n registerBuildsGet(builds);\n registerBuildsCreate(builds);\n registerBuildsUpdate(builds);\n}\n", "import { CliError } from \"@/errors.js\";\n\nexport function parseCaseIds(raw: string): string[] {\n const ids = raw\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (ids.length === 0) {\n throw new CliError(\"--ids must contain at least one case ID.\");\n }\n\n if (ids.length > 100) {\n throw new CliError(\"--ids must contain at most 100 case IDs.\");\n }\n\n return ids;\n}\n", "import { caseBulkDelegateResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { parseCaseIds } from \"./parse-case-ids.js\";\n\ntype BulkDelegateOptions = {\n queue: string;\n agent: string;\n ids: string;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerCasesBulkDelegate(cases: Command): void {\n cases\n .command(\"bulk-delegate\")\n .description(\n \"Delegate multiple cases to a chosen agent (1-100). Interrupts any active runs.\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue the cases belong to\")\n .requiredOption(\n \"--agent <id>\",\n \"agent ID to delegate to (must be a queue consumer; list via `duvo queues agents <queue-id>`)\"\n )\n .requiredOption(\"--ids <list>\", \"comma-separated case IDs (1-100)\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function bulkDelegateAction(\n this: Command,\n options: BulkDelegateOptions\n ) {\n const caseIds = parseCaseIds(options.ids);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Delegate ${caseIds.length} case(s) in queue \"${options.queue}\" to agent \"${options.agent}\"?`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases/bulk-delegate`,\n apiKey,\n apiBaseUrl,\n body: { case_ids: caseIds, agent_id: options.agent },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseBulkDelegateResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const result = parsed.data;\n\n console.log(green(\"Bulk delegate complete.\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"Delegated\", value: String(result.delegatedCount) },\n { label: \"Skipped\", value: String(result.skippedCount) },\n ])\n );\n });\n}\n", "import {\n caseBulkDeleteResponseSchema,\n caseDetailResponseSchema,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { parseCaseIds } from \"./parse-case-ids.js\";\n\ntype BulkDeleteOptions = {\n queue: string;\n ids: string;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerCasesBulkDelete(cases: Command): void {\n cases\n .command(\"bulk-delete\")\n .description(\n \"Delete multiple cases from a queue (1-100). Interrupts any running jobs first.\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue the cases belong to\")\n .requiredOption(\"--ids <list>\", \"comma-separated case IDs (1-100)\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function bulkDeleteAction(\n this: Command,\n options: BulkDeleteOptions\n ) {\n const caseIds = parseCaseIds(options.ids);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const message = await buildConfirmMessage({\n caseIds,\n queue: options.queue,\n skip: Boolean(options.yes),\n apiKey,\n apiBaseUrl,\n });\n\n await confirmDestructive({\n message,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases/bulk-delete`,\n apiKey,\n apiBaseUrl,\n body: { case_ids: caseIds },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseBulkDeleteResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const result = parsed.data;\n\n console.log(green(\"Bulk delete complete.\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"Deleted cases\", value: String(result.deletedCount) },\n {\n label: \"Interrupted runs\",\n value: String(result.interruptedRunIds.length),\n },\n ])\n );\n });\n}\n\nasync function buildConfirmMessage(args: {\n caseIds: string[];\n queue: string;\n skip: boolean;\n apiKey: string;\n apiBaseUrl: string;\n}): Promise<string> {\n const baseMessage = `Delete ${args.caseIds.length} case(s) from queue \"${args.queue}\"?`;\n if (args.skip || !process.stdin.isTTY) {\n return baseMessage;\n }\n\n const titles = await fetchCaseTitles(\n args.caseIds,\n args.apiKey,\n args.apiBaseUrl\n );\n const lines = titles.map((line) => ` - ${line}`).join(\"\\n\");\n return `Delete the following ${args.caseIds.length} case(s) from queue \"${args.queue}\"?\\n${lines}`;\n}\n\nconst FETCH_TITLES_CONCURRENCY = 10;\n\nasync function fetchCaseTitles(\n ids: readonly string[],\n apiKey: string,\n apiBaseUrl: string\n): Promise<string[]> {\n const chunks: string[][] = [];\n for (let i = 0; i < ids.length; i += FETCH_TITLES_CONCURRENCY) {\n chunks.push([...ids.slice(i, i + FETCH_TITLES_CONCURRENCY)]);\n }\n\n // Batches must run sequentially so we cap concurrent in-flight requests at\n // FETCH_TITLES_CONCURRENCY.\n const results: PromiseSettledResult<unknown>[] = [];\n for (const chunk of chunks) {\n // eslint-disable-next-line no-await-in-loop\n const batch = await Promise.allSettled(\n chunk.map((id) =>\n httpRequest({\n method: \"GET\",\n path: `/v1/cases/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n })\n )\n );\n results.push(...batch);\n }\n\n return results.map((result, i) => {\n const id = ids[i];\n if (result.status === \"rejected\") {\n return `${id} (could not fetch)`;\n }\n\n const parsed = caseDetailResponseSchema.safeParse(result.value);\n if (!parsed.success) {\n return `${id} (could not parse)`;\n }\n\n return `${id} \u2014 ${parsed.data.case.title}`;\n });\n}\n", "import { caseBulkRetryResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { parseCaseIds } from \"./parse-case-ids.js\";\n\ntype BulkRetryOptions = {\n queue: string;\n ids: string;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerCasesBulkRetry(cases: Command): void {\n cases\n .command(\"bulk-retry\")\n .description(\n \"Retry multiple cases by resetting them to pending (1-100). Interrupts any active runs.\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue the cases belong to\")\n .requiredOption(\"--ids <list>\", \"comma-separated case IDs (1-100)\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function bulkRetryAction(\n this: Command,\n options: BulkRetryOptions\n ) {\n const caseIds = parseCaseIds(options.ids);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Retry ${caseIds.length} case(s) in queue \"${options.queue}\"?`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases/bulk-retry`,\n apiKey,\n apiBaseUrl,\n body: { case_ids: caseIds },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseBulkRetryResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const result = parsed.data;\n\n console.log(green(\"Bulk retry complete.\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"Retried\", value: String(result.retriedCount) },\n { label: \"Skipped\", value: String(result.skippedCount) },\n ])\n );\n });\n}\n", "import { caseBulkStatusUpdateResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { parseCaseIds } from \"./parse-case-ids.js\";\n\nconst CASE_TERMINAL_STATUSES = [\"completed\", \"failed\"] as const;\ntype CaseTerminalStatus = (typeof CASE_TERMINAL_STATUSES)[number];\n\ntype BulkUpdateStatusOptions = {\n queue: string;\n ids: string;\n status: string;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerCasesBulkUpdateStatus(cases: Command): void {\n cases\n .command(\"bulk-update-status\")\n .description(\n \"Update the status of multiple cases to completed or failed (1-100). Interrupts any active runs.\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue the cases belong to\")\n .requiredOption(\"--ids <list>\", \"comma-separated case IDs (1-100)\")\n .requiredOption(\n \"--status <status>\",\n `terminal status (${CASE_TERMINAL_STATUSES.join(\", \")})`\n )\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function bulkUpdateStatusAction(\n this: Command,\n options: BulkUpdateStatusOptions\n ) {\n const caseIds = parseCaseIds(options.ids);\n const status = parseStatus(options.status);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Set ${caseIds.length} case(s) in queue \"${options.queue}\" to \"${status}\"?`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases/bulk-update-status`,\n apiKey,\n apiBaseUrl,\n body: { case_ids: caseIds, status },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseBulkStatusUpdateResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const result = parsed.data;\n\n console.log(green(\"Bulk status update complete.\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"Updated\", value: String(result.updatedCount) },\n { label: \"Skipped\", value: String(result.skippedCount) },\n {\n label: \"Interrupted runs\",\n value: String(result.interruptedRunIds.length),\n },\n ])\n );\n });\n}\n\nfunction parseStatus(raw: string): CaseTerminalStatus {\n if (!CASE_TERMINAL_STATUSES.includes(raw as CaseTerminalStatus)) {\n throw new CliError(\n `Invalid --status value \"${raw}\". Allowed: ${CASE_TERMINAL_STATUSES.join(\", \")}.`\n );\n }\n\n return raw as CaseTerminalStatus;\n}\n", "import {\n caseClearQueueResponseSchema,\n casesListResponseSchema,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ClearOptions = {\n queue: string;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerCasesClear(cases: Command): void {\n cases\n .command(\"clear\")\n .description(\n \"Delete every case in a queue. Interrupts any running jobs first.\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue to clear\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function clearAction(this: Command, options: ClearOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const message = await buildConfirmMessage({\n queue: options.queue,\n skip: Boolean(options.yes),\n apiKey,\n apiBaseUrl,\n });\n\n await confirmDestructive({\n message,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseClearQueueResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const result = parsed.data;\n if (!result.success) {\n throw new CliError(\"Failed to clear queue cases.\");\n }\n\n console.log(green(\"Queue cleared!\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"Deleted cases\", value: String(result.deletedCount) },\n {\n label: \"Interrupted runs\",\n value: String(result.interruptedRunIds.length),\n },\n ])\n );\n });\n}\n\nasync function buildConfirmMessage(args: {\n queue: string;\n skip: boolean;\n apiKey: string;\n apiBaseUrl: string;\n}): Promise<string> {\n if (args.skip || !process.stdin.isTTY) {\n return `Delete every case in queue \"${args.queue}\"?`;\n }\n\n const total = await fetchQueueCaseCount(\n args.queue,\n args.apiKey,\n args.apiBaseUrl\n );\n if (total === null) {\n return `Delete every case in queue \"${args.queue}\"?`;\n }\n\n return `Delete every case (${total}) in queue \"${args.queue}\"?`;\n}\n\nasync function fetchQueueCaseCount(\n queueId: string,\n apiKey: string,\n apiBaseUrl: string\n): Promise<number | null> {\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", \"1\");\n searchParams.append(\"offset\", \"0\");\n\n try {\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/queues/${encodeURIComponent(queueId)}/cases`,\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n const parsed = casesListResponseSchema.safeParse(raw);\n if (!parsed.success) {\n return null;\n }\n\n return parsed.data.total ?? null;\n } catch {\n return null;\n }\n}\n", "import { readFile } from \"node:fs/promises\";\n\nimport { caseCreateResponseSchema, type CaseQueueItem } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype CreateOptions = {\n queue: string;\n title?: string;\n data?: string;\n label?: string[];\n fromFile?: string;\n json?: boolean;\n};\n\ntype CaseInput = {\n title: string;\n data?: string;\n labels?: { key: string; value: string }[];\n};\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: CaseQueueItem) => row.id },\n { header: \"TITLE\", cell: (row: CaseQueueItem) => row.title, maxWidth: 50 },\n { header: \"STATUS\", cell: (row: CaseQueueItem) => row.status },\n] as const;\n\nexport function registerCasesCreate(cases: Command): void {\n cases\n .command(\"create\")\n .description(\n \"Create one or more cases in a queue. Provide --title for one case or --from-file with a JSON array for many.\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue to create cases in\")\n .option(\"--title <text>\", \"case title (max 500 chars)\")\n .option(\"--data <text>\", \"free-form data passed to the assignment on claim\")\n .option(\n \"--label <key=value>\",\n \"label to assign to the case (omit key for a simple tag, repeat for multiple)\",\n collectLabel,\n [] as string[]\n )\n .option(\n \"--from-file <path>\",\n 'JSON file with a single case object or an array of cases (max 100). \"-\" reads from stdin.'\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function createAction(this: Command, options: CreateOptions) {\n const body = await buildRequestBody(options);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseCreateResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { added_cases: addedCases } = parsed.data;\n\n console.log(\n green(\n addedCases.length === 1\n ? \"Case created!\"\n : `${addedCases.length} cases created!`\n )\n );\n console.log();\n console.log(renderTable(TABLE_COLUMNS, addedCases));\n });\n}\n\nfunction collectLabel(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nasync function buildRequestBody(\n options: CreateOptions\n): Promise<{ case?: CaseInput; cases?: CaseInput[] }> {\n if (options.fromFile !== undefined) {\n if (\n options.title !== undefined ||\n options.data !== undefined ||\n (options.label?.length ?? 0) > 0\n ) {\n throw new CliError(\n \"--from-file cannot be combined with --title, --data, or --label.\"\n );\n }\n\n return readCasesFromFile(options.fromFile);\n }\n\n if (options.title === undefined || options.title.trim().length === 0) {\n throw new CliError(\"--title is required (or use --from-file).\");\n }\n\n const labels = parseLabels(options.label);\n const single: CaseInput = { title: options.title };\n if (options.data !== undefined) {\n single.data = options.data;\n }\n\n if (labels) {\n single.labels = labels;\n }\n\n return { case: single };\n}\n\nasync function readCasesFromFile(\n path: string\n): Promise<{ case?: CaseInput; cases?: CaseInput[] }> {\n let raw: string;\n try {\n raw = path === \"-\" ? await readStdin() : await readFile(path, \"utf8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Could not read cases file \"${path}\": ${message}`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Cases file \"${path}\" is not valid JSON: ${message}`);\n }\n\n if (Array.isArray(parsed)) {\n if (parsed.length === 0) {\n throw new CliError(\"Cases file must contain at least one case.\");\n }\n\n if (parsed.length > 100) {\n throw new CliError(\"Cases file must contain at most 100 cases.\");\n }\n\n return { cases: parsed.map((c, i) => coerceCase(c, `cases[${i}]`)) };\n }\n\n return { case: coerceCase(parsed, \"case\") };\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction coerceCase(value: unknown, location: string): CaseInput {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new CliError(`${location} must be a JSON object.`);\n }\n\n const obj = value as Record<string, unknown>;\n const title = obj.title;\n if (typeof title !== \"string\" || title.trim().length === 0) {\n throw new CliError(`${location}.title must be a non-empty string.`);\n }\n\n const out: CaseInput = { title };\n if (obj.data !== undefined) {\n if (typeof obj.data !== \"string\") {\n throw new CliError(`${location}.data must be a string when present.`);\n }\n\n out.data = obj.data;\n }\n\n if (obj.labels !== undefined) {\n if (!Array.isArray(obj.labels)) {\n throw new CliError(`${location}.labels must be an array when present.`);\n }\n\n out.labels = obj.labels.map((l, i) =>\n coerceLabel(l, `${location}.labels[${i}]`)\n );\n }\n\n return out;\n}\n\nfunction coerceLabel(\n value: unknown,\n location: string\n): { key: string; value: string } {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new CliError(`${location} must be a JSON object.`);\n }\n\n const obj = value as Record<string, unknown>;\n const labelValue = obj.value;\n if (typeof labelValue !== \"string\" || labelValue.length === 0) {\n throw new CliError(`${location}.value must be a non-empty string.`);\n }\n\n const key = obj.key === undefined ? \"\" : obj.key;\n if (typeof key !== \"string\") {\n throw new CliError(`${location}.key must be a string when present.`);\n }\n\n return { key, value: labelValue };\n}\n\nfunction parseLabels(\n raw: string[] | undefined\n): { key: string; value: string }[] | undefined {\n if (!raw || raw.length === 0) {\n return undefined;\n }\n\n return raw.map((entry) => {\n const eq = entry.indexOf(\"=\");\n if (eq === -1) {\n const trimmed = entry.trim();\n if (trimmed.length === 0) {\n throw new CliError(\"Label value must be a non-empty string.\");\n }\n\n return { key: \"\", value: trimmed };\n }\n\n if (eq === 0) {\n throw new CliError(\n `Invalid label \"${entry}\": omit the leading \"=\" for a simple tag (use \"value\") or provide a non-empty key (use \"key=value\").`\n );\n }\n\n const key = entry.slice(0, eq).trim();\n if (key.length === 0) {\n throw new CliError(\n `Invalid label \"${entry}\": omit the leading \"=\" for a simple tag (use \"value\") or provide a non-empty key (use \"key=value\").`\n );\n }\n\n const value = entry.slice(eq + 1).trim();\n if (value.length === 0) {\n throw new CliError(`Label \"${entry}\" has an empty value.`);\n }\n\n return { key, value };\n });\n}\n", "import { caseDeleteResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype DeleteOptions = {\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerCasesDelete(cases: Command): void {\n cases\n .command(\"delete <id>\")\n .description(\"Delete a case. Interrupts any associated running jobs.\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function deleteAction(\n this: Command,\n id: string,\n options: DeleteOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Delete case \"${id}\"?`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/cases/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseDeleteResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const result = parsed.data;\n if (!result.success) {\n throw new CliError(\"Failed to delete case.\");\n }\n\n console.log(green(\"Case deleted!\"));\n console.log();\n console.log(\n renderKeyValue([\n {\n label: \"Interrupted runs\",\n value: String(result.interruptedRunIds.length),\n },\n ])\n );\n });\n}\n", "import { caseDetailResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype GetOptions = {\n json?: boolean;\n};\n\nexport function registerCasesGet(cases: Command): void {\n cases\n .command(\"get <id>\")\n .description(\"Get a case by ID with its event history\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function getAction(\n this: Command,\n id: string,\n options: GetOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/cases/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseDetailResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { case: caseItem, events } = parsed.data;\n\n console.log(\n renderKeyValue([\n { label: \"ID\", value: caseItem.id },\n { label: \"Queue\", value: caseItem.queue_id },\n { label: \"Title\", value: caseItem.title },\n { label: \"Status\", value: caseItem.status },\n { label: \"Data\", value: caseItem.data ?? \"\" },\n { label: \"Claimed\", value: caseItem.claimed_at ?? \"\" },\n { label: \"Claimed by run\", value: caseItem.claimed_by_run_id ?? \"\" },\n { label: \"Completed\", value: caseItem.completed_at ?? \"\" },\n { label: \"Postponed to\", value: caseItem.postponed_to ?? \"\" },\n { label: \"Created\", value: caseItem.created_at ?? \"\" },\n { label: \"Updated\", value: caseItem.updated_at ?? \"\" },\n ])\n );\n\n if (events && events.length > 0) {\n console.log(\"\");\n console.log(`Events (${events.length}):`);\n for (const event of events) {\n console.log(` - ${event.created_at ?? \"\"} ${event.type}`);\n }\n }\n });\n}\n", "import {\n caseLabelAssignResponseSchema,\n caseLabelsListResponseSchema,\n caseLabelUnlinkResponseSchema,\n type CaseQueueLabel,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\nconst MAX_LABELS_PER_REQUEST = 50;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: CaseQueueLabel) => row.id },\n { header: \"KEY\", cell: (row: CaseQueueLabel) => row.key },\n { header: \"VALUE\", cell: (row: CaseQueueLabel) => row.value },\n { header: \"COLOR HUE\", cell: (row: CaseQueueLabel) => String(row.color_hue) },\n] as const;\n\ntype ListOptions = {\n queue: string;\n json?: boolean;\n};\n\ntype AssignOptions = {\n queue: string;\n label?: string[];\n json?: boolean;\n};\n\ntype UnlinkOptions = {\n queue: string;\n labelId?: string[];\n json?: boolean;\n};\n\nexport function registerCasesLabels(cases: Command): void {\n const labels = cases\n .command(\"labels\")\n .description(\"Manage labels assigned to a case\");\n\n labels\n .command(\"list <case-id>\")\n .description(\"List labels assigned to a case\")\n .requiredOption(\"--queue <id>\", \"ID of the queue the case belongs to\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(\n this: Command,\n caseId: string,\n options: ListOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases/${encodeURIComponent(caseId)}/labels`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseLabelsListResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.labels.length === 0) {\n console.log(\"No labels assigned.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, parsed.data.labels));\n console.log(`Showing ${parsed.data.labels.length}`);\n });\n\n labels\n .command(\"assign <case-id>\")\n .description(\n \"Assign one or more labels to a case (creates labels on the queue if they don't exist)\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue the case belongs to\")\n .requiredOption(\n \"--label <kv>\",\n 'label as \"key=value\" or \"value\" for tag-only (repeatable, 1-50)',\n collectRepeatable,\n [] as string[]\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function assignAction(\n this: Command,\n caseId: string,\n options: AssignOptions\n ) {\n const labelInputs = options.label ?? [];\n if (labelInputs.length === 0) {\n throw new CliError(\"Pass at least one --label\");\n }\n\n if (labelInputs.length > MAX_LABELS_PER_REQUEST) {\n throw new CliError(\n `Pass at most ${MAX_LABELS_PER_REQUEST} --label values per request`\n );\n }\n\n const labelEntries = labelInputs.map(parseLabel);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases/${encodeURIComponent(caseId)}/labels`,\n apiKey,\n apiBaseUrl,\n body: { labels: labelEntries },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseLabelAssignResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n console.log(green(\"Labels assigned!\"));\n console.log(renderTable(TABLE_COLUMNS, parsed.data.labels));\n });\n\n labels\n .command(\"unlink <case-id>\")\n .description(\"Remove one or more labels from a case\")\n .requiredOption(\"--queue <id>\", \"ID of the queue the case belongs to\")\n .requiredOption(\n \"--label-id <id>\",\n \"label ID to unlink (repeatable, at least one required)\",\n collectRepeatable,\n [] as string[]\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function unlinkAction(\n this: Command,\n caseId: string,\n options: UnlinkOptions\n ) {\n const labelIds = options.labelId ?? [];\n if (labelIds.length === 0) {\n throw new CliError(\"Pass at least one --label-id\");\n }\n\n if (labelIds.length > MAX_LABELS_PER_REQUEST) {\n throw new CliError(\n `Pass at most ${MAX_LABELS_PER_REQUEST} --label-id values per request`\n );\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases/${encodeURIComponent(caseId)}/labels/unlink`,\n apiKey,\n apiBaseUrl,\n body: { label_ids: labelIds },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseLabelUnlinkResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n throw new CliError(\"Failed to unlink labels.\");\n }\n\n console.log(green(`Unlinked ${labelIds.length} label(s).`));\n });\n}\n\nfunction collectRepeatable(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nfunction parseLabel(input: string): { key: string; value: string } {\n const eq = input.indexOf(\"=\");\n if (eq === -1) {\n const value = input.trim();\n if (value.length === 0) {\n throw new CliError(`--label \"${input}\" must have a non-empty value`);\n }\n\n return { key: \"\", value };\n }\n\n const key = input.slice(0, eq).trim();\n const value = input.slice(eq + 1).trim();\n if (key.length === 0) {\n throw new CliError(\n `--label \"${input}\" must have a non-empty key (drop the leading \\`=\\` for tag-only labels)`\n );\n }\n\n if (value.length === 0) {\n throw new CliError(`--label \"${input}\" must have a non-empty value`);\n }\n\n return { key, value };\n}\n", "import {\n type CaseFilterStatus,\n caseFilterStatusSchema,\n type CaseQueueItem,\n casesListResponseSchema,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { parseLimit, parseOffset } from \"../shared/pagination.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n queue: string;\n limit?: string;\n offset?: string;\n status?: string;\n search?: string;\n createdAtFrom?: string;\n updatedAtFrom?: string;\n sortBy?: string;\n sortOrder?: string;\n json?: boolean;\n};\n\nconst DEFAULT_LIMIT = 20;\nconst MIN_LIMIT = 1;\nconst MAX_LIMIT = 100;\nconst SORT_FIELDS = [\"created_at\", \"updated_at\", \"postponed_to\"] as const;\nconst SORT_ORDERS = [\"asc\", \"desc\"] as const;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: CaseQueueItem) => row.id },\n { header: \"TITLE\", cell: (row: CaseQueueItem) => row.title, maxWidth: 50 },\n { header: \"STATUS\", cell: (row: CaseQueueItem) => row.status },\n { header: \"CREATED\", cell: (row: CaseQueueItem) => row.created_at ?? \"\" },\n] as const;\n\nexport function registerCasesList(cases: Command): void {\n cases\n .command(\"list\", { isDefault: true })\n .description(\"List cases in a queue\")\n .requiredOption(\"--queue <id>\", \"ID of the queue to list cases for\")\n .option(\"--limit <n>\", `page size (${MIN_LIMIT}-${MAX_LIMIT})`)\n .option(\"--offset <n>\", \"number of cases to skip\")\n .option(\n \"--status <statuses>\",\n `comma-separated case statuses (${caseFilterStatusSchema.options.join(\", \")})`\n )\n .option(\"--search <text>\", \"full-text search across title and data\")\n .option(\n \"--created-at-from <iso>\",\n \"include cases created on or after this ISO-8601 timestamp\"\n )\n .option(\n \"--updated-at-from <iso>\",\n \"include cases updated on or after this ISO-8601 timestamp\"\n )\n .option(\"--sort-by <field>\", `sort field (${SORT_FIELDS.join(\", \")})`)\n .option(\n \"--sort-order <order>\",\n `sort direction (${SORT_ORDERS.join(\", \")})`\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const limit = parseLimit(options.limit, {\n defaultValue: DEFAULT_LIMIT,\n min: MIN_LIMIT,\n max: MAX_LIMIT,\n });\n const offset = parseOffset(options.offset);\n const statuses = parseStatuses(options.status);\n const sortBy = parseSortBy(options.sortBy);\n const sortOrder = parseSortOrder(options.sortOrder);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", String(limit));\n searchParams.append(\"offset\", String(offset));\n if (statuses) {\n searchParams.append(\"status\", statuses.join(\",\"));\n }\n\n if (options.search !== undefined) {\n searchParams.append(\"search\", options.search);\n }\n\n if (options.createdAtFrom !== undefined) {\n searchParams.append(\"created_at_from\", options.createdAtFrom);\n }\n\n if (options.updatedAtFrom !== undefined) {\n searchParams.append(\"updated_at_from\", options.updatedAtFrom);\n }\n\n if (sortBy !== undefined) {\n searchParams.append(\"sort_by\", sortBy);\n }\n\n if (sortOrder !== undefined) {\n searchParams.append(\"sort_order\", sortOrder);\n }\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases`,\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = casesListResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const response = parsed.data;\n\n if (response.cases.length === 0) {\n console.log(\"No cases found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, response.cases));\n const resolvedOffset = response.offset ?? offset;\n const total = response.total ?? null;\n const summary =\n total === null\n ? `Showing ${response.cases.length} \u00B7 offset ${resolvedOffset}`\n : `Showing ${response.cases.length} of ${total} \u00B7 offset ${resolvedOffset}`;\n console.log(summary);\n });\n}\n\nfunction parseStatuses(\n raw: string | undefined\n): CaseFilterStatus[] | undefined {\n if (raw === undefined) {\n return undefined;\n }\n\n const parts = raw\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n throw new CliError(\n `Invalid --status value \"${raw}\". Allowed: ${caseFilterStatusSchema.options.join(\", \")}.`\n );\n }\n\n const allowed = new Set<string>(caseFilterStatusSchema.options);\n const invalid = parts.filter((p) => !allowed.has(p));\n if (invalid.length > 0) {\n throw new CliError(\n `Invalid --status value(s): ${invalid.join(\", \")}. Allowed: ${caseFilterStatusSchema.options.join(\", \")}.`\n );\n }\n\n return parts as CaseFilterStatus[];\n}\n\nfunction parseSortBy(raw: string | undefined): string | undefined {\n if (raw === undefined) {\n return undefined;\n }\n\n if (!SORT_FIELDS.includes(raw as (typeof SORT_FIELDS)[number])) {\n throw new CliError(\n `Invalid --sort-by value \"${raw}\". Allowed: ${SORT_FIELDS.join(\", \")}.`\n );\n }\n\n return raw;\n}\n\nfunction parseSortOrder(raw: string | undefined): string | undefined {\n if (raw === undefined) {\n return undefined;\n }\n\n if (!SORT_ORDERS.includes(raw as (typeof SORT_ORDERS)[number])) {\n throw new CliError(\n `Invalid --sort-order value \"${raw}\". Allowed: ${SORT_ORDERS.join(\", \")}.`\n );\n }\n\n return raw;\n}\n", "import { caseJobsResponseSchema, type CaseJobSummary } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype RunsOptions = {\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"RUN ID\", cell: (row: CaseJobSummary) => row.id },\n { header: \"AGENT\", cell: (row: CaseJobSummary) => row.agent_name },\n { header: \"STATUS\", cell: (row: CaseJobSummary) => row.status },\n { header: \"CLAIMED\", cell: (row: CaseJobSummary) => row.claimed_at },\n {\n header: \"COMPLETED\",\n cell: (row: CaseJobSummary) => row.completed_at ?? \"\",\n },\n {\n header: \"PENDING REQUEST\",\n cell: (row: CaseJobSummary) =>\n row.has_pending_human_request\n ? (row.pending_human_request_title ?? \"(unknown)\")\n : \"\",\n },\n] as const;\n\nexport function registerCasesRuns(cases: Command): void {\n cases\n .command(\"runs <case-id>\")\n .description(\"List jobs (agent runs) that have worked on a case\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function runsAction(\n this: Command,\n caseId: string,\n options: RunsOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/cases/${encodeURIComponent(caseId)}/runs`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseJobsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.runs.length === 0) {\n console.log(\"No runs found for this case.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, parsed.data.runs));\n console.log(`Showing ${parsed.data.runs.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerCasesBulkDelegate } from \"./bulk-delegate.js\";\nimport { registerCasesBulkDelete } from \"./bulk-delete.js\";\nimport { registerCasesBulkRetry } from \"./bulk-retry.js\";\nimport { registerCasesBulkUpdateStatus } from \"./bulk-update-status.js\";\nimport { registerCasesClear } from \"./clear.js\";\nimport { registerCasesCreate } from \"./create.js\";\nimport { registerCasesDelete } from \"./delete.js\";\nimport { registerCasesGet } from \"./get.js\";\nimport { registerCasesLabels } from \"./labels.js\";\nimport { registerCasesList } from \"./list.js\";\nimport { registerCasesRuns } from \"./runs.js\";\n\nexport function registerCases(program: Command): void {\n const cases = program\n .command(\"cases\")\n .description(\"Manage cases in the Duvo public API\");\n\n registerCasesList(cases);\n registerCasesGet(cases);\n registerCasesCreate(cases);\n registerCasesDelete(cases);\n registerCasesClear(cases);\n registerCasesBulkDelete(cases);\n registerCasesBulkRetry(cases);\n registerCasesBulkUpdateStatus(cases);\n registerCasesBulkDelegate(cases);\n registerCasesRuns(cases);\n registerCasesLabels(cases);\n}\n", "import { teamFileContentResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ContentOptions = {\n json?: boolean;\n};\n\nexport function registerFilesContent(files: Command): void {\n files\n .command(\"content <path>\")\n .description(\"Get the content of a text file (binary files are rejected)\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function contentAction(\n this: Command,\n filePath: string,\n options: ContentOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const encodedPath = filePath\n .split(\"/\")\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/files/content/${encodedPath}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = teamFileContentResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n process.stdout.write(parsed.data.content);\n });\n}\n", "import { readFileSync } from \"node:fs\";\n\nimport { teamFileSuccessResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ContentSetOptions = {\n content?: string;\n contentFile?: string;\n json?: boolean;\n};\n\nexport function registerFilesContentSet(files: Command): void {\n files\n .command(\"content-set <path>\")\n .description(\"Update the content of a text file in team storage\")\n .option(\"--content <text>\", \"new content as a string\")\n .option(\n \"--content-file <path>\",\n 'path to a file with the new content, or \"-\" for stdin'\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function contentSetAction(\n this: Command,\n filePath: string,\n options: ContentSetOptions\n ) {\n if (options.content !== undefined && options.contentFile !== undefined) {\n throw new CliError(\n \"Pass either --content or --content-file, not both.\"\n );\n }\n\n const content = readContent(options);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const encodedPath = filePath\n .split(\"/\")\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n\n const raw = await httpRequest({\n method: \"PUT\",\n path: `/v1/files/content/${encodedPath}`,\n apiKey,\n apiBaseUrl,\n body: { content },\n });\n\n const parsed = teamFileSuccessResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n if (options.json) {\n printJson(raw);\n }\n\n throw new CliError(\"Failed to update file.\");\n }\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n console.log(green(\"File updated!\"));\n });\n}\n\nfunction readContent(options: ContentSetOptions): string {\n if (options.content !== undefined) {\n return options.content;\n }\n\n if (options.contentFile === undefined) {\n throw new CliError(\"Pass either --content or --content-file\");\n }\n\n if (options.contentFile === \"-\") {\n return readFileSync(0, \"utf8\");\n }\n\n try {\n return readFileSync(options.contentFile, \"utf8\");\n } catch (error) {\n throw new CliError(\n `Cannot read --content-file ${options.contentFile}: ${(error as Error).message}`\n );\n }\n}\n", "import { teamFileSuccessResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype DeleteOptions = {\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerFilesDelete(files: Command): void {\n files\n .command(\"delete <path>\")\n .description(\"Delete a team file\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function deleteAction(\n this: Command,\n filePath: string,\n options: DeleteOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Delete file \"${filePath}\"?`,\n skip: Boolean(options.yes),\n });\n\n const encodedPath = filePath\n .split(\"/\")\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/files/${encodedPath}`,\n apiKey,\n apiBaseUrl,\n });\n\n const parsed = teamFileSuccessResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n if (options.json) {\n printJson(raw);\n }\n\n throw new CliError(\"Failed to delete file.\");\n }\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n console.log(green(\"File deleted!\"));\n });\n}\n", "import { teamFileDownloadUrlResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype DownloadUrlOptions = {\n json?: boolean;\n};\n\nexport function registerFilesDownloadUrl(files: Command): void {\n files\n .command(\"download-url <path>\")\n .description(\"Get a presigned download URL for a team file\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function downloadUrlAction(\n this: Command,\n filePath: string,\n options: DownloadUrlOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const encodedPath = filePath\n .split(\"/\")\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/files/download-url/${encodedPath}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = teamFileDownloadUrlResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n console.log(\n renderKeyValue([\n { label: \"URL\", value: parsed.data.url },\n { label: \"Expires\", value: parsed.data.expiresAt },\n ])\n );\n });\n}\n", "import {\n listTeamFilesResponseSchema,\n type TeamFileItem,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"PATH\", cell: (row: TeamFileItem) => row.path },\n { header: \"NAME\", cell: (row: TeamFileItem) => row.name },\n {\n header: \"MIME\",\n cell: (row: TeamFileItem) => row.metadata?.mimetype ?? \"\",\n },\n {\n header: \"SIZE\",\n cell: (row: TeamFileItem) =>\n row.metadata?.size === undefined ? \"\" : String(row.metadata.size),\n },\n {\n header: \"UPDATED\",\n cell: (row: TeamFileItem) => row.updated_at ?? \"\",\n },\n] as const;\n\nexport function registerFilesList(files: Command): void {\n files\n .command(\"list\", { isDefault: true })\n .description(\"List team files\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/files\",\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listTeamFilesResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.files.length === 0) {\n console.log(\"No files found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, parsed.data.files));\n console.log(`Showing ${parsed.data.files.length}`);\n });\n}\n", "import { teamFileSuccessResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype RenameOptions = {\n path: string;\n newName: string;\n json?: boolean;\n};\n\nconst PATH_SEPARATOR = /[\\\\/]/;\n\nexport function registerFilesRename(files: Command): void {\n files\n .command(\"rename\")\n .description(\n \"Rename a team file (only the filename changes; extension is preserved)\"\n )\n .requiredOption(\"--path <path>\", \"current relative path of the file\")\n .requiredOption(\n \"--new-name <name>\",\n \"new filename without extension (extension is preserved automatically)\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function renameAction(this: Command, options: RenameOptions) {\n const newName = options.newName.trim();\n if (\n newName.length === 0 ||\n newName === \".\" ||\n newName === \"..\" ||\n PATH_SEPARATOR.test(newName)\n ) {\n throw new CliError(\n \"--new-name must be a filename only (no path separators, no `.` or `..`)\"\n );\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"PATCH\",\n path: \"/v1/files\",\n apiKey,\n apiBaseUrl,\n body: {\n relativePath: options.path,\n newFilenameOnly: newName,\n },\n });\n\n const parsed = teamFileSuccessResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n if (options.json) {\n printJson(raw);\n }\n\n throw new CliError(\"Failed to rename file.\");\n }\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n console.log(green(\"File renamed!\"));\n });\n}\n", "import { createTeamFileUploadUrlResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype UploadUrlOptions = {\n fileName: string;\n contentType: string;\n json?: boolean;\n};\n\nexport function registerFilesUploadUrl(files: Command): void {\n files\n .command(\"upload-url\")\n .description(\"Get a presigned upload URL for a team file\")\n .requiredOption(\"--file-name <name>\", \"name of the file to upload\")\n .requiredOption(\"--content-type <mime>\", \"MIME type of the file\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function uploadUrlAction(\n this: Command,\n options: UploadUrlOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/files/create-upload-url\",\n apiKey,\n apiBaseUrl,\n body: {\n fileName: options.fileName,\n contentType: options.contentType,\n },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = createTeamFileUploadUrlResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n console.log(\n renderKeyValue([\n { label: \"Path\", value: parsed.data.filePath },\n { label: \"Signed URL\", value: parsed.data.signedUrl },\n { label: \"Expires\", value: parsed.data.expiresAt },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerFilesContent } from \"./content.js\";\nimport { registerFilesContentSet } from \"./content-set.js\";\nimport { registerFilesDelete } from \"./delete.js\";\nimport { registerFilesDownloadUrl } from \"./download-url.js\";\nimport { registerFilesList } from \"./list.js\";\nimport { registerFilesRename } from \"./rename.js\";\nimport { registerFilesUploadUrl } from \"./upload-url.js\";\n\nexport function registerFiles(program: Command): void {\n const files = program\n .command(\"files\")\n .description(\"Manage team files exposed by the Duvo public API\");\n\n registerFilesList(files);\n registerFilesUploadUrl(files);\n registerFilesDownloadUrl(files);\n registerFilesRename(files);\n registerFilesDelete(files);\n registerFilesContent(files);\n registerFilesContentSet(files);\n}\n", "import { isCancel, password, text } from \"@clack/prompts\";\nimport { type Command } from \"commander\";\n\nimport { DEFAULT_API_BASE_URL } from \"@/config/defaults.js\";\nimport { addProfile, isValidProfileName } from \"@/config/profiles.js\";\nimport { readConfig, writeConfig } from \"@/config/store.js\";\nimport { AuthCliError, CancelCliError, CliError } from \"@/errors.js\";\n\ntype LoginOptions = {\n name?: string;\n apiKey?: string;\n baseUrl?: string;\n};\n\nexport function registerLogin(program: Command): void {\n program\n .command(\"login\")\n .description(\"Store an API key under a named profile\")\n .option(\n \"--name <profile>\",\n \"profile name to store this key under (prompted if omitted)\"\n )\n .option(\n \"--api-key <key>\",\n \"API key (non-interactive; skips the masked prompt)\"\n )\n .option(\n \"--base-url <url>\",\n `API base URL for this profile (default: ${DEFAULT_API_BASE_URL})`\n )\n .action(async (options: LoginOptions) => {\n await runLogin(options);\n });\n}\n\nasync function runLogin(options: LoginOptions): Promise<void> {\n const config = await readConfig();\n const existingCount = Object.keys(config.profiles).length;\n\n const name = await resolveProfileName(options.name, existingCount);\n const apiKey = await resolveApiKey(options.apiKey);\n const apiBaseUrl = options.baseUrl ?? DEFAULT_API_BASE_URL;\n\n const next = addProfile(config, name, { apiKey, apiBaseUrl });\n await writeConfig(next);\n\n const isNew = !(name in config.profiles);\n const verb = isNew ? \"Saved\" : \"Updated\";\n console.log(`${verb} profile \"${name}\".`);\n if (next.defaultProfile === name && config.defaultProfile !== name) {\n console.log(`Set \"${name}\" as the default profile.`);\n }\n}\n\nasync function resolveProfileName(\n flag: string | undefined,\n existingCount: number\n): Promise<string> {\n if (flag !== undefined) {\n if (!isValidProfileName(flag)) {\n throw new CliError(\n `Invalid profile name \"${flag}\". Use lowercase letters, digits, ` +\n `\".\", \"-\" or \"_\", max 40 chars.`\n );\n }\n\n return flag;\n }\n\n const placeholder = existingCount === 0 ? \"default\" : \"\";\n const answer = await text({\n message: \"Profile name\",\n placeholder: placeholder || \"e.g. acme\",\n defaultValue: placeholder,\n validate: (value) => {\n if (!value || value.length === 0) {\n return \"Profile name is required.\";\n }\n\n if (!isValidProfileName(value)) {\n return 'Use lowercase letters, digits, \".\", \"-\" or \"_\" only (max 40 chars).';\n }\n\n return undefined;\n },\n });\n if (isCancel(answer)) {\n throw new CancelCliError(\"Login cancelled.\");\n }\n\n return answer;\n}\n\nasync function resolveApiKey(flag: string | undefined): Promise<string> {\n if (flag !== undefined) {\n if (flag.length === 0) {\n throw new AuthCliError(\"--api-key cannot be empty.\");\n }\n\n return flag;\n }\n\n const answer = await password({\n message: \"API key\",\n validate: (value) => {\n if (!value || value.length === 0) {\n return \"API key is required.\";\n }\n\n return undefined;\n },\n });\n if (isCancel(answer)) {\n throw new CancelCliError(\"Login cancelled.\");\n }\n\n return answer;\n}\n", "import { type Config, type Profile } from \"@/config/types.js\";\n\nconst PROFILE_NAME_PATTERN = /^[a-z0-9._-]+$/;\nconst MAX_PROFILE_NAME_LENGTH = 40;\n\nexport function isValidProfileName(name: string): boolean {\n if (name.length === 0 || name.length > MAX_PROFILE_NAME_LENGTH) {\n return false;\n }\n\n return PROFILE_NAME_PATTERN.test(name);\n}\n\nfunction assertValidProfileName(name: string): void {\n if (!isValidProfileName(name)) {\n throw new Error(\n `Invalid profile name \"${name}\". Use lowercase letters, digits, ` +\n `\".\", \"-\" or \"_\", max ${MAX_PROFILE_NAME_LENGTH} chars.`\n );\n }\n}\n\n/**\n * Add (or replace) a profile. The first profile added becomes the\n * default automatically. Returns the updated config without mutating\n * the input.\n */\nexport function addProfile(\n config: Config,\n name: string,\n profile: Profile\n): Config {\n assertValidProfileName(name);\n const profiles = { ...config.profiles, [name]: profile };\n const defaultProfile =\n config.defaultProfile === null ? name : config.defaultProfile;\n return { defaultProfile, profiles };\n}\n\n/**\n * Remove a profile. If the removed profile was the default, picks\n * another profile alphabetically as the new default, or clears it if\n * none remain.\n */\nexport function removeProfile(config: Config, name: string): Config {\n if (!(name in config.profiles)) {\n return config;\n }\n\n const profiles = { ...config.profiles };\n delete profiles[name];\n\n if (config.defaultProfile !== name) {\n return { defaultProfile: config.defaultProfile, profiles };\n }\n\n const remaining = Object.keys(profiles).sort();\n const defaultProfile = remaining.length > 0 ? remaining[0] : null;\n return { defaultProfile, profiles };\n}\n\nexport function renameProfile(\n config: Config,\n oldName: string,\n newName: string\n): Config {\n if (!(oldName in config.profiles)) {\n throw new Error(`Profile \"${oldName}\" does not exist.`);\n }\n\n if (oldName === newName) {\n return config;\n }\n\n assertValidProfileName(newName);\n if (newName in config.profiles) {\n throw new Error(`Profile \"${newName}\" already exists.`);\n }\n\n const profiles = { ...config.profiles };\n profiles[newName] = profiles[oldName];\n delete profiles[oldName];\n\n const defaultProfile =\n config.defaultProfile === oldName ? newName : config.defaultProfile;\n return { defaultProfile, profiles };\n}\n\nexport function setDefaultProfile(config: Config, name: string): Config {\n if (!(name in config.profiles)) {\n throw new Error(`Profile \"${name}\" does not exist.`);\n }\n\n return { ...config, defaultProfile: name };\n}\n\nexport type ProfileSummary = {\n name: string;\n apiKey: string;\n apiBaseUrl: string;\n isDefault: boolean;\n};\n\nexport function listProfiles(config: Config): readonly ProfileSummary[] {\n return Object.entries(config.profiles)\n .map(([name, profile]): ProfileSummary => {\n return {\n name,\n apiKey: profile.apiKey,\n apiBaseUrl: profile.apiBaseUrl,\n isDefault: config.defaultProfile === name,\n };\n })\n .sort((a, b) => a.name.localeCompare(b.name));\n}\n", "import { type Command } from \"commander\";\n\nimport { removeProfile } from \"@/config/profiles.js\";\nimport { readConfig, writeConfig } from \"@/config/store.js\";\n\nimport { confirmDestructive } from \"./shared/confirm.js\";\n\ntype LogoutOptions = {\n name?: string;\n yes?: boolean;\n};\n\nexport function registerLogout(program: Command): void {\n program\n .command(\"logout\")\n .description(\"Remove a stored profile (default: the default one)\")\n .option(\n \"--name <profile>\",\n \"profile to remove (defaults to the default profile)\"\n )\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .action(async (options: LogoutOptions) => {\n await runLogout(options);\n });\n}\n\nasync function runLogout(options: LogoutOptions): Promise<void> {\n const config = await readConfig();\n const target = options.name ?? config.defaultProfile;\n\n if (!target) {\n console.log(\"No profile to remove \u2014 you are not logged in.\");\n return;\n }\n\n if (!(target in config.profiles)) {\n console.log(`Profile \"${target}\" does not exist.`);\n return;\n }\n\n await confirmDestructive({\n message: `Remove profile \"${target}\"?`,\n skip: options.yes ?? false,\n });\n\n const next = removeProfile(config, target);\n await writeConfig(next);\n\n console.log(`Removed profile \"${target}\".`);\n if (next.defaultProfile && next.defaultProfile !== config.defaultProfile) {\n console.log(`Default profile is now \"${next.defaultProfile}\".`);\n } else if (!next.defaultProfile) {\n console.log(\"No profiles remaining.\");\n }\n}\n", "import {\n type CatalogPlugin,\n pluginCatalogResponseSchema,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"NAME\", cell: (row: CatalogPlugin) => row.name },\n { header: \"TYPE\", cell: (row: CatalogPlugin) => row.type },\n {\n header: \"DESCRIPTION\",\n cell: (row: CatalogPlugin) => row.description,\n maxWidth: 60,\n },\n] as const;\n\nexport function registerPluginsList(plugins: Command): void {\n plugins\n .command(\"list\", { isDefault: true })\n .description(\n \"List plugins that can be referenced by name in a build's plugins array\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/plugins/catalog\",\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = pluginCatalogResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.plugins.length === 0) {\n console.log(\"No plugins found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, parsed.data.plugins));\n console.log(`Showing ${parsed.data.plugins.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerPluginsList } from \"./list.js\";\n\nexport function registerPlugins(program: Command): void {\n const plugins = program\n .command(\"plugins\")\n .description(\n \"Browse plugins that can be referenced in a build's plugins array\"\n );\n\n registerPluginsList(plugins);\n}\n", "const FALLBACK_PREFIX_LEN = 11;\n\n/**\n * Mask the secret portion of an API key, leaving the non-secret prefix\n * visible so users can distinguish keys in listings.\n *\n * Keys have the shape `dv_<prefix>-<secret>`. Everything up to and\n * including the first `-` is the public id; everything after is masked.\n * Keys without a dash (shouldn't happen in practice) fall back to a\n * fixed-length prefix so we never leak the tail regardless of format.\n */\nexport function truncateApiKey(key: string): string {\n const dashIdx = key.indexOf(\"-\");\n const visibleLen = dashIdx >= 0 ? dashIdx + 1 : FALLBACK_PREFIX_LEN;\n if (key.length <= visibleLen) {\n return key;\n }\n\n const visible = key.slice(0, visibleLen);\n const masked = \"*\".repeat(key.length - visibleLen);\n return `${visible}${masked}`;\n}\n\nexport function padRight(value: string, width: number): string {\n if (value.length >= width) {\n return value;\n }\n\n return value + \" \".repeat(width - value.length);\n}\n", "import { type ProfileSummary } from \"@/config/profiles.js\";\nimport { truncateApiKey } from \"@/output/format.js\";\nimport { type Column, renderTable } from \"@/output/table.js\";\n\nexport const DEFAULT_MARKER = \"\u25B6\";\nexport const NON_DEFAULT_MARKER = \" \";\n\nconst COLUMNS: readonly Column<ProfileSummary>[] = [\n {\n header: \"\",\n cell: (item) => (item.isDefault ? DEFAULT_MARKER : NON_DEFAULT_MARKER),\n },\n { header: \"NAME\", cell: (item) => item.name },\n];\n\n/**\n * Format the profile list as an aligned text table. The leading marker\n * column flags the active profile (\u25B6) and stays a single character wide\n * so non-default rows align cleanly. The masked API key is intentionally\n * omitted \u2014 `duvo whoami` shows it for the active profile, and including\n * the full masked key here forced an unhelpfully wide column.\n */\nexport function renderProfileTable(items: readonly ProfileSummary[]): string {\n return renderTable(COLUMNS, items);\n}\n\n/**\n * JSON output mirrors the text view's masked keys \u2014 never emit raw\n * credentials from a listing command.\n */\nexport function renderProfileJson(items: readonly ProfileSummary[]): string {\n const masked = items.map((item) => {\n return { ...item, apiKey: truncateApiKey(item.apiKey) };\n });\n return JSON.stringify(masked, null, 2);\n}\n", "import { type Command } from \"commander\";\n\nimport { listProfiles } from \"@/config/profiles.js\";\nimport { readConfig } from \"@/config/store.js\";\n\nimport { renderProfileJson, renderProfileTable } from \"./render-list.js\";\n\ntype ListOptions = {\n json?: boolean;\n};\n\nexport function registerList(profiles: Command): void {\n profiles\n .command(\"list\", { isDefault: true })\n .description(\"List stored profiles; mark the default one with \u25B6\")\n .option(\"--json\", \"output raw JSON\")\n .action(async (options: ListOptions) => {\n const config = await readConfig();\n const items = listProfiles(config);\n\n if (options.json) {\n console.log(renderProfileJson(items));\n return;\n }\n\n if (items.length === 0) {\n console.log(\"No profiles stored. Run `duvo login` to add one.\");\n return;\n }\n\n console.log(renderProfileTable(items));\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { removeProfile } from \"@/config/profiles.js\";\nimport { readConfig, writeConfig } from \"@/config/store.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\n\ntype RemoveOptions = {\n yes?: boolean;\n};\n\nexport function registerRemove(profiles: Command): void {\n profiles\n .command(\"remove <name>\")\n .description(\"Remove a stored profile (alias of `duvo logout --name`)\")\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .action(async (name: string, options: RemoveOptions) => {\n const config = await readConfig();\n if (!(name in config.profiles)) {\n console.log(`Profile \"${name}\" does not exist.`);\n return;\n }\n\n await confirmDestructive({\n message: `Remove profile \"${name}\"?`,\n skip: options.yes ?? false,\n });\n\n const next = removeProfile(config, name);\n await writeConfig(next);\n console.log(`Removed profile \"${name}\".`);\n if (\n next.defaultProfile &&\n next.defaultProfile !== config.defaultProfile\n ) {\n console.log(`Default profile is now \"${next.defaultProfile}\".`);\n } else if (!next.defaultProfile) {\n console.log(\"No profiles remaining.\");\n }\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { renameProfile } from \"@/config/profiles.js\";\nimport { readConfig, writeConfig } from \"@/config/store.js\";\nimport { CliError, EXIT_CODE } from \"@/errors.js\";\n\nexport function registerRename(profiles: Command): void {\n profiles\n .command(\"rename <old> <new>\")\n .description(\"Rename a stored profile, preserving its credentials\")\n .action(async (oldName: string, newName: string) => {\n const config = await readConfig();\n try {\n const next = renameProfile(config, oldName, newName);\n await writeConfig(next);\n console.log(`Renamed profile \"${oldName}\" to \"${newName}\".`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(message, EXIT_CODE.GENERIC);\n }\n });\n}\n", "import { isCancel, select } from \"@clack/prompts\";\nimport { type Command } from \"commander\";\n\nimport {\n listProfiles,\n type ProfileSummary,\n setDefaultProfile,\n} from \"@/config/profiles.js\";\nimport { readConfig, writeConfig } from \"@/config/store.js\";\nimport { type Config } from \"@/config/types.js\";\nimport { AuthCliError, CancelCliError, CliError } from \"@/errors.js\";\nimport { padRight, truncateApiKey } from \"@/output/format.js\";\n\nimport { DEFAULT_MARKER, NON_DEFAULT_MARKER } from \"./render-list.js\";\n\nconst NAME_HEADER = \"NAME\";\n\nexport function registerUse(profiles: Command): void {\n profiles\n .command(\"use [name]\")\n .description(\n \"Switch the default profile (interactive picker when name is omitted)\"\n )\n .action(async (name: string | undefined) => {\n const target =\n name ?? (await pickProfileInteractively(await readConfig()));\n\n const config = await readConfig();\n if (!(target in config.profiles)) {\n throw new AuthCliError(\n `Profile \"${target}\" does not exist. Run \\`duvo profiles list\\` to see available profiles.`\n );\n }\n\n const next = setDefaultProfile(config, target);\n await writeConfig(next);\n console.log(`Default profile is now \"${target}\".`);\n });\n}\n\nasync function pickProfileInteractively(config: Config): Promise<string> {\n const profiles = listProfiles(config);\n if (profiles.length === 0) {\n throw new CliError(\n \"No profiles configured. Run `duvo login` to add one first.\"\n );\n }\n\n if (!process.stdin.isTTY) {\n throw new CliError(\n \"Profile name is required in non-interactive shells. \" +\n \"Run `duvo profiles use <name>`.\"\n );\n }\n\n const options = buildPickerOptions(profiles);\n\n const answer = await select({\n message: \"Select default profile\",\n initialValue: config.defaultProfile ?? profiles[0].name,\n options,\n });\n if (isCancel(answer)) {\n throw new CancelCliError(\"Profile switch cancelled.\");\n }\n\n return answer;\n}\n\ntype PickerOption = {\n value: string;\n label: string;\n};\n\nfunction buildPickerOptions(\n profiles: readonly ProfileSummary[]\n): PickerOption[] {\n const maskedKeys = profiles.map((profile) => truncateApiKey(profile.apiKey));\n const nameWidth = Math.max(\n NAME_HEADER.length,\n ...profiles.map((profile) => profile.name.length)\n );\n\n return profiles.map((profile, index) => {\n const marker = profile.isDefault ? DEFAULT_MARKER : NON_DEFAULT_MARKER;\n const label = `${marker} ${padRight(profile.name, nameWidth)} ${maskedKeys[index]}`;\n return {\n value: profile.name,\n label,\n };\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerList } from \"./list.js\";\nimport { registerRemove } from \"./remove.js\";\nimport { registerRename } from \"./rename.js\";\nimport { registerUse } from \"./use.js\";\n\nexport function registerProfiles(program: Command): void {\n const profiles = program\n .command(\"profiles\")\n .description(\"Manage stored API-key profiles\");\n\n registerList(profiles);\n registerUse(profiles);\n registerRename(profiles);\n registerRemove(profiles);\n}\n", "import {\n type CaseLabelCreateResponse,\n caseLabelCreateResponseSchema,\n caseLabelsWithCountsListResponseSchema,\n caseLabelUnlinkResponseSchema,\n caseLabelUpdateResponseSchema,\n type CaseQueueLabelWithCount,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: CaseQueueLabelWithCount) => row.id },\n { header: \"KEY\", cell: (row: CaseQueueLabelWithCount) => row.key },\n { header: \"VALUE\", cell: (row: CaseQueueLabelWithCount) => row.value },\n {\n header: \"COLOR HUE\",\n cell: (row: CaseQueueLabelWithCount) => String(row.color_hue),\n },\n {\n header: \"CASES\",\n cell: (row: CaseQueueLabelWithCount) => String(row.case_count),\n },\n] as const;\n\ntype ListOptions = {\n queue: string;\n limit?: string;\n offset?: string;\n json?: boolean;\n};\n\ntype CreateOptions = {\n queue: string;\n key?: string;\n value: string;\n colorHue?: string;\n json?: boolean;\n};\n\ntype UpdateOptions = {\n queue: string;\n key?: string;\n value?: string;\n colorHue?: string;\n json?: boolean;\n};\n\ntype DeleteOptions = {\n queue: string;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerQueueLabels(program: Command): void {\n const labels = program\n .command(\"queue-labels\")\n .description(\"Manage label vocabularies on a queue\");\n\n registerList(labels);\n registerCreate(labels);\n registerUpdate(labels);\n registerDelete(labels);\n}\n\nfunction registerList(labels: Command): void {\n labels\n .command(\"list\", { isDefault: true })\n .description(\n \"List labels defined on a queue along with the number of cases each is assigned to\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue\")\n .option(\"--limit <n>\", \"page size (1-1000, default 1000)\")\n .option(\"--offset <n>\", \"number of labels to skip\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n if (options.limit !== undefined) {\n searchParams.append(\"limit\", options.limit);\n }\n\n if (options.offset !== undefined) {\n searchParams.append(\"offset\", options.offset);\n }\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/labels`,\n apiKey,\n apiBaseUrl,\n searchParams: searchParams.size > 0 ? searchParams : undefined,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseLabelsWithCountsListResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.labels.length === 0) {\n console.log(\"No labels defined on this queue.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, parsed.data.labels));\n console.log(`Showing ${parsed.data.labels.length}`);\n });\n}\n\nfunction registerCreate(labels: Command): void {\n labels\n .command(\"create\")\n .description(\"Create a label on a queue without assigning it to a case\")\n .requiredOption(\"--queue <id>\", \"ID of the queue\")\n .option(\"--key <text>\", \"label key (omit for tag-only labels)\")\n .requiredOption(\"--value <text>\", \"label value (required, non-empty)\")\n .option(\"--color-hue <n>\", \"color hue 0-360 (auto-derived if omitted)\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function createAction(this: Command, options: CreateOptions) {\n if (options.value.trim().length === 0) {\n throw new CliError(\"--value must not be empty\");\n }\n\n const colorHue = parseColorHue(options.colorHue);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const body: Record<string, unknown> = { value: options.value };\n if (options.key !== undefined) {\n body.key = options.key;\n }\n\n if (colorHue !== undefined) {\n body.color_hue = colorHue;\n }\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/labels`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseLabelCreateResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { label } = parsed.data as CaseLabelCreateResponse;\n console.log(green(\"Label created!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: label.id },\n { label: \"Key\", value: label.key },\n { label: \"Value\", value: label.value },\n { label: \"Color hue\", value: String(label.color_hue) },\n { label: \"Cases\", value: String(label.case_count) },\n ])\n );\n });\n}\n\nfunction registerUpdate(labels: Command): void {\n labels\n .command(\"update <label-id>\")\n .description(\n \"Rename a label or change its color (affects every case it's assigned to)\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue the label belongs to\")\n .option(\"--key <text>\", \"new label key (omit to leave unchanged)\")\n .option(\"--value <text>\", \"new label value\")\n .option(\"--color-hue <n>\", \"new color hue 0-360\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function updateAction(\n this: Command,\n labelId: string,\n options: UpdateOptions\n ) {\n const colorHue = parseColorHue(options.colorHue);\n\n const body: Record<string, unknown> = {};\n if (options.key !== undefined) {\n body.key = options.key;\n }\n\n if (options.value !== undefined) {\n if (options.value.trim().length === 0) {\n throw new CliError(\"--value must not be empty\");\n }\n\n body.value = options.value;\n }\n\n if (colorHue !== undefined) {\n body.color_hue = colorHue;\n }\n\n // The schema requires `value`; the server will reject if missing. But\n // leaving body empty also makes no sense, so guard early.\n if (Object.keys(body).length === 0) {\n throw new CliError(\n \"Pass at least one of --key, --value, or --color-hue.\"\n );\n }\n\n if (body.value === undefined) {\n throw new CliError(\n \"--value is required by the API; pass --value <text> to keep or change it.\"\n );\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"PATCH\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/labels/${encodeURIComponent(labelId)}`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseLabelUpdateResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { label } = parsed.data;\n console.log(green(\"Label updated!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: label.id },\n { label: \"Key\", value: label.key },\n { label: \"Value\", value: label.value },\n { label: \"Color hue\", value: String(label.color_hue) },\n ])\n );\n });\n}\n\nfunction registerDelete(labels: Command): void {\n labels\n .command(\"delete <label-id>\")\n .description(\n \"Delete a label from a queue (cascade-removes from every case it was assigned to)\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue the label belongs to\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function deleteAction(\n this: Command,\n labelId: string,\n options: DeleteOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Delete label \"${labelId}\" from queue \"${options.queue}\"? Cases assigned to this label will lose it.`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/labels/${encodeURIComponent(labelId)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseLabelUnlinkResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n throw new CliError(\"Failed to delete label.\");\n }\n\n console.log(green(\"Label deleted!\"));\n });\n}\n\nfunction parseColorHue(raw: string | undefined): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n\n const value = Number.parseInt(raw, 10);\n if (Number.isNaN(value) || value < 0 || value > 360) {\n throw new CliError(\"--color-hue must be an integer between 0 and 360\");\n }\n\n return value;\n}\n", "import {\n type QueueAgentConsumer,\n type QueueAgentProducer,\n queueAgentsResponseSchema,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype AgentsOptions = {\n json?: boolean;\n};\n\nconst PRODUCER_COLUMNS = [\n { header: \"AGENT ID\", cell: (row: QueueAgentProducer) => row.agent_id },\n { header: \"NAME\", cell: (row: QueueAgentProducer) => row.agent_name },\n {\n header: \"TRIGGER ENABLED\",\n cell: (row: QueueAgentProducer) =>\n row.case_trigger_enabled ? \"yes\" : \"no\",\n },\n {\n header: \"TRIGGER QUEUE\",\n cell: (row: QueueAgentProducer) => row.case_trigger_queue_name ?? \"\",\n },\n {\n header: \"PROBLEMS\",\n cell: (row: QueueAgentProducer) =>\n row.problems.length === 0 ? \"\" : row.problems.join(\", \"),\n },\n] as const;\n\nconst CONSUMER_COLUMNS = [\n { header: \"AGENT ID\", cell: (row: QueueAgentConsumer) => row.agent_id },\n { header: \"NAME\", cell: (row: QueueAgentConsumer) => row.agent_name },\n {\n header: \"TRIGGER ENABLED\",\n cell: (row: QueueAgentConsumer) =>\n row.case_trigger_enabled ? \"yes\" : \"no\",\n },\n {\n header: \"HANDOVER TARGET\",\n cell: (row: QueueAgentConsumer) => (row.is_handover_target ? \"yes\" : \"no\"),\n },\n {\n header: \"PROBLEMS\",\n cell: (row: QueueAgentConsumer) =>\n row.problems.length === 0 ? \"\" : row.problems.join(\", \"),\n },\n] as const;\n\nexport function registerQueuesAgents(queues: Command): void {\n queues\n .command(\"agents <queue-id>\")\n .description(\n \"List agents bound to a queue (producers push cases in; consumers are triggered by cases)\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function agentsAction(\n this: Command,\n queueId: string,\n options: AgentsOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/queues/${encodeURIComponent(queueId)}/agents`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = queueAgentsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { queue_name, producers, consumers } = parsed.data;\n console.log(`Queue: ${queue_name}`);\n console.log(\"\");\n\n console.log(`Producers (${producers.length})`);\n if (producers.length === 0) {\n console.log(\" (none)\");\n } else {\n console.log(renderTable(PRODUCER_COLUMNS, producers));\n }\n\n console.log(\"\");\n\n console.log(`Consumers (${consumers.length})`);\n if (consumers.length === 0) {\n console.log(\" (none)\");\n } else {\n console.log(renderTable(CONSUMER_COLUMNS, consumers));\n }\n });\n}\n", "import { caseCreateQueueResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype CreateOptions = {\n name?: string;\n description?: string;\n folderId?: string;\n json?: boolean;\n};\n\ntype RequestBody = {\n name: string;\n description?: string | null;\n folder_id?: string | null;\n};\n\nexport function registerQueuesCreate(queues: Command): void {\n queues\n .command(\"create\")\n .description(\"Create a new case queue\")\n .requiredOption(\"--name <name>\", \"queue name (must be unique within team)\")\n .option(\"--description <text>\", \"human-readable description\")\n .option(\"--folder-id <id>\", \"folder to nest the queue under\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function createAction(this: Command, options: CreateOptions) {\n if (options.name === undefined || options.name.trim().length === 0) {\n throw new CliError(\"--name must not be empty\");\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const body: RequestBody = { name: options.name.trim() };\n if (options.description !== undefined) {\n body.description = options.description;\n }\n\n if (options.folderId !== undefined) {\n const trimmedFolderId = options.folderId.trim();\n if (trimmedFolderId.length === 0) {\n throw new CliError(\"--folder-id must not be empty\");\n }\n\n body.folder_id = trimmedFolderId;\n }\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/queues\",\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseCreateQueueResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { queue } = parsed.data;\n\n console.log(green(\"Queue created!\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"ID\", value: queue.id },\n { label: \"Name\", value: queue.name },\n { label: \"Description\", value: queue.description ?? \"\" },\n { label: \"Folder\", value: queue.folder_id ?? \"\" },\n { label: \"Created\", value: queue.created_at ?? \"\" },\n ])\n );\n });\n}\n", "import { deleteQueueResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype DeleteOptions = {\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerQueuesDelete(queues: Command): void {\n queues\n .command(\"delete <id>\")\n .description(\n \"Delete a case queue. Interrupts running jobs and removes all cases.\"\n )\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function deleteAction(\n this: Command,\n id: string,\n options: DeleteOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Delete queue \"${id}\" and all of its cases?`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/queues/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = deleteQueueResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const result = parsed.data;\n if (!result.success) {\n throw new CliError(\"Failed to delete queue.\");\n }\n\n console.log(green(\"Queue deleted!\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"Deleted cases\", value: String(result.deleted_case_count) },\n {\n label: \"Interrupted runs\",\n value: String(result.interrupted_run_ids.length),\n },\n ])\n );\n });\n}\n", "import { caseGetQueueResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype GetOptions = {\n json?: boolean;\n};\n\nexport function registerQueuesGet(queues: Command): void {\n queues\n .command(\"get <id>\")\n .description(\"Get a case queue by ID\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function getAction(\n this: Command,\n id: string,\n options: GetOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/queues/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseGetQueueResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { queue } = parsed.data;\n\n console.log(\n renderKeyValue([\n { label: \"ID\", value: queue.id },\n { label: \"Name\", value: queue.name },\n { label: \"Description\", value: queue.description ?? \"\" },\n { label: \"Folder\", value: queue.folder_id ?? \"\" },\n { label: \"Created\", value: queue.created_at ?? \"\" },\n ])\n );\n });\n}\n", "import { type CaseQueue, caseQueuesResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { parseLimit, parseOffset } from \"../shared/pagination.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n limit?: string;\n offset?: string;\n json?: boolean;\n};\n\nconst DEFAULT_LIMIT = 20;\nconst MIN_LIMIT = 1;\nconst MAX_LIMIT = 100;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: CaseQueue) => row.id },\n { header: \"NAME\", cell: (row: CaseQueue) => row.name },\n {\n header: \"DESCRIPTION\",\n cell: (row: CaseQueue) => row.description ?? \"\",\n maxWidth: 40,\n },\n { header: \"CREATED\", cell: (row: CaseQueue) => row.created_at ?? \"\" },\n] as const;\n\nexport function registerQueuesList(queues: Command): void {\n queues\n .command(\"list\", { isDefault: true })\n .description(\"List case queues for your team\")\n .option(\"--limit <n>\", `page size (${MIN_LIMIT}-${MAX_LIMIT})`)\n .option(\"--offset <n>\", \"number of queues to skip\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const limit = parseLimit(options.limit, {\n defaultValue: DEFAULT_LIMIT,\n min: MIN_LIMIT,\n max: MAX_LIMIT,\n });\n const offset = parseOffset(options.offset);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", String(limit));\n searchParams.append(\"offset\", String(offset));\n\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/queues\",\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseQueuesResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const response = parsed.data;\n\n if (response.queues.length === 0) {\n console.log(\"No queues found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, response.queues));\n const resolvedOffset = response.offset ?? offset;\n const total = response.total ?? null;\n const summary =\n total === null\n ? `Showing ${response.queues.length} \u00B7 offset ${resolvedOffset}`\n : `Showing ${response.queues.length} of ${total} \u00B7 offset ${resolvedOffset}`;\n console.log(summary);\n });\n}\n", "import { caseUpdateQueueResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype UpdateOptions = {\n name?: string;\n description?: string;\n clearDescription?: boolean;\n folderId?: string;\n clearFolder?: boolean;\n json?: boolean;\n};\n\ntype RequestBody = {\n name?: string;\n description?: string | null;\n folder_id?: string | null;\n};\n\nexport function registerQueuesUpdate(queues: Command): void {\n queues\n .command(\"update <id>\")\n .description(\"Update a case queue\")\n .option(\"--name <name>\", \"new queue name\")\n .option(\"--description <text>\", \"new description\")\n .option(\"--clear-description\", \"clear the existing description\")\n .option(\"--folder-id <id>\", \"move queue under a folder\")\n .option(\"--clear-folder\", \"move queue out of any folder (root)\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function updateAction(\n this: Command,\n id: string,\n options: UpdateOptions\n ) {\n if (\n options.description !== undefined &&\n Boolean(options.clearDescription)\n ) {\n throw new CliError(\n \"Pass either --description or --clear-description, not both.\"\n );\n }\n\n if (options.folderId !== undefined && Boolean(options.clearFolder)) {\n throw new CliError(\n \"Pass either --folder-id or --clear-folder, not both.\"\n );\n }\n\n const body: RequestBody = {};\n if (options.name !== undefined) {\n const trimmed = options.name.trim();\n if (trimmed.length === 0) {\n throw new CliError(\"--name must not be empty\");\n }\n\n body.name = trimmed;\n }\n\n if (options.description !== undefined) {\n const trimmedDescription = options.description.trim();\n if (trimmedDescription.length === 0) {\n throw new CliError(\n \"--description must not be empty; use --clear-description to remove it.\"\n );\n }\n\n body.description = trimmedDescription;\n } else if (options.clearDescription) {\n body.description = null;\n }\n\n if (options.folderId !== undefined) {\n const trimmedFolderId = options.folderId.trim();\n if (trimmedFolderId.length === 0) {\n throw new CliError(\"--folder-id must not be empty\");\n }\n\n body.folder_id = trimmedFolderId;\n } else if (options.clearFolder) {\n body.folder_id = null;\n }\n\n if (Object.keys(body).length === 0) {\n throw new CliError(\n \"Provide at least one field to update (--name, --description, --clear-description, --folder-id, --clear-folder).\"\n );\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"PATCH\",\n path: `/v1/queues/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseUpdateQueueResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { queue } = parsed.data;\n\n console.log(green(\"Queue updated!\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"ID\", value: queue.id },\n { label: \"Name\", value: queue.name },\n { label: \"Description\", value: queue.description ?? \"\" },\n { label: \"Folder\", value: queue.folder_id ?? \"\" },\n { label: \"Created\", value: queue.created_at ?? \"\" },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerQueuesAgents } from \"./agents.js\";\nimport { registerQueuesCreate } from \"./create.js\";\nimport { registerQueuesDelete } from \"./delete.js\";\nimport { registerQueuesGet } from \"./get.js\";\nimport { registerQueuesList } from \"./list.js\";\nimport { registerQueuesUpdate } from \"./update.js\";\n\nexport function registerQueues(program: Command): void {\n const queues = program\n .command(\"queues\")\n .description(\"Manage case queues in the Duvo public API\");\n\n registerQueuesList(queues);\n registerQueuesGet(queues);\n registerQueuesCreate(queues);\n registerQueuesUpdate(queues);\n registerQueuesDelete(queues);\n registerQueuesAgents(queues);\n}\n", "import { type JobListItem, jobListResponseSchema } from \"@taskcrew/shared\";\nimport { z } from \"zod\";\n\nexport { jobListResponseSchema as listRunsResponseSchema };\nexport type { JobListItem };\nexport type ListRunsResponse = z.infer<typeof jobListResponseSchema>;\n\nconst publicRunSchema = z.object({\n id: z.string(),\n agent_id: z.string(),\n build_id: z.string(),\n status: z.string(),\n source: z.string().nullish(),\n sandbox_id: z.string().nullish(),\n started_at: z.string().nullish(),\n completed_at: z.string().nullish(),\n created_at: z.string(),\n updated_at: z.string().nullish(),\n human_in_the_loop_enabled: z.boolean().nullish(),\n});\n\nexport type PublicRun = z.infer<typeof publicRunSchema>;\n\nexport const startRunResponseSchema = z.object({\n run: publicRunSchema,\n});\n\nexport type StartRunResponse = z.infer<typeof startRunResponseSchema>;\n\nconst questionOptionSchema = z.object({\n label: z.string(),\n description: z.string().nullish(),\n});\n\nconst questionSchema = z.object({\n question: z.string(),\n header: z.string().nullish(),\n options: z.array(questionOptionSchema).nullish(),\n multi_select: z.boolean().nullish(),\n});\n\nconst pendingHumanRequestSchema = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string().nullish(),\n created_at: z.string(),\n type: z.string(),\n questions: z.array(questionSchema).nullish(),\n});\n\nexport type PendingHumanRequest = z.infer<typeof pendingHumanRequestSchema>;\n\nexport const getRunResponseSchema = z.object({\n run: publicRunSchema.nullable(),\n pending_human_request: pendingHumanRequestSchema.nullish(),\n});\n\nexport type GetRunResponse = z.infer<typeof getRunResponseSchema>;\n\nexport const stopRunResponseSchema = z.object({\n success: z.boolean(),\n message: z.string().nullish(),\n});\n\nexport type StopRunResponse = z.infer<typeof stopRunResponseSchema>;\n\nconst runMessageSchema = z.object({\n id: z.string(),\n type: z.string(),\n role: z.string(),\n timestamp: z.string(),\n text_content: z.string().nullish(),\n tool_call: z\n .object({\n id: z.string(),\n name: z.string(),\n arguments: z.record(z.string(), z.unknown()).nullish(),\n })\n .nullish(),\n tool_result: z\n .object({\n tool_call_id: z.string(),\n result: z.unknown().nullish(),\n error: z.string().nullish(),\n })\n .nullish(),\n});\n\nexport type RunMessage = z.infer<typeof runMessageSchema>;\n\nexport const listRunMessagesResponseSchema = z.object({\n messages: z.array(runMessageSchema),\n total: z.number().nullish(),\n limit: z.number().nullish(),\n offset: z.number().nullish(),\n});\n\nexport type ListRunMessagesResponse = z.infer<\n typeof listRunMessagesResponseSchema\n>;\n\nconst postedMessageSchema = z.object({\n id: z.string(),\n type: z.string(),\n role: z.string(),\n timestamp: z.string(),\n text_content: z.string(),\n});\n\nexport const postRunMessageResponseSchema = z.object({\n message: postedMessageSchema,\n});\n\nexport type PostRunMessageResponse = z.infer<\n typeof postRunMessageResponseSchema\n>;\n\nexport const respondHumanRequestResponseSchema = z.object({\n human_request: z.object({\n id: z.string(),\n run_id: z.string(),\n title: z.string(),\n description: z.string().nullish(),\n response: z.string().nullish(),\n responded_at: z.string().nullish(),\n created_at: z.string(),\n }),\n});\n\nexport type RespondHumanRequestResponse = z.infer<\n typeof respondHumanRequestResponseSchema\n>;\n", "import { type Command } from \"commander\";\n\nimport { getRunResponseSchema } from \"@/api/run-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype GetOptions = {\n json?: boolean;\n};\n\nexport function registerRunsGet(runs: Command): void {\n runs\n .command(\"get <id>\")\n .description(\"Get an agent run by ID\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function getAction(\n this: Command,\n id: string,\n options: GetOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/runs/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = getRunResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { run, pending_human_request: pendingHumanRequest } = parsed.data;\n\n if (!run) {\n throw new CliError(`Run \"${id}\" not found.`);\n }\n\n console.log(\n renderKeyValue([\n { label: \"ID\", value: run.id },\n { label: \"Agent\", value: run.agent_id },\n { label: \"Build\", value: run.build_id },\n { label: \"Status\", value: run.status },\n { label: \"Source\", value: run.source ?? \"\" },\n { label: \"Sandbox\", value: run.sandbox_id ?? \"\" },\n { label: \"Started\", value: run.started_at ?? \"\" },\n { label: \"Completed\", value: run.completed_at ?? \"\" },\n { label: \"Created\", value: run.created_at },\n { label: \"Updated\", value: run.updated_at ?? \"\" },\n ])\n );\n\n if (pendingHumanRequest) {\n console.log(\"\");\n console.log(\"Pending human request:\");\n console.log(\n renderKeyValue([\n { label: \"ID\", value: pendingHumanRequest.id },\n { label: \"Type\", value: pendingHumanRequest.type },\n { label: \"Title\", value: pendingHumanRequest.title },\n {\n label: \"Description\",\n value: pendingHumanRequest.description ?? \"\",\n },\n { label: \"Created\", value: pendingHumanRequest.created_at },\n ])\n );\n }\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { type JobListItem, listRunsResponseSchema } from \"@/api/run-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { parseLimit, parseOffset } from \"../shared/pagination.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n limit?: string;\n offset?: string;\n sortOrder?: string;\n status?: string;\n agent?: string;\n user?: string;\n caseQueue?: string;\n source?: string;\n search?: string;\n hasIssues?: string;\n json?: boolean;\n};\n\nconst DEFAULT_LIMIT = 20;\nconst MIN_LIMIT = 1;\nconst MAX_LIMIT = 100;\n\nconst SORT_ORDERS = [\"asc\", \"desc\"] as const;\ntype SortOrder = (typeof SORT_ORDERS)[number];\n\nconst HAS_ISSUES_VALUES = [\"true\", \"false\"] as const;\ntype HasIssuesValue = (typeof HAS_ISSUES_VALUES)[number];\n\nconst TITLE_PREVIEW_WIDTH = 50;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: JobListItem) => row.id },\n { header: \"RUN#\", cell: (row: JobListItem) => String(row.run_number) },\n { header: \"STATUS\", cell: (row: JobListItem) => row.status },\n { header: \"AGENT\", cell: (row: JobListItem) => row.agent_name },\n {\n header: \"TITLE\",\n cell: (row: JobListItem) => row.title,\n maxWidth: TITLE_PREVIEW_WIDTH,\n },\n {\n header: \"CREATED\",\n cell: (row: JobListItem) => row.created_at.toISOString(),\n },\n] as const;\n\nfunction isSortOrder(value: string): value is SortOrder {\n return (SORT_ORDERS as readonly string[]).includes(value);\n}\n\nfunction isHasIssuesValue(value: string): value is HasIssuesValue {\n return (HAS_ISSUES_VALUES as readonly string[]).includes(value);\n}\n\nexport function registerRunsList(runs: Command): void {\n runs\n .command(\"list\")\n .description(\"List agent runs for your team\")\n .option(\"--limit <n>\", `page size (${MIN_LIMIT}-${MAX_LIMIT})`)\n .option(\"--offset <n>\", \"number of runs to skip\")\n .option(\"--sort-order <order>\", `sort direction (${SORT_ORDERS.join(\"|\")})`)\n .option(\n \"--status <status>\",\n \"filter by status (e.g. running, completed, failed, waiting, interrupted, stopped, needs_attention)\"\n )\n .option(\"--agent <id>\", \"filter by agent ID\")\n .option(\"--user <id>\", \"filter by user ID\")\n .option(\"--case-queue <id>\", \"filter by case queue ID\")\n .option(\"--source <source>\", \"filter by source\")\n .option(\"--search <query>\", \"free-text search across runs\")\n .option(\n \"--has-issues <true|false>\",\n `show only runs with (or without) issues (${HAS_ISSUES_VALUES.join(\"|\")})`\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const limit = parseLimit(options.limit, {\n defaultValue: DEFAULT_LIMIT,\n min: MIN_LIMIT,\n max: MAX_LIMIT,\n });\n const offset = parseOffset(options.offset);\n\n if (options.sortOrder !== undefined && !isSortOrder(options.sortOrder)) {\n throw new CliError(\n `--sort-order must be one of: ${SORT_ORDERS.join(\", \")}`\n );\n }\n\n if (\n options.hasIssues !== undefined &&\n !isHasIssuesValue(options.hasIssues)\n ) {\n throw new CliError(\n `--has-issues must be one of: ${HAS_ISSUES_VALUES.join(\", \")}`\n );\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", String(limit));\n searchParams.append(\"offset\", String(offset));\n\n if (options.sortOrder !== undefined) {\n searchParams.append(\"sort_order\", options.sortOrder);\n }\n\n if (options.status !== undefined) {\n searchParams.append(\"status\", options.status);\n }\n\n if (options.agent !== undefined) {\n searchParams.append(\"agent_id\", options.agent);\n }\n\n if (options.user !== undefined) {\n searchParams.append(\"user_id\", options.user);\n }\n\n if (options.caseQueue !== undefined) {\n searchParams.append(\"case_queue_id\", options.caseQueue);\n }\n\n if (options.source !== undefined) {\n searchParams.append(\"source\", options.source);\n }\n\n if (options.search !== undefined) {\n searchParams.append(\"search\", options.search);\n }\n\n if (options.hasIssues !== undefined) {\n searchParams.append(\"has_issues\", options.hasIssues);\n }\n\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/runs\",\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listRunsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const response = parsed.data;\n\n if (response.data.length === 0) {\n console.log(\"No runs found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, response.data));\n console.log(\n `Showing ${response.data.length} of ${response.total} \u00B7 offset ${offset}`\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport {\n listRunMessagesResponseSchema,\n type RunMessage,\n} from \"@/api/run-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { parseLimit, parseOffset } from \"../shared/pagination.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype MessagesOptions = {\n limit?: string;\n offset?: string;\n json?: boolean;\n};\n\nconst DEFAULT_LIMIT = 20;\nconst MIN_LIMIT = 1;\nconst MAX_LIMIT = 50;\n\nconst TEXT_PREVIEW_WIDTH = 60;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: RunMessage) => row.id },\n { header: \"ROLE\", cell: (row: RunMessage) => row.role },\n { header: \"TYPE\", cell: (row: RunMessage) => row.type },\n { header: \"TIMESTAMP\", cell: (row: RunMessage) => row.timestamp },\n {\n header: \"PREVIEW\",\n cell: previewCell,\n maxWidth: TEXT_PREVIEW_WIDTH,\n },\n] as const;\n\nfunction previewCell(row: RunMessage): string {\n if (row.text_content) {\n return row.text_content.replace(/\\s+/g, \" \").trim();\n }\n\n if (row.tool_call) {\n return `tool_call ${row.tool_call.name}`;\n }\n\n if (row.tool_result) {\n return `tool_result ${row.tool_result.tool_call_id}`;\n }\n\n return \"\";\n}\n\nexport function registerRunsMessages(runs: Command): void {\n runs\n .command(\"messages <id>\")\n .description(\"List messages for an agent run\")\n .option(\"--limit <n>\", `page size (${MIN_LIMIT}-${MAX_LIMIT})`)\n .option(\"--offset <n>\", \"number of messages to skip\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function messagesAction(\n this: Command,\n id: string,\n options: MessagesOptions\n ) {\n const limit = parseLimit(options.limit, {\n defaultValue: DEFAULT_LIMIT,\n min: MIN_LIMIT,\n max: MAX_LIMIT,\n });\n const offset = parseOffset(options.offset);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", String(limit));\n searchParams.append(\"offset\", String(offset));\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/runs/${encodeURIComponent(id)}/messages`,\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listRunMessagesResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const response = parsed.data;\n\n if (response.messages.length === 0) {\n console.log(\"No messages found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, response.messages));\n const resolvedOffset = response.offset ?? offset;\n const summary =\n response.total === null || response.total === undefined\n ? `Showing ${response.messages.length} \u00B7 offset ${resolvedOffset}`\n : `Showing ${response.messages.length} of ${response.total} \u00B7 offset ${resolvedOffset}`;\n console.log(summary);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport {\n getRunResponseSchema,\n respondHumanRequestResponseSchema,\n} from \"@/api/run-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype RespondOptions = {\n approve?: boolean;\n deny?: boolean;\n answer?: readonly string[];\n json?: boolean;\n};\n\ntype RequestBody = {\n approved?: boolean;\n answers?: Record<string, string>;\n};\n\nfunction collectAnswer(\n value: string,\n previous: readonly string[] = []\n): readonly string[] {\n return [...previous, value];\n}\n\nfunction parseAnswers(raw: readonly string[]): Record<string, string> {\n const answers: Record<string, string> = Object.create(null) as Record<\n string,\n string\n >;\n for (const entry of raw) {\n const eq = entry.indexOf(\"=\");\n if (eq === -1 || eq === 0) {\n throw new CliError(\n `Invalid --answer \"${entry}\". Expected \"question=answer\".`\n );\n }\n\n const question = entry.slice(0, eq);\n const answer = entry.slice(eq + 1);\n if (Object.prototype.hasOwnProperty.call(answers, question)) {\n throw new CliError(\n `Duplicate --answer for question \"${question}\". Each question may be answered once.`\n );\n }\n\n answers[question] = answer;\n }\n\n return answers;\n}\n\nfunction buildBody(options: RespondOptions): RequestBody {\n const approveSet = options.approve === true;\n const denySet = options.deny === true;\n const answers = options.answer ?? [];\n\n if (approveSet && denySet) {\n throw new CliError(\"Pass either --approve or --deny, not both.\");\n }\n\n if ((approveSet || denySet) && answers.length > 0) {\n throw new CliError(\n \"Pass either --approve/--deny (for approval-type requests) or --answer (for question-type requests), not both.\"\n );\n }\n\n if (approveSet) {\n return { approved: true };\n }\n\n if (denySet) {\n return { approved: false };\n }\n\n if (answers.length > 0) {\n return { answers: parseAnswers(answers) };\n }\n\n throw new CliError(\n \"Provide --approve, --deny, or at least one --answer question=answer.\"\n );\n}\n\nasync function resolvePendingRequestId(\n runId: string,\n apiKey: string,\n apiBaseUrl: string\n): Promise<string> {\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/runs/${encodeURIComponent(runId)}`,\n apiKey,\n apiBaseUrl,\n });\n const parsed = getRunResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const pending = parsed.data.pending_human_request;\n if (!pending) {\n throw new CliError(\n `Run ${runId} has no pending human request. Pass the request ID explicitly.`\n );\n }\n\n return pending.id;\n}\n\nexport function registerRunsRespond(runs: Command): void {\n runs\n .command(\"respond <run-id> [request-id]\")\n .description(\n \"Respond to a human-in-the-loop request on a run (defaults to the run's pending request)\"\n )\n .option(\"--approve\", \"approve an approval-type request\")\n .option(\"--deny\", \"deny an approval-type request\")\n .option(\n \"--answer <question=answer>\",\n \"answer a question-type request (repeatable)\",\n collectAnswer,\n [] as readonly string[]\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function respondAction(\n this: Command,\n runId: string,\n requestIdArg: string | undefined,\n options: RespondOptions\n ) {\n const body = buildBody(options);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const requestId =\n requestIdArg ??\n (await resolvePendingRequestId(runId, apiKey, apiBaseUrl));\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/runs/${encodeURIComponent(runId)}/human-requests/${encodeURIComponent(requestId)}/respond`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = respondHumanRequestResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { human_request: humanRequest } = parsed.data;\n\n console.log(green(\"Response sent!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: humanRequest.id },\n { label: \"Run\", value: humanRequest.run_id },\n { label: \"Title\", value: humanRequest.title },\n { label: \"Description\", value: humanRequest.description ?? \"\" },\n { label: \"Response\", value: humanRequest.response ?? \"\" },\n { label: \"Responded\", value: humanRequest.responded_at ?? \"\" },\n { label: \"Created\", value: humanRequest.created_at },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { postRunMessageResponseSchema } from \"@/api/run-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype SendMessageOptions = {\n message: string;\n json?: boolean;\n};\n\nexport function registerRunsSendMessage(runs: Command): void {\n runs\n .command(\"send-message <id>\")\n .description(\"Post a message to an agent run\")\n .requiredOption(\"--message <text>\", \"the message content to send\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function sendMessageAction(\n this: Command,\n id: string,\n options: SendMessageOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/runs/${encodeURIComponent(id)}/messages`,\n apiKey,\n apiBaseUrl,\n body: { message: options.message },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = postRunMessageResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { message } = parsed.data;\n\n console.log(green(\"Message sent!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: message.id },\n { label: \"Role\", value: message.role },\n { label: \"Type\", value: message.type },\n { label: \"Timestamp\", value: message.timestamp },\n { label: \"Content\", value: message.text_content },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { startRunResponseSchema } from \"@/api/run-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype StartOptions = {\n agent: string;\n message?: string;\n sandboxId?: string;\n webhookUrl?: string;\n json?: boolean;\n};\n\ntype RequestBody = {\n agent_id: string;\n message?: string;\n sandbox_id?: string;\n webhook_url?: string;\n};\n\nexport function registerRunsStart(runs: Command): void {\n runs\n .command(\"start\")\n .description(\"Start a new agent run\")\n .requiredOption(\"--agent <id>\", \"ID of the agent to run\")\n .option(\n \"--message <text>\",\n \"optional initial message to start the run with\"\n )\n .option(\"--sandbox-id <id>\", \"optional sandbox ID with pre-uploaded files\")\n .option(\"--webhook-url <url>\", \"optional webhook URL to POST run events to\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function startAction(this: Command, options: StartOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const body: RequestBody = {\n agent_id: options.agent,\n ...(options.message !== undefined ? { message: options.message } : {}),\n ...(options.sandboxId !== undefined\n ? { sandbox_id: options.sandboxId }\n : {}),\n ...(options.webhookUrl !== undefined\n ? { webhook_url: options.webhookUrl }\n : {}),\n };\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/runs\",\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = startRunResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { run } = parsed.data;\n\n console.log(green(\"Run started!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: run.id },\n { label: \"Agent\", value: run.agent_id },\n { label: \"Build\", value: run.build_id },\n { label: \"Status\", value: run.status },\n { label: \"Created\", value: run.created_at },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { stopRunResponseSchema } from \"@/api/run-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype StopOptions = {\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerRunsStop(runs: Command): void {\n runs\n .command(\"stop <id>\")\n .description(\"Stop a running agent run\")\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function stopAction(\n this: Command,\n id: string,\n options: StopOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Stop run \"${id}\"?`,\n skip: options.yes ?? false,\n });\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/runs/${encodeURIComponent(id)}/stop`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = stopRunResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { success, message } = parsed.data;\n if (!success) {\n throw new CliError(message ?? `Failed to stop run \"${id}\".`);\n }\n\n const label = message ?? `Run \"${id}\" stopped.`;\n console.log(green(label));\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerRunsGet } from \"./get.js\";\nimport { registerRunsList } from \"./list.js\";\nimport { registerRunsMessages } from \"./messages.js\";\nimport { registerRunsRespond } from \"./respond.js\";\nimport { registerRunsSendMessage } from \"./send-message.js\";\nimport { registerRunsStart } from \"./start.js\";\nimport { registerRunsStop } from \"./stop.js\";\n\nexport function registerRuns(program: Command): void {\n const runs = program\n .command(\"runs\")\n .description(\"Manage agent runs in the Duvo public API\");\n\n registerRunsStart(runs);\n registerRunsList(runs);\n registerRunsGet(runs);\n registerRunsMessages(runs);\n registerRunsSendMessage(runs);\n registerRunsRespond(runs);\n registerRunsStop(runs);\n}\n", "import { z } from \"zod\";\n\nexport const createSandboxResponseSchema = z.object({\n sandbox_id: z.string(),\n expires_at: z.string(),\n});\n\nexport type CreateSandboxResponse = z.infer<typeof createSandboxResponseSchema>;\n\nexport const createSandboxUploadUrlResponseSchema = z.object({\n upload_url: z.string(),\n path: z.string(),\n expires_in_seconds: z.number(),\n});\n\nexport type CreateSandboxUploadUrlResponse = z.infer<\n typeof createSandboxUploadUrlResponseSchema\n>;\n\nconst sandboxFileSchema = z.object({\n name: z.string(),\n path: z.string(),\n type: z.enum([\"file\", \"dir\"]),\n size_bytes: z.number(),\n});\n\nexport type SandboxFile = z.infer<typeof sandboxFileSchema>;\n\nexport const listSandboxFilesResponseSchema = z.object({\n files: z.array(sandboxFileSchema),\n});\n\nexport type ListSandboxFilesResponse = z.infer<\n typeof listSandboxFilesResponseSchema\n>;\n\nexport const uploadSandboxFileResponseSchema = z.object({\n path: z.string(),\n size_bytes: z.number(),\n});\n\nexport type UploadSandboxFileResponse = z.infer<\n typeof uploadSandboxFileResponseSchema\n>;\n\nexport const DEFAULT_SANDBOX_FILES_PATH = \"/workspace\";\n", "import { type Command } from \"commander\";\n\nimport { createSandboxResponseSchema } from \"@/api/sandbox-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype CreateOptions = {\n json?: boolean;\n};\n\nexport function registerSandboxesCreate(sandboxes: Command): void {\n sandboxes\n .command(\"create\")\n .description(\"Create a new sandbox for staging files before a run\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function createAction(this: Command, options: CreateOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/sandboxes\",\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = createSandboxResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { sandbox_id: sandboxId, expires_at: expiresAt } = parsed.data;\n\n console.log(green(\"Sandbox created!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: sandboxId },\n { label: \"Expires\", value: expiresAt },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport {\n DEFAULT_SANDBOX_FILES_PATH,\n listSandboxFilesResponseSchema,\n type SandboxFile,\n} from \"@/api/sandbox-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype FilesOptions = {\n path?: string;\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"TYPE\", cell: (row: SandboxFile) => row.type },\n { header: \"NAME\", cell: (row: SandboxFile) => row.name },\n { header: \"PATH\", cell: (row: SandboxFile) => row.path },\n { header: \"SIZE\", cell: (row: SandboxFile) => String(row.size_bytes) },\n] as const;\n\nexport function registerSandboxesFiles(sandboxes: Command): void {\n sandboxes\n .command(\"files <sandbox_id>\")\n .description(\"List files in a sandbox directory\")\n .option(\n \"--path <path>\",\n `directory to list (defaults to ${DEFAULT_SANDBOX_FILES_PATH})`\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function filesAction(\n this: Command,\n sandboxId: string,\n options: FilesOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n if (options.path !== undefined) {\n searchParams.append(\"path\", options.path);\n }\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/sandboxes/${encodeURIComponent(sandboxId)}/files`,\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listSandboxFilesResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { files } = parsed.data;\n\n if (files.length === 0) {\n console.log(\"No files found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, files));\n console.log(`Showing ${files.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { createSandboxUploadUrlResponseSchema } from \"@/api/sandbox-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype PrepareUploadUrlOptions = {\n path: string;\n json?: boolean;\n};\n\nexport function registerSandboxesPrepareUploadUrl(sandboxes: Command): void {\n sandboxes\n .command(\"prepare-upload-url <sandbox_id>\")\n .description(\n \"Request a presigned URL for uploading a file larger than 10MB to a sandbox\"\n )\n .requiredOption(\n \"--path <path>\",\n \"destination path inside the sandbox (e.g. /workspace/data.csv)\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function prepareUploadUrlAction(\n this: Command,\n sandboxId: string,\n options: PrepareUploadUrlOptions\n ) {\n const trimmedPath = options.path.trim();\n if (trimmedPath.length === 0) {\n throw new CliError(\"--path must not be empty\");\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/sandboxes/${encodeURIComponent(sandboxId)}/upload-urls`,\n apiKey,\n apiBaseUrl,\n body: { path: trimmedPath },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = createSandboxUploadUrlResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const {\n upload_url: uploadUrl,\n path: resolvedPath,\n expires_in_seconds: expiresInSeconds,\n } = parsed.data;\n\n console.log(\n renderKeyValue([\n { label: \"URL\", value: uploadUrl },\n { label: \"Path\", value: resolvedPath },\n { label: \"Expires in\", value: `${expiresInSeconds}s` },\n ])\n );\n });\n}\n", "import { readFile, stat } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\n\nimport { type Command } from \"commander\";\n\nimport { uploadSandboxFileResponseSchema } from \"@/api/sandbox-schemas.js\";\nimport { httpUpload } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype UploadOptions = {\n path?: string;\n json?: boolean;\n};\n\nconst MAX_DIRECT_UPLOAD_BYTES = 10 * 1024 * 1024;\n\nexport function registerSandboxesUpload(sandboxes: Command): void {\n sandboxes\n .command(\"upload <sandbox_id> <file>\")\n .description(\n \"Upload a local file directly to a sandbox (max 10MB; use prepare-upload-url for larger files)\"\n )\n .option(\n \"--path <path>\",\n \"destination path inside the sandbox (defaults to /workspace/<filename>)\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function uploadAction(\n this: Command,\n sandboxId: string,\n file: string,\n options: UploadOptions\n ) {\n const trimmedPath = options.path?.trim();\n if (trimmedPath === \"\") {\n throw new CliError(\"--path must not be empty\");\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const stats = await stat(file).catch((error) => {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Could not read file \"${file}\": ${message}`);\n });\n if (!stats.isFile()) {\n throw new CliError(`Could not read file \"${file}\": not a regular file`);\n }\n\n if (stats.size > MAX_DIRECT_UPLOAD_BYTES) {\n throw new CliError(\n `File \"${file}\" is ${stats.size} bytes, larger than the ${MAX_DIRECT_UPLOAD_BYTES}-byte direct-upload limit. Use \\`duvo sandboxes prepare-upload-url\\` for larger files.`\n );\n }\n\n const content = await readFile(file).catch((error) => {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Could not read file \"${file}\": ${message}`);\n });\n const filename = basename(file);\n const formData = new FormData();\n formData.append(\"file\", new Blob([new Uint8Array(content)]), filename);\n if (trimmedPath !== undefined) {\n formData.append(\"path\", trimmedPath);\n }\n\n const raw = await httpUpload({\n path: `/v1/sandboxes/${encodeURIComponent(sandboxId)}/files`,\n apiKey,\n apiBaseUrl,\n formData,\n }).catch((error) => {\n if (error instanceof CliError && /\\b413\\b/.test(error.message)) {\n throw new CliError(\n \"Sandbox rejected the upload because the file is too large. Use `duvo sandboxes prepare-upload-url` for larger files.\"\n );\n }\n\n throw error;\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = uploadSandboxFileResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { path: resolvedPath, size_bytes: sizeBytes } = parsed.data;\n\n console.log(green(\"File uploaded!\"));\n console.log(\n renderKeyValue([\n { label: \"Path\", value: resolvedPath },\n { label: \"Size\", value: `${sizeBytes} bytes` },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerSandboxesCreate } from \"./create.js\";\nimport { registerSandboxesFiles } from \"./files.js\";\nimport { registerSandboxesPrepareUploadUrl } from \"./prepare-upload-url.js\";\nimport { registerSandboxesUpload } from \"./upload.js\";\n\nexport function registerSandboxes(program: Command): void {\n const sandboxes = program\n .command(\"sandboxes\")\n .description(\"Manage sandboxes in the Duvo public API\");\n\n registerSandboxesCreate(sandboxes);\n registerSandboxesFiles(sandboxes);\n registerSandboxesUpload(sandboxes);\n registerSandboxesPrepareUploadUrl(sandboxes);\n}\n", "import { deleteSkillResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype DeleteOptions = {\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerSkillsDelete(skills: Command): void {\n skills\n .command(\"delete <skill-id>\")\n .description(\"Delete a custom skill from the current team\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function deleteAction(\n this: Command,\n skillId: string,\n options: DeleteOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Delete skill \"${skillId}\"?`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/skills/${encodeURIComponent(skillId)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = deleteSkillResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n throw new CliError(`Failed to delete skill: ${parsed.data.message}`);\n }\n\n console.log(green(\"Skill deleted!\"));\n if (parsed.data.message) {\n console.log(parsed.data.message);\n }\n });\n}\n", "import { writeFileSync } from \"node:fs\";\n\nimport { type Command } from \"commander\";\n\nimport { CliError, EXIT_CODE } from \"@/errors.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype DownloadOptions = {\n output?: string;\n};\n\nexport function registerSkillsDownload(skills: Command): void {\n skills\n .command(\"download <skill-id>\")\n .description(\"Download a custom skill as a ZIP archive\")\n .option(\n \"-o, --output <path>\",\n 'path to write the zip to (default \"<skill-id>.zip\"; use \"-\" for stdout)'\n )\n .action(async function downloadAction(\n this: Command,\n skillId: string,\n options: DownloadOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n // The download endpoint returns binary, so bypass the JSON helper and\n // call fetch directly.\n const url = new URL(\n `/v1/skills/${encodeURIComponent(skillId)}/download`,\n apiBaseUrl.endsWith(\"/\") ? apiBaseUrl : `${apiBaseUrl}/`\n );\n\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"application/zip\",\n },\n });\n\n if (response.status === 401) {\n throw new CliError(\n \"Unauthorized. Check that the API key is valid.\",\n EXIT_CODE.AUTH\n );\n }\n\n if (response.status === 404) {\n throw new CliError(\n `Not found: GET /v1/skills/${skillId}/download`,\n EXIT_CODE.NOT_FOUND\n );\n }\n\n if (!response.ok) {\n const detail = await response.text().catch(() => \"\");\n const suffix = detail.length > 0 ? `: ${detail}` : \"\";\n throw new CliError(\n `Request failed (${response.status} ${response.statusText})${suffix}`\n );\n }\n\n const buffer = Buffer.from(await response.arrayBuffer());\n const target = options.output ?? `${skillId}.zip`;\n\n if (target === \"-\") {\n process.stdout.write(buffer);\n return;\n }\n\n writeFileSync(target, buffer);\n console.log(`Wrote ${buffer.length} bytes to ${target}`);\n });\n}\n", "import { getSkillFileContentResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype FileGetOptions = {\n json?: boolean;\n};\n\nexport function registerSkillsFileGet(skills: Command): void {\n skills\n .command(\"file-get <skill-id> <path>\")\n .description(\n \"Get the content of a file in a skill (path is the relative file path inside the skill, e.g. SKILL.md)\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function fileGetAction(\n this: Command,\n skillId: string,\n filePath: string,\n options: FileGetOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n // Encode each path segment but leave slashes so the wildcard route\n // matches multi-segment paths like `references/foo.md`.\n const encodedPath = filePath\n .split(\"/\")\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/skills/${encodeURIComponent(skillId)}/files/${encodedPath}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = getSkillFileContentResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n // Stream the file content straight to stdout so it's pipeable.\n process.stdout.write(parsed.data.content);\n });\n}\n", "import { readFileSync } from \"node:fs\";\n\nimport { updateSkillFileResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/green.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype FileUpdateOptions = {\n content?: string;\n contentFile?: string;\n json?: boolean;\n};\n\nexport function registerSkillsFileUpdate(skills: Command): void {\n skills\n .command(\"file-update <skill-id> <path>\")\n .description(\n \"Update the content of a file in a skill (path is the relative file path inside the skill)\"\n )\n .option(\"--content <text>\", \"new file content as a string\")\n .option(\n \"--content-file <path>\",\n 'path to a file to read content from, or \"-\" for stdin'\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function fileUpdateAction(\n this: Command,\n skillId: string,\n filePath: string,\n options: FileUpdateOptions\n ) {\n if (options.content !== undefined && options.contentFile !== undefined) {\n throw new CliError(\n \"Pass either --content or --content-file, not both.\"\n );\n }\n\n const content = readContent(options);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const encodedPath = filePath\n .split(\"/\")\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n\n const raw = await httpRequest({\n method: \"PUT\",\n path: `/v1/skills/${encodeURIComponent(skillId)}/files/${encodedPath}`,\n apiKey,\n apiBaseUrl,\n body: { content },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = updateSkillFileResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n throw new CliError(`Failed to update file: ${parsed.data.message}`);\n }\n\n console.log(green(\"File updated!\"));\n if (parsed.data.message) {\n console.log(parsed.data.message);\n }\n });\n}\n\nfunction readContent(options: FileUpdateOptions): string {\n if (options.content !== undefined) {\n return options.content;\n }\n\n if (options.contentFile === undefined) {\n throw new CliError(\"Pass either --content or --content-file\");\n }\n\n if (options.contentFile === \"-\") {\n return readFileSync(0, \"utf8\");\n }\n\n try {\n return readFileSync(options.contentFile, \"utf8\");\n } catch (error) {\n throw new CliError(\n `Cannot read --content-file ${options.contentFile}: ${(error as Error).message}`\n );\n }\n}\n", "import {\n listSkillFilesResponseSchema,\n type SkillFileItem,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype FilesOptions = {\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"PATH\", cell: (row: SkillFileItem) => row.path },\n { header: \"NAME\", cell: (row: SkillFileItem) => row.name },\n {\n header: \"SIZE\",\n cell: (row: SkillFileItem) =>\n row.size === undefined ? \"\" : String(row.size),\n },\n {\n header: \"CONTENT TYPE\",\n cell: (row: SkillFileItem) => row.contentType ?? \"\",\n },\n {\n header: \"UPDATED\",\n cell: (row: SkillFileItem) => row.updatedAt ?? \"\",\n },\n] as const;\n\nexport function registerSkillsFiles(skills: Command): void {\n skills\n .command(\"files <skill-id>\")\n .description(\"List files in a skill\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function filesAction(\n this: Command,\n skillId: string,\n options: FilesOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/skills/${encodeURIComponent(skillId)}/files`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listSkillFilesResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.files.length === 0) {\n console.log(\"No files found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, parsed.data.files));\n console.log(`Showing ${parsed.data.files.length}`);\n });\n}\n", "import { readFileSync } from \"node:fs\";\n\nimport { generateSkillResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype GenerateOptions = {\n prompt: string;\n existingContentFile?: string;\n json?: boolean;\n};\n\nexport function registerSkillsGenerate(skills: Command): void {\n skills\n .command(\"generate\")\n .description(\n \"Generate a SKILL.md file from a natural-language description (does not persist)\"\n )\n .requiredOption(\n \"--prompt <text>\",\n \"natural-language description of the skill (1-2000 chars)\"\n )\n .option(\n \"--existing-content-file <path>\",\n 'path to a file with existing SKILL.md content to refine, or \"-\" for stdin'\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function generateAction(\n this: Command,\n options: GenerateOptions\n ) {\n const body: Record<string, unknown> = { prompt: options.prompt };\n\n if (options.existingContentFile !== undefined) {\n body.existingContent = readExistingContent(options.existingContentFile);\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/skills/generate\",\n apiKey,\n apiBaseUrl,\n body,\n timeoutMs: 120_000,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = generateSkillResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n // Generated SKILL.md content goes straight to stdout so it's pipeable.\n process.stdout.write(parsed.data.content);\n });\n}\n\nfunction readExistingContent(source: string): string {\n const target = source === \"-\" ? 0 : source;\n const label = source === \"-\" ? \"stdin\" : `--existing-content-file ${source}`;\n try {\n return readFileSync(target, \"utf8\");\n } catch (error) {\n throw new CliError(`Cannot read ${label}: ${(error as Error).message}`);\n }\n}\n", "import {\n listSkillsResponseSchema,\n listSystemSkillsResponseSchema,\n type SkillApi,\n type SystemSkill,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n system?: boolean;\n json?: boolean;\n};\n\nconst TEAM_COLUMNS = [\n { header: \"ID\", cell: (row: SkillApi) => row.id },\n { header: \"NAME\", cell: (row: SkillApi) => row.name },\n {\n header: \"DESCRIPTION\",\n cell: (row: SkillApi) => row.description,\n maxWidth: 60,\n },\n {\n header: \"SYSTEM\",\n cell: (row: SkillApi) => (row.team_id === null ? \"yes\" : \"no\"),\n },\n] as const;\n\nconst SYSTEM_COLUMNS = [\n { header: \"ID\", cell: (row: SystemSkill) => row.id },\n { header: \"NAME\", cell: (row: SystemSkill) => row.name },\n {\n header: \"DESCRIPTION\",\n cell: (row: SystemSkill) => row.description,\n maxWidth: 60,\n },\n] as const;\n\nexport function registerSkillsList(skills: Command): void {\n skills\n .command(\"list\", { isDefault: true })\n .description(\"List skills available to your team (or system skills only)\")\n .option(\"--system\", \"list system skills only\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const path = options.system ? \"/v1/skills/system\" : \"/v1/skills\";\n const raw = await httpRequest({\n method: \"GET\",\n path,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n if (options.system) {\n const parsed = listSystemSkillsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.skills.length === 0) {\n console.log(\"No system skills found.\");\n return;\n }\n\n console.log(renderTable(SYSTEM_COLUMNS, parsed.data.skills));\n console.log(`Showing ${parsed.data.skills.length}`);\n return;\n }\n\n const parsed = listSkillsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.skills.length === 0) {\n console.log(\"No skills found.\");\n return;\n }\n\n console.log(renderTable(TEAM_COLUMNS, parsed.data.skills));\n console.log(`Showing ${parsed.data.skills.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerSkillsDelete } from \"./delete.js\";\nimport { registerSkillsDownload } from \"./download.js\";\nimport { registerSkillsFileGet } from \"./file-get.js\";\nimport { registerSkillsFileUpdate } from \"./file-update.js\";\nimport { registerSkillsFiles } from \"./files.js\";\nimport { registerSkillsGenerate } from \"./generate.js\";\nimport { registerSkillsList } from \"./list.js\";\n\nexport function registerSkills(program: Command): void {\n const skills = program\n .command(\"skills\")\n .description(\"Manage skills (custom and system)\");\n\n registerSkillsList(skills);\n registerSkillsDelete(skills);\n registerSkillsFiles(skills);\n registerSkillsFileGet(skills);\n registerSkillsFileUpdate(skills);\n registerSkillsDownload(skills);\n registerSkillsGenerate(skills);\n}\n", "import {\n listTeamMembersResponseSchema,\n publicProfileResponseSchema,\n type TeamMemberApi,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { parseLimit, parseOffset } from \"../shared/pagination.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype MembersOptions = {\n team?: string;\n limit?: string;\n offset?: string;\n json?: boolean;\n};\n\nconst DEFAULT_LIMIT = 50;\nconst MIN_LIMIT = 1;\nconst MAX_LIMIT = 100;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: TeamMemberApi) => row.id },\n { header: \"NAME\", cell: (row: TeamMemberApi) => row.name ?? \"\" },\n { header: \"EMAIL\", cell: (row: TeamMemberApi) => row.email },\n { header: \"ROLE\", cell: (row: TeamMemberApi) => row.role },\n {\n header: \"INHERITED\",\n cell: (row: TeamMemberApi) => (row.inheritedFromOrg ? \"yes\" : \"no\"),\n },\n] as const;\n\nexport function registerTeamMembers(team: Command): void {\n team\n .command(\"members\")\n .description(\"List members of a team\")\n .option(\n \"--team <id>\",\n \"team ID (defaults to the team scoped to your API key)\"\n )\n .option(\"--limit <n>\", `page size (${MIN_LIMIT}-${MAX_LIMIT})`)\n .option(\"--offset <n>\", \"number of members to skip\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function membersAction(\n this: Command,\n options: MembersOptions\n ) {\n const limit = parseLimit(options.limit, {\n defaultValue: DEFAULT_LIMIT,\n min: MIN_LIMIT,\n max: MAX_LIMIT,\n });\n const offset = parseOffset(options.offset);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const teamId =\n options.team ?? (await resolveTeamFromApiKey({ apiKey, apiBaseUrl }));\n\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", String(limit));\n searchParams.append(\"offset\", String(offset));\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/teams/${encodeURIComponent(teamId)}/members`,\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listTeamMembersResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const response = parsed.data;\n if (response.members.length === 0) {\n console.log(\"No members found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, response.members));\n console.log(\n `Showing ${response.members.length} of ${response.total} \u00B7 offset ${response.offset}`\n );\n });\n}\n\nasync function resolveTeamFromApiKey(options: {\n apiKey: string;\n apiBaseUrl: string;\n}): Promise<string> {\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/profile\",\n apiKey: options.apiKey,\n apiBaseUrl: options.apiBaseUrl,\n });\n const parsed = publicProfileResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API while resolving the team: ${parsed.error.message}`\n );\n }\n\n const teamId = parsed.data.profile.teamId;\n if (!teamId) {\n throw new CliError(\n \"Could not determine a team for this API key. Pass --team <id> explicitly.\"\n );\n }\n\n return teamId;\n}\n", "import { type Command } from \"commander\";\n\nimport { registerTeamMembers } from \"./members.js\";\n\nexport function registerTeam(program: Command): void {\n const team = program\n .command(\"team\")\n .description(\"Inspect team data exposed by the Duvo public API\");\n\n registerTeamMembers(team);\n}\n", "import { publicProfileResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { truncateApiKey } from \"@/output/format.js\";\n\nimport { requireAuthenticatedConfig } from \"./shared/require-auth.js\";\n\nexport function registerWhoami(program: Command): void {\n program\n .command(\"whoami\")\n .description(\n \"Print the active profile, the API key owner's name and email, the truncated API key, and the base URL\"\n )\n .action(async function whoamiAction(this: Command) {\n const resolved = await requireAuthenticatedConfig(this);\n\n const profileLabel =\n resolved.profileName ?? \"(env-only, no stored profile)\";\n console.log(`Profile ${profileLabel}`);\n\n const userLine = await fetchUserLine({\n apiKey: resolved.apiKey,\n apiBaseUrl: resolved.apiBaseUrl,\n });\n if (userLine !== null) {\n console.log(`User ${userLine}`);\n }\n\n console.log(`API key ${truncateApiKey(resolved.apiKey)}`);\n console.log(`Base URL ${resolved.apiBaseUrl}`);\n });\n}\n\nasync function fetchUserLine(options: {\n apiKey: string;\n apiBaseUrl: string;\n}): Promise<string | null> {\n try {\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/profile\",\n apiKey: options.apiKey,\n apiBaseUrl: options.apiBaseUrl,\n });\n const parsed = publicProfileResponseSchema.safeParse(raw);\n if (!parsed.success) {\n return null;\n }\n\n const { name, email } = parsed.data.profile;\n return name ? `${name} <${email}>` : email;\n } catch {\n return null;\n }\n}\n", "#!/usr/bin/env node\nimport { createProgram } from \"@/bin/create-program.js\";\nimport { handleCliError } from \"@/errors.js\";\n\ncreateProgram()\n .parseAsync(process.argv)\n .catch((error: unknown) => {\n handleCliError(error);\n });\n"],
5
- "mappings": ";;;;;AAAA,SAAS,gBAAAA,qBAAoB;AAC7B,SAAS,WAAAC,UAAS,QAAAC,aAAY;AAC9B,SAAS,qBAAqB;AAE9B,SAAS,eAAe;;;ACJxB,SAAS,SAAS;AAElB,IAAM,0BAA0B,EAAE,OAAO;AAAA,EACvC,IAAI,EAAE,OAAO;AAAA,EACb,MAAM,EAAE,OAAO;AAAA,EACf,SAAS,EAAE,OAAO,EAAE,QAAQ;AAAA,EAC5B,kBAAkB,EAAE,OAAO,EAAE,QAAQ;AAAA,EACrC,YAAY,EAAE,OAAO,EAAE,QAAQ;AAAA,EAC/B,YAAY,EAAE,OAAO,EAAE,QAAQ;AAAA,EAC/B,aAAa,EAAE,OAAO,EAAE,QAAQ;AAAA,EAChC,iBAAiB,EAAE,OAAO,EAAE,QAAQ;AACtC,CAAC;AAIM,IAAM,iCAAiC,EAAE,OAAO;AAAA,EACrD,SAAS,EAAE,MAAM,uBAAuB;AAC1C,CAAC;AAMM,IAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,QAAQ;AACV,CAAC;AAIM,IAAM,6BAA6B,EAAE,OAAO;AAAA,EACjD,SAAS,EAAE,QAAQ;AACrB,CAAC;AAIM,IAAM,2BAA2B,EAAE,OAAO;AAAA,EAC/C,SAAS,EAAE,QAAQ;AAAA,EACnB,aAAa,EAAE,OAAO;AACxB,CAAC;;;ACtCM,IAAM,YAAY;AAAA,EACvB,SAAS;AAAA,EACT,SAAS;AAAA,EACT,MAAM;AAAA,EACN,WAAW;AACb;AAIO,IAAM,WAAN,cAAuB,MAAM;AAAA,EATpC,OASoC;AAAA;AAAA;AAAA,EACl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;EAClB;EACA,0BAA0B;IACxB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,wBAAwB;IACtB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,qBAAqB;IACnB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,2BAA2B;IACzB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,oBAAoB;IAClB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,8BAA8B;IAC5B,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,6BAA6B;IAC3B,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,6BAA6B;IAC3B,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,6BAA6B;IAC3B,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,gBAAgB;IACd,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,uBAAuB;IACrB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,uBAAuB;IACrB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,2BAA2B;IACzB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,sBAAsB;IACpB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,0BAA0B;IACxB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,cAAc;IACZ,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,oBAAo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ACpC,SAAS,GAAG,KAAK,WAAW,4EAA4E,YAAY;QACtH,CAAC;MACH;IACF;EACF,CAAC;AACH;AAnFgB;AAAAC,QAAA,iBAAA,iBAAA;ADDhB,IAAM,mBAAmBC,IAAE,OAAO;EAChC,aAAaA,IACV,OAAO,EACP,IAAI,CAAC,EACL;IACC;EACF;EACF,SAASA,IACN,OAAO,EACP,IAAI,CAAC,EACL;IACC;EACF;AACJ,CAAC;AAED,IAAM,iBAAiBA,IAAE,OAAO;EAC9B,QAAQA,IACL,OAAO,EACP,IAAI,CAAC,EACL;IACC;EACF;EACF,OAAOA,IACJ,OAAO,EACP,SAAS,EACT;IACC;EACF;EACF,WAAWA,IACR,QAAQ,EACR;IACC;EACF;AACJ,CAAC;AAEM,IAAM,wBAAwBA,IAAE,OAAO;EAC5C,IAAIA,IACD,OAAO,EACP,IAAI,CAAC,EACL;IACC;EACF;EAEF,UAAUA,IACP,KAAK,uBAAuB,EAC5B;IACC;EACF;EACF,aAAaA,IACV,KAAK;IACJ,GAAG;IACH,GAAG;IACH,GAAG;EACL,CAAC,EACA;IACC;EACF;EAEF,aAAaA,IACV,MAAM,cAAc,EACpB;IACC;EACF;EAEF,OAAOA,IACJ,OAAO,EACP,IAAI,CAAC,EACL;IACC;EACF;EACF,aAAaA,IACV,OAAO,EACP,IAAI,CAAC,EACL;IACC;EACF;EACF,QAAQA,IACL,OAAO,EACP,IAAI,CAAC,EACL,SAAS,EACT;IACC;EACF;EACF,WAAWA,IACR,OAAO,EACP,IAAI,CAAC,EACL;IACC;EACF;EACF,MAAMA,IACH,OAAO,EACP,IAAI,CAAC,EACL,SAAS,EACT;IACC;EACF;EACF,SAASA,IACN,MAAM,gBAAgB,EACtB,IAAI,CAAC,EACL;IACC;EACF;EAEF,QAAQA,IACL,OAAO,EACP,SAAS,EACT;IACC;EACF;EACF,OAAOA,IACJ,OAAO,EACP,SAAS,EACT;IACC;EACF;EACF,QAAQA,IACL,OAAO,EACP,SAAS,EACT;IACC;EACF;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SAAS,yBAAyB;AAC7E,CAAC;ACnCM,IAAM,yBAAyB;EACpC,0BAA0B;IACxB,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,uBAAuB;IACrB,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,yBAAyB;IACvB,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,6BAA6B;IAC3B,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,wBAAwB;IACtB,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,iBAAiB;IACf,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,iBAAiB;IACf,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,2BAA2B;IACzB,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,eAAe;IACb,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,0BAA0B;IACxB,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,kBAAkB;IAChB,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,0BAA0B;IACxB,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,qBAAqB;IACnB,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,YAAY;IACV,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,wBAAwB;IACtB,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,cAAc;IACZ,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,kBAAkB;IAChB,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,eAAe;IACb,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,WAAW;IACT,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,cAAc;IACZ,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,mBAAmB;IACjB,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,oBAAoB;IAClB,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,wBAAwB;IACtB,KAAK;IACL,cAAc;IACd,aACE;EACJ;EACA,gBAAgB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C,UAAmB;AACzB,iBAAe,KAAK;AACtB,CAAC;",
6
- "names": ["readFileSync", "dirname", "join", "text", "text", "z", "z", "RESET", "text", "readFile", "confirm", "isCancel", "z", "JSONRepairError", "Error", "constructor", "message", "position", "codeSpace", "codeNewline", "codeTab", "codeReturn", "codeNonBreakingSpace", "codeEnQuad", "codeHairSpace", "codeNarrowNoBreakSpace", "codeMediumMathematicalSpace", "codeIdeographicSpace", "isHex", "char", "test", "isDigit", "isValidStringCharacter", "isDelimiter", "includes", "isFunctionNameCharStart", "isFunctionNameChar", "regexUrlStart", "regexUrlChar", "isUnquotedStringDelimiter", "isStartOfValue", "isQuote", "regexStartOfValue", "isControlCharacter", "isWhitespace", "text", "index", "code", "charCodeAt", "isWhitespaceExceptNewline", "isSpecialWhitespace", "isDoubleQuoteLike", "isSingleQuoteLike", "isDoubleQuote", "isSingleQuote", "stripLastOccurrence", "textToStrip", "stripRemainingText", "arguments", "length", "undefined", "lastIndexOf", "substring", "insertBeforeLastWhitespace", "textToInsert", "removeAtIndex", "start", "count", "endsWithCommaOrNewline", "controlCharacters", "escapeCharacters", "b", "f", "n", "r", "t", "jsonrepair", "text", "i", "output", "parseMarkdownCodeBlock", "processed", "parseValue", "throwUnexpectedEnd", "processedComma", "parseCharacter", "parseWhitespaceAndSkipComments", "isStartOfValue", "endsWithCommaOrNewline", "insertBeforeLastWhitespace", "parseNewlineDelimitedJSON", "stripLastOccurrence", "length", "throwUnexpectedCharacter", "parseObject", "parseArray", "parseString", "parseNumber", "parseKeywords", "parseUnquotedString", "parseRegex", "skipNewline", "arguments", "undefined", "start", "changed", "parseWhitespace", "parseComment", "_isWhiteSpace", "isWhitespace", "isWhitespaceExceptNewline", "whitespace", "isSpecialWhitespace", "atEndOfBlockComment", "blocks", "skipMarkdownCodeBlock", "isFunctionNameCharStart", "isFunctionNameChar", "block", "end", "slice", "char", "skipCharacter", "skipEscapeCharacter", "skipEllipsis", "initial", "processedKey", "throwObjectKeyExpected", "processedColon", "truncatedText", "throwColonExpected", "processedValue", "stopAtDelimiter", "stopAtIndex", "skipEscapeChars", "isQuote", "isEndQuote", "isDoubleQuote", "isSingleQuote", "isSingleQuoteLike", "isDoubleQuoteLike", "iBefore", "oBefore", "str", "iPrev", "prevNonWhitespaceIndex", "isDelimiter", "charAt", "substring", "iQuote", "oQuote", "isDigit", "parseConcatenatedString", "iPrevChar", "prevChar", "isUnquotedStringDelimiter", "regexUrlStart", "test", "regexUrlChar", "escapeChar", "j", "isHex", "throwInvalidUnicodeCharacter", "isControlCharacter", "isValidStringCharacter", "throwInvalidCharacter", "parsedStr", "removeAtIndex", "atEndOfNumber", "repairNumberEndingWithNumericSymbol", "num", "hasInvalidLeadingZero", "parseKeyword", "name", "value", "isKey", "symbol", "JSON", "stringify", "prev", "JSONRepairError", "chars", "z", "__name", "z", "z", "__name", "z", "__name", "__name", "__name", "__name", "__name", "z", "__name", "z", "__name", "z", "__name", "z", "z", "z", "z", "z", "__name", "__name", "z", "z", "__name", "z", "z", "z", "__name", "__name", "z", "__name", "text", "z", "trimmed", "isCancel", "confirm", "readFile", "TABLE_COLUMNS", "z", "TABLE_COLUMNS", "buildBody", "readFileSync", "readFile", "readFileSync", "collect", "z", "z", "publicBuildSchema", "z", "listBuildsResponseSchema", "DEFAULT_LIMIT", "MIN_LIMIT", "MAX_LIMIT", "TABLE_COLUMNS", "listBuildsResponseSchema", "buildConfirmMessage", "readFile", "TABLE_COLUMNS", "readStdin", "readFile", "TABLE_COLUMNS", "value", "DEFAULT_LIMIT", "MIN_LIMIT", "MAX_LIMIT", "TABLE_COLUMNS", "TABLE_COLUMNS", "readFileSync", "readFileSync", "TABLE_COLUMNS", "isCancel", "text", "text", "isCancel", "TABLE_COLUMNS", "isCancel", "isCancel", "TABLE_COLUMNS", "registerList", "DEFAULT_LIMIT", "MIN_LIMIT", "MAX_LIMIT", "TABLE_COLUMNS", "z", "z", "DEFAULT_LIMIT", "MIN_LIMIT", "MAX_LIMIT", "SORT_ORDERS", "TABLE_COLUMNS", "DEFAULT_LIMIT", "MIN_LIMIT", "MAX_LIMIT", "TABLE_COLUMNS", "buildBody", "z", "TABLE_COLUMNS", "readFile", "readFile", "readFileSync", "readContent", "readFileSync", "TABLE_COLUMNS", "readFileSync", "readFileSync", "parsed", "DEFAULT_LIMIT", "MIN_LIMIT", "MAX_LIMIT", "TABLE_COLUMNS", "join", "dirname", "readFileSync"]
3
+ "sources": ["../../src/bin/create-program.ts", "../../src/api/agent-folder-schemas.ts", "../../src/errors.ts", "../../src/client/client.ts", "../../src/output/should-color.ts", "../../src/output/colors.ts", "../../src/output/json.ts", "../../src/output/text.ts", "../../src/config/types.ts", "../../src/config/defaults.ts", "../../src/config/env.ts", "../../src/config/profiles.ts", "../../src/config/store.ts", "../../src/config/paths.ts", "../../src/oauth/auth0-client.ts", "../../src/config/resolve.ts", "../../src/commands/shared/profile-flag.ts", "../../src/commands/shared/require-auth.ts", "../../src/commands/shared/trim-required.ts", "../../src/commands/agent-folders/create.ts", "../../src/commands/shared/confirm.ts", "../../src/commands/agent-folders/delete.ts", "../../src/output/table-header.ts", "../../src/output/table.ts", "../../src/commands/agent-folders/list.ts", "../../src/commands/agent-folders/move-agents.ts", "../../src/commands/agent-folders/update.ts", "../../src/commands/agent-folders/index.ts", "../../src/commands/agents/create.ts", "../../../packages/shared/src/analytics/events.ts", "../../../packages/shared/src/billing/customer-portal.ts", "../../../packages/shared/src/billing/entitlements.ts", "../../../packages/shared/src/billing/invoices.ts", "../../../packages/shared/src/billing/plan-versions.ts", "../../../packages/shared/src/billing/plan-display.ts", "../../../packages/shared/src/billing/subscription-details.ts", "../../../packages/shared/src/billing/subscription-status.ts", "../../../packages/shared/src/billing/usage.ts", "../../../packages/shared/src/types/agent-run.ts", "../../../packages/shared/src/schemas/automation-message.ts", "../../../packages/shared/src/schemas/run-evaluation.ts", "../../../packages/shared/src/constants/models.ts", "../../../packages/shared/src/constants/agent.ts", "../../../packages/shared/src/constants/browser.ts", "../../../packages/shared/src/constants/build.ts", "../../../packages/shared/src/constants/case-queue.ts", "../../../packages/shared/src/constants/e2b.ts", "../../../packages/shared/src/constants/evaluation-rubrics.ts", "../../../packages/shared/src/constants/human-request.ts", "../../../packages/shared/src/constants/integration-credentials.ts", "../../../packages/shared/src/constants/plugins.ts", "../../../packages/shared/src/constants/solutions.ts", "../../../packages/shared/src/constants/triggers.ts", "../../../packages/shared/src/cookies/constants.ts", "../../../packages/shared/src/clarity-screenshare/types.ts", "../../../packages/shared/src/clarity-v2/api-schema.ts", "../../../packages/shared/src/types/clarity.ts", "../../../packages/shared/src/clarity-v2/process-data.ts", "../../../packages/shared/src/clarity-v2/validators.ts", "../../../packages/shared/src/clarity-v2/socket-events.ts", "../../../packages/shared/src/error-handling/stringify-error.ts", "../../../packages/shared/src/error-handling/make-sentry-reporter.ts", "../../../packages/shared/src/organization-roles.ts", "../../../packages/shared/src/roles.ts", "../../../packages/shared/src/schemas/api-keys.ts", "../../../packages/shared/src/schemas/ask-user-question.ts", "../../../packages/shared/src/schemas/browser-replay.ts", "../../../packages/shared/src/schemas/clarity-screenshare-session.ts", "../../../packages/shared/src/schemas/error.ts", "../../../packages/shared/src/schemas/human-request.ts", "../../../packages/shared/src/schemas/logo.ts", "../../../packages/shared/src/schemas/success.ts", "../../../packages/shared/src/types/admin-organization.ts", "../../../packages/shared/src/types/organization.ts", "../../../packages/shared/src/types/agent-api.ts", "../../../packages/shared/src/types/agent-config.ts", "../../../packages/shared/src/types/agent-feedback.ts", "../../../packages/shared/src/types/agent-folder-api.ts", "../../../packages/shared/src/types/agent-learning.ts", "../../../packages/shared/src/types/browser-agent.ts", "../../../packages/shared/src/types/build-api.ts", "../../../packages/shared/src/types/case-approval.ts", "../../../packages/shared/src/types/case-queue-filters.ts", "../../../packages/shared/src/types/case-queue-folder-api.ts", "../../../packages/shared/src/types/case-queue-labels.ts", "../../../packages/shared/src/types/case-triggers.ts", "../../../packages/shared/src/types/cases-ui.ts", "../../../packages/shared/src/types/clarity-overview.ts", "../../../packages/shared/src/types/composio.ts", "../../../packages/shared/src/types/credentials.ts", "../../../packages/shared/src/types/feature-flags.ts", "../../../packages/shared/src/types/files-api.ts", "../../../packages/shared/src/types/global-admin.ts", "../../../packages/shared/src/types/integration.ts", "../../../packages/shared/src/types/job-list.ts", "../../../packages/shared/src/types/mcp-workflow.ts", "../../../packages/shared/src/types/plugin-api.ts", "../../../packages/shared/src/types/profile.ts", "../../../packages/shared/src/types/recording-session.ts", "../../../packages/shared/src/types/run-config.ts", "../../../packages/shared/src/types/skill-api.ts", "../../../packages/shared/src/types/team.ts", "../../../packages/shared/src/types/team-invitation.ts", "../../../packages/shared/src/types/team-insights.ts", "../../../packages/shared/src/types/team-invite-link.ts", "../../../packages/shared/src/utils/agent-run-api-key.ts", "../../../packages/shared/src/utils/case-queue-filter-params.ts", "../../../packages/shared/src/utils/composio.ts", "../../../packages/shared/src/utils/domain.ts", "../../../packages/shared/src/utils/extract-agent-mention-ids.ts", "../../../packages/shared/src/utils/extract-system-prompt-text.ts", "../../../packages/shared/src/utils/get-sentry-environment.ts", "../../../packages/shared/src/utils/has-instructions.ts", "../../../packages/shared/src/utils/json/safe-parse-json.ts", "../../../packages/shared/src/utils/label-color-hue.ts", "../../../packages/shared/src/utils/mcp-server-label.ts", "../../../packages/shared/src/utils/normalize-agent-config.ts", "../../../packages/shared/src/utils/p-retry.ts", "../../../packages/shared/src/utils/parse-agent-config.ts", "../../../packages/shared/src/utils/parse-run-config.ts", "../../../node_modules/.pnpm/jsonrepair@3.13.2/node_modules/jsonrepair/src/utils/JSONRepairError.ts", "../../../node_modules/.pnpm/jsonrepair@3.13.2/node_modules/jsonrepair/src/utils/stringUtils.ts", "../../../node_modules/.pnpm/jsonrepair@3.13.2/node_modules/jsonrepair/src/regular/jsonrepair.ts", "../../src/api/agent-schemas.ts", "../../src/commands/agents/get.ts", "../../src/commands/shared/pagination.ts", "../../src/commands/agents/list.ts", "../../src/api/schedule-schemas.ts", "../../src/commands/agents/schedules.ts", "../../src/commands/agents/update.ts", "../../src/commands/agents/index.ts", "../../src/api/parse-fields.ts", "../../src/api/read-input.ts", "../../src/commands/api-render.ts", "../../src/commands/api.ts", "../../src/api/integration-schemas.ts", "../../src/commands/build-integrations/attach.ts", "../../src/commands/build-integrations/connections-list.ts", "../../src/commands/build-integrations/connections-pin.ts", "../../src/commands/build-integrations/connections-unpin.ts", "../../src/commands/build-integrations/list.ts", "../../src/commands/build-integrations/remove.ts", "../../src/commands/build-integrations/index.ts", "../../src/api/build-schemas.ts", "../../src/api/json-value.ts", "../../src/commands/builds/create.ts", "../../src/commands/builds/get.ts", "../../src/commands/builds/list.ts", "../../src/commands/builds/update.ts", "../../src/commands/builds/index.ts", "../../src/commands/cases/parse-case-ids.ts", "../../src/commands/cases/bulk-delegate.ts", "../../src/commands/cases/bulk-delete.ts", "../../src/commands/cases/bulk-retry.ts", "../../src/commands/cases/bulk-update-status.ts", "../../src/commands/cases/clear.ts", "../../src/commands/cases/create.ts", "../../src/commands/cases/delete.ts", "../../src/commands/cases/get.ts", "../../src/commands/cases/labels.ts", "../../src/commands/cases/list.ts", "../../src/commands/cases/runs.ts", "../../src/commands/cases/index.ts", "../../src/commands/connections/get.ts", "../../src/commands/connections/list.ts", "../../src/commands/connections/index.ts", "../../src/commands/files/content.ts", "../../src/commands/files/content-set.ts", "../../src/commands/files/delete.ts", "../../src/commands/files/download-url.ts", "../../src/commands/files/list.ts", "../../src/commands/files/rename.ts", "../../src/commands/files/upload-url.ts", "../../src/commands/files/index.ts", "../../src/commands/integrations/list.ts", "../../src/commands/integrations/index.ts", "../../src/commands/login.ts", "../../src/oauth/auth0-config.ts", "../../src/oauth/loopback.ts", "../../src/oauth/open-browser.ts", "../../src/oauth/pkce.ts", "../../src/commands/logout.ts", "../../src/commands/plugins/list.ts", "../../src/commands/plugins/index.ts", "../../src/output/format.ts", "../../src/commands/profiles/render-list.ts", "../../src/commands/profiles/list.ts", "../../src/commands/profiles/remove.ts", "../../src/commands/profiles/rename.ts", "../../src/commands/profiles/use.ts", "../../src/commands/profiles/index.ts", "../../src/commands/queue-labels/index.ts", "../../src/commands/queues/agents.ts", "../../src/commands/queues/create.ts", "../../src/commands/queues/delete.ts", "../../src/commands/queues/get.ts", "../../src/commands/queues/list.ts", "../../src/commands/queues/update.ts", "../../src/commands/queues/index.ts", "../../src/api/run-schemas.ts", "../../src/commands/runs/get.ts", "../../src/commands/runs/list.ts", "../../src/commands/runs/messages.ts", "../../src/commands/runs/respond.ts", "../../src/commands/runs/send-message.ts", "../../src/commands/runs/start.ts", "../../src/commands/runs/stop.ts", "../../src/commands/runs/index.ts", "../../src/api/sandbox-schemas.ts", "../../src/commands/sandboxes/create.ts", "../../src/commands/sandboxes/files.ts", "../../src/commands/sandboxes/prepare-upload-url.ts", "../../src/commands/sandboxes/upload.ts", "../../src/commands/sandboxes/index.ts", "../../src/commands/skills/delete.ts", "../../src/commands/skills/download.ts", "../../src/commands/skills/file-get.ts", "../../src/commands/skills/file-update.ts", "../../src/commands/skills/files.ts", "../../src/commands/skills/generate.ts", "../../src/commands/skills/list.ts", "../../src/commands/skills/index.ts", "../../src/commands/team/members.ts", "../../src/commands/team/index.ts", "../../src/commands/whoami.ts", "../../src/bin/duvo.ts"],
4
+ "sourcesContent": ["import { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { Command } from \"commander\";\n\nimport { registerAgentFolders } from \"@/commands/agent-folders/index.js\";\nimport { registerAgents } from \"@/commands/agents/index.js\";\nimport { registerApi } from \"@/commands/api.js\";\nimport { registerBuildIntegrations } from \"@/commands/build-integrations/index.js\";\nimport { registerBuilds } from \"@/commands/builds/index.js\";\nimport { registerCases } from \"@/commands/cases/index.js\";\nimport { registerConnections } from \"@/commands/connections/index.js\";\nimport { registerFiles } from \"@/commands/files/index.js\";\nimport { registerIntegrations } from \"@/commands/integrations/index.js\";\nimport { registerLogin } from \"@/commands/login.js\";\nimport { registerLogout } from \"@/commands/logout.js\";\nimport { registerPlugins } from \"@/commands/plugins/index.js\";\nimport { registerProfiles } from \"@/commands/profiles/index.js\";\nimport { registerQueueLabels } from \"@/commands/queue-labels/index.js\";\nimport { registerQueues } from \"@/commands/queues/index.js\";\nimport { registerRuns } from \"@/commands/runs/index.js\";\nimport { registerSandboxes } from \"@/commands/sandboxes/index.js\";\nimport { registerSkills } from \"@/commands/skills/index.js\";\nimport { registerTeam } from \"@/commands/team/index.js\";\nimport { registerWhoami } from \"@/commands/whoami.js\";\n\nconst packageJsonPath = join(\n dirname(fileURLToPath(import.meta.url)),\n \"../../package.json\"\n);\nconst { version } = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as {\n version: string;\n};\n\n/**\n * Build a fresh `Command` tree for the CLI. Shared between the real\n * binary (`bin/duvo.ts`) and the test harness so tests can never\n * silently drift out of sync with the production command set.\n */\nexport function createProgram(): Command {\n const program = new Command();\n\n program\n .name(\"duvo\")\n .description(\"Command-line interface for the Duvo public API\")\n .version(version)\n .option(\n \"--profile <name>\",\n \"use a specific profile for this invocation (overrides default profile)\"\n );\n\n registerLogin(program);\n registerLogout(program);\n registerWhoami(program);\n registerProfiles(program);\n registerApi(program);\n registerAgents(program);\n registerAgentFolders(program);\n registerBuilds(program);\n registerBuildIntegrations(program);\n registerIntegrations(program);\n registerConnections(program);\n registerRuns(program);\n registerQueues(program);\n registerQueueLabels(program);\n registerCases(program);\n registerSandboxes(program);\n registerFiles(program);\n registerPlugins(program);\n registerSkills(program);\n registerTeam(program);\n\n return program;\n}\n", "import { z } from \"zod\";\n\nconst publicAgentFolderSchema = z.object({\n id: z.string(),\n name: z.string(),\n team_id: z.string().nullish(),\n parent_folder_id: z.string().nullish(),\n created_at: z.string().nullish(),\n updated_at: z.string().nullish(),\n agent_count: z.number().nullish(),\n subfolder_count: z.number().nullish(),\n});\n\nexport type PublicAgentFolder = z.infer<typeof publicAgentFolderSchema>;\n\nexport const listAgentFoldersResponseSchema = z.object({\n folders: z.array(publicAgentFolderSchema),\n});\n\nexport type ListAgentFoldersResponse = z.infer<\n typeof listAgentFoldersResponseSchema\n>;\n\nexport const folderResponseSchema = z.object({\n folder: publicAgentFolderSchema,\n});\n\nexport type FolderResponse = z.infer<typeof folderResponseSchema>;\n\nexport const deleteFolderResponseSchema = z.object({\n success: z.boolean(),\n});\n\nexport type DeleteFolderResponse = z.infer<typeof deleteFolderResponseSchema>;\n\nexport const moveAgentsResponseSchema = z.object({\n success: z.boolean(),\n moved_count: z.number(),\n});\n\nexport type MoveAgentsResponse = z.infer<typeof moveAgentsResponseSchema>;\n", "export const EXIT_CODE = {\n SUCCESS: 0,\n GENERIC: 1,\n AUTH: 2,\n NOT_FOUND: 3,\n} as const;\n\nexport type ExitCode = (typeof EXIT_CODE)[keyof typeof EXIT_CODE];\n\nexport class CliError extends Error {\n public readonly exitCode: ExitCode;\n\n constructor(message: string, exitCode: ExitCode = EXIT_CODE.GENERIC) {\n super(message);\n this.name = \"CliError\";\n this.exitCode = exitCode;\n }\n}\n\nexport class AuthCliError extends CliError {\n constructor(message: string) {\n super(message, EXIT_CODE.AUTH);\n this.name = \"AuthCliError\";\n }\n}\n\n/** Signals a cooperative user-driven cancel (Ctrl-C, answering \"no\"). */\nexport class CancelCliError extends CliError {\n constructor(message = \"Cancelled.\") {\n super(message, EXIT_CODE.GENERIC);\n this.name = \"CancelCliError\";\n }\n}\n\nexport function handleCliError(error: unknown): never {\n if (error instanceof CliError) {\n process.stderr.write(`${error.message}\\n`);\n process.exit(error.exitCode);\n }\n\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`error: ${message}\\n`);\n process.exit(EXIT_CODE.GENERIC);\n}\n", "import { CliError, EXIT_CODE } from \"@/errors.js\";\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\nexport type HttpRequestOptions = {\n method: string;\n path: string;\n apiKey: string;\n apiBaseUrl: string;\n /** JSON body. Omitted for GET/HEAD-style requests. */\n body?: unknown;\n /** Appended to the resolved URL. */\n searchParams?: URLSearchParams;\n /** Request timeout in ms. Defaults to {@link DEFAULT_REQUEST_TIMEOUT_MS}. */\n timeoutMs?: number;\n};\n\nexport type HttpUploadOptions = {\n path: string;\n apiKey: string;\n apiBaseUrl: string;\n /** Multipart form fields. File parts go through `Blob`. */\n formData: FormData;\n /** Request timeout in ms. Defaults to {@link DEFAULT_REQUEST_TIMEOUT_MS}. */\n timeoutMs?: number;\n};\n\n/**\n * Makes an authenticated request to the Duvo public API and returns the\n * parsed JSON response. Maps well-known status codes to `CliError` with\n * the right exit code; other non-2xx responses throw a generic\n * `CliError` containing the server's response body.\n *\n * Empty response bodies resolve to `null`. Non-JSON responses resolve to\n * the raw text \u2014 the caller decides how to render it.\n */\nexport async function httpRequest(\n options: HttpRequestOptions\n): Promise<unknown> {\n const url = buildUrl(options.apiBaseUrl, options.path, options.searchParams);\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${options.apiKey}`,\n Accept: \"application/json\",\n };\n\n const timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n const init: RequestInit = {\n method: options.method,\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n };\n if (options.body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n init.body = JSON.stringify(options.body);\n }\n\n try {\n const response = await fetch(url, init);\n return await handleResponse(response, options.method, options.path);\n } catch (error) {\n if (isTimeoutError(error)) {\n throw new CliError(\n `Request timed out after ${timeoutMs}ms: ${options.method} ${options.path}`\n );\n }\n\n throw error;\n }\n}\n\n/**\n * Uploads a multipart/form-data request to the Duvo public API and\n * returns the parsed JSON response. The browser fetch builds the\n * `Content-Type` header (with the multipart boundary) from the\n * `FormData` body \u2014 do not set it manually.\n */\nexport async function httpUpload(options: HttpUploadOptions): Promise<unknown> {\n const url = buildUrl(options.apiBaseUrl, options.path, undefined);\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${options.apiKey}`,\n Accept: \"application/json\",\n };\n\n const timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n const init: RequestInit = {\n method: \"POST\",\n headers,\n body: options.formData,\n signal: AbortSignal.timeout(timeoutMs),\n };\n\n try {\n const response = await fetch(url, init);\n return await handleResponse(response, \"POST\", options.path);\n } catch (error) {\n if (isTimeoutError(error)) {\n throw new CliError(\n `Request timed out after ${timeoutMs}ms: POST ${options.path}`\n );\n }\n\n throw error;\n }\n}\n\nfunction isTimeoutError(error: unknown): boolean {\n return (\n error instanceof DOMException &&\n (error.name === \"TimeoutError\" || error.name === \"AbortError\")\n );\n}\n\n/**\n * Resolves an API path against the configured base URL. The base URL must\n * be an origin only (scheme + host + optional port) \u2014 any path component\n * is discarded, because `new URL(\"/v1/agents\", \"https://host/foo/\")`\n * resolves to `https://host/v1/agents`, not `https://host/foo/v1/agents`.\n */\nconst ABSOLUTE_URL = /^[a-zA-Z][a-zA-Z\\d+.-]*:\\/\\//;\n\nfunction buildUrl(\n base: string,\n path: string,\n searchParams: URLSearchParams | undefined\n): URL {\n if (ABSOLUTE_URL.test(path)) {\n throw new CliError(\n `Invalid path \"${path}\". Expected an API path like \"/v1/agents\" \u2014 absolute URLs are not allowed.`\n );\n }\n\n const normalized = path.startsWith(\"/\") ? path : `/${path}`;\n const url = new URL(normalized, ensureTrailingSlash(base));\n if (searchParams) {\n for (const [key, value] of searchParams) {\n url.searchParams.append(key, value);\n }\n }\n\n return url;\n}\n\nfunction ensureTrailingSlash(base: string): string {\n return base.endsWith(\"/\") ? base : `${base}/`;\n}\n\nasync function handleResponse(\n response: Response,\n method: string,\n path: string\n): Promise<unknown> {\n if (response.status === 401) {\n throw new CliError(\n \"Unauthorized. Run `duvo login` to sign in again, or check your API key.\",\n EXIT_CODE.AUTH\n );\n }\n\n if (response.status === 404) {\n throw new CliError(`Not found: ${method} ${path}`, EXIT_CODE.NOT_FOUND);\n }\n\n if (!response.ok) {\n const detail = await safeReadText(response);\n const suffix = detail.length > 0 ? `: ${detail}` : \"\";\n throw new CliError(\n `Request failed (${response.status} ${response.statusText})${suffix}`\n );\n }\n\n const text = await safeReadText(response);\n if (text.length === 0) {\n return null;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nasync function safeReadText(response: Response): Promise<string> {\n try {\n return await response.text();\n } catch {\n return \"\";\n }\n}\n", "/**\n * Returns whether ANSI styling should be emitted. Honors `NO_COLOR` and\n * skips styling when stdout is not a TTY so piped output stays clean.\n */\nexport function shouldColor(): boolean {\n if (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== \"\") {\n return false;\n }\n\n return Boolean(process.stdout.isTTY);\n}\n", "import { shouldColor } from \"./should-color.js\";\n\nconst ANSI = {\n reset: \"\\x1b[0m\",\n green: \"\\x1b[32m\",\n red: \"\\x1b[31m\",\n cyan: \"\\x1b[36m\",\n dim: \"\\x1b[2m\",\n bold: \"\\x1b[1m\",\n orange: \"\\x1b[38;5;208m\",\n yellow: \"\\x1b[38;5;178m\",\n} as const;\n\nfunction wrap(code: string, text: string): string {\n if (!shouldColor()) {\n return text;\n }\n\n return `${code}${text}${ANSI.reset}`;\n}\n\nexport const green = (text: string): string => wrap(ANSI.green, text);\nexport const red = (text: string): string => wrap(ANSI.red, text);\nexport const cyan = (text: string): string => wrap(ANSI.cyan, text);\nexport const bold = (text: string): string => wrap(ANSI.bold, text);\nexport const yellow = (text: string): string => wrap(ANSI.yellow, text);\n", "/**\n * Prints a value as pretty JSON (2-space indent) to stdout. This is the\n * stable output contract \u2014 scripts should always be able to `| jq` the\n * result. No colour, no truncation.\n */\nexport function printJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2));\n}\n", "export type KeyValueEntry = {\n label: string;\n value: string;\n};\n\n/**\n * Renders a labelled key/value block for single-resource views.\n * Labels are left-padded to the widest label so values line up.\n */\nexport function renderKeyValue(entries: readonly KeyValueEntry[]): string {\n if (entries.length === 0) {\n return \"\";\n }\n\n const labelWidth = Math.max(...entries.map((e) => e.label.length));\n return entries\n .map((entry) => `${entry.label.padEnd(labelWidth)} ${entry.value}`)\n .join(\"\\n\");\n}\n", "/**\n * Config schema versions:\n * - v1 (implicit): legacy API-key-only profiles, no `config_version` field.\n * - v2: profiles may hold either an API key or an OAuth credential set.\n */\nexport const CURRENT_CONFIG_VERSION = 2;\n\nexport type ApiKeyProfile = {\n type: \"api-key\";\n apiKey: string;\n apiBaseUrl: string;\n};\n\nexport type OAuthProfile = {\n type: \"oauth\";\n apiBaseUrl: string;\n accessToken: string;\n refreshToken: string;\n /** Unix milliseconds at which the access token expires. */\n expiresAt: number;\n /** Auth0 issuer URL (e.g. `https://login.duvo.ai/`). */\n issuer: string;\n /** Auth0 client_id used for this profile (the static `Duvo CLI` app). */\n clientId: string;\n /** Cached identity for `duvo whoami` enrichment. */\n userId?: string;\n teamId?: string;\n email?: string;\n};\n\nexport type Profile = ApiKeyProfile | OAuthProfile;\n\nexport type Config = {\n configVersion: number;\n defaultProfile: string | null;\n profiles: Record<string, Profile>;\n};\n", "import { type Config, CURRENT_CONFIG_VERSION } from \"@/config/types.js\";\n\nexport const DEFAULT_API_BASE_URL = \"https://api.duvo.ai\";\n\nexport function emptyConfig(): Config {\n return {\n configVersion: CURRENT_CONFIG_VERSION,\n defaultProfile: null,\n profiles: {},\n };\n}\n", "import { z } from \"zod\";\n\nconst optionalEnvString = z\n .string()\n .optional()\n .transform((value) =>\n value === undefined || value === \"\" ? undefined : value\n );\n\nconst CliEnvSchema = z.object({\n DUVO_PROFILE: optionalEnvString,\n DUVO_API_KEY: optionalEnvString,\n DUVO_API_BASE_URL: optionalEnvString,\n});\n\nexport type CliEnv = z.output<typeof CliEnvSchema>;\n\nexport function parseCliEnv(env: NodeJS.ProcessEnv): CliEnv {\n return CliEnvSchema.parse(env);\n}\n", "import { type Config, type Profile } from \"@/config/types.js\";\n\nconst PROFILE_NAME_PATTERN = /^[a-z0-9._-]+$/;\nconst MAX_PROFILE_NAME_LENGTH = 40;\n\nexport function isValidProfileName(name: string): boolean {\n if (name.length === 0 || name.length > MAX_PROFILE_NAME_LENGTH) {\n return false;\n }\n\n return PROFILE_NAME_PATTERN.test(name);\n}\n\nfunction assertValidProfileName(name: string): void {\n if (!isValidProfileName(name)) {\n throw new Error(\n `Invalid profile name \"${name}\". Use lowercase letters, digits, ` +\n `\".\", \"-\" or \"_\", max ${MAX_PROFILE_NAME_LENGTH} chars.`\n );\n }\n}\n\nexport function addProfile(\n config: Config,\n name: string,\n profile: Profile\n): Config {\n assertValidProfileName(name);\n const profiles = { ...config.profiles, [name]: profile };\n const defaultProfile =\n config.defaultProfile === null ? name : config.defaultProfile;\n return { ...config, defaultProfile, profiles };\n}\n\nexport function removeProfile(config: Config, name: string): Config {\n if (!(name in config.profiles)) {\n return config;\n }\n\n const profiles = { ...config.profiles };\n delete profiles[name];\n\n if (config.defaultProfile !== name) {\n return { ...config, profiles };\n }\n\n const remaining = Object.keys(profiles).sort();\n const defaultProfile = remaining.length > 0 ? remaining[0] : null;\n return { ...config, defaultProfile, profiles };\n}\n\nexport function renameProfile(\n config: Config,\n oldName: string,\n newName: string\n): Config {\n if (!(oldName in config.profiles)) {\n throw new Error(`Profile \"${oldName}\" does not exist.`);\n }\n\n if (oldName === newName) {\n return config;\n }\n\n assertValidProfileName(newName);\n if (newName in config.profiles) {\n throw new Error(`Profile \"${newName}\" already exists.`);\n }\n\n const profiles = { ...config.profiles };\n profiles[newName] = profiles[oldName];\n delete profiles[oldName];\n\n const defaultProfile =\n config.defaultProfile === oldName ? newName : config.defaultProfile;\n return { ...config, defaultProfile, profiles };\n}\n\nexport function setDefaultProfile(config: Config, name: string): Config {\n if (!(name in config.profiles)) {\n throw new Error(`Profile \"${name}\" does not exist.`);\n }\n\n return { ...config, defaultProfile: name };\n}\n\nexport type ProfileSummary = {\n name: string;\n authType: \"api-key\" | \"oauth\";\n apiBaseUrl: string;\n /** Present only for API-key profiles. */\n apiKey?: string;\n /** Present only for OAuth profiles. */\n email?: string;\n isDefault: boolean;\n};\n\nexport function listProfiles(config: Config): readonly ProfileSummary[] {\n return Object.entries(config.profiles)\n .map(([name, profile]): ProfileSummary => {\n const summary: ProfileSummary = {\n name,\n authType: profile.type,\n apiBaseUrl: profile.apiBaseUrl,\n isDefault: config.defaultProfile === name,\n };\n if (profile.type === \"api-key\") {\n summary.apiKey = profile.apiKey;\n } else {\n summary.email = profile.email;\n }\n\n return summary;\n })\n .sort((a, b) => a.name.localeCompare(b.name));\n}\n", "import { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nimport { DEFAULT_API_BASE_URL, emptyConfig } from \"@/config/defaults.js\";\nimport { getConfigPath } from \"@/config/paths.js\";\nimport {\n type Config,\n CURRENT_CONFIG_VERSION,\n type Profile,\n} from \"@/config/types.js\";\nimport { CliError } from \"@/errors.js\";\n\nconst FILE_MODE = 0o600;\nconst DIR_MODE = 0o700;\n\nexport async function readConfig(): Promise<Config> {\n const path = getConfigPath();\n try {\n const raw = await readFile(path, \"utf8\");\n const parsed = JSON.parse(raw) as unknown;\n return normalizeConfig(parsed);\n } catch (error) {\n if (isNotFound(error)) {\n return emptyConfig();\n }\n\n throw error;\n }\n}\n\nexport async function writeConfig(config: Config): Promise<void> {\n const path = getConfigPath();\n await mkdir(dirname(path), { recursive: true, mode: DIR_MODE });\n const serialized: Config = {\n ...config,\n configVersion: CURRENT_CONFIG_VERSION,\n };\n await writeFile(path, JSON.stringify(serialized, null, 2), {\n mode: FILE_MODE,\n encoding: \"utf8\",\n });\n}\n\nexport async function deleteConfig(): Promise<boolean> {\n const path = getConfigPath();\n try {\n await rm(path);\n return true;\n } catch (error) {\n if (isNotFound(error)) {\n return false;\n }\n\n throw error;\n }\n}\n\n/**\n * Read and migrate stored config. Accepts:\n * - v1 single-profile (`{ apiKey, apiBaseUrl }`) \u2014 wrapped under `default`.\n * - v1 multi-profile (no `config_version` field, profiles hold `apiKey`).\n * - v2 multi-profile (`config_version: 2`, profiles may hold OAuth tokens).\n *\n * v2 is forward-compatible: an unknown profile shape is dropped silently. A\n * file written by a future CLI (`config_version > 2`) is rejected.\n */\nfunction normalizeConfig(parsed: unknown): Config {\n if (parsed === null || typeof parsed !== \"object\") {\n return emptyConfig();\n }\n\n const record = parsed as Record<string, unknown>;\n\n const rawVersion = record.config_version ?? record.configVersion;\n const version = typeof rawVersion === \"number\" ? rawVersion : 1;\n if (version > CURRENT_CONFIG_VERSION) {\n throw new CliError(\n `Config file uses an unsupported version (${version}). Please upgrade the Duvo CLI.`\n );\n }\n\n if (\n typeof record.apiKey === \"string\" &&\n record.profiles === undefined &&\n record.defaultProfile === undefined\n ) {\n const apiBaseUrl =\n typeof record.apiBaseUrl === \"string\"\n ? record.apiBaseUrl\n : DEFAULT_API_BASE_URL;\n return {\n configVersion: CURRENT_CONFIG_VERSION,\n defaultProfile: \"default\",\n profiles: {\n default: {\n type: \"api-key\",\n apiKey: record.apiKey,\n apiBaseUrl,\n },\n },\n };\n }\n\n const profiles: Record<string, Profile> = {};\n const rawProfiles =\n record.profiles && typeof record.profiles === \"object\"\n ? (record.profiles as Record<string, unknown>)\n : {};\n\n for (const [name, value] of Object.entries(rawProfiles)) {\n const normalized = normalizeProfile(value);\n if (normalized) {\n profiles[name] = normalized;\n }\n }\n\n const defaultProfile =\n typeof record.defaultProfile === \"string\" &&\n record.defaultProfile in profiles\n ? record.defaultProfile\n : null;\n\n return {\n configVersion: CURRENT_CONFIG_VERSION,\n defaultProfile,\n profiles,\n };\n}\n\nfunction normalizeProfile(value: unknown): Profile | null {\n if (value === null || typeof value !== \"object\") {\n return null;\n }\n\n const profile = value as Record<string, unknown>;\n const apiBaseUrl =\n typeof profile.apiBaseUrl === \"string\"\n ? profile.apiBaseUrl\n : DEFAULT_API_BASE_URL;\n\n if (\n profile.type === \"oauth\" ||\n typeof profile.accessToken === \"string\" ||\n typeof profile.refreshToken === \"string\"\n ) {\n if (\n typeof profile.accessToken !== \"string\" ||\n typeof profile.refreshToken !== \"string\" ||\n typeof profile.expiresAt !== \"number\" ||\n typeof profile.issuer !== \"string\" ||\n typeof profile.clientId !== \"string\"\n ) {\n return null;\n }\n\n return {\n type: \"oauth\",\n apiBaseUrl,\n accessToken: profile.accessToken,\n refreshToken: profile.refreshToken,\n expiresAt: profile.expiresAt,\n issuer: profile.issuer,\n clientId: profile.clientId,\n userId: typeof profile.userId === \"string\" ? profile.userId : undefined,\n teamId: typeof profile.teamId === \"string\" ? profile.teamId : undefined,\n email: typeof profile.email === \"string\" ? profile.email : undefined,\n };\n }\n\n if (typeof profile.apiKey === \"string\") {\n return {\n type: \"api-key\",\n apiKey: profile.apiKey,\n apiBaseUrl,\n };\n }\n\n return null;\n}\n\nfunction isNotFound(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code: unknown }).code === \"ENOENT\"\n );\n}\n", "import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst CONFIG_DIR_NAME = \"duvo\";\nconst CONFIG_FILE_NAME = \"config.json\";\n\nfunction getConfigDir(): string {\n const xdg = process.env.XDG_CONFIG_HOME;\n if (xdg && xdg.length > 0) {\n return join(xdg, CONFIG_DIR_NAME);\n }\n\n return join(homedir(), \".config\", CONFIG_DIR_NAME);\n}\n\nexport function getConfigPath(): string {\n return join(getConfigDir(), CONFIG_FILE_NAME);\n}\n", "import { CliError } from \"@/errors.js\";\n\nimport { type Auth0Config } from \"./auth0-config.js\";\n\nconst AUTH0_REQUEST_TIMEOUT_MS = 30_000;\n\nfunction timeoutSignal(): AbortSignal {\n return AbortSignal.timeout(AUTH0_REQUEST_TIMEOUT_MS);\n}\n\nasync function postForm(\n url: string,\n body: URLSearchParams,\n context: string\n): Promise<Response> {\n try {\n return await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: body.toString(),\n signal: timeoutSignal(),\n });\n } catch (err) {\n if (err instanceof DOMException && err.name === \"TimeoutError\") {\n throw new CliError(\n `Auth0 ${context} timed out after ${AUTH0_REQUEST_TIMEOUT_MS}ms`\n );\n }\n\n throw err;\n }\n}\n\nexport type TokenResponse = {\n access_token: string;\n refresh_token?: string;\n id_token?: string;\n token_type: string;\n expires_in: number;\n scope?: string;\n};\n\nexport type Auth0Error = {\n error: string;\n error_description?: string;\n};\n\n/**\n * Wraps a non-OK response from Auth0's token endpoint so callers can switch\n * on the structured `error` code (e.g. `invalid_grant`) instead of pattern-\n * matching on the human-readable message \u2014 Auth0 always returns\n * `error_description` and that's what we surface in `message`, so the literal\n * `error` code never appears there.\n */\nexport class Auth0TokenError extends CliError {\n public readonly code: string | null;\n constructor(code: string | null, message: string) {\n super(message);\n this.name = \"Auth0TokenError\";\n this.code = code;\n }\n}\n\nfunction buildAuthorizeUrl(\n config: Auth0Config,\n args: {\n redirectUri: string;\n codeChallenge: string;\n state: string;\n }\n): string {\n const params = new URLSearchParams({\n response_type: \"code\",\n client_id: config.clientId,\n code_challenge: args.codeChallenge,\n code_challenge_method: \"S256\",\n redirect_uri: args.redirectUri,\n state: args.state,\n scope: \"openid profile email offline_access\",\n audience: config.audience,\n resource: config.audience,\n });\n return `${config.issuer}authorize?${params.toString()}`;\n}\n\nexport function buildAuthorizationUrl(\n config: Auth0Config,\n args: { redirectUri: string; codeChallenge: string; state: string }\n): string {\n return buildAuthorizeUrl(config, args);\n}\n\nexport async function exchangeCodeForTokens(\n config: Auth0Config,\n args: {\n code: string;\n codeVerifier: string;\n redirectUri: string;\n }\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: \"authorization_code\",\n client_id: config.clientId,\n code: args.code,\n code_verifier: args.codeVerifier,\n redirect_uri: args.redirectUri,\n audience: config.audience,\n resource: config.audience,\n });\n\n const response = await postForm(\n `${config.issuer}oauth/token`,\n body,\n \"code exchange\"\n );\n\n return parseTokenResponse(response);\n}\n\nexport async function refreshTokens(\n config: Auth0Config,\n refreshToken: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: \"refresh_token\",\n client_id: config.clientId,\n refresh_token: refreshToken,\n });\n\n const response = await postForm(\n `${config.issuer}oauth/token`,\n body,\n \"token refresh\"\n );\n\n return parseTokenResponse(response);\n}\n\nexport async function revokeRefreshToken(\n config: Auth0Config,\n refreshToken: string\n): Promise<void> {\n const body = new URLSearchParams({\n client_id: config.clientId,\n token: refreshToken,\n token_type_hint: \"refresh_token\",\n });\n\n const response = await postForm(\n `${config.issuer}oauth/revoke`,\n body,\n \"token revocation\"\n );\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new CliError(\n `Token revocation failed (${response.status}): ${text || response.statusText}`\n );\n }\n}\n\nasync function parseTokenResponse(response: Response): Promise<TokenResponse> {\n const text = await response.text();\n if (!response.ok) {\n let detail = text;\n let code: string | null = null;\n try {\n const parsed = JSON.parse(text) as Auth0Error;\n detail = parsed.error_description ?? parsed.error ?? text;\n code = parsed.error ?? null;\n } catch {\n // fall through with raw text\n }\n\n throw new Auth0TokenError(\n code,\n `Auth0 token endpoint returned ${response.status}: ${detail}`\n );\n }\n\n try {\n const json = JSON.parse(text) as TokenResponse;\n if (typeof json.access_token !== \"string\") {\n throw new CliError(\"Auth0 token response missing access_token\");\n }\n\n return json;\n } catch (err) {\n if (err instanceof CliError) {\n throw err;\n }\n\n throw new CliError(\"Auth0 token response was not valid JSON\");\n }\n}\n", "import { DEFAULT_API_BASE_URL } from \"@/config/defaults.js\";\nimport { type CliEnv, parseCliEnv } from \"@/config/env.js\";\nimport { addProfile } from \"@/config/profiles.js\";\nimport { readConfig, writeConfig } from \"@/config/store.js\";\nimport {\n type Config,\n type OAuthProfile,\n type Profile,\n} from \"@/config/types.js\";\nimport { AuthCliError } from \"@/errors.js\";\nimport { Auth0TokenError, refreshTokens } from \"@/oauth/auth0-client.js\";\n\n/** Refresh OAuth tokens this many ms before expiry. */\nconst REFRESH_LEEWAY_MS = 60_000;\n\nexport type ResolvedConfig = {\n /**\n * Bearer token to send on outbound HTTP requests. May be either a Duvo\n * API key (e.g. `dv_pat_*`, legacy `dv_*`, `duvo_*`) or an Auth0 access\n * token (RS256 JWT). The public API auth adapter routes by token shape.\n */\n apiKey: string | null;\n apiBaseUrl: string;\n /** Name of the profile we resolved to, or null if we fell through to env-only. */\n profileName: string | null;\n /** Type of credential resolved (`null` for env-only). */\n authType: \"api-key\" | \"oauth\" | null;\n};\n\nexport type ResolveOptions = {\n profileFlag?: string | undefined;\n};\n\nexport async function resolveConfig(\n options: ResolveOptions = {}\n): Promise<ResolvedConfig> {\n const config = await readConfig();\n const env = parseCliEnv(process.env);\n\n if (env.DUVO_API_KEY) {\n return {\n apiKey: env.DUVO_API_KEY,\n apiBaseUrl: env.DUVO_API_BASE_URL ?? DEFAULT_API_BASE_URL,\n profileName: null,\n authType: \"api-key\",\n };\n }\n\n const profileName = selectProfileName(config, options, env);\n const profile =\n profileName !== null ? (config.profiles[profileName] ?? null) : null;\n\n if (profileName === null || profile === null) {\n return {\n apiKey: null,\n apiBaseUrl: env.DUVO_API_BASE_URL ?? DEFAULT_API_BASE_URL,\n profileName,\n authType: null,\n };\n }\n\n if (profile.type === \"api-key\") {\n return {\n apiKey: profile.apiKey,\n apiBaseUrl: env.DUVO_API_BASE_URL ?? profile.apiBaseUrl,\n profileName,\n authType: \"api-key\",\n };\n }\n\n const fresh = await ensureFreshOAuthProfile(config, profileName, profile);\n return {\n apiKey: fresh.accessToken,\n apiBaseUrl: env.DUVO_API_BASE_URL ?? fresh.apiBaseUrl,\n profileName,\n authType: \"oauth\",\n };\n}\n\nexport function selectEffectiveConfig(\n config: Config,\n options: ResolveOptions,\n env: CliEnv\n): {\n profileName: string | null;\n profile: Profile | null;\n apiBaseUrl: string;\n} {\n const profileName = selectProfileName(config, options, env);\n const profile = profileName ? (config.profiles[profileName] ?? null) : null;\n const apiBaseUrl =\n env.DUVO_API_BASE_URL ?? profile?.apiBaseUrl ?? DEFAULT_API_BASE_URL;\n return { profileName, profile, apiBaseUrl };\n}\n\nfunction selectProfileName(\n config: Config,\n options: ResolveOptions,\n env: CliEnv\n): string | null {\n const flag = options.profileFlag;\n if (flag && flag.length > 0) {\n if (!(flag in config.profiles)) {\n throw new UnknownProfileError(flag);\n }\n\n return flag;\n }\n\n if (env.DUVO_PROFILE && env.DUVO_PROFILE in config.profiles) {\n return env.DUVO_PROFILE;\n }\n\n return config.defaultProfile;\n}\n\nasync function ensureFreshOAuthProfile(\n config: Config,\n profileName: string,\n profile: OAuthProfile\n): Promise<OAuthProfile> {\n if (profile.expiresAt - Date.now() > REFRESH_LEEWAY_MS) {\n return profile;\n }\n\n let response;\n try {\n response = await refreshTokens(\n {\n domain: new URL(profile.issuer).host,\n clientId: profile.clientId,\n audience: \"\",\n issuer: profile.issuer,\n },\n profile.refreshToken\n );\n } catch (err) {\n if (err instanceof Auth0TokenError && err.code === \"invalid_grant\") {\n throw new AuthCliError(\n `Session for profile \"${profileName}\" has expired. Run \\`duvo login\\` to sign in again.`\n );\n }\n\n throw err;\n }\n\n const refreshed: OAuthProfile = {\n ...profile,\n accessToken: response.access_token,\n refreshToken: response.refresh_token ?? profile.refreshToken,\n expiresAt: Date.now() + response.expires_in * 1000,\n };\n\n const next = addProfile(config, profileName, refreshed);\n await writeConfig(next);\n return refreshed;\n}\n\nexport class UnknownProfileError extends AuthCliError {\n constructor(public readonly profileName: string) {\n super(\n `Profile \"${profileName}\" does not exist. Run \\`duvo profiles list\\` to see available profiles.`\n );\n this.name = \"UnknownProfileError\";\n }\n}\n", "import { type Command } from \"commander\";\n\n/**\n * Pulls the global `--profile` option off the root command. Commander\n * merges parent options into `opts()` for subcommands, but the value\n * lives on the root \u2014 this helper walks up to find it regardless of how\n * deep the subcommand sits.\n */\nexport function getProfileFlag(command: Command): string | undefined {\n let node: Command | null = command;\n while (node) {\n const opts = node.opts<{ profile?: string }>();\n if (opts.profile) {\n return opts.profile;\n }\n\n node = node.parent ?? null;\n }\n\n return undefined;\n}\n", "import { type Command } from \"commander\";\n\nimport { resolveConfig, type ResolvedConfig } from \"@/config/resolve.js\";\nimport { AuthCliError } from \"@/errors.js\";\n\nimport { getProfileFlag } from \"./profile-flag.js\";\n\nexport type AuthenticatedConfig = ResolvedConfig & { apiKey: string };\n\n/**\n * Resolves the effective profile for this invocation and guarantees an\n * API key is present. Intended for every command that hits the API \u2014\n * throws `AuthCliError` (exit code 2) if no key is stored or passed via\n * env, so callers can assume `apiKey` is a non-null string.\n */\nexport async function requireAuthenticatedConfig(\n command: Command\n): Promise<AuthenticatedConfig> {\n const resolved = await resolveConfig({\n profileFlag: getProfileFlag(command),\n });\n if (!resolved.apiKey) {\n throw new AuthCliError(\n \"Not logged in. Run `duvo login` to sign in (or `duvo login --api-key <key>` to use an API key).\"\n );\n }\n\n return { ...resolved, apiKey: resolved.apiKey };\n}\n", "import { CliError } from \"@/errors.js\";\n\n/**\n * Trims a CLI flag value and rejects whitespace-only input. Returns the\n * trimmed string when valid, throws `CliError` otherwise. Use for any\n * required-when-passed flag (folder IDs, names, etc.) so we never send\n * an empty string to the API.\n */\nexport function trimRequired(value: string, flag: string): string {\n const trimmed = value.trim();\n if (trimmed.length === 0) {\n throw new CliError(`${flag} must not be empty`);\n }\n\n return trimmed;\n}\n", "import { type Command } from \"commander\";\n\nimport { folderResponseSchema } from \"@/api/agent-folder-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { trimRequired } from \"../shared/trim-required.js\";\n\ntype CreateOptions = {\n name: string;\n parent?: string;\n json?: boolean;\n};\n\ntype RequestBody = {\n name: string;\n parent_folder_id?: string;\n};\n\nexport function registerAgentFoldersCreate(folders: Command): void {\n folders\n .command(\"create\")\n .description(\"Create a new agent folder\")\n .requiredOption(\"--name <name>\", \"human-readable folder name\")\n .option(\n \"--parent <id>\",\n \"parent folder ID (omit to create at the root level)\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function createAction(this: Command, options: CreateOptions) {\n const name = trimRequired(options.name, \"--name\");\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const body: RequestBody = { name };\n if (options.parent !== undefined) {\n body.parent_folder_id = trimRequired(options.parent, \"--parent\");\n }\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/agent-folders\",\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = folderResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { folder } = parsed.data;\n\n console.log(green(\"Folder created!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: folder.id },\n { label: \"Name\", value: folder.name },\n { label: \"Parent\", value: folder.parent_folder_id ?? \"(root)\" },\n { label: \"Created\", value: folder.created_at ?? \"\" },\n ])\n );\n });\n}\n", "import { confirm, isCancel } from \"@clack/prompts\";\n\nimport { CancelCliError, CliError } from \"@/errors.js\";\n\ntype ConfirmOptions = {\n /** Question shown to the user, e.g. `Remove profile \"acme\"?`. */\n message: string;\n /** Caller already collected consent (e.g. via `--yes`). */\n skip: boolean;\n};\n\n/**\n * Prompt for [y/N] confirmation on a destructive action. Skipped when\n * the caller passes `skip: true` (typically from a `--yes` flag).\n *\n * In non-interactive shells (no TTY on stdin) we refuse rather than\n * silently treat piped input as consent. The caller must opt in via\n * `--yes` to proceed without a prompt.\n *\n * Throws instead of calling `process.exit` so the top-level error\n * handler remains the single chokepoint for process termination.\n */\nexport async function confirmDestructive(\n options: ConfirmOptions\n): Promise<void> {\n if (options.skip) {\n return;\n }\n\n if (!process.stdin.isTTY) {\n throw new CliError(\n `${options.message} Pass --yes to confirm without an interactive prompt.`\n );\n }\n\n const answer = await confirm({\n message: options.message,\n initialValue: false,\n });\n\n if (isCancel(answer) || !answer) {\n throw new CancelCliError();\n }\n}\n", "import { type Command } from \"commander\";\n\nimport { deleteFolderResponseSchema } from \"@/api/agent-folder-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { trimRequired } from \"../shared/trim-required.js\";\n\ntype DeleteOptions = {\n force?: boolean;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerAgentFoldersDelete(folders: Command): void {\n folders\n .command(\"delete <id>\")\n .description(\"Delete an agent folder\")\n .option(\n \"--force\",\n \"delete even if the folder contains assignments or subfolders (contained agents move to the root)\"\n )\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function deleteAction(\n this: Command,\n id: string,\n options: DeleteOptions\n ) {\n const folderId = trimRequired(id, \"<id>\");\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Delete folder \"${folderId}\"?`,\n skip: options.yes ?? false,\n });\n\n const searchParams = new URLSearchParams();\n if (options.force === true) {\n searchParams.append(\"force\", \"true\");\n }\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/agent-folders/${encodeURIComponent(folderId)}`,\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = deleteFolderResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n throw new CliError(`Failed to delete folder \"${folderId}\".`);\n }\n\n console.log(green(`Folder \"${folderId}\" deleted.`));\n });\n}\n", "import { shouldColor } from \"./should-color.js\";\n\nconst STYLE = \"\\x1b[4;90m\";\nconst RESET = \"\\x1b[0m\";\n\n/**\n * Style a column header (grey + underline). Wrap *after* padding \u2014\n * ANSI escape codes count toward `string.length` and would otherwise\n * misalign neighbouring columns.\n */\nexport function tableHeader(text: string): string {\n if (!shouldColor()) {\n return text;\n }\n\n return `${STYLE}${text}${RESET}`;\n}\n", "import { tableHeader } from \"./table-header.js\";\n\nexport type Column<T> = {\n header: string;\n cell: (row: T) => string;\n /**\n * Optional cap on the rendered width of the column. Cells wider than\n * this are truncated with a trailing `\u2026` to keep each row on one line.\n * The header is truncated too so the column never exceeds the cap.\n */\n maxWidth?: number;\n};\n\n/**\n * Renders a fixed-width ASCII table. Columns auto-size to the widest\n * cell (including the header) but never exceed `maxWidth` when set.\n * Headers are styled via `tableHeader` (cyan + underline) when stdout\n * is a TTY; in non-TTY contexts the styling is a no-op so piped output\n * stays clean.\n */\nexport function renderTable<T>(\n columns: readonly Column<T>[],\n rows: readonly T[]\n): string {\n if (columns.length === 0) {\n return \"\";\n }\n\n const cells = rows.map((row) => columns.map((col) => col.cell(row)));\n const widths = columns.map((col, i) => {\n const contentWidth = Math.max(\n col.header.length,\n ...cells.map((row) => row[i].length)\n );\n return col.maxWidth ? Math.min(col.maxWidth, contentWidth) : contentWidth;\n });\n\n const headerLine = columns\n .map((col, i) =>\n tableHeader(pad(truncate(col.header, widths[i]), widths[i]))\n )\n .join(\" \");\n const bodyLines = cells.map((row) =>\n row.map((cell, i) => pad(truncate(cell, widths[i]), widths[i])).join(\" \")\n );\n\n return [headerLine, ...bodyLines].join(\"\\n\");\n}\n\nfunction pad(value: string, width: number): string {\n if (value.length >= width) {\n return value;\n }\n\n return value + \" \".repeat(width - value.length);\n}\n\nfunction truncate(value: string, width: number): string {\n if (value.length <= width) {\n return value;\n }\n\n if (width <= 1) {\n return \"\u2026\".slice(0, width);\n }\n\n return `${value.slice(0, width - 1)}\u2026`;\n}\n", "import { type Command } from \"commander\";\n\nimport {\n listAgentFoldersResponseSchema,\n type PublicAgentFolder,\n} from \"@/api/agent-folder-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: PublicAgentFolder) => row.id },\n { header: \"NAME\", cell: (row: PublicAgentFolder) => row.name },\n {\n header: \"PARENT\",\n cell: (row: PublicAgentFolder) => row.parent_folder_id ?? \"(root)\",\n },\n {\n header: \"AGENTS\",\n cell: (row: PublicAgentFolder) =>\n row.agent_count === undefined || row.agent_count === null\n ? \"\"\n : String(row.agent_count),\n },\n {\n header: \"SUBFOLDERS\",\n cell: (row: PublicAgentFolder) =>\n row.subfolder_count === undefined || row.subfolder_count === null\n ? \"\"\n : String(row.subfolder_count),\n },\n] as const;\n\nexport function registerAgentFoldersList(folders: Command): void {\n folders\n .command(\"list\", { isDefault: true })\n .description(\"List all agent folders for your team\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/agent-folders\",\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listAgentFoldersResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.folders.length === 0) {\n console.log(\"No folders found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, parsed.data.folders));\n console.log(`Showing ${parsed.data.folders.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { moveAgentsResponseSchema } from \"@/api/agent-folder-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { trimRequired } from \"../shared/trim-required.js\";\n\ntype MoveAgentsOptions = {\n agent: readonly string[];\n folder?: string;\n toRoot?: boolean;\n json?: boolean;\n};\n\ntype RequestBody = {\n agent_ids: readonly string[];\n folder_id: string | null;\n};\n\nfunction collect(\n value: string,\n previous: readonly string[] = []\n): readonly string[] {\n return [...previous, value];\n}\n\nfunction resolveFolderId(options: MoveAgentsOptions): string | null {\n if (options.folder !== undefined && options.toRoot === true) {\n throw new CliError(\"Pass either --folder or --to-root, not both.\");\n }\n\n if (options.toRoot === true) {\n return null;\n }\n\n if (options.folder !== undefined) {\n return trimRequired(options.folder, \"--folder\");\n }\n\n throw new CliError(\n \"Provide --folder <id> to move agents into a folder, or --to-root to move them to the root level.\"\n );\n}\n\nexport function registerAgentFoldersMoveAgents(folders: Command): void {\n folders\n .command(\"move-agents\")\n .description(\"Move one or more agents into a folder, or to the root level\")\n .requiredOption(\n \"--agent <id>\",\n \"agent ID to move (repeat for multiple)\",\n collect,\n [] as readonly string[]\n )\n .option(\"--folder <id>\", \"destination folder ID\")\n .option(\"--to-root\", \"move the agents to the root level\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function moveAgentsAction(\n this: Command,\n options: MoveAgentsOptions\n ) {\n if (options.agent.length === 0) {\n throw new CliError(\"Provide at least one --agent <id>.\");\n }\n\n const agentIds = options.agent.map((id) => trimRequired(id, \"--agent\"));\n if (new Set(agentIds).size !== agentIds.length) {\n throw new CliError(\"--agent values must be unique.\");\n }\n\n const folderId = resolveFolderId(options);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const body: RequestBody = {\n agent_ids: agentIds,\n folder_id: folderId,\n };\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/agent-folders/move-agents\",\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = moveAgentsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n throw new CliError(\"Failed to move agents.\");\n }\n\n const target =\n folderId === null ? \"the root level\" : `folder ${folderId}`;\n console.log(\n green(`Moved ${parsed.data.moved_count} agent(s) to ${target}.`)\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { folderResponseSchema } from \"@/api/agent-folder-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { trimRequired } from \"../shared/trim-required.js\";\n\ntype UpdateOptions = {\n name?: string;\n parent?: string;\n moveToRoot?: boolean;\n json?: boolean;\n};\n\ntype RequestBody = {\n name?: string;\n parent_folder_id?: string | null;\n};\n\nfunction buildBody(options: UpdateOptions): RequestBody {\n const body: RequestBody = {};\n\n if (options.name !== undefined) {\n body.name = trimRequired(options.name, \"--name\");\n }\n\n if (options.parent !== undefined && options.moveToRoot === true) {\n throw new CliError(\"Pass either --parent or --move-to-root, not both.\");\n }\n\n if (options.parent !== undefined) {\n body.parent_folder_id = trimRequired(options.parent, \"--parent\");\n } else if (options.moveToRoot === true) {\n body.parent_folder_id = null;\n }\n\n if (Object.keys(body).length === 0) {\n throw new CliError(\n \"Provide at least one field to update (e.g. --name, --parent, --move-to-root).\"\n );\n }\n\n return body;\n}\n\nexport function registerAgentFoldersUpdate(folders: Command): void {\n folders\n .command(\"update <id>\")\n .description(\"Rename an agent folder or move it to a new parent\")\n .option(\"--name <name>\", \"new folder name\")\n .option(\"--parent <id>\", \"new parent folder ID\")\n .option(\"--move-to-root\", \"move the folder to the root level\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function updateAction(\n this: Command,\n id: string,\n options: UpdateOptions\n ) {\n const folderId = trimRequired(id, \"<id>\");\n const body = buildBody(options);\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"PATCH\",\n path: `/v1/agent-folders/${encodeURIComponent(folderId)}`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = folderResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { folder } = parsed.data;\n\n console.log(green(\"Folder updated!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: folder.id },\n { label: \"Name\", value: folder.name },\n { label: \"Parent\", value: folder.parent_folder_id ?? \"(root)\" },\n { label: \"Updated\", value: folder.updated_at ?? \"\" },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerAgentFoldersCreate } from \"./create.js\";\nimport { registerAgentFoldersDelete } from \"./delete.js\";\nimport { registerAgentFoldersList } from \"./list.js\";\nimport { registerAgentFoldersMoveAgents } from \"./move-agents.js\";\nimport { registerAgentFoldersUpdate } from \"./update.js\";\n\nexport function registerAgentFolders(program: Command): void {\n const folders = program\n .command(\"agent-folders\")\n .description(\"Manage agent folders in the Duvo public API\");\n\n registerAgentFoldersList(folders);\n registerAgentFoldersCreate(folders);\n registerAgentFoldersUpdate(folders);\n registerAgentFoldersDelete(folders);\n registerAgentFoldersMoveAgents(folders);\n}\n", "import { readFile } from \"node:fs/promises\";\n\nimport { confirm, isCancel, text } from \"@clack/prompts\";\nimport { AGENT_CONFIG_VERSION, DEFAULT_AGENT_CONFIG } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport {\n type BuildConfig,\n buildConfigSchema,\n createAgentResponseSchema,\n DEFAULT_BUILD_CONFIG,\n DEFAULT_BUILD_NAME,\n DEFAULT_NEW_AGENT_NAME,\n} from \"@/api/agent-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CancelCliError, CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype CreateOptions = {\n name?: string;\n config?: string;\n input?: string;\n build?: boolean;\n json?: boolean;\n};\n\ntype BuildBody = {\n name: string;\n config: BuildConfig;\n};\n\nexport function registerAgentsCreate(agents: Command): void {\n agents\n .command(\"create\")\n .description(\"Create a new agent\")\n .option(\"--name <name>\", \"human-readable agent name\")\n .option(\n \"--input <text>\",\n \"initial agent instructions (merged into the default build config)\"\n )\n .option(\n \"--config <path>\",\n \"path to a JSON file with the full build config (overrides --input)\"\n )\n .option(\"--no-build\", \"create the agent without an initial build\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function createAction(this: Command, options: CreateOptions) {\n const resolved = await requireAuthenticatedConfig(this);\n\n const name = await resolveName(options.name);\n\n const body: { name: string; build?: BuildBody } = { name };\n if (options.build !== false) {\n const config = await resolveBuildConfig(options);\n if (config) {\n body.build = {\n name: DEFAULT_BUILD_NAME,\n config,\n };\n }\n }\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/agents\",\n apiKey: resolved.apiKey,\n apiBaseUrl: resolved.apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = createAgentResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { agent, build } = parsed.data;\n\n const entries = [\n { label: \"ID\", value: agent.id },\n { label: \"Name\", value: agent.name },\n { label: \"Created\", value: agent.created_at ?? \"\" },\n ];\n if (build) {\n entries.push({ label: \"Build\", value: `${build.id} (${build.name})` });\n }\n\n console.log(green(\"Agent created!\"));\n console.log();\n console.log(renderKeyValue(entries));\n });\n}\n\nfunction isInteractiveTerminal(): boolean {\n return process.stdin.isTTY === true && process.stdout.isTTY === true;\n}\n\nasync function resolveName(flag: string | undefined): Promise<string> {\n if (flag !== undefined) {\n const trimmed = flag.trim();\n if (trimmed.length === 0) {\n throw new CliError(\"--name must not be empty\");\n }\n\n return trimmed;\n }\n\n if (!isInteractiveTerminal()) {\n return DEFAULT_NEW_AGENT_NAME;\n }\n\n const answer = await text({\n message: \"Agent name\",\n placeholder: DEFAULT_NEW_AGENT_NAME,\n defaultValue: DEFAULT_NEW_AGENT_NAME,\n validate: (value) => {\n if (value && value.trim().length === 0) {\n return \"Agent name must not be blank.\";\n }\n\n return undefined;\n },\n });\n if (isCancel(answer)) {\n throw new CancelCliError(\"Create cancelled.\");\n }\n\n const trimmed = answer.trim();\n return trimmed.length === 0 ? DEFAULT_NEW_AGENT_NAME : trimmed;\n}\n\nasync function resolveBuildConfig(\n options: Pick<CreateOptions, \"config\" | \"input\">\n): Promise<BuildConfig | undefined> {\n if (options.config !== undefined) {\n const trimmed = options.config.trim();\n if (trimmed.length === 0) {\n throw new CliError(\"--config must be a non-empty file path\");\n }\n\n return readConfigFromFile(trimmed);\n }\n\n if (options.input !== undefined) {\n return buildConfigWithInput(options.input);\n }\n\n if (!isInteractiveTerminal()) {\n return DEFAULT_BUILD_CONFIG;\n }\n\n const hasCustomConfig = await confirm({\n message: \"Do you have your own build config?\",\n initialValue: false,\n });\n if (isCancel(hasCustomConfig)) {\n throw new CancelCliError(\"Create cancelled.\");\n }\n\n if (hasCustomConfig) {\n const path = await text({\n message: \"Path to build config JSON\",\n validate: (value) => {\n if (!value || value.trim().length === 0) {\n return \"A file path is required.\";\n }\n\n return undefined;\n },\n });\n if (isCancel(path)) {\n throw new CancelCliError(\"Create cancelled.\");\n }\n\n return readConfigFromFile(path.trim());\n }\n\n const input = await text({\n message: \"Initial instructions for the agent (leave empty for the default)\",\n defaultValue: \"\",\n });\n if (isCancel(input)) {\n throw new CancelCliError(\"Create cancelled.\");\n }\n\n const trimmed = input.trim();\n if (trimmed.length === 0) {\n return DEFAULT_BUILD_CONFIG;\n }\n\n return buildConfigWithInput(trimmed);\n}\n\nfunction buildConfigWithInput(input: string): BuildConfig {\n const trimmed = input.trim();\n if (trimmed.length === 0) {\n return DEFAULT_BUILD_CONFIG;\n }\n\n return {\n version: AGENT_CONFIG_VERSION,\n data: {\n ...DEFAULT_AGENT_CONFIG,\n input: [\n {\n role: \"system\",\n content: [{ type: \"input_text\", text: trimmed }],\n },\n ],\n },\n };\n}\n\nasync function readConfigFromFile(path: string): Promise<BuildConfig> {\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Could not read config file \"${path}\": ${message}`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Config file \"${path}\" is not valid JSON: ${message}`);\n }\n\n const result = buildConfigSchema.safeParse(parsed);\n if (!result.success) {\n throw new CliError(\n `Config file \"${path}\" does not match expected build config shape (version \"${AGENT_CONFIG_VERSION}\"): ${result.error.message}`\n );\n }\n\n return result.data;\n}\n", "export const ANALYTICS_EVENTS = [\n \"agent_builder_ai_config_edit_failed\",\n \"agent_builder_ai_config_edit_started\",\n \"agent_builder_ai_config_edit_succeeded\",\n \"agent_builder_generate_clicked\",\n \"agent_builder_start_from_scratch_clicked\",\n \"agent_builder_build_config_completed\",\n \"agent_builder_build_config_failed\",\n \"agent_builder_file_removed\",\n \"agent_builder_files_updated\",\n \"agent_builder_instructions_edited\",\n \"agent_builder_instructions_updated\",\n \"agent_builder_skill_removed\",\n \"agent_builder_skills_updated\",\n \"agent_builder_loaded\",\n \"agent_builder_memory_saved\",\n \"agent_builder_memory_toggled\",\n \"agent_builder_model_changed\",\n \"agent_builder_model_selector_expanded\",\n \"opus46_tooltip_dismissed\",\n \"opus46_tooltip_shown\",\n \"agent_builder_name_updated\",\n \"agent_builder_plugin_added\",\n \"agent_builder_plugin_removed\",\n \"agent_builder_sub_assignment_added\",\n \"agent_builder_sub_assignment_removed\",\n \"agent_builder_prompt_starter_clicked\",\n \"agent_builder_prompt_submitted\",\n \"agent_builder_voice_prompt_started\",\n \"agent_builder_voice_prompt_submitted\",\n \"agent_builder_voice_prompt_failed\",\n \"agent_builder_voice_prompt_cancelled\",\n \"agent_builder_slack_toggle_failed\",\n \"agent_builder_slack_toggled\",\n \"agent_case_trigger_updated\",\n \"agent_builder_tab_changed\",\n \"agent_builder_tool_actions_updated\",\n \"agent_builder_tool_added\",\n \"agent_builder_tool_removed\",\n \"agent_builder_tools_batch_updated\",\n \"agent_builder_new_revision_created\",\n \"agent_builder_revision_changed\",\n \"agent_builder_browsing_model_changed\",\n \"agent_builder_sop_login_hint_dismissed\",\n \"agent_builder_sop_login_hint_add_clicked\",\n \"agent_builder_sop_login_hint_shown\",\n \"agent_builder_sop_team_member_mentioned\",\n \"agent_builder_sop_mention_copied\",\n \"agent_builder_sop_mention_cut\",\n \"agent_builder_sop_mention_pasted\",\n \"agent_builder_build_promoted\",\n \"agent_builder_draft_accepted\",\n \"agent_builder_draft_declined\",\n \"agent_builder_draft_deleted\",\n \"agent_browser_preview_minimized\",\n \"agent_browser_preview_shown\",\n \"agent_desktop_preview_expanded\",\n \"agent_desktop_preview_minimized\",\n \"agent_desktop_preview_shown\",\n \"agent_chat_collapsed\",\n \"agent_chat_expanded\",\n \"agent_connection_removed\",\n \"agent_created\",\n \"agent_created_from_template\",\n \"agent_duplicated\",\n \"agent_created_on_signup\",\n \"agent_evaluate_run\",\n \"agent_execution_completed\",\n \"agent_execution_failed\",\n \"agent_execution_files_attached\",\n \"agent_execution_file_removed\",\n \"agent_execution_interrupted\",\n \"agent_execution_message_received\",\n \"agent_execution_processing_failed\",\n \"agent_execution_reset\",\n \"agent_execution_rerun\",\n \"agent_execution_started\",\n \"agent_test_clicked\",\n \"agent_test_generate_assignment_clicked\",\n \"agent_test_with_trigger_message\",\n \"agent_builder_test_case_selected\",\n \"agent_feedback_submitted\",\n \"agent_follow_up_started\",\n \"agent_builder_follow_up_questions_shown\",\n \"agent_builder_follow_up_questions_submitted\",\n \"agent_handover_approved\",\n \"agent_handover_pending_approval\",\n \"agent_handover_rejected\",\n \"agent_learn_from_run\",\n \"agent_run_detail_access_denied\",\n \"agent_run_detail_failed\",\n \"agent_run_detail_loaded\",\n \"agent_run_detail_missing\",\n \"agent_run_detail_integration_instances_loaded\",\n \"agent_run_selected\",\n \"agent_runs_list_failed\",\n \"agent_runs_list_loaded\",\n \"agent_schedule_due\",\n \"agent_schedule_load_failed\",\n \"agent_schedule_loaded\",\n \"agent_schedule_modal_opened\",\n \"agent_schedule_nl_convert_failed\",\n \"agent_schedule_nl_converted\",\n \"agent_schedule_run_created\",\n \"agent_schedule_run_skipped\",\n \"agent_schedule_saved\",\n \"agent_schedule_suggestion_accepted\",\n \"agent_schedule_suggestion_dismissed\",\n \"agent_schedule_update_failed\",\n \"agent_schedule_updated\",\n \"agent_schedule_deleted\",\n \"agent_schedule_added_from_modal\",\n \"agent_trigger_modal_opened\",\n \"agent_template_selected\",\n \"agent_template_used\",\n \"auth_error_viewed\",\n \"auth_login_attempt\",\n \"auth_login_post_check\",\n \"auth_login_result\",\n \"auth_logout\",\n \"auth_password_change_attempt\",\n \"auth_password_change_result\",\n \"auth_password_reset_requested\",\n \"auth_password_reset_result\",\n \"auth_provider_clicked\",\n \"auth_provider_result\",\n \"auth_signup_attempt\",\n \"auth_signup_result\",\n \"billing_checkout_created\",\n \"billing_checkout_failed\",\n \"billing_free_subscription_created\",\n \"billing_details_viewed\",\n \"billing_manage_subscription_clicked\",\n \"billing_subscribe_initiated\",\n \"billing_subscribe_failed\",\n \"billing_subscribe_redirected\",\n \"billing_subscription_created\",\n \"billing_subscription_updated\",\n \"billing_subscription_deleted\",\n \"billing_trial_will_end\",\n \"billing_upgrade_section_viewed\",\n \"clarity_capture_deleted\",\n \"clarity_capture_resumed\",\n \"clarity_captures_sheet_opened\",\n \"clarity_capture_viewed\",\n \"clarity_extra_capture_request_assigned\",\n \"clarity_extra_capture_request_unassigned\",\n \"clarity_contributors_updated\",\n \"clarity_create_assignment_clicked\",\n \"clarity_process_created\",\n \"clarity_process_deleted\",\n \"clarity_process_duplicated\",\n \"clarity_process_name_suggestion_clicked\",\n \"clarity_process_generate_completed\",\n \"clarity_process_generate_failed\",\n \"clarity_process_generate_started\",\n \"clarity_process_interview_paused\",\n \"clarity_process_interview_resumed\",\n \"clarity_process_interview_save_failed\",\n \"clarity_process_interview_saved\",\n \"clarity_process_interview_started\",\n \"clarity_process_interview_stopped\",\n \"clarity_process_interview_transcript_downloaded\",\n \"clarity_process_diagram_downloaded\",\n \"clarity_process_custom_prompt_saved\",\n \"clarity_process_phone_interview_initiated\",\n \"clarity_process_phone_interview_completed\",\n \"clarity_process_phone_interview_failed\",\n \"clarity_process_marked_complete\",\n \"clarity_process_renamed\",\n \"admin_clarity_analysis_edit_started\",\n \"admin_clarity_analysis_copied\",\n \"admin_clarity_analysis_overwritten\",\n \"admin_clarity_analysis_overwrite_failed\",\n \"admin_clarity_v2_json_viewer_clear_search\",\n \"admin_clarity_v2_json_viewer_collapse_all\",\n \"admin_clarity_v2_json_viewer_expand_all\",\n \"admin_clarity_v2_json_viewer_search\",\n \"admin_clarity_v2_json_viewer_toggle_path\",\n \"admin_clarity_v2_snapshot_cancel_edit\",\n \"admin_clarity_v2_snapshot_copied\",\n \"admin_clarity_v2_snapshot_save_initiated\",\n \"admin_clarity_v2_snapshot_save_succeeded\",\n \"admin_clarity_v2_snapshot_start_edit\",\n \"clarity_process_video_analysis_completed\",\n \"clarity_process_video_analysis_failed\",\n \"clarity_process_video_analysis_started\",\n \"clarity_process_video_removed\",\n \"clarity_process_video_selected\",\n \"clarity_process_video_upload_completed\",\n \"clarity_process_video_upload_failed\",\n \"clarity_process_video_upload_started\",\n \"clarity_process_document_removed\",\n \"clarity_process_document_selected\",\n \"clarity_process_document_upload_completed\",\n \"clarity_process_document_upload_failed\",\n \"clarity_process_document_upload_started\",\n \"clarity_team_settings_updated\",\n \"clarity_transformation_guidance_cloned\",\n \"clarity_transformation_guidance_clone_failed\",\n \"clarity_transformation_guidance_saved\",\n \"clarity_transformation_guidance_save_failed\",\n \"clarity_transformation_regenerate_started\",\n \"clarity_transformation_regenerate_failed\",\n \"clarity_transformation_regenerate_finished\",\n \"clarity_transformation_proposal_viewed\",\n \"clarity_transformation_proposal_accepted\",\n \"clarity_transformation_proposal_rejected\",\n \"clarity_session_created\",\n \"clarity_v2_current_process_saved\",\n \"clarity_v2_transformation_proposal_saved\",\n \"clarity_v2_current_process_promoted\",\n \"clarity_v2_transformation_proposal_promoted\",\n \"clarity_v2_session_created\",\n \"clarity_v2_session_completed\",\n \"clarity_v2_director_decision\",\n \"clarity_v2_doc_generated\",\n \"clarity_v2_onboarding_shown\",\n \"clarity_v2_onboarding_dismissed\",\n \"clarity_v2_onboarding_replayed\",\n \"clarity_v2_mic_muted\",\n \"clarity_v2_mic_unmuted\",\n \"clarity_v2_session_resumed\",\n \"clarity_v2_language_selected\",\n \"clarity_v2_pip_opened\",\n \"clarity_v2_pip_closed\",\n \"clarity_v2_edit_mode_entered\",\n \"clarity_v2_edit_history_redone\",\n \"clarity_v2_edit_history_undone\",\n \"clarity_v2_connection_failure_shown\",\n \"clarity_v2_gateway_default_edge_set\",\n \"clarity_v2_graph_validation_node_focused\",\n \"clarity_v2_graph_validation_panel_closed\",\n \"clarity_v2_node_created_from_edge\",\n \"clarity_v2_nodes_deleted\",\n \"clarity_v2_upgrade_started\",\n \"clarity_v2_upgrade_succeeded\",\n \"clarity_v2_upgrade_failed\",\n \"clarity_video_removed\",\n \"clarity_video_selected\",\n \"clarity_video_upload_completed\",\n \"clarity_video_upload_failed\",\n \"clarity_video_upload_started\",\n \"clarity_voice_interview_started\",\n \"clarity_voice_interview_stopped\",\n \"clarity_voice_transcript_saved\",\n \"clarity_process_share_link_copied\",\n \"clarity_process_sharing_disabled\",\n \"clarity_process_sharing_enabled\",\n \"clarity_ontology_extraction_started\",\n \"clarity_ontology_extraction_completed\",\n \"clarity_ontology_extraction_failed\",\n \"clarity_ontology_merge_completed\",\n \"clarity_ontology_merge_failed\",\n \"clarity_portfolio_intelligence_started\",\n \"clarity_portfolio_intelligence_completed\",\n \"clarity_portfolio_intelligence_failed\",\n \"clarity_portfolio_intelligence_viewed\",\n \"clarity_portfolio_message_sent\",\n \"clarity_library_filter_changed\",\n \"clarity_library_sort_changed\",\n \"clarity_overview_created\",\n \"clarity_overview_deleted\",\n \"browser_login_attached_to_build\",\n \"browser_login_detached_from_build\",\n \"credential_attached_to_build\",\n \"credential_copied\",\n \"credential_created\",\n \"credential_create_failed\",\n \"credential_deleted\",\n \"credential_delete_failed\",\n \"credential_detached_from_build\",\n \"credential_edit_clicked\",\n \"credential_import_failed\",\n \"credential_import_succeeded\",\n \"credential_shared_with_team\",\n \"credential_updated\",\n \"credential_update_failed\",\n \"credential_viewed\",\n \"human_in_loop_bulk_delete_all\",\n \"human_in_loop_bulk_delete_responded\",\n \"human_in_loop_bulk_mark_responded\",\n \"human_in_loop_request_deleted\",\n \"human_in_loop_request_responded\",\n \"human_in_loop_request_responded_structured\",\n \"human_in_loop_request_responded_via_slack\",\n \"human_in_loop_request_responded_via_slack_dm\",\n \"human_in_loop_request_selected\",\n \"human_in_loop_run_failed\",\n \"human_in_loop_run_loaded\",\n \"human_in_loop_tab_changed\",\n \"human_in_loop_viewed\",\n \"impersonation_executed\",\n \"impersonation_execute_failed\",\n \"custom_connection_create_failed\",\n \"custom_connection_create_requested\",\n \"custom_connection_create_succeeded\",\n \"custom_connection_delete_failed\",\n \"custom_connection_delete_requested\",\n \"custom_connection_delete_succeeded\",\n \"custom_connection_instance_modal_opened\",\n \"custom_connection_oauth_initiated\",\n \"integration_connect_failed\",\n \"integration_connect_requested\",\n \"integration_connect_succeeded\",\n \"integration_connected\",\n \"integration_disconnected\",\n \"integration_latency\",\n \"integration_beta_access_requested\",\n \"integration_requested\",\n \"integration_update_failed\",\n \"integration_update_requested\",\n \"integration_update_succeeded\",\n \"integrations_custom_mcp_modal_opened\",\n \"integrations_mcp_test_failed\",\n \"integrations_mcp_test_started\",\n \"integrations_mcp_test_succeeded\",\n \"integrations_search_updated\",\n \"integrations_tab_changed\",\n \"team_files_file_delete_failed\",\n \"team_files_file_deleted\",\n \"team_files_file_downloaded\",\n \"team_files_file_dropped\",\n \"team_files_file_rename_failed\",\n \"team_files_file_renamed\",\n \"team_files_file_upload_failed\",\n \"team_files_file_uploaded\",\n \"team_files_files_list_failed\",\n \"team_files_files_listed\",\n \"team_files_search_changed\",\n \"team_files_sort_changed\",\n \"team_files_upload_button_clicked\",\n \"team_files_upload_completed\",\n \"team_files_upload_dialog_opened\",\n \"team_files_upload_file_removed\",\n \"team_files_upload_files_added\",\n \"team_files_upload_results_cleared\",\n \"team_files_upload_started\",\n \"team_files_viewed\",\n \"onboarding_connection_connect_clicked\",\n \"onboarding_connections_completed\",\n \"onboarding_connections_viewed\",\n \"onboarding_org_created_from_discovery\",\n \"onboarding_org_join_requested\",\n \"onboarding_org_setup_completed\",\n \"organization_discovery_banner_dismissed\",\n \"organization_discovery_join_requested\",\n \"organization_logo_removed\",\n \"organization_logo_remove_failed\",\n \"organization_logo_uploaded\",\n \"organization_logo_upload_failed\",\n \"onboarding_plans_success\",\n \"onboarding_plans_viewed\",\n \"onboarding_team_name_entered\",\n \"onboarding_team_name_submitted\",\n \"onboarding_team_name_viewed\",\n \"onboarding_welcome_get_started_clicked\",\n \"onboarding_welcome_viewed\",\n \"profile_email_digest_disabled\",\n \"profile_email_digest_enabled\",\n \"profile_email_digest_time_updated\",\n \"profile_name_updated\",\n \"profile_teams_notifications_enabled\",\n \"profile_teams_notifications_disabled\",\n \"profile_eval_notifications_enabled\",\n \"profile_eval_notifications_disabled\",\n \"process_analysis_cancel_failed\",\n \"process_analysis_cancel_requested\",\n \"process_analysis_create_requested\",\n \"process_analysis_detail_viewed\",\n \"process_analysis_execution_completed\",\n \"process_analysis_execution_error\",\n \"process_analysis_execution_failed\",\n \"process_analysis_execution_fetch_failed\",\n \"process_analysis_execution_started\",\n \"process_analysis_list_refresh_failed\",\n \"process_analysis_list_refreshed\",\n \"process_analysis_list_viewed\",\n \"process_analysis_mining_failed\",\n \"process_analysis_mining_started\",\n \"process_analysis_selected\",\n \"process_analysis_stream_completed\",\n \"process_analysis_stream_error\",\n \"process_analysis_stream_opened\",\n \"skill_editor_opened\",\n \"skill_viewer_opened\",\n \"skill_file_save_completed\",\n \"skill_file_save_started\",\n \"skill_file_save_confirmed\",\n \"skill_file_save_cancelled\",\n \"skill_browser_opened\",\n \"skill_recording_completed\",\n \"skill_recording_error\",\n \"skill_recording_no_events\",\n \"skill_recording_started\",\n \"skill_recording_stopped\",\n \"skill_upload_completed\",\n \"skill_create_completed\",\n \"skill_create_started\",\n \"skill_creator_opened\",\n \"skill_ai_generate_started\",\n \"skill_ai_generate_completed\",\n \"skill_upload_dialog_opened\",\n \"skill_upload_file_added\",\n \"skill_upload_started\",\n \"file_editor_opened\",\n \"file_save_completed\",\n \"file_save_started\",\n \"slack_user_connect_clicked\",\n \"slack_user_unlink_failed\",\n \"slack_user_unlinked\",\n \"solution_request_failed\",\n \"solution_request_opened\",\n \"solution_request_submitted\",\n \"solution_selected\",\n \"custom_solution_request_failed\",\n \"custom_solution_request_opened\",\n \"custom_solution_request_submitted\",\n \"team_created\",\n \"team_deleted\",\n \"team_switched\",\n \"team_member_invite_deleted\",\n \"team_member_invite_failed\",\n \"team_member_invite_resent\",\n \"team_member_invited\",\n \"team_invite_role_updated\",\n \"team_members_bulk_invited\",\n \"team_members_bulk_invite_failed\",\n \"team_member_removed\",\n \"team_member_role_updated\",\n \"team_logo_removed\",\n \"team_logo_remove_failed\",\n \"team_logo_uploaded\",\n \"team_logo_upload_failed\",\n \"team_access_mode_updated\",\n \"team_browser_location_override_updated\",\n \"team_join_request_approved\",\n \"team_join_request_denied\",\n \"org_team_join_request_approved\",\n \"org_team_join_request_denied\",\n \"team_name_update_failed\",\n \"team_name_updated\",\n \"team_settings_cancel_edit\",\n \"team_settings_viewed\",\n \"team_invitation_created\",\n \"team_invitation_accepted\",\n \"team_invitation_accept_failed\",\n \"team_invitation_declined\",\n \"team_invitation_decline_failed\",\n \"team_invitation_email_sent\",\n \"team_invitation_email_failed\",\n \"team_invite_link_copied\",\n \"team_invite_link_created\",\n \"team_invite_link_deleted\",\n \"team_invite_link_regenerated\",\n \"organization_invitation_created\",\n \"organization_invitation_accepted\",\n \"organization_invitation_declined\",\n \"organization_invitation_email_sent\",\n \"organization_invitation_email_failed\",\n \"organization_invitation_copied\",\n \"organization_invite_link_accepted\",\n \"organization_invite_link_copied\",\n \"organization_invite_link_created\",\n \"organization_invite_link_deleted\",\n \"organization_invite_link_regenerated\",\n \"organization_member_role_updated\",\n \"organization_members_searched\",\n \"organization_members_page_changed\",\n \"admin_org_member_added\",\n \"team_bulk_invite_completed\",\n \"team_bulk_invite_failed\",\n \"settings_section_viewed\",\n \"team_slack_add_button_clicked\",\n \"team_slack_install_clicked\",\n \"team_slack_install_completed\",\n \"team_slack_install_failed\",\n \"team_slack_install_started\",\n \"team_slack_organization_disconnect_failed\",\n \"team_slack_organization_disconnected\",\n \"team_slack_settings_modal_opened\",\n \"team_slack_settings_save_failed\",\n \"team_slack_settings_saved\",\n \"team_ms_teams_install_clicked\",\n \"team_ms_teams_connect_clicked\",\n \"team_ms_teams_organization_disconnected\",\n \"team_ms_teams_settings_saved\",\n \"ms_teams_user_unlinked\",\n \"case_list_viewed\",\n \"case_list_filtered\",\n \"case_filter_applied\",\n \"case_filter_removed\",\n \"case_list_searched\",\n \"case_list_sorted\",\n \"case_detail_viewed\",\n \"case_job_opened\",\n \"case_job_assignment_opened\",\n \"case_job_hitl_respond_clicked\",\n \"case_stats_loaded\",\n \"case_created\",\n \"case_deleted\",\n \"case_retried\",\n \"case_delegated\",\n \"case_status_updated\",\n \"case_needs_input_badge_clicked\",\n \"case_awaiting_approval_badge_clicked\",\n \"case_approval_responded\",\n \"case_approval_resolved\",\n \"cases_bulk_deleted\",\n \"cases_bulk_retried\",\n \"cases_bulk_delegated\",\n \"cases_bulk_status_updated\",\n \"case_queue_cleared\",\n \"case_queue_created\",\n \"case_queue_deleted\",\n \"case_queue_exported\",\n \"case_queue_imported\",\n \"case_queue_description_updated\",\n \"case_queue_moved\",\n \"case_queue_renamed\",\n \"case_queue_switched\",\n \"case_queue_stats_period_changed\",\n \"case_attribute_assigned\",\n \"case_attribute_unassigned\",\n \"case_attribute_created\",\n \"case_attribute_deleted\",\n \"case_attribute_renamed\",\n \"case_attribute_color_changed\",\n \"case_attribute_values_updated\",\n \"case_label_assigned\",\n \"case_label_unassigned\",\n \"case_label_created\",\n \"case_label_deleted\",\n \"case_label_renamed\",\n \"workflow_builder_plan_started\",\n \"workflow_builder_refinement_submitted\",\n \"job_list_viewed\",\n \"job_list_filtered\",\n \"job_list_searched\",\n \"job_list_sorted\",\n \"clarity_overview_capture_deleted\",\n \"clarity_overview_capture_viewed\",\n \"clarity_overview_document_removed\",\n \"clarity_overview_document_selected\",\n \"clarity_overview_document_upload_completed\",\n \"clarity_overview_document_upload_failed\",\n \"clarity_overview_document_upload_started\",\n \"clarity_overview_filter_applied\",\n \"clarity_overview_filter_cleared\",\n \"clarity_overview_generate_failed\",\n \"clarity_overview_generate_started\",\n \"clarity_overview_interview_paused\",\n \"clarity_overview_interview_resumed\",\n \"clarity_overview_interview_save_failed\",\n \"clarity_overview_interview_saved\",\n \"clarity_overview_interview_started\",\n \"clarity_overview_interview_stopped\",\n \"clarity_overview_interview_transcript_downloaded\",\n \"clarity_overview_process_selected\",\n \"clarity_overview_video_analysis_completed\",\n \"clarity_overview_video_analysis_failed\",\n \"clarity_overview_video_analysis_started\",\n \"clarity_overview_video_removed\",\n \"clarity_overview_video_selected\",\n \"clarity_overview_video_upload_completed\",\n \"clarity_overview_video_upload_failed\",\n \"clarity_overview_video_upload_started\",\n \"clarity_automation_created\",\n \"clarity_automation_agent_assigned\",\n \"clarity_automation_activated\",\n \"clarity_automation_run_started\",\n \"clarity_automation_run_completed\",\n \"clarity_automation_run_failed\",\n \"clarity_flow_version_created\",\n \"clarity_flow_version_edited\",\n \"clarity_flow_version_compared\",\n \"linear_trigger_enabled\",\n \"linear_trigger_disabled\",\n \"linear_trigger_updated\",\n \"slack_mention_trigger_disabled\",\n \"slack_mention_trigger_enabled\",\n \"slack_trigger_created\",\n \"slack_trigger_deleted\",\n \"slack_trigger_fired\",\n \"slack_trigger_updated\",\n \"teams_mention_trigger_disabled\",\n \"teams_mention_trigger_enabled\",\n \"job_issue_alerts_toggled\",\n \"job_issue_alerts_rubrics_changed\",\n \"job_issue_alert_email_sent\",\n \"assignment_list_sorted\",\n \"oauth_login_started\",\n \"oauth_login_completed\",\n \"oauth_login_failed\",\n \"oauth_logout_completed\",\n \"oauth_mcp_authorized\",\n \"oauth_authentication_failed\",\n \"folder_moved\",\n] as const;\n\nexport type AnalyticsEventName = (typeof ANALYTICS_EVENTS)[number];\n", "import { z } from \"zod\";\n\nexport const customerPortalResponseSchema = z.object({\n url: z.string(),\n});\n\nexport type CustomerPortalResponse = z.infer<\n typeof customerPortalResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport { BasePlan, PlanFeature, RunCountingMode } from \"./plan-versions\";\n\n/**\n * Resource types that have plan limits\n */\nexport type LimitedResource = \"assignment\" | \"agent_run\";\n\n/**\n * Result of checking if a resource can be created\n */\nexport interface CanCreateResult {\n allowed: boolean;\n current: number;\n limit: number | \"unlimited\";\n upgradeRequired: boolean;\n}\n\n/**\n * All entitlements for a team\n */\nexport interface PlanEntitlements {\n planVersionId: string;\n planName: string;\n basePlan: BasePlan;\n features: readonly PlanFeature[];\n limits: {\n maxAgents: number | \"unlimited\";\n maxAgentRunsPerMonth: number | \"unlimited\";\n runCountingMode: RunCountingMode;\n };\n usage: {\n currentAssignments: number;\n currentMonthAgentRuns: number;\n };\n subscription: {\n status: \"active\" | \"trialing\" | \"canceled\" | \"past_due\";\n trialEndsAt: Date | null;\n currentPeriodEnd: Date | null;\n };\n canCreateTeams: boolean;\n}\n\n/**\n * EntitlementService API\n */\nexport interface EntitlementService {\n hasFeature(teamId: string, feature: PlanFeature): Promise<boolean>;\n getLimit(\n teamId: string,\n limit: \"maxAgents\" | \"maxAgentRunsPerMonth\"\n ): Promise<number | \"unlimited\">;\n canCreate(\n teamId: string,\n resource: LimitedResource\n ): Promise<CanCreateResult>;\n getTeamEntitlements(teamId: string): Promise<PlanEntitlements>;\n}\n\nconst limitSchema = z.union([z.number(), z.literal(\"unlimited\")]);\n\nexport const entitlementsResponseSchema = z.object({\n planVersionId: z.string(),\n planName: z.string(),\n basePlan: z.enum([\"free\", \"pro\", \"enterprise\"]),\n features: z.array(z.string()),\n limits: z.object({\n maxAgents: limitSchema,\n maxAgentRunsPerMonth: limitSchema,\n runCountingMode: z.enum([\"monthly\", \"lifetime\"]),\n }),\n usage: z.object({\n currentAssignments: z.number(),\n currentMonthAgentRuns: z.number(),\n }),\n subscription: z.object({\n status: z.enum([\"active\", \"trialing\", \"canceled\", \"past_due\"]),\n trialEndsAt: z.coerce.date().nullable(),\n currentPeriodEnd: z.coerce.date().nullable(),\n }),\n canCreateTeams: z.boolean(),\n});\n\nexport type EntitlementsResponse = z.infer<typeof entitlementsResponseSchema>;\n", "import { z } from \"zod\";\n\nexport const invoiceSchema = z.object({\n id: z.string(),\n number: z.string().nullable(),\n status: z.enum([\"draft\", \"open\", \"paid\", \"uncollectible\", \"void\"]),\n amountDue: z.number(),\n amountPaid: z.number(),\n currency: z.string(),\n createdAt: z.string(),\n paidAt: z.string().nullable(),\n hostedInvoiceUrl: z.string().nullable(),\n invoicePdf: z.string().nullable(),\n});\n\nexport type Invoice = z.infer<typeof invoiceSchema>;\n\nexport const invoicesResponseSchema = z.object({\n invoices: z.array(invoiceSchema),\n hasMore: z.boolean(),\n nextCursor: z.string().nullable(),\n});\n\nexport type InvoicesResponse = z.infer<typeof invoicesResponseSchema>;\n", "/**\n * Plan features that can be enabled per plan\n */\nexport const PLAN_FEATURE = {\n API_ACCESS: \"api_access\",\n BROWSER_AUTOMATION: \"browser_automation\",\n ADVANCED_INTEGRATIONS: \"advanced_integrations\",\n CUSTOM_MCP_SERVERS: \"custom_mcp_servers\",\n CASE_QUEUE: \"case_queue\",\n CLARITY: \"clarity\",\n CLARITY_OVERVIEW: \"clarity_overview\",\n SSO: \"sso\",\n AUDIT_LOGS: \"audit_logs\",\n PRIORITY_SUPPORT: \"priority_support\",\n CAN_CREATE_TEAMS: \"can_create_teams\",\n LEARNINGS: \"learnings\",\n BROWSING_SKILL_RECORDING: \"browsing_skill_recording\",\n WORKFLOW_BUILDER: \"workflow_builder\",\n AGENTIC_MEMORY: \"agentic_memory\",\n} as const;\n\nexport type PlanFeature = (typeof PLAN_FEATURE)[keyof typeof PLAN_FEATURE];\n\n/**\n * Base plan types\n */\nexport type BasePlan = \"pro\" | \"enterprise\" | \"free\";\n\n/**\n * How agent runs are counted against plan limits\n * - \"monthly\": Resets each billing period (default for paid plans)\n * - \"lifetime\": Counts all runs ever, never resets (used for free tier)\n */\nexport type RunCountingMode = \"monthly\" | \"lifetime\";\n\n/**\n * Plan version definition\n */\nexport interface PlanVersionDefinition {\n /** Display name for the plan */\n name: string;\n /** Base plan slug */\n basePlan: BasePlan;\n /** Maximum number of agents */\n maxAgents: number | \"unlimited\";\n /** Maximum agent runs per month (or total for lifetime mode) */\n maxAgentRunsPerMonth: number | \"unlimited\";\n /** How runs are counted: \"monthly\" resets each period, \"lifetime\" counts all-time */\n runCountingMode: RunCountingMode;\n /** Maximum concurrent agent runs */\n maxConcurrentRuns: number | \"unlimited\";\n /** Enabled features for this plan version */\n features: readonly PlanFeature[];\n /** Whether this version is currently available for new subscriptions */\n isActive: boolean;\n /** Monthly price in cents (for display purposes, actual billing via Stripe) */\n monthlyPriceCents: number;\n /** Stripe price ID for this plan version (if applicable) */\n stripePriceId?: string;\n}\n\n/**\n * Versioned plan definitions\n *\n * Format: {basePlan}_v{version}\n *\n * When changing plan features:\n * 1. Create a new version (e.g., pro_v2)\n * 2. Set isActive: false on the old version\n * 3. Set isActive: true on the new version\n * 4. Existing subscribers keep their version (grandfathered)\n */\nexport const PLAN_VERSIONS = {\n free_v1: {\n name: \"Pro Trial Plan\",\n basePlan: \"free\",\n maxAgents: 1,\n maxAgentRunsPerMonth: 100,\n runCountingMode: \"lifetime\",\n maxConcurrentRuns: 1,\n features: [],\n isActive: true,\n monthlyPriceCents: 0,\n },\n pro_v1: {\n name: \"Pro\",\n basePlan: \"pro\",\n maxAgents: \"unlimited\",\n maxAgentRunsPerMonth: 500,\n runCountingMode: \"monthly\",\n maxConcurrentRuns: 1,\n features: [\n PLAN_FEATURE.BROWSER_AUTOMATION,\n PLAN_FEATURE.ADVANCED_INTEGRATIONS,\n PLAN_FEATURE.CUSTOM_MCP_SERVERS,\n PLAN_FEATURE.BROWSING_SKILL_RECORDING,\n PLAN_FEATURE.AGENTIC_MEMORY,\n ],\n isActive: true,\n monthlyPriceCents: 19900, // $199/month\n },\n\n enterprise_v1: {\n name: \"Enterprise\",\n basePlan: \"enterprise\",\n maxAgents: \"unlimited\",\n maxAgentRunsPerMonth: \"unlimited\",\n runCountingMode: \"monthly\",\n maxConcurrentRuns: \"unlimited\",\n features: [\n PLAN_FEATURE.API_ACCESS,\n PLAN_FEATURE.BROWSER_AUTOMATION,\n PLAN_FEATURE.ADVANCED_INTEGRATIONS,\n PLAN_FEATURE.CUSTOM_MCP_SERVERS,\n PLAN_FEATURE.CASE_QUEUE,\n PLAN_FEATURE.CLARITY,\n PLAN_FEATURE.CLARITY_OVERVIEW,\n PLAN_FEATURE.SSO,\n PLAN_FEATURE.AUDIT_LOGS,\n PLAN_FEATURE.PRIORITY_SUPPORT,\n PLAN_FEATURE.CAN_CREATE_TEAMS,\n PLAN_FEATURE.LEARNINGS,\n PLAN_FEATURE.BROWSING_SKILL_RECORDING,\n PLAN_FEATURE.WORKFLOW_BUILDER,\n PLAN_FEATURE.AGENTIC_MEMORY,\n ],\n isActive: true,\n monthlyPriceCents: 0, // Custom pricing\n },\n} as const satisfies Record<string, PlanVersionDefinition>;\n\nexport type PlanVersionId = keyof typeof PLAN_VERSIONS;\n\nexport const FREE_PLAN_VERSION_ID = \"free_v1\";\nexport const PRO_PLAN_VERSION_ID = \"pro_v1\";\nexport const ENTERPRISE_PLAN_VERSION_ID = \"enterprise_v1\";\n\nexport type BillingEnvironment =\n | \"development\"\n | \"staging\"\n | \"production\"\n | \"test\";\n\nconst STRIPE_PRICE_IDS: Record<\n BillingEnvironment,\n Partial<Record<PlanVersionId, string>>\n> = {\n development: {\n pro_v1: \"price_1SsNA0G2suWmkoit1EDZ1yIp\", // Test mode\n free_v1: \"price_1SzK5cG2suWmkoit6MBgzq1O\", // Test mode\n },\n test: {\n pro_v1: \"price_TEST_PRO_V1\",\n free_v1: \"price_TEST_FREE_V1\",\n },\n staging: {\n pro_v1: \"price_1Suwy95poyNfxXdjeBEG4ZUR\", // Stripe Staging Sandbox\n free_v1: \"price_1T03AQ5poyNfxXdj3vGmHt6f\", // Stripe Staging Sandbox\n },\n production: {\n pro_v1: \"price_1SuYr7G2suWmkoitumMHF23S\", // Live mode\n free_v1: \"price_1SzvwvG2suWmkoityHM6SDMp\", // Live mode\n },\n};\n\n/**\n * Get the Stripe price ID for a plan version in the given environment\n */\nexport function getStripePriceId(\n planVersionId: PlanVersionId,\n environment: BillingEnvironment\n): string | null {\n const prices = STRIPE_PRICE_IDS[environment];\n return prices[planVersionId] ?? null;\n}\n\n/**\n * Get plan version definition by ID\n */\nexport function getPlanVersion(\n planVersionId: string\n): PlanVersionDefinition | null {\n return (\n (PLAN_VERSIONS as Record<string, PlanVersionDefinition>)[planVersionId] ??\n null\n );\n}\n\n/**\n * Get the current active version for a base plan\n */\nexport function getCurrentPlanVersion(\n basePlan: BasePlan\n): PlanVersionId | null {\n const entry = Object.entries(PLAN_VERSIONS).find(\n ([, def]) => def.basePlan === basePlan && def.isActive\n );\n return entry ? (entry[0] as PlanVersionId) : null;\n}\n\n/**\n * Check if a plan version has a specific feature\n */\nexport function planHasFeature(\n planVersionId: string,\n feature: PlanFeature\n): boolean {\n const plan = getPlanVersion(planVersionId);\n if (!plan) {\n return false;\n }\n\n return plan.features.includes(feature);\n}\n\n/**\n * Get a limit value from a plan version\n */\nexport function getPlanLimit(\n planVersionId: string,\n limit: \"maxAgents\" | \"maxAgentRunsPerMonth\" | \"maxConcurrentRuns\"\n): number | \"unlimited\" {\n const plan = getPlanVersion(planVersionId);\n if (!plan) {\n return 0;\n }\n\n return plan[limit];\n}\n\n/**\n * Get the run counting mode for a plan version\n */\nexport function getRunCountingMode(planVersionId: string): RunCountingMode {\n const plan = getPlanVersion(planVersionId);\n if (!plan) {\n return \"monthly\";\n }\n\n return plan.runCountingMode;\n}\n\n/**\n * Check if a value is within the plan limit\n */\nexport function isWithinPlanLimit(\n planVersionId: string,\n limit: \"maxAgents\" | \"maxAgentRunsPerMonth\" | \"maxConcurrentRuns\",\n currentValue: number\n): boolean {\n const planLimit = getPlanLimit(planVersionId, limit);\n if (planLimit === \"unlimited\") {\n return true;\n }\n\n return currentValue < planLimit;\n}\n", "import { type BasePlan, PLAN_FEATURE, type PlanFeature } from \"./plan-versions\";\n\n/**\n * Human-readable labels for plan features\n */\nexport const PLAN_FEATURE_LABELS: Record<PlanFeature, string> = {\n [PLAN_FEATURE.API_ACCESS]: \"API Access\",\n [PLAN_FEATURE.BROWSER_AUTOMATION]: \"Browser Automation\",\n [PLAN_FEATURE.ADVANCED_INTEGRATIONS]: \"Advanced Integrations\",\n [PLAN_FEATURE.CUSTOM_MCP_SERVERS]: \"Custom MCP Servers\",\n [PLAN_FEATURE.CASE_QUEUE]: \"Case Queue\",\n [PLAN_FEATURE.CLARITY]: \"Clarity\",\n [PLAN_FEATURE.CLARITY_OVERVIEW]: \"Clarity Overview\",\n [PLAN_FEATURE.SSO]: \"Single Sign-On (SSO)\",\n [PLAN_FEATURE.AUDIT_LOGS]: \"Audit Logs\",\n [PLAN_FEATURE.PRIORITY_SUPPORT]: \"Priority Support\",\n [PLAN_FEATURE.CAN_CREATE_TEAMS]: \"Create Teams\",\n [PLAN_FEATURE.LEARNINGS]: \"Learnings\",\n [PLAN_FEATURE.BROWSING_SKILL_RECORDING]: \"Browsing Skill Recording\",\n [PLAN_FEATURE.WORKFLOW_BUILDER]: \"Workflow Builder\",\n [PLAN_FEATURE.AGENTIC_MEMORY]: \"Agentic Memory\",\n};\n\n/**\n * Get the display label for a plan feature\n */\nexport function getFeatureLabel(feature: PlanFeature): string {\n return PLAN_FEATURE_LABELS[feature];\n}\n\n/**\n * Format a price in cents to a display string\n */\nexport function formatPrice(priceCents: number, basePlan?: BasePlan): string {\n if (priceCents === 0 && basePlan === \"free\") {\n return \"Free\";\n }\n\n if (priceCents === 0) {\n return \"Custom pricing\";\n }\n\n return `$${(priceCents / 100).toLocaleString()}/month`;\n}\n\n/**\n * Format a limit value for display\n */\nexport function formatLimit(value: number | \"unlimited\"): string {\n if (value === \"unlimited\") {\n return \"Unlimited\";\n }\n\n return value.toLocaleString();\n}\n", "import { z } from \"zod\";\n\nexport const subscriptionDetailsSchema = z.object({\n planName: z.string(),\n price: z.number(),\n currency: z.string(),\n interval: z.enum([\"month\", \"year\"]),\n status: z.string(),\n currentPeriodEnd: z.string(),\n cancelAtPeriodEnd: z.boolean(),\n});\n\nexport type SubscriptionDetails = z.infer<typeof subscriptionDetailsSchema>;\n\nexport const subscriptionDetailsResponseSchema = z.object({\n subscription: subscriptionDetailsSchema.nullable(),\n});\n\nexport type SubscriptionDetailsResponse = z.infer<\n typeof subscriptionDetailsResponseSchema\n>;\n", "import { z } from \"zod\";\n\nexport const subscriptionStatusSchema = z.object({\n hasActiveSubscription: z.boolean(),\n isEnterprise: z.boolean(),\n planVersionId: z.string().nullable(),\n status: z.string().nullable(),\n canCreateTeams: z.boolean(),\n});\n\nexport type SubscriptionStatus = z.infer<typeof subscriptionStatusSchema>;\n", "import { z } from \"zod\";\n\nimport { type AgentRunSource, agentRunSourceSchema } from \"../types/agent-run\";\n\n/**\n * Usage period information\n */\nexport const usagePeriodSchema = z.object({\n start: z.coerce.date(),\n end: z.coerce.date(),\n});\n\nexport type UsagePeriod = z.infer<typeof usagePeriodSchema>;\n\n/**\n * Resource usage with limit information\n */\nexport const resourceUsageSchema = z.object({\n used: z.number(),\n limit: z.union([z.number(), z.literal(\"unlimited\")]),\n remaining: z.union([z.number(), z.literal(\"unlimited\")]),\n});\n\nexport type ResourceUsage = z.infer<typeof resourceUsageSchema>;\n\n/**\n * Resource usage without remaining (for seats/assignments that don't have monthly limits)\n */\nexport const resourceCountSchema = z.object({\n used: z.number(),\n limit: z.union([z.number(), z.literal(\"unlimited\")]),\n});\n\nexport type ResourceCount = z.infer<typeof resourceCountSchema>;\n\n/**\n * Team-level usage data\n */\nexport const teamUsageSchema = z.object({\n teamId: z.guid(),\n period: usagePeriodSchema,\n agentRuns: resourceUsageSchema,\n assignments: resourceCountSchema,\n concurrency: resourceCountSchema,\n});\n\nexport type TeamUsage = z.infer<typeof teamUsageSchema>;\n\n/**\n * Usage breakdown by source\n */\nexport const usageBySourceSchema = z.partialRecord(\n agentRunSourceSchema,\n z.number()\n);\n\nexport type UsageBySource = Partial<Record<AgentRunSource, number>>;\n\n/**\n * User-level usage data within a team\n */\nexport const userUsageSchema = z.object({\n userId: z.guid(),\n teamId: z.guid(),\n period: usagePeriodSchema,\n totalRuns: z.number(),\n assignmentsUsed: z.array(z.guid()),\n bySource: usageBySourceSchema,\n});\n\nexport type UserUsage = z.infer<typeof userUsageSchema>;\n\n/**\n * Reasons why execution may not be allowed\n */\nexport const executionBlockedReasonSchema = z.enum([\n \"limit_exceeded\",\n \"concurrent_limit_exceeded\",\n \"no_subscription\",\n \"subscription_inactive\",\n]);\n\nexport type ExecutionBlockedReason = z.infer<\n typeof executionBlockedReasonSchema\n>;\n\n/**\n * Result of checking if an agent run can be executed\n */\nexport const canExecuteResultSchema = z.object({\n allowed: z.boolean(),\n reason: executionBlockedReasonSchema.optional(),\n usage: z.object({\n current: z.number(),\n limit: z.union([z.number(), z.literal(\"unlimited\")]),\n remaining: z.union([z.number(), z.literal(\"unlimited\")]),\n periodEnd: z.coerce.date(),\n }),\n});\n\nexport type CanExecuteResult = z.infer<typeof canExecuteResultSchema>;\n\n/**\n * Result of checking if a concurrent agent run can be executed\n */\nexport const canExecuteConcurrentResultSchema = z.object({\n allowed: z.boolean(),\n reason: executionBlockedReasonSchema.optional(),\n usage: z.object({\n current: z.number(),\n limit: z.union([z.number(), z.literal(\"unlimited\")]),\n remaining: z.union([z.number(), z.literal(\"unlimited\")]),\n }),\n});\n\nexport type CanExecuteConcurrentResult = z.infer<\n typeof canExecuteConcurrentResultSchema\n>;\n\n/**\n * UsageService interface for checking and tracking usage\n */\nexport interface UsageService {\n /**\n * Get current usage for a team including all resource types\n */\n getCurrentUsage(teamId: string): Promise<TeamUsage>;\n\n /**\n * Get usage for a specific user within a team\n */\n getUserUsage(\n teamId: string,\n userId: string,\n startDate?: Date\n ): Promise<UserUsage>;\n\n /**\n * Check if a team can execute an agent run (pre-execution check for monthly limits)\n */\n canExecuteRun(teamId: string): Promise<CanExecuteResult>;\n\n /**\n * Check if a team can execute a concurrent agent run (pre-execution check for concurrent limits)\n */\n canExecuteConcurrentRun(teamId: string): Promise<CanExecuteConcurrentResult>;\n}\n", "import { z } from \"zod\";\n\nimport { agentMessageSchema } from \"../schemas/automation-message\";\nimport { evalSummarySchema } from \"../schemas/run-evaluation\";\n\nexport const DISPATCH_MAX_RETRIES = 100;\n\n/**\n * Agent run status values\n */\nexport const AGENT_RUN_STATUSES = [\n \"not_started\", // Legacy status (pre-dispatcher)\n \"pending\", // Queued, waiting for dispatch\n \"starting\", // Dispatched by dispatcher, webhook fired, awaiting ack from cc-server\n \"running\", // Acknowledged by cc-server, actively executing\n \"waiting\", // Paused waiting for human input (e.g., AskUserQuestion)\n // Terminal states\n \"completed\", // Finished successfully\n \"failed\", // Finished with error\n \"interrupted\", // User interrupted\n] as const;\n\nexport const ACTIVE_AGENT_RUN_STATUSES = [\n \"not_started\",\n \"pending\",\n \"starting\",\n \"running\",\n \"waiting\",\n] as const satisfies AgentRunStatus[];\n\nexport const TERMINAL_AGENT_RUN_STATUSES = [\n \"completed\",\n \"failed\",\n \"interrupted\",\n] as const satisfies AgentRunStatus[];\n\nexport type AgentRunStatus = (typeof AGENT_RUN_STATUSES)[number];\n\ntype TerminalAgentRunStatus = (typeof TERMINAL_AGENT_RUN_STATUSES)[number];\ntype ActiveAgentRunStatus = (typeof ACTIVE_AGENT_RUN_STATUSES)[number];\n\n/**\n * Type-level check: TERMINAL + ACTIVE must cover all AGENT_RUN_STATUSES with no overlap.\n * If a status is missing or duplicated, these assertions will fail to compile.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-expressions\n(function _agentRunStatusChecks() {\n type AllStatuses = TerminalAgentRunStatus | ActiveAgentRunStatus;\n\n /** Fails if any status is missing from TERMINAL or ACTIVE. */\n const _complete: [AgentRunStatus] extends [AllStatuses] ? true : never = true;\n\n /** Fails if TERMINAL and ACTIVE have any overlap. */\n const _noOverlap: [TerminalAgentRunStatus & ActiveAgentRunStatus] extends [\n never,\n ]\n ? true\n : never = true;\n\n return [_complete, _noOverlap];\n});\n\nexport const agentRunStatusSchema = z.enum(AGENT_RUN_STATUSES);\n\n/**\n * Agent run sources - where the agent run was initiated from\n */\nexport const AGENT_RUN_SOURCES = [\n \"app\",\n \"scheduling\",\n \"slack\",\n \"teams\",\n \"api\",\n \"case_trigger\",\n \"handover\",\n \"postpone\",\n \"delegate\",\n \"trigger\",\n] as const;\n\n/**\n * Type representing the source of an agent run\n */\nexport type AgentRunSource = (typeof AGENT_RUN_SOURCES)[number];\n\n/**\n * Zod schema for validating agent run sources\n */\nexport const agentRunSourceSchema = z.enum(AGENT_RUN_SOURCES);\n\n/**\n * Agent invocation initiators - internal classification of how/why a run was started.\n * Some initiators map from sources, others are set directly (e.g., \"url-upload\", \"builder\").\n */\nexport const AGENT_INVOCATION_INITIATORS = [\n \"api\",\n \"builder\",\n \"case-queue\",\n \"clarity\",\n \"handover\",\n \"schedule\",\n \"slack\",\n \"teams\",\n \"trigger\",\n \"url-upload\",\n \"user-trigger\",\n \"workflow-builder\",\n] as const;\n\nexport type AgentInvocationInitiator =\n (typeof AGENT_INVOCATION_INITIATORS)[number];\n\nexport const agentInvocationInitiatorSchema = z.enum(\n AGENT_INVOCATION_INITIATORS\n);\n\nconst SOURCE_TO_INITIATOR: Record<AgentRunSource, AgentInvocationInitiator> = {\n app: \"user-trigger\",\n scheduling: \"schedule\",\n slack: \"slack\",\n teams: \"teams\",\n api: \"api\",\n case_trigger: \"case-queue\",\n handover: \"handover\",\n postpone: \"case-queue\",\n delegate: \"case-queue\",\n trigger: \"trigger\",\n};\n\n/**\n * Map a source value to its corresponding initiator.\n * Validates with Zod and falls back to \"user-trigger\" for invalid sources.\n */\nexport function mapSourceToInitiator(\n source: string | null | undefined\n): AgentInvocationInitiator {\n const parsed = agentRunSourceSchema.safeParse(source);\n if (!parsed.success) {\n return \"user-trigger\";\n }\n\n return SOURCE_TO_INITIATOR[parsed.data];\n}\n\n/**\n * Schema for a single agent run\n */\nexport const agentRunSchema = z.object({\n id: z.guid(),\n created_at: z.coerce.date(),\n updated_at: z.coerce.date(),\n agent_id: z.guid(),\n build_id: z.guid(),\n started_at: z.coerce.date().nullable(),\n completed_at: z.coerce.date().nullable(),\n last_session_id: z.string().nullable(),\n user_id: z.guid().nullable(),\n source: z.string().nullable(),\n bb_session_id: z.string().nullable(),\n computer_session_id: z.string().nullable().optional(),\n status: agentRunStatusSchema.optional(),\n /** Case queue item ID for case-bound runs (set by claim_case or pre-bound at start) */\n case_queue_item_id: z.guid().nullable().optional(),\n // API run and webhook status fields (for runs started via public API)\n is_api_run: z.boolean().optional(),\n has_webhook: z.boolean().optional(),\n latest_webhook_triggered_at: z.string().nullable().optional(),\n latest_webhook_status_code: z.number().nullable().optional(),\n latest_webhook_error: z.string().nullable().optional(),\n eval_summaries: evalSummarySchema.nullable().optional(),\n user_name: z.string().nullable().optional(),\n user_email: z.string().nullable().optional(),\n submitted_prompt_count: z.number().int().min(0).optional(),\n});\n\n/**\n * Type inferred from agentRunSchema\n */\nexport type AgentRun = z.infer<typeof agentRunSchema>;\n\n/**\n * Response schema for the agent runs list endpoint\n */\nexport const agentRunsListResponseSchema = z.object({\n data: z.array(agentRunSchema),\n total: z.number(),\n learningSourceRunId: z.guid().nullable(),\n});\n\n/**\n * Type inferred from agentRunsListResponseSchema\n */\nexport type AgentRunsListResponse = z.infer<typeof agentRunsListResponseSchema>;\n\n/**\n * Schema for integration instance metadata in agent run detail\n */\nexport const integrationInstanceMetadataSchema = z.object({\n instanceId: z.string(),\n name: z.string(),\n integrationType: z.string(),\n iconUrl: z.string().nullish(),\n});\n\nexport type IntegrationInstanceMetadata = z.infer<\n typeof integrationInstanceMetadataSchema\n>;\n\n/**\n * Schema for conversation pagination metadata\n */\nexport const conversationPaginationSchema = z.object({\n total: z.number(),\n included: z.number(),\n hasMore: z.boolean(),\n});\n\nexport type ConversationPagination = z.infer<\n typeof conversationPaginationSchema\n>;\n\n/**\n * Handover status values for the handover info object\n */\nexport const handoverStatusSchema = z.enum([\n \"pending\",\n \"evaluating\",\n \"pending_approval\",\n \"approved\",\n \"rejected\",\n]);\n\nexport type HandoverStatus = z.infer<typeof handoverStatusSchema>;\n\n/**\n * Schema for handover info attached to an agent run\n */\nexport const handoverInfoSchema = z.object({\n targetAgentId: z.guid(),\n targetAgentName: z.string(),\n status: handoverStatusSchema,\n targetRunId: z.guid().nullable(),\n targetBuildId: z.guid().nullable(),\n rejectionReason: z.string().nullable(),\n});\n\nexport type HandoverInfo = z.infer<typeof handoverInfoSchema>;\n\n/**\n * Slim view of a sub-assignment that was frozen into the run config at\n * creation time. Used by the message renderer to map the `subagent_type`\n * slug Claude reports back to a human-readable assignment name and an\n * agent ID for click-through.\n *\n * Shipped as a separate slim shape so we never expose the sub-assignment's\n * full SOP/prompt or redacted MCP server map to the frontend.\n */\nexport const runSubAgentRefSchema = z.object({\n agentId: z.guid(),\n slug: z\n .string()\n .describe(\n \"Stable kebab-case slug Claude Code uses as the subagent name (matches `subagent_type` on Agent tool calls)\"\n ),\n displayName: z.string(),\n});\n\nexport type RunSubAgentRef = z.infer<typeof runSubAgentRefSchema>;\n\n/**\n * Schema for agent run detail (includes conversation)\n */\nconst agentRunDetailSchemaData = z.object({\n id: z.guid(),\n created_at: z.coerce.date(),\n updated_at: z.coerce.date(),\n agent_id: z.guid(),\n build_id: z.guid(),\n started_at: z.coerce.date().nullable(),\n completed_at: z.coerce.date().nullable(),\n last_session_id: z.string().nullable(),\n user_id: z.guid().nullable(),\n source: z.string().nullable(),\n bb_session_id: z.string().nullable(),\n computer_session_id: z.string().nullable().optional(),\n sandbox_id: z.string().nullable(),\n status: agentRunStatusSchema.optional(),\n conversation: agentMessageSchema.array().optional(),\n conversationPagination: conversationPaginationSchema.optional(),\n integrationInstances: integrationInstanceMetadataSchema.array().optional(),\n subAgents: runSubAgentRefSchema.array().optional(),\n /** Case queue item ID for case-triggered runs */\n case_queue_item_id: z.guid().nullable().optional(),\n handover: handoverInfoSchema.nullable().optional(),\n eval_summaries: evalSummarySchema.nullable().optional(),\n user_name: z.string().nullable().optional(),\n user_email: z.string().nullable().optional(),\n submitted_prompt_count: z.number().int().min(0).optional(),\n});\n\nexport const agentRunDetailSchema = z.object({\n data: agentRunDetailSchemaData.nullable(),\n});\n\n/**\n * Type inferred from agentRunDetailSchema\n */\nexport type AgentRunDetail = z.infer<typeof agentRunDetailSchema>;\n", "import { z } from \"zod\";\n\nexport const agentRuntimeSchema = z.union([\n z.literal(\"responses\"),\n z.literal(\"terminal-agent\"),\n]);\n\nconst agentMessageRoleSchema = z.union([\n z.literal(\"user\"),\n z.literal(\"assistant\"),\n z.literal(\"system\"),\n]);\n\nconst agentMessageTypeSchema = z.union([\n z.literal(\"text\"),\n z.literal(\"tool_call\"),\n z.literal(\"tool_result\"),\n z.literal(\"system\"),\n z.literal(\"thinking\"),\n]);\n\nconst duvoMessageTypeSchema = z.union([\n z.literal(\"agent_run_created\"),\n z.literal(\"session_started\"),\n z.literal(\"session_completed\"),\n z.literal(\"session_interrupted\"),\n z.literal(\"session_error\"),\n z.literal(\"browser_session_created\"),\n]);\n\nconst duvoBaseSystemMessageSchema = z.object({\n id: z.string(),\n runtime: agentRuntimeSchema,\n timestamp: z.string(),\n role: z.literal(\"duvo\"),\n type: duvoMessageTypeSchema,\n});\n\nconst duvoSystemSessionStartedMessageSchema = duvoBaseSystemMessageSchema.and(\n z.object({\n type: z.literal(\"session_started\"),\n })\n);\n\nconst duvoSystemSessionCompletedMessageSchema = duvoBaseSystemMessageSchema.and(\n z.object({\n type: z.literal(\"session_completed\"),\n })\n);\n\nconst duvoSystemSessionInterruptedMessageSchema =\n duvoBaseSystemMessageSchema.and(\n z.object({\n type: z.literal(\"session_interrupted\"),\n })\n );\n\nconst duvoSystemSessionErrorMessageSchema = duvoBaseSystemMessageSchema.and(\n z.object({\n type: z.literal(\"session_error\"),\n error: z.string(),\n })\n);\n\nconst duvoSystemAgentRunCreatedMessageSchema = duvoBaseSystemMessageSchema.and(\n z.object({\n type: z.literal(\"agent_run_created\"),\n agent_run_id: z.string(),\n })\n);\n\nconst duvoSystemBrowserSessionCreatedMessageSchema =\n duvoBaseSystemMessageSchema.and(\n z.object({\n type: z.literal(\"browser_session_created\"),\n browser_session_id: z.string(),\n })\n );\n\nexport const agentRuntimeMessageTypeSchema = z.union([\n agentMessageTypeSchema,\n duvoMessageTypeSchema,\n]);\n\nexport const duvoSystemMessageSchema = z.union([\n duvoSystemSessionStartedMessageSchema,\n duvoSystemSessionCompletedMessageSchema,\n duvoSystemSessionInterruptedMessageSchema,\n duvoSystemAgentRunCreatedMessageSchema,\n duvoSystemBrowserSessionCreatedMessageSchema,\n duvoSystemSessionErrorMessageSchema,\n]);\n\nexport const sdkMessageSchema = z.looseObject({\n session_id: z.string(),\n uuid: z.string(),\n});\n\nexport const pausableToolCategorySchema = z.union([\n z.literal(\"question\"),\n z.literal(\"approval\"),\n z.literal(\"confirmation\"),\n z.literal(\"input\"),\n z.literal(\"credentials\"),\n]);\n\nexport const toolPausedEventSchema = z.object({\n type: z.literal(\"tool_paused\"),\n executionId: z.string(),\n sessionId: z.string().optional(),\n toolName: z.string(),\n toolInput: z.record(z.string(), z.unknown()),\n category: pausableToolCategorySchema,\n behavior: z.union([z.literal(\"canUseTool\"), z.literal(\"interrupt\")]),\n timestamp: z.string().optional(),\n});\n\nexport const responseSchema = z.any();\n\nconst baseMessageSchema = z.object({\n id: z.string(),\n type: agentMessageTypeSchema,\n runtime: agentRuntimeSchema,\n timestamp: z.string(),\n raw_message: z.union([sdkMessageSchema, responseSchema]),\n role: agentMessageRoleSchema,\n});\n\nconst textMessageSchema = baseMessageSchema.and(\n z.object({\n type: z.literal(\"text\"),\n role: z.union([z.literal(\"assistant\"), z.literal(\"user\")]),\n text_content: z.string(),\n metadata: z\n .looseObject({\n isAgentInstruction: z.boolean().optional(),\n })\n .optional(),\n })\n);\n\nconst thinkingMessageSchema = baseMessageSchema.and(\n z.object({\n type: z.literal(\"thinking\"),\n role: z.literal(\"assistant\"),\n text_content: z.string(),\n })\n);\n\nconst toolCallMessageSchema = baseMessageSchema.and(\n z.object({\n type: z.literal(\"tool_call\"),\n role: z.literal(\"assistant\"),\n mcp_server_label: z.string().optional(),\n tool_call: z.object({\n id: z.string(),\n name: z.string(),\n arguments: z.record(z.string(), z.unknown()).optional(),\n }),\n })\n);\n\nconst toolResultMessageSchema = baseMessageSchema.and(\n z.object({\n type: z.literal(\"tool_result\"),\n role: z.literal(\"assistant\"),\n mcp_server_label: z.string().optional(),\n tool_result: z.object({\n tool_call_id: z.string(),\n result: z.unknown().optional(),\n error: z.string().optional(),\n }),\n })\n);\n\nexport const agentMessageSchema = z.union([\n textMessageSchema,\n thinkingMessageSchema,\n toolCallMessageSchema,\n toolResultMessageSchema,\n duvoSystemMessageSchema,\n]);\n", "import { z } from \"zod\";\n\nexport const evaluationDataSchema = z.record(\n z.string(),\n z.union([z.boolean(), z.string(), z.null()])\n);\n\nexport const evaluationOutputSchema = z.object({\n schemaId: z.string().optional(),\n schemaVersion: z.string().optional(),\n data: evaluationDataSchema,\n});\n\nexport const runEvaluationResponseSchema = z.object({\n data: z\n .object({\n id: z.guid(),\n created_at: z.string(),\n run_id: z.guid(),\n source: z.string().nullable(),\n output: evaluationOutputSchema,\n })\n .nullable(),\n});\n\nexport type RunEvaluationResponse = z.infer<typeof runEvaluationResponseSchema>;\n\nexport const evalSeverityCountsSchema = z.object({\n critical: z.int().nonnegative(),\n medium: z.int().nonnegative(),\n low: z.int().nonnegative(),\n});\n\nexport type EvalSeverityCountsData = z.infer<typeof evalSeverityCountsSchema>;\n\nexport const evalSummarySchema = z.object({\n passed: z.number(),\n total: z.number(),\n final_comment: z.string().optional(),\n status: z.enum([\"ready\", \"unavailable\", \"in_progress\"]),\n severityCounts: evalSeverityCountsSchema.optional(),\n});\n\nexport type EvalSummaryData = z.infer<typeof evalSummarySchema>;\n\nexport const evalFlagCountSchema = z.object({\n flag: z.string(),\n count: z.int(),\n});\n\nexport type EvalFlagCount = z.infer<typeof evalFlagCountSchema>;\n\nexport const evalScoresResponseSchema = z.object({\n total_evaluated: z.int(),\n with_issues: z.int(),\n flag_distribution: z.array(evalFlagCountSchema),\n});\n\nexport type EvalScoresResponse = z.infer<typeof evalScoresResponseSchema>;\n\nexport const evalCountsSchema = z.object({\n total_evaluated: z.int(),\n with_issues: z.int(),\n});\n\nexport type EvalCounts = z.infer<typeof evalCountsSchema>;\n\nexport const evalCountsByAgentResponseSchema = z.object({\n by_agent: z.record(z.string(), evalCountsSchema),\n});\n\nexport type EvalCountsByAgentResponse = z.infer<\n typeof evalCountsByAgentResponseSchema\n>;\n\nexport const summarizeEvalScoresBodySchema = z.object({\n since: z.iso.datetime(),\n});\n\nexport type SummarizeEvalScoresBody = z.infer<\n typeof summarizeEvalScoresBodySchema\n>;\n\nexport const summarizeEvalScoresResponseSchema = z.object({\n data: z.object({\n summary: z.string(),\n run_count: z.int(),\n }),\n});\n\nexport type SummarizeEvalScoresResponse = z.infer<\n typeof summarizeEvalScoresResponseSchema\n>;\n", "import { z } from \"zod\";\n\n/**\n * Zod schema for browsing providers supported by Stagehand\n */\nexport const BrowsingProviderSchema = z.enum([\"google\", \"anthropic\"]);\n\nexport type BrowsingProvider = z.infer<typeof BrowsingProviderSchema>;\n\n/**\n * Platform-wide default models for agent configuration\n */\nexport const PLATFORM_DEFAULT_MODELS = {\n agent: {\n model: \"claude-sonnet-4-6[1m]\",\n },\n browsing: {\n provider: \"google\",\n model: \"gemini-2.5-pro\",\n },\n} as const satisfies {\n agent: { model: ClaudeModelId };\n browsing: { provider: BrowsingProvider; model: BrowsingModelId };\n};\n\ntype ModelMetadata = {\n displayName: string;\n description?: string;\n};\n\n/**\n * Core Claude model IDs (canonical identifiers) \u2014 the set of models selectable\n * in the UI and accepted unchanged by the runtime. Everything else is treated\n * as legacy and resolves to `PLATFORM_DEFAULT_MODELS.agent.model`.\n */\nexport const CLAUDE_MODEL_IDS = [\n \"claude-sonnet-4-6\",\n \"claude-sonnet-4-6[1m]\",\n \"claude-opus-4-6\",\n \"claude-opus-4-6[1m]\",\n \"claude-opus-4-7\",\n \"claude-opus-4-7[1m]\",\n] as const;\n\n/**\n * Tombstone IDs: values that may still appear in historic agent_run.run_config\n * snapshots and therefore need to parse through `ClaudeModelIdSchema`, but are\n * no longer selectable and always resolve to the platform default at runtime.\n */\nconst LEGACY_MODEL_IDS = [\n // Old duvo wrapper aliases\n \"d1-max\",\n \"duvo-1-max\",\n \"duvo-1-max-sonnet-1m\",\n \"duvo-1-max-sonnet-4.5\",\n \"duvo-1-max-sonnet-4.5-1m\",\n \"duvo-1-max-opus\",\n \"duvo-1-max-opus-4.5\",\n // Legacy OpenAI models (never actually ran \u2014 silently fell back to Claude)\n \"gpt-4.1\",\n \"gpt-4o\",\n \"gpt-4o-mini\",\n \"gpt-5\",\n \"gpt-5.1\",\n // Retired canonical Claude model IDs\n \"claude-sonnet-4-20250514\",\n \"claude-sonnet-4-20250514[1m]\",\n \"claude-sonnet-4-5-20250929\",\n \"claude-sonnet-4-5-20250929[1m]\",\n \"claude-opus-4-1-20250805\",\n \"claude-opus-4-5-20251101\",\n] as const;\n\n/**\n * Zod schema for Claude model IDs (includes legacy model IDs for backward compatibility)\n */\nexport const ClaudeModelIdSchema = z.enum([\n ...CLAUDE_MODEL_IDS,\n ...LEGACY_MODEL_IDS,\n]);\n\nexport type ClaudeModelId = z.infer<typeof ClaudeModelIdSchema>;\n\n/**\n * Core Claude model ID type (excludes legacy IDs)\n */\nexport type CoreClaudeModelId = (typeof CLAUDE_MODEL_IDS)[number];\n\n/**\n * Available main agent models \u2014 shown in the UI model picker.\n */\nexport const AVAILABLE_AGENT_MODELS: Record<CoreClaudeModelId, ModelMetadata> =\n {\n \"claude-sonnet-4-6\": {\n displayName: \"Claude Sonnet 4.6\",\n },\n \"claude-sonnet-4-6[1m]\": {\n displayName: \"Claude Sonnet 4.6\",\n description: \"Fast and capable for everyday tasks\",\n },\n \"claude-opus-4-6\": {\n displayName: \"Claude Opus 4.6\",\n description: \"Advanced model for complex work\",\n },\n \"claude-opus-4-6[1m]\": {\n displayName: \"Claude Opus 4.6\",\n description: \"Advanced model for complex work\",\n },\n \"claude-opus-4-7\": {\n displayName: \"Claude Opus 4.7\",\n description: \"Our most capable model \\u2014 best for complex work\",\n },\n \"claude-opus-4-7[1m]\": {\n displayName: \"Claude Opus 4.7\",\n description: \"Our most capable model \\u2014 best for complex work\",\n },\n } as const;\n\nexport type BrowsingModelMetadata = {\n displayName: string;\n provider: BrowsingProvider;\n};\n\n/**\n * Zod schema for browsing model IDs\n */\nexport const BrowsingModelIdSchema = z.enum([\n \"gemini-2.5-pro\",\n \"gemini-2.5-flash\",\n \"gemini-3-pro-preview\",\n \"claude-haiku-4-5\",\n \"claude-sonnet-4-5\",\n \"claude-opus-4-1\",\n]);\n\nexport type BrowsingModelId = z.infer<typeof BrowsingModelIdSchema>;\n\nexport const EVALUATION_MODEL: CoreClaudeModelId = \"claude-sonnet-4-6[1m]\";\n\nexport const INPUT_SAFETY_MODEL = \"claude-haiku-4-5-20251001\";\n\n/**\n * Target that retired/legacy model IDs resolve to at runtime. A stored\n * `build.config` model string that isn't in `CLAUDE_MODEL_IDS` (legacy aliases,\n * retired canonical IDs, OpenAI stubs, null/garbage) maps to this ID.\n *\n * Kept separate from `PLATFORM_DEFAULT_MODELS.agent.model` so legacy routing\n * can diverge from new-Assignment defaults if product ever wants to pin them\n * apart (e.g. route legacy traffic to a cheaper tier while keeping new\n * Assignments on the latest flagship).\n */\nexport const LEGACY_DEFAULT_MODEL: CoreClaudeModelId = \"claude-sonnet-4-6[1m]\";\n\n/**\n * A model ID as it might appear from any source: a current canonical string,\n * a legacy alias, a retired canonical, `null` (Postgres NULL \u2192 JS null on\n * reads), `undefined` (optional chaining / missing JSON keys), or an empty\n * string. Both `mapModelToClaudeModel` and `isLegacyModelId` accept this\n * shape so callers don't have to normalize `undefined \u2192 null` at the boundary.\n */\nexport type MaybeStoredModelId = string | null | undefined;\n\n/**\n * Resolve any stored model ID (current, legacy alias, or retired canonical) to\n * a currently-runnable canonical Claude model. Anything not in `CLAUDE_MODEL_IDS`\n * routes to `LEGACY_DEFAULT_MODEL` \u2014 single source of truth for legacy routing.\n */\nexport function mapModelToClaudeModel(\n model: MaybeStoredModelId\n): CoreClaudeModelId {\n if (model && CLAUDE_MODEL_IDS.includes(model as CoreClaudeModelId)) {\n return model as CoreClaudeModelId;\n }\n\n return LEGACY_DEFAULT_MODEL;\n}\n\n/**\n * Returns true when a stored model ID is a legacy alias or retired canonical\n * ID \u2014 anything not in the currently-selectable `CLAUDE_MODEL_IDS`. Useful for\n * UI affordances (e.g. showing a \"legacy model, will be routed\" indicator).\n * Null / undefined / empty string \u2192 false (no stored model, not a legacy value).\n */\nexport function isLegacyModelId(model: MaybeStoredModelId): boolean {\n return (\n model != null &&\n model !== \"\" &&\n !CLAUDE_MODEL_IDS.includes(model as CoreClaudeModelId)\n );\n}\n", "import {\n type BrowserProviderType,\n type StoredAgentConfigV2,\n} from \"../types/agent-config\";\nimport type { EditableAgentConfig } from \"../utils/normalize-agent-config\";\nimport { PLATFORM_DEFAULT_MODELS } from \"./models\";\n\nexport const AGENT_CONFIG_VERSION: StoredAgentConfigV2[\"version\"] = \"v2\";\n\n/**\n * Default browser provider for NEW agent runs.\n */\nexport const DEFAULT_BROWSER_PROVIDER: BrowserProviderType = \"browserbase\";\n\n/**\n * Legacy default browser provider for backward compatibility.\n * Used when agent_run.run_config is null (pre-run_config runs)\n * or when browserProvider is not specified in the config.\n */\nexport const LEGACY_DEFAULT_BROWSER_PROVIDER: BrowserProviderType =\n \"browserbase\";\n\nexport const DEFAULT_AGENT_NAME = \"New Assignment\";\n\n/**\n * Maximum SOP (Standard Operating Procedure) size in bytes.\n * Larger SOPs cause 413 errors when dispatching to cc-server.\n */\nexport const MAX_SOP_SIZE_BYTES = 512 * 1024; // 0.5MB\n\n/**\n * Maximum number of sub-assignments a parent assignment can declare.\n * Bounds breadth/fan-out at delegation time; large fan-outs balloon the\n * cc-server payload and the parent's prompt cache cost.\n */\nexport const MAX_SUB_AGENTS = 16;\n\n/**\n * Maximum aggregate size, in bytes, of all sub-assignment prompts plus\n * descriptions plus names in a single run config. Each sub ships its own\n * SOP in the cc-server payload, so this caps the request body even when\n * the parent task itself is well under MAX_SOP_SIZE_BYTES.\n */\nexport const MAX_SUB_AGENTS_TOTAL_BYTES = 512 * 1024; // 0.5MB\n\nexport const DEFAULT_AGENT_CONFIG: EditableAgentConfig = {\n models: {\n agent: {\n model: PLATFORM_DEFAULT_MODELS.agent.model,\n },\n browsing: {\n provider: PLATFORM_DEFAULT_MODELS.browsing.provider,\n model: PLATFORM_DEFAULT_MODELS.browsing.model,\n },\n },\n input: [],\n files: [], // Context files\n skills: [], // Attached skill IDs\n subAgents: [], // Sub-assignment agent IDs\n options: {\n browserProvider: DEFAULT_BROWSER_PROVIDER,\n },\n};\n", "export const BROWSER_VIEWPORT_WIDTH = 1536;\nexport const BROWSER_VIEWPORT_HEIGHT = 864;\n\nexport const BROWSER_RECORDING_VIEWPORT_WIDTH = 1920;\nexport const BROWSER_RECORDING_VIEWPORT_HEIGHT = 1080;\n\nexport const BROWSER_SCREENSHOT_WIDTH = 1280;\nexport const BROWSER_SCREENSHOT_HEIGHT = 720;\n", "export const BUILD_STATUS = {\n DRAFT: \"draft\",\n LIVE: \"live\",\n HISTORIC: \"historic\",\n} as const;\n\nexport type BuildStatus = (typeof BUILD_STATUS)[keyof typeof BUILD_STATUS];\n", "// Case queue item status constants\nexport const CASE_QUEUE_ITEM_STATUS = {\n PENDING: \"pending\",\n CLAIMED: \"claimed\",\n COMPLETED: \"completed\",\n FAILED: \"failed\",\n} as const;\n\nexport type CaseQueueItemStatus =\n (typeof CASE_QUEUE_ITEM_STATUS)[keyof typeof CASE_QUEUE_ITEM_STATUS];\n\n/**\n * Statuses from which a case can be retried. A case in any of these states\n * will be reset to `pending` by the retry flow; any active runs attached to\n * a claimed case are interrupted first. `pending` is the only status excluded\n * \u2014 there is nothing to retry.\n */\nexport const RETRYABLE_CASE_STATUSES = [\n CASE_QUEUE_ITEM_STATUS.COMPLETED,\n CASE_QUEUE_ITEM_STATUS.FAILED,\n CASE_QUEUE_ITEM_STATUS.CLAIMED,\n] as const satisfies readonly CaseQueueItemStatus[];\n\nexport function isRetryableCaseStatus(status: CaseQueueItemStatus): boolean {\n return (RETRYABLE_CASE_STATUSES as readonly CaseQueueItemStatus[]).includes(\n status\n );\n}\n\n/**\n * Minimum wait, in minutes, before a postponed case can be re-handled.\n * The default applies to all teams; the WITH_FLAG value applies to teams that\n * have the `minute_scheduling` feature flag enabled.\n *\n * Backend-node uses these to coerce values below the floor; the MCP postpone\n * tool description surfaces them to the agent so it can pick a valid value\n * up front.\n */\nexport const MIN_POSTPONE_MINUTES_DEFAULT = 60;\nexport const MIN_POSTPONE_MINUTES_WITH_MINUTE_SCHEDULING = 5;\n", "export const E2B_SANDBOX_TIMEOUT_MS = 43_200_000; // 12 hour timeout\n", "/**\n * Central evaluation rubric catalog shared across backend and frontend.\n *\n * This is the ever-growing catalog of every rubric that has ever been used.\n * Never remove entries \u2014 the admin dashboard needs them to display\n * historical evaluation data.\n */\n\n/**\n * High-level cause classification for evaluation rubrics.\n *\n * Each class needs different treatment when a spike is detected:\n *\n * - `sop_gap` \u2014 The user's instructions are missing, ambiguous, or under-specified.\n * Fix: the user improves their SOP (e.g. adds explicit defaults, clarifies scope).\n *\n * - `agent_misbehavior` \u2014 The agent acted incorrectly despite clear instructions.\n * Fix: auto-correct via learnings (e.g. the agent skipped tasks, hallucinated, or\n * ignored stated constraints).\n *\n * - `platform_issue` \u2014 Our infrastructure or tooling failed.\n * Fix: we fix the underlying platform problem (e.g. broken integrations, flaky\n * browser automation, expired credentials).\n *\n * - `user_access_gap` \u2014 The agent cannot make progress until a human admin on\n * the customer side provisions access (e.g. grants a role in the target system,\n * enables a feature for the account, adds the agent user to a group).\n * Fix: a customer-side administrator grants the missing access in the external\n * system. Distinct from `sop_gap` (which is about instructions) and from\n * `platform_issue` (which is something we fix on our side).\n */\nexport type EvaluationRubricCause =\n | \"sop_gap\"\n | \"agent_misbehavior\"\n | \"platform_issue\"\n | \"user_access_gap\";\n\nexport const ALL_EVALUATION_RUBRIC_SEVERITIES = [\n \"critical\",\n \"medium\",\n \"low\",\n] as const;\n\nexport type EvaluationRubricSeverity =\n (typeof ALL_EVALUATION_RUBRIC_SEVERITIES)[number];\n\nexport interface EvaluationRubricDefinition {\n label: string;\n description: string;\n nullable: boolean;\n cause: EvaluationRubricCause;\n is_recommended: boolean;\n}\n\nexport const EVALUATION_RUBRIC_CATALOG = {\n skipped_known_items: {\n label: \"Skipped known items\",\n description:\n \"Did the agent fail to complete one or more explicitly enumerated tasks or items from the original instructions while presenting the task as completed?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: true,\n },\n skipped_discovered_items: {\n label: \"Skipped discovered items\",\n description:\n \"Did the agent fail to process all relevant items discovered during task execution (e.g. files, rows, documents) while presenting the task as completed?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n unrequested_activities: {\n label: \"Unrequested activities\",\n description:\n \"Did the agent spend a significant number of steps on activities that were neither requested by the user nor clearly necessary to unblock required work?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n ignored_constraints: {\n label: \"Ignored constraints\",\n description:\n 'Did the agent explicitly ignore or contradict a clearly stated instruction or constraint (e.g. required format, required steps, \"do not do X\") and still present the task as completed?',\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n format_compliance_failure: {\n label: \"Format compliance failure\",\n description:\n \"Did the agent fail to produce the required output format, structure, or schema (e.g. template, JSON shape, table columns), even if the underlying content was otherwise correct?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: true,\n },\n priority_inversion: {\n label: \"Priority inversion\",\n description:\n \"Did the agent focus on lower-priority or secondary work first and fail to complete critical required tasks as a result?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n unsure_missing_required_step: {\n label: \"Unsure: missing required step\",\n description:\n \"Did the agent explicitly state uncertainty because it could not perform or identify a core, required step defined in the instructions?\",\n nullable: false,\n cause: \"sop_gap\",\n is_recommended: true,\n },\n unsure_missing_instructions: {\n label: \"Unsure: missing instructions\",\n description:\n \"Did the agent explicitly state uncertainty because necessary instructions were missing or ambiguous and not knowable at task start?\",\n nullable: false,\n cause: \"sop_gap\",\n is_recommended: true,\n },\n integration_or_tool_missing: {\n label: \"Integration or tool missing\",\n description:\n \"Did the agent fail to complete required work because a necessary tool or integration was missing or not configured, including cases where the agent explicitly stated uncertainty because the required tool or capability did not exist?\",\n nullable: false,\n cause: \"platform_issue\",\n is_recommended: false,\n },\n integration_or_tool_failure: {\n label: \"Integration or tool failure\",\n description:\n \"Did the agent fail to complete required work because a necessary tool or integration was inaccessible or failed at runtime (e.g. permission or authentication errors, expired credentials, resource not found, execution failure)? IMPORTANT: Do NOT include rate-limit errors here \u2014 any occurrence of HTTP 429, 'too many requests', 'rate limit', 'retry after', 'throttled', or quota-exceeded errors must be evaluated under `rate_limit_hit` instead, even if other non-rate-limit failures also occurred in the same run.\",\n nullable: false,\n cause: \"platform_issue\",\n is_recommended: false,\n },\n rate_limit_hit: {\n label: \"Rate limit hit\",\n description:\n \"Did an external tool or integration return rate-limit errors (HTTP 429, 'too many requests', 'rate limit', 'retry after', 'throttled', quota exceeded) that materially impacted the agent's execution \u2014 whether by causing it to abandon or skip work, wait or retry for extended periods, or significantly degrade throughput? Set to true if rate-limit errors appeared and caused any meaningful disruption, even if the agent eventually completed the task.\",\n nullable: false,\n cause: \"platform_issue\",\n is_recommended: false,\n },\n uncaught_tool_failure: {\n label: \"Uncaught tool failure\",\n description:\n \"Did a tool or execution step fail, but the agent proceeded as if it had succeeded or failed to acknowledge and recover from the failure?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n missed_human_approval: {\n label: \"Missed human approval\",\n description:\n \"Did the agent require human approval to proceed but fail to invoke the HITL (human-in-the-loop) tool?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: true,\n },\n overreach_without_consent: {\n label: \"Overreach without consent\",\n description:\n \"Did the agent take or attempt an action that should reasonably require explicit user or human approval without asking first?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: true,\n },\n missed_user_question: {\n label: \"Missed user question\",\n description:\n \"Did the agent require additional information from the user to continue but fail to ask a question using the AskUserQuestion tool?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n unused_provided_artifact: {\n label: \"Unused provided artifact\",\n description:\n \"Was the agent provided with a file or artifact necessary for the task but failed to use it?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n unused_skill: {\n label: \"Unused skill\",\n description:\n \"Was a skill available that provides capabilities required by the task, but the agent failed to read or invoke it?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n hallucinated_facts: {\n label: \"Hallucinated facts\",\n description:\n \"Did the agent invent facts, data, claims, or details not supported by provided inputs, artifacts, or tool outputs?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: true,\n },\n wrong_assumptions: {\n label: \"Wrong assumptions\",\n description:\n \"Did the agent make a key unstated assumption (e.g. units, definitions, defaults, scope) that materially affected the result without flagging or validating it?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n over_refusal: {\n label: \"Over-refusal\",\n description:\n \"Did the agent unnecessarily refuse or decline a request that was allowed and feasible, or fail to provide partial help when it reasonably could have?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n user_said_wrong: {\n label: \"User said wrong\",\n description:\n \"Did the user explicitly state that the agent's output was wrong, incorrect, off-topic, or low-quality?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: true,\n },\n user_asked_to_continue: {\n label: \"User asked to continue\",\n description:\n \"Did the user explicitly ask the agent to continue or finish remaining work that was still feasible without restarting?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n user_said_incomplete: {\n label: \"User said incomplete\",\n description:\n \"Did the user explicitly state that the final output was incomplete in a way that would require restarting or major rework to fix?\",\n nullable: false,\n cause: \"agent_misbehavior\",\n is_recommended: true,\n },\n browser_repetitive_actions: {\n label: \"Browser repetitive actions\",\n description:\n \"Did the agent perform repetitive browser actions without making meaningful progress (e.g., scrolling up/down multiple times in sequence, taking multiple similar screenshots or snapshots, clicking or extracting from the same elements 3+ times, or repeatedly using the same tool with similar parameters without success)?\",\n nullable: true,\n cause: \"platform_issue\",\n is_recommended: false,\n },\n browser_auth_failure: {\n label: \"Browser auth failure\",\n description:\n \"When browser authentication was required, did the agent fail to properly use available credential tools (list_credentials, fill_username, fill_password, fill_otp), attempt to manually type credentials in an insecure way, or give up on login flows without exhausting available authentication methods?\",\n nullable: true,\n cause: \"platform_issue\",\n is_recommended: false,\n },\n browser_authentication_issues: {\n label: \"Browser authentication issues\",\n description:\n \"When browser authentication was required, did the agent struggle with the login process \u2014 for example, retrying credential entry multiple times, cycling through authentication methods inefficiently, taking an excessive number of steps to complete login, failing to handle TOTP or multi-factor prompts smoothly, or encountering and recovering from repeated auth-related errors \u2014 even if it eventually succeeded?\",\n nullable: true,\n cause: \"platform_issue\",\n is_recommended: false,\n },\n browser_inappropriate_tools: {\n label: \"Browser inappropriate tools\",\n description:\n \"Did the agent repeatedly use inappropriate browser tools for the task at hand (e.g., using only screenshots when element inspection tools would be better, performing actions without first identifying target elements, using data extraction tools repeatedly when they're failing instead of trying different approaches), or fail to adapt its browsing strategy after multiple consecutive failures?\",\n nullable: true,\n cause: \"agent_misbehavior\",\n is_recommended: false,\n },\n browser_permission_wall: {\n label: \"Browser permission wall\",\n description:\n \"After the agent successfully authenticated to a browser-based target site, did the site block a required action because the authenticated account lacks a specific role, permission, or entitlement (e.g., 'Access denied. Required role: X', 'insufficient privileges', '403 Forbidden', 'you do not have permission to perform this action', 'this feature is not enabled for your account')? Set to true ONLY when login itself succeeded and the block appears at a post-login authorization layer; do NOT set true for login/credential failures, missing credentials that the agent could have requested via the request_credentials tool, or generic tool errors unrelated to authorization. This signals that a customer-side administrator must provision additional access on the target system \u2014 it is not a platform defect, not an agent mistake, and cannot be fixed in-run.\",\n nullable: true,\n cause: \"user_access_gap\",\n is_recommended: false,\n },\n browser_network_access_blocked: {\n label: \"Browser network access blocked\",\n description:\n \"Did the agent fail to reach a browser target because the network layer itself was blocked \u2014 i.e., navigation or connection never completed and no login form could be shown (e.g., 'ERR_CONNECTION_TIMED_OUT', 'ERR_NAME_NOT_RESOLVED', 'ERR_TUNNEL_CONNECTION_FAILED', 'this site can't be reached', 'DNS_PROBE_FINISHED_NXDOMAIN', explicit 'You must be connected to VPN' landing pages, or the target resolves only from a corporate network)? Set to true when the failure occurs at navigation/connection time BEFORE any authentication attempt. Do NOT set true for: post-login authorization errors (use browser_permission_wall), rate limits (use rate_limit_hit), login/credential failures, or transient single-request failures that the agent recovered from. This signals that a customer-side administrator must grant network access to the agent's egress \u2014 by allowlisting our IPs, providing VPN access, or exposing the target via a reachable URL.\",\n nullable: true,\n cause: \"user_access_gap\",\n is_recommended: false,\n },\n} as const satisfies Record<string, EvaluationRubricDefinition>;\n\nexport type EvaluationRubricKey = keyof typeof EVALUATION_RUBRIC_CATALOG;\n\nexport const ALL_EVALUATION_RUBRIC_KEYS = Object.keys(\n EVALUATION_RUBRIC_CATALOG\n) as EvaluationRubricKey[];\n\n/**\n * Field on `run_evaluations.output.data` that holds the judge's free-text\n * summary. Excluded when iterating over rubric flags.\n */\nexport const EVALUATION_FINAL_COMMENT_KEY = \"final_comment\";\n\n/**\n * Suffix appended to a rubric key to produce its companion severity field on\n * `run_evaluations.output.data`. The judge writes one of\n * `ALL_EVALUATION_RUBRIC_SEVERITIES` when the rubric flag is `true`, and\n * `null` otherwise.\n */\nexport const EVALUATION_SEVERITY_KEY_SUFFIX = \"_severity\";\n\n/**\n * Suffix appended to a rubric key to produce its companion reason field on\n * `run_evaluations.output.data`. The judge writes a 1-2 sentence explanation\n * (\u2264 EVALUATION_REASON_MAX_LENGTH chars) when the rubric flag is `true`, and\n * `null` otherwise.\n */\nexport const EVALUATION_REASON_KEY_SUFFIX = \"_reason\";\n\nexport const EVALUATION_REASON_MAX_LENGTH = 280;\n\nexport function getRubricSeverityKey(key: EvaluationRubricKey): string {\n return `${key}${EVALUATION_SEVERITY_KEY_SUFFIX}`;\n}\n\nexport function getRubricReasonKey(key: EvaluationRubricKey): string {\n return `${key}${EVALUATION_REASON_KEY_SUFFIX}`;\n}\n\n/**\n * Returns true when `value` is a severity field paired with a rubric flag on\n * `run_evaluations.output.data` (i.e. ends with `_severity` and has a non-empty\n * base). The base does not need to be in `EVALUATION_RUBRIC_CATALOG`: schema\n * generators add boolean rubrics outside the catalog (for example\n * `failed_success_criteria`) that also receive a severity sibling.\n */\nexport function isEvaluationSeverityKey(value: string): boolean {\n return (\n value.length > EVALUATION_SEVERITY_KEY_SUFFIX.length &&\n value.endsWith(EVALUATION_SEVERITY_KEY_SUFFIX)\n );\n}\n\nexport function isEvaluationRubricKey(\n value: string\n): value is EvaluationRubricKey {\n return Object.prototype.hasOwnProperty.call(EVALUATION_RUBRIC_CATALOG, value);\n}\n\nexport const ALL_EVALUATION_RUBRIC_CAUSES = [\n \"sop_gap\",\n \"agent_misbehavior\",\n \"platform_issue\",\n \"user_access_gap\",\n] as const;\n\nexport const EVALUATION_RUBRIC_KEYS_BY_CAUSE: Readonly<\n Record<EvaluationRubricCause, readonly EvaluationRubricKey[]>\n> = (() => {\n const mutable: Record<EvaluationRubricCause, EvaluationRubricKey[]> = {\n sop_gap: [],\n agent_misbehavior: [],\n platform_issue: [],\n user_access_gap: [],\n } satisfies Record<EvaluationRubricCause, EvaluationRubricKey[]>;\n\n for (const key of ALL_EVALUATION_RUBRIC_KEYS) {\n mutable[EVALUATION_RUBRIC_CATALOG[key].cause].push(key);\n }\n\n return mutable;\n})();\n", "/**\n * Human request types for the Activity Inbox feature.\n * - approval: Traditional HITL request requiring user approval\n * - question: AskUserQuestion tool request for clarification\n * - credentials: Agent needs login credentials for a website\n */\nexport const HUMAN_REQUEST_TYPE = {\n APPROVAL: \"approval\",\n QUESTION: \"question\",\n CREDENTIALS: \"credentials\",\n} as const;\n\nexport type HumanRequestType =\n (typeof HUMAN_REQUEST_TYPE)[keyof typeof HUMAN_REQUEST_TYPE];\n", "const SENSITIVE_FIELD_KEYWORDS = [\n \"password\",\n \"passphrase\",\n \"secret\",\n \"token\",\n \"key\",\n \"credential\",\n \"authorization\",\n \"service-account\",\n] as const;\n\nexport function isSensitiveFieldName(fieldName: string): boolean {\n const lower = fieldName.toLowerCase();\n return SENSITIVE_FIELD_KEYWORDS.some((keyword) => lower.includes(keyword));\n}\n\nexport { SENSITIVE_FIELD_KEYWORDS };\n", "/**\n * Duvo platform plugins that are pre-installed in E2B sandbox images.\n * These plugins are distinct from:\n * - Anthropic built-in plugins (from github.com/anthropics/claude-code/plugins/)\n * - GitHub custom plugins (downloaded at runtime from user-specified URLs)\n */\nexport const DUVO_PLATFORM_PLUGINS = [\"browsing\", \"default-skills\"] as const;\n\nexport type DuvoPlatformPlugin = (typeof DUVO_PLATFORM_PLUGINS)[number];\n\nexport const DUVO_PLATFORM_PLUGIN_DESCRIPTIONS: Record<\n DuvoPlatformPlugin,\n string\n> = {\n browsing: \"Enables the assignment to browse the web.\",\n \"default-skills\":\n \"Bundles Duvo's default skills (docx, pdf, pptx, google-sheets, snowflake) so the assignment can read and produce common document formats.\",\n};\n\nexport function isDuvoPlatformPlugin(name: string): name is DuvoPlatformPlugin {\n return (DUVO_PLATFORM_PLUGINS as readonly string[]).includes(name);\n}\n\n// Skill UUIDs now delivered via the default-skills plugin baked into the\n// E2B sandbox image. Soft-deleted from the DB \u2014 used to filter stale\n// references in old build configs.\nexport const PLUGIN_BACKED_DEFAULT_SKILL_IDS = new Set([\n \"a7f3d8e2-9b4c-4e6a-8c3f-1d2e5f7a9b3c\", // docx\n \"b8e4c9f1-3a5d-4b7e-9d2c-6f8a1c3e5d7b\", // pdf\n \"c9d5b8a2-4f6e-4c8a-8e3d-7b9c2d4f6a8e\", // pptx\n \"d8f6e7a3-5b7c-4d9a-9e4f-8c7b3f2a6d5e\", // google-sheets\n \"bad3cc47-8180-4fca-99bd-a51b543c6d87\", // snowflake\n]);\n", "/**\n * Available solution categories for retail solutions\n */\nexport const SOLUTION_CATEGORIES = [\n \"category-merchandising\",\n \"vendor-trade\",\n \"supply-chain\",\n \"finance-ops\",\n \"commercial-marketing\",\n] as const;\n\n/**\n * Solution category type derived from available categories\n */\nexport type SolutionCategory = (typeof SOLUTION_CATEGORIES)[number];\n\n/**\n * Map of solution category slugs to human-readable display labels\n */\nexport const SOLUTION_CATEGORY_LABELS: Record<SolutionCategory, string> = {\n \"category-merchandising\": \"Category & Merchandising\",\n \"vendor-trade\": \"Vendor & Trade\",\n \"supply-chain\": \"Supply Chain\",\n \"finance-ops\": \"Finance Ops\",\n \"commercial-marketing\": \"Commercial & Marketing\",\n} as const;\n\n/**\n * Format solution category slug into display label\n */\nexport const formatSolutionCategoryLabel = (\n category: SolutionCategory\n): string => {\n return SOLUTION_CATEGORY_LABELS[category] || category;\n};\n", "export const LINEAR_TRIGGER_TYPE = \"linear_event\" as const;\n\nexport const LINEAR_EVENT_TYPES = [\n \"new_issue\",\n \"issue_state_changed\",\n \"issue_assigned\",\n \"new_comment\",\n] as const;\n\nexport type LinearEventType = (typeof LINEAR_EVENT_TYPES)[number];\n", "export const COOKIE_NAMES = {\n IMPERSONATION: \"impersonation\",\n OTP_IMPORT_GUIDE_DISMISSED: \"otp_import_guide_dismissed\",\n LAST_VISITED_QUEUE_ID: \"duvo_last_visited_queue_id\",\n POST_LOGOUT_REDIRECT: \"post_logout_redirect\",\n} as const;\n\nexport type CookieName = (typeof COOKIE_NAMES)[keyof typeof COOKIE_NAMES];\n", "import { z } from \"zod\";\n\nexport const CLARITY_SCREENSHARE_SESSION_STATUSES = [\n \"active\",\n \"completing\",\n \"completed\",\n] as const;\n\nexport type ClarityScreenshareSessionStatus =\n (typeof CLARITY_SCREENSHARE_SESSION_STATUSES)[number];\n\nexport const CLARITY_SCREENSHARE_COVERAGE_AREAS = [\n \"processIdentity\",\n \"stepsAndFlow\",\n \"inputsAndResources\",\n \"toolsAndSystems\",\n \"outputsAndRecords\",\n \"timingAndControls\",\n \"exceptionsAndFailureModes\",\n \"painPoints\",\n] as const;\n\nexport type ClarityScreenshareCoverageArea =\n (typeof CLARITY_SCREENSHARE_COVERAGE_AREAS)[number];\n\nexport const CLARITY_SCREENSHARE_AREA_STATUSES = [\n \"not_started\",\n \"partial\",\n \"covered\",\n] as const;\n\nexport type ClarityScreenshareAreaStatus =\n (typeof CLARITY_SCREENSHARE_AREA_STATUSES)[number];\n\nexport const CLARITY_SCREENSHARE_DECISIONS = [\n \"suggestion\",\n \"context\",\n \"close\",\n \"silence\",\n] as const;\n\nexport type ClarityScreenshareDecision =\n (typeof CLARITY_SCREENSHARE_DECISIONS)[number];\n\n// --- Coverage ---\n\nconst areaStatusSchema = z.enum(CLARITY_SCREENSHARE_AREA_STATUSES);\n\nconst processIdentityExtractedSchema = z.object({\n processName: z.string().nullable(),\n owner: z.string().nullable(),\n trigger: z.string().nullable(),\n finalOutput: z.string().nullable(),\n recentInstance: z.string().nullable(),\n});\n\nconst stepsAndFlowExtractedSchema = z.object({\n majorPhases: z.array(z.object({ name: z.string(), description: z.string() })),\n handoffs: z.array(\n z.object({\n from: z.string(),\n to: z.string(),\n description: z.string(),\n })\n ),\n});\n\nconst inputsAndResourcesExtractedSchema = z.object({\n inputs: z.array(\n z.object({\n step: z.string(),\n items: z.array(z.string()),\n source: z.string(),\n })\n ),\n missingOrLateInputs: z.array(z.string()),\n phaseOwners: z.array(\n z.object({ phase: z.string(), role: z.string(), team: z.string() })\n ),\n totalPeopleInvolved: z.string().nullable(),\n});\n\nconst toolsAndSystemsExtractedSchema = z.object({\n toolsPerStep: z.array(\n z.object({ step: z.string(), tools: z.array(z.string()) })\n ),\n manualReentry: z.array(z.string()),\n});\n\nconst outputsAndRecordsExtractedSchema = z.object({\n outputsPerStage: z.array(\n z.object({ stage: z.string(), artifacts: z.array(z.string()) })\n ),\n systemOfRecord: z.string().nullable(),\n scattered: z.boolean().nullable(),\n});\n\nconst timingAndControlsExtractedSchema = z.object({\n cycleTimePerStep: z.array(\n z.object({ step: z.string(), duration: z.string() })\n ),\n waitingPoints: z.array(z.string()),\n approvalsAndChecks: z.array(\n z.object({ description: z.string(), whereRecorded: z.string() })\n ),\n overallCycleTime: z.string().nullable(),\n});\n\nconst exceptionsAndFailureModesExtractedSchema = z.object({\n exceptions: z.array(\n z.object({\n description: z.string(),\n percentageAffected: z.string(),\n additionalTime: z.string(),\n })\n ),\n});\n\nconst painPointsExtractedSchema = z.object({\n painPoints: z.array(\n z.object({ description: z.string(), estimatedMonthlyCost: z.string() })\n ),\n topBottlenecks: z.array(\n z.object({ description: z.string(), timeImpact: z.string() })\n ),\n});\n\nconst areaSchema = <T extends z.ZodType>(extractedSchema: T) =>\n z.object({\n status: areaStatusSchema,\n extracted: extractedSchema,\n });\n\nexport const clarityScreenshareCoverageSchema = z.object({\n startedAt: z.number(),\n roundNumber: z.number(),\n elapsedSeconds: z.number(),\n timeTargetSeconds: z.number(),\n processName: z.string(),\n areas: z.object({\n processIdentity: areaSchema(processIdentityExtractedSchema),\n stepsAndFlow: areaSchema(stepsAndFlowExtractedSchema),\n inputsAndResources: areaSchema(inputsAndResourcesExtractedSchema),\n toolsAndSystems: areaSchema(toolsAndSystemsExtractedSchema),\n outputsAndRecords: areaSchema(outputsAndRecordsExtractedSchema),\n timingAndControls: areaSchema(timingAndControlsExtractedSchema),\n exceptionsAndFailureModes: areaSchema(\n exceptionsAndFailureModesExtractedSchema\n ),\n painPoints: areaSchema(painPointsExtractedSchema),\n }),\n gaps: z.array(z.string()),\n});\n\nexport type ClarityScreenshareCoverage = z.infer<\n typeof clarityScreenshareCoverageSchema\n>;\n\nexport function createInitialCoverage(\n processName: string\n): ClarityScreenshareCoverage {\n return {\n startedAt: 0,\n roundNumber: 0,\n elapsedSeconds: 0,\n timeTargetSeconds: 600,\n processName,\n areas: {\n processIdentity: {\n status: \"not_started\",\n extracted: {\n processName: null,\n owner: null,\n trigger: null,\n finalOutput: null,\n recentInstance: null,\n },\n },\n stepsAndFlow: {\n status: \"not_started\",\n extracted: { majorPhases: [], handoffs: [] },\n },\n inputsAndResources: {\n status: \"not_started\",\n extracted: {\n inputs: [],\n missingOrLateInputs: [],\n phaseOwners: [],\n totalPeopleInvolved: null,\n },\n },\n toolsAndSystems: {\n status: \"not_started\",\n extracted: { toolsPerStep: [], manualReentry: [] },\n },\n outputsAndRecords: {\n status: \"not_started\",\n extracted: {\n outputsPerStage: [],\n systemOfRecord: null,\n scattered: null,\n },\n },\n timingAndControls: {\n status: \"not_started\",\n extracted: {\n cycleTimePerStep: [],\n waitingPoints: [],\n approvalsAndChecks: [],\n overallCycleTime: null,\n },\n },\n exceptionsAndFailureModes: {\n status: \"not_started\",\n extracted: { exceptions: [] },\n },\n painPoints: {\n status: \"not_started\",\n extracted: { painPoints: [], topBottlenecks: [] },\n },\n },\n gaps: [\n \"Process identity: name, owner, trigger, output, recent instance\",\n \"Steps and flow: major phases, handoffs\",\n \"Inputs and resources: inputs per step, missing/late, phase owners, headcount\",\n \"Tools and systems: tools per step, manual re-entry\",\n \"Outputs and records: artifacts per stage, system of record\",\n \"Timing and controls: SLAs, waiting points, approvals\",\n \"Exceptions and failure modes: common exceptions, % affected, resolution time\",\n \"Pain points: top 3 time sinks, estimated monthly cost\",\n ],\n };\n}\n\n// --- Transcript ---\n\nexport const clarityScreenshareTranscriptEntrySchema = z.object({\n id: z.string(),\n timestamp: z.number(),\n role: z.enum([\"user\", \"assistant\", \"interviewer\"]),\n text: z.string(),\n});\n\nexport type ClarityScreenshareTranscriptEntry = z.infer<\n typeof clarityScreenshareTranscriptEntrySchema\n>;\n\n// --- Frame ---\n\nexport const clarityScreenshareFrameSchema = z.object({\n base64: z.string(),\n timestamp: z.number(),\n});\n\nexport type ClarityScreenshareFrame = z.infer<\n typeof clarityScreenshareFrameSchema\n>;\n\n// --- Screenshare language ---\n\nexport const screenshareLanguageSchema = z.enum([\n \"cs\",\n \"de\",\n \"en\",\n \"es\",\n \"fr\",\n \"pl\",\n]);\n\nexport type ScreenshareLanguage = z.infer<typeof screenshareLanguageSchema>;\n\n// --- Turn submission (FE -> BE) ---\n\nexport const clarityScreenshareTurnBodySchema = z.object({\n transcript: z.array(clarityScreenshareTranscriptEntrySchema),\n images: z.array(clarityScreenshareFrameSchema),\n coverage: clarityScreenshareCoverageSchema,\n turnNumber: z.number(),\n elapsedSeconds: z.number(),\n language: screenshareLanguageSchema,\n});\n\nexport type ClarityScreenshareTurnBody = z.infer<\n typeof clarityScreenshareTurnBodySchema\n>;\n\n// --- Turn response (BE -> FE) ---\n\nexport const clarityScreenshareTurnResponseSchema = z.object({\n decision: z.enum(CLARITY_SCREENSHARE_DECISIONS),\n text: z.string().nullable(),\n coverage: clarityScreenshareCoverageSchema,\n turnNumber: z.number(),\n});\n\nexport type ClarityScreenshareTurnResponse = z.infer<\n typeof clarityScreenshareTurnResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport {\n clarityCaptureSchema,\n clarityProcessStatusSchema,\n generationProgressSchema,\n} from \"../types/clarity\";\nimport {\n clarityV2SnapshotCreatorTypeSchema,\n clarityV2SnapshotStatusSchema,\n postprocessClarityCurrentProcessDataSchema,\n postprocessClarityStepBaseSchema,\n postprocessClarityTransformationProposalDataSchema,\n} from \"./process-data\";\nimport { refineStepGraph } from \"./validators\";\n\nconst versioningApiFields = {\n status: clarityV2SnapshotStatusSchema.describe(\n \"Versioning state. Only one 'live' row per process at a time; everything else is 'historic'.\"\n ),\n creator_type: clarityV2SnapshotCreatorTypeSchema.describe(\n \"Whether this row was created by a user edit ('human') or an AI pipeline run ('ai').\"\n ),\n user_id: z\n .guid()\n .nullable()\n .describe(\"Creator user id (the human who edited or triggered the run).\"),\n sandbox_id: z\n .string()\n .nullable()\n .describe(\"E2B sandbox id that produced AI rows; null for user edits.\"),\n};\n\n/**\n * Wire-format current-process snapshot for the v2 read model. Wrapper fields\n * are snake_case per the public-API guide; the nested `data` payload is an\n * LLM-produced BPMN graph that stays camelCase as a documented opaque\n * payload \u2014 converting the inner schema would touch every prompt and\n * postprocess agent.\n */\nexport const clarityCurrentProcessSnapshotApiSchema = z.object({\n id: z.guid().describe(\"Snapshot id\"),\n data: postprocessClarityCurrentProcessDataSchema.describe(\n \"Opaque BPMN payload describing the captured process. Field names inside `data` are camelCase by design.\"\n ),\n created_at: z.string().describe(\"ISO 8601 creation timestamp\"),\n updated_at: z.string().describe(\"ISO 8601 last-update timestamp\"),\n ...versioningApiFields,\n});\n\nexport const clarityTransformationProposalSnapshotApiSchema = z.object({\n id: z.guid().describe(\"Proposal id\"),\n data: postprocessClarityTransformationProposalDataSchema.describe(\n \"Opaque BPMN payload for the proposed transformed process. Field names inside `data` are camelCase by design.\"\n ),\n created_at: z.string().describe(\"ISO 8601 creation timestamp\"),\n updated_at: z.string().describe(\"ISO 8601 last-update timestamp\"),\n ...versioningApiFields,\n});\n\nexport const EXTRA_CAPTURE_REQUEST_PRIORITIES = [\n \"low\",\n \"medium\",\n \"high\",\n] as const;\n\nexport const EXTRA_CAPTURE_REQUEST_STATUSES = [\n \"requested\",\n \"captured\",\n \"resolved\",\n] as const;\n\n/**\n * Wire-format shape of one row from `clarity_proposal_extra_capture_request`.\n * Callers key by `id` to look up which steps still need a capture\n * (`status === \"requested\"`) versus which have already been filled in by a\n * prior capture (`status === \"captured\" | \"resolved\"`).\n *\n * `requested_user_id` is the team member assigned to fulfil the capture\n * (set by an admin/manager via the assign route). When non-null, only that\n * user should see the \"Add capture\" button; everyone else sees the assignee.\n */\nexport const clarityProposalExtraCaptureRequestSchema = z.object({\n id: z.guid().describe(\"Extra-capture-request id\"),\n proposal_id: z\n .guid()\n .describe(\"The transformation proposal this request belongs to\"),\n step_id: z.string().describe(\"Step id within the proposal's BPMN graph\"),\n capture_id: z\n .guid()\n .nullable()\n .describe(\"Capture that fulfilled this request, once one is created\"),\n requested_user_id: z\n .guid()\n .nullable()\n .describe(\"Assigned team member, if any\"),\n status: z\n .enum(EXTRA_CAPTURE_REQUEST_STATUSES)\n .describe(\"Lifecycle status of the request\"),\n gap: z.string().describe(\"Plain-language gap blocking automation\"),\n suggested_prompt: z\n .string()\n .nullable()\n .describe(\"LLM-produced suggested capture prompt\"),\n priority: z\n .enum(EXTRA_CAPTURE_REQUEST_PRIORITIES)\n .describe(\"Priority of fulfilling this request\"),\n created_at: z.string().describe(\"ISO 8601 creation timestamp\"),\n updated_at: z.string().describe(\"ISO 8601 last-update timestamp\"),\n});\n\nexport type ClarityProposalExtraCaptureRequest = z.infer<\n typeof clarityProposalExtraCaptureRequestSchema\n>;\n\n/**\n * Lightweight version-list row. Drops the heavy `data` JSONB so the picker\n * can render dozens of versions cheaply. The full snapshot is fetched on\n * demand via the per-snapshot detail endpoint.\n */\nexport const clarityCurrentProcessVersionApiSchema = z.object({\n id: z.guid().describe(\"Snapshot id\"),\n process_id: z.guid().describe(\"Parent clarity_process id\"),\n created_at: z.string().describe(\"ISO 8601 creation timestamp\"),\n ...versioningApiFields,\n});\n\nexport const clarityTransformationProposalVersionApiSchema =\n clarityCurrentProcessVersionApiSchema.extend({\n clarity_current_process_id: z\n .guid()\n .describe(\n \"The current-process snapshot this proposal was generated against (provenance only; the live proposal can target any current-process snapshot).\"\n ),\n extra_capture_requests: z\n .array(clarityProposalExtraCaptureRequestSchema)\n .describe(\n \"Active extra-capture requests for this proposal. Populated only on the live proposal version row so the FE can render assignment UI without a second round-trip; historic versions return an empty array. The standalone list endpoint stays the source of truth for paginated/admin views.\"\n ),\n });\n\nexport type ClarityCurrentProcessVersionApi = z.infer<\n typeof clarityCurrentProcessVersionApiSchema\n>;\n\nexport type ClarityTransformationProposalVersionApi = z.infer<\n typeof clarityTransformationProposalVersionApiSchema\n>;\n\nexport type ClarityCurrentProcessSnapshotApi = z.infer<\n typeof clarityCurrentProcessSnapshotApiSchema\n>;\n\nexport type ClarityTransformationProposalSnapshotApi = z.infer<\n typeof clarityTransformationProposalSnapshotApiSchema\n>;\n\n/**\n * Internal in-memory snapshot used by repos and route handlers. Identical\n * to the wire-format API schema except it carries the parent FK columns\n * (`process_id`, plus `clarity_current_process_id` for proposals) so the\n * BE can validate cross-resource invariants without an extra round-trip.\n * The Fastify response serializer parses against the wire schema, which\n * strips those extra fields automatically \u2014 so handlers can return the\n * full snapshot directly without a separate camelCase serialization step.\n */\nexport type ClarityCurrentProcessSnapshot = ClarityCurrentProcessSnapshotApi & {\n process_id: string;\n};\n\nexport type ClarityTransformationProposalSnapshot =\n ClarityTransformationProposalSnapshotApi & {\n process_id: string;\n clarity_current_process_id: string;\n };\n\n/** Internal version-list rows used by repos. Aliases for consistency with\n * the snapshot-types convention above; the wire schemas already include\n * every field these aliases need. */\nexport type ClarityCurrentProcessVersion = ClarityCurrentProcessVersionApi;\nexport type ClarityTransformationProposalVersion =\n ClarityTransformationProposalVersionApi;\n\nexport const clarityV2ProcessReadModelSchema = z.object({\n process: z.object({\n id: z.guid().describe(\"Clarity process id\"),\n team_id: z.guid().describe(\"Owning team id\"),\n user_id: z.guid().describe(\"Creator user id\"),\n name: z.string().describe(\"Process name\"),\n status: clarityProcessStatusSchema.describe(\"Lifecycle status\"),\n version: z.number().int().describe(\"Schema version (always 2 here)\"),\n generation_error: z\n .string()\n .nullable()\n .describe(\"Error message from the most recent failed generation, if any\"),\n generation_progress: generationProgressSchema\n .nullable()\n .describe(\n \"Live progress checklist while a generation is in flight; null otherwise. Field names inside the payload are camelCase, matching the legacy v1 generation-progress shape.\"\n ),\n custom_prompt: z\n .string()\n .nullable()\n .describe(\"User-supplied custom prompt that steers generation\"),\n created_at: z.string().describe(\"ISO 8601 creation timestamp\"),\n updated_at: z.string().describe(\"ISO 8601 last-update timestamp\"),\n }),\n current_process_versions: z\n .array(clarityCurrentProcessVersionApiSchema)\n .describe(\n \"All non-deleted current-process snapshots, newest first. Lightweight rows (no `data`) for the version-picker UI. Clients lazy-fetch the live (or selected) snapshot via the per-snapshot detail endpoint.\"\n ),\n transformation_proposal_versions: z\n .array(clarityTransformationProposalVersionApiSchema)\n .describe(\n \"All non-deleted transformation-proposal snapshots, newest first. Lightweight rows (no `data`) for the version-picker UI.\"\n ),\n captures: z\n .array(clarityCaptureSchema)\n .describe(\n \"All captures (videos, interviews, documents) attached to this process. Field names follow the legacy v1 capture wire format (camelCase) so existing capture consumers keep working unchanged.\"\n ),\n});\n\nexport type ClarityV2ProcessReadModel = z.infer<\n typeof clarityV2ProcessReadModelSchema\n>;\n\n/**\n * Response shape for the per-proposal extra-capture-request list endpoint.\n * Includes pagination metadata as required by the public-API guide.\n */\nexport const clarityProposalExtraCaptureRequestListResponseSchema = z.object({\n requests: z.array(clarityProposalExtraCaptureRequestSchema),\n total: z.number().int().describe(\"Total matching rows across all pages\"),\n limit: z.number().int().describe(\"Page size that was applied\"),\n offset: z.number().int().describe(\"Offset that was applied\"),\n});\n\nexport type ClarityProposalExtraCaptureRequestListResponse = z.infer<\n typeof clarityProposalExtraCaptureRequestListResponseSchema\n>;\n\n/**\n * Body for the assign route. `user_id` is the team member to assign; pass\n * `null` to clear the existing assignment.\n */\nexport const assignClarityProposalExtraCaptureRequestRequestSchema = z.object({\n user_id: z\n .guid()\n .nullable()\n .describe(\"Team member to assign, or null to unassign\"),\n});\n\n/**\n * Body for the save-current-process route. Persists a user-edited steps array\n * as a new `clarity_current_process` snapshot. The new row is automatically\n * marked `live`, demoting any previously live row to `historic` in the same\n * transaction.\n *\n * `steps` is validated against the same graph rules the pipeline applies via\n * `refineStepGraph`, so the FE cannot bypass invariants by going through this\n * route.\n *\n * `baselineSnapshotId` is the snapshot the user was editing (live or\n * historic). It is no longer used for optimistic concurrency: the route never\n * returns 409. It is still required because the postprocess slice merge needs\n * to know which row the edit forked from \u2014 without it the merge would\n * silently use whichever row happens to be live, which is wrong when editing\n * a historic version.\n */\nexport const saveClarityV2CurrentProcessBodySchema = z.object({\n steps: z\n .array(postprocessClarityStepBaseSchema)\n .min(1)\n .superRefine(refineStepGraph),\n baselineSnapshotId: z.guid(),\n});\n\n/**\n * Body for the save-transformation-proposal route. Persists a user-edited\n * steps array as a new `clarity_transformation_proposal` snapshot. The new\n * row is automatically marked `live`, demoting any previously live row to\n * `historic` in the same transaction.\n *\n * Same notes as `saveClarityV2CurrentProcessBodySchema`: `baselineSnapshotId`\n * is for merge-source provenance, not conflict detection.\n */\nexport const saveClarityV2TransformationProposalBodySchema = z.object({\n steps: z\n .array(postprocessClarityStepBaseSchema)\n .min(1)\n .superRefine(refineStepGraph),\n baselineSnapshotId: z.guid(),\n clarityCurrentProcessId: z.guid(),\n});\n\n/**\n * Response for both save routes. Reuses the public read-model API schemas so\n * the FE can drop the response straight into its query cache without\n * reshaping snake_case \u2194 camelCase keys on every save.\n */\nexport const saveClarityV2CurrentProcessResponseSchema = z.object({\n snapshot: clarityCurrentProcessSnapshotApiSchema,\n});\n\nexport type SaveClarityV2CurrentProcessResponse = z.infer<\n typeof saveClarityV2CurrentProcessResponseSchema\n>;\n\nexport const saveClarityV2TransformationProposalResponseSchema = z.object({\n snapshot: clarityTransformationProposalSnapshotApiSchema,\n});\n\nexport type SaveClarityV2TransformationProposalResponse = z.infer<\n typeof saveClarityV2TransformationProposalResponseSchema\n>;\n\n/**\n * Body for the postprocess route. Re-runs the postprocessing agents on an\n * existing snapshot identified by the discriminated `type`. Used to recover\n * when an agent silently failed and a tab is left without data.\n */\nexport const postprocessClarityV2SnapshotBodySchema = z.discriminatedUnion(\n \"type\",\n [\n z.object({\n type: z.literal(\"current_process\"),\n current_process_id: z\n .guid()\n .describe(\n \"ID of the `clarity_current_process` snapshot to re-postprocess.\"\n ),\n }),\n z.object({\n type: z.literal(\"transformation_proposal\"),\n transformation_proposal_id: z\n .guid()\n .describe(\n \"ID of the `clarity_transformation_proposal` snapshot to re-postprocess.\"\n ),\n }),\n ]\n);\n\nexport type PostprocessClarityV2SnapshotBody = z.infer<\n typeof postprocessClarityV2SnapshotBodySchema\n>;\n\n/**\n * Response shape for the per-snapshot detail endpoints. Returns the full row\n * including the heavy `data` JSONB. Lazy-fetched when the user picks a\n * specific version. The lightweight version arrays are returned by the\n * read model itself (`current_process_versions` /\n * `transformation_proposal_versions`); there is no separate list endpoint.\n */\nexport const clarityV2CurrentProcessSnapshotDetailResponseSchema = z.object({\n snapshot: clarityCurrentProcessSnapshotApiSchema,\n});\n\nexport type ClarityV2CurrentProcessSnapshotDetailResponse = z.infer<\n typeof clarityV2CurrentProcessSnapshotDetailResponseSchema\n>;\n\nexport const clarityV2TransformationProposalSnapshotDetailResponseSchema =\n z.object({\n snapshot: clarityTransformationProposalSnapshotApiSchema,\n });\n\nexport type ClarityV2TransformationProposalSnapshotDetailResponse = z.infer<\n typeof clarityV2TransformationProposalSnapshotDetailResponseSchema\n>;\n\n/**\n * Response for the promote endpoints. Returns the now-live snapshot with full\n * data so the FE can display it without an extra fetch.\n */\nexport const promoteClarityV2CurrentProcessResponseSchema =\n clarityV2CurrentProcessSnapshotDetailResponseSchema;\n\nexport const promoteClarityV2TransformationProposalResponseSchema =\n clarityV2TransformationProposalSnapshotDetailResponseSchema;\n", "import { z } from \"zod\";\n\nexport const CLARITY_PROCESS_STATUSES = [\n \"draft\",\n \"collecting\",\n \"generating\",\n \"review\",\n \"complete\",\n \"generation_failed\",\n] as const;\n\nexport type ClarityProcessStatus = (typeof CLARITY_PROCESS_STATUSES)[number];\n\nexport const clarityProcessStatusSchema = z.enum(CLARITY_PROCESS_STATUSES);\n\nexport const CLARITY_CAPTURE_STATUSES = [\n \"pending\",\n \"recording\",\n \"processing\",\n \"complete\",\n \"failed\",\n] as const;\n\nexport type ClarityCaptureStatus = (typeof CLARITY_CAPTURE_STATUSES)[number];\n\nexport const clarityCaptureStatusSchema = z.enum(CLARITY_CAPTURE_STATUSES);\n\nexport const CLARITY_CAPTURE_TYPES = [\n \"video\",\n \"interview\",\n \"document\",\n \"screenshare\",\n] as const;\n\nexport type ClarityCaptureType = (typeof CLARITY_CAPTURE_TYPES)[number];\n\nexport const clarityCaptureTypeSchema = z.enum(CLARITY_CAPTURE_TYPES);\n\nexport const conversationMessageSchema = z.object({\n source: z.enum([\"ai\", \"user\", \"interviewer\"]),\n message: z.string().min(1),\n timestamp: z.number().optional(),\n});\n\nexport type ConversationMessage = z.infer<typeof conversationMessageSchema>;\n\nexport type ClarityStep = {\n title: string;\n /** Legacy markdown blob. Retained so old analyses still render. Prefer the structured fields below for new data. */\n description?: string;\n action?: string;\n role?: string;\n system?: string;\n input?: string;\n output?: string;\n condition?: string;\n exception?: string;\n handling?: string;\n order?: number;\n};\n\nexport const CLARITY_STEP_STRUCTURED_FIELDS = [\n \"action\",\n \"role\",\n \"system\",\n \"input\",\n \"output\",\n \"condition\",\n \"exception\",\n \"handling\",\n] as const;\n\nexport type ClarityStepStructuredField =\n (typeof CLARITY_STEP_STRUCTURED_FIELDS)[number];\n\nfunction hasNonEmptyStepValue(value: string | undefined): boolean {\n return (value ?? \"\").trim().length > 0;\n}\n\nfunction hasClarityStepContent(step: ClarityStep): boolean {\n return (\n hasNonEmptyStepValue(step.description) ||\n CLARITY_STEP_STRUCTURED_FIELDS.some((field) =>\n hasNonEmptyStepValue(step[field])\n )\n );\n}\n\nexport const editableClarityStepSchema = z\n .object({\n title: z.string().min(1),\n description: z.string().optional(),\n action: z.string().optional(),\n role: z.string().optional(),\n system: z.string().optional(),\n input: z.string().optional(),\n output: z.string().optional(),\n condition: z.string().optional(),\n exception: z.string().optional(),\n handling: z.string().optional(),\n order: z.int().positive().optional(),\n })\n .superRefine((step, ctx) => {\n if (hasClarityStepContent(step)) {\n return;\n }\n\n ctx.addIssue({\n code: \"custom\",\n message:\n \"Step must include a description or at least one structured field with content\",\n });\n });\n\nexport const clarityStepSchema = z.object({\n title: z.string().min(1),\n description: z.string().min(1),\n action: z.string().optional(),\n role: z.string().optional(),\n system: z.string().optional(),\n input: z.string().optional(),\n output: z.string().optional(),\n condition: z.string().optional(),\n exception: z.string().optional(),\n handling: z.string().optional(),\n order: z.int().positive().optional(),\n});\n\nexport const CLARITY_STEP_TARGETS = [\"current\", \"proposed\"] as const;\nexport type ClarityStepTarget = (typeof CLARITY_STEP_TARGETS)[number];\nexport const clarityStepTargetSchema = z.enum(CLARITY_STEP_TARGETS);\n\nexport const updateClarityStepsSchema = z.object({\n target: clarityStepTargetSchema,\n steps: z.array(editableClarityStepSchema).min(1),\n});\n\nexport type UpdateClarityStepsBody = z.infer<typeof updateClarityStepsSchema>;\n\nexport const resetClarityStepsSchema = z.object({\n target: clarityStepTargetSchema,\n});\n\nexport type ResetClarityStepsBody = z.infer<typeof resetClarityStepsSchema>;\n\n/**\n * ClarityInsight represents a unified finding that combines\n * what were previously separate \"gaps\" and \"opportunities\".\n * Each insight captures an issue and its recommendation.\n * Array position conveys priority (first = highest impact).\n */\nexport type ClarityInsight = {\n title: string;\n issue: string;\n recommendation: string;\n};\n\nexport const clarityInsightSchema = z.object({\n title: z.string().min(1),\n issue: z.string().min(1),\n recommendation: z.string().min(1),\n});\n\n/**\n * A single phase in the process transformation roadmap.\n * Describes the transition from current state to proposed state.\n */\nexport type TransformationPhase = {\n title: string;\n currentState: string;\n proposedState: string;\n /** Required for new generations; optional for backward compatibility with old data */\n rationale?: string;\n};\n\nexport const transformationPhaseSchema = z.object({\n title: z.string().min(1),\n currentState: z.string().min(1),\n proposedState: z.string().min(1),\n rationale: z.string().min(1).optional(),\n});\n\n/**\n * ProcessTransformation proposes a complete redesign of the process,\n * questioning fundamental assumptions rather than just patching issues.\n * Think: \"If we designed this from scratch today, what would it look like?\"\n */\nexport type ProcessTransformation = {\n /** 2-3 sentence \"north star\" description of the ideal end state */\n visionStatement: string;\n /** Brief summary of how the process works today */\n currentProcessSummary: string;\n /** Brief summary of the proposed redesigned process */\n proposedProcessSummary: string;\n /** Legacy phased implementation roadmap. Replaced by top-level proposedProcessFlow + proposedSteps. */\n phases?: TransformationPhase[];\n /** Process-specific key metrics + money impact with calculation basis. Null if no team context. */\n projectedImpact: string | null;\n};\n\nexport const processTransformationSchema = z.object({\n visionStatement: z.string().min(1),\n currentProcessSummary: z.string().min(1),\n proposedProcessSummary: z.string().min(1),\n phases: z.array(transformationPhaseSchema).min(1).max(4).optional(),\n projectedImpact: z.string().nullable().default(null),\n});\n\n// Risk & resilience types for process vulnerability analysis\nexport const RESILIENCE_RATINGS = [\n \"fragile\",\n \"brittle\",\n \"moderate\",\n \"resilient\",\n] as const;\n\nexport type ResilienceRating = (typeof RESILIENCE_RATINGS)[number];\n\nexport type ProcessVulnerability = {\n title: string;\n description: string;\n};\n\nexport const processVulnerabilitySchema = z.object({\n title: z.string().min(1),\n description: z.string().min(1),\n});\n\nexport type ProcessRiskResilience = {\n resilienceRating: ResilienceRating;\n resilienceNarrative: string;\n vulnerabilities: ProcessVulnerability[];\n};\n\nexport const processRiskResilienceSchema = z.object({\n resilienceRating: z.enum(RESILIENCE_RATINGS),\n resilienceNarrative: z.string().min(1),\n vulnerabilities: z.array(processVulnerabilitySchema).min(1).max(10),\n});\n\n// BPMN-aligned node types (Level 1)\nexport const PROCESS_FLOW_NODE_TYPES = [\"event\", \"task\", \"gateway\"] as const;\n\nexport const PROCESS_FLOW_EVENT_SUBTYPES = [\n \"start\",\n \"end\",\n \"timer\",\n \"message\",\n \"escalation\",\n] as const;\n\nexport const PROCESS_FLOW_TASK_SUBTYPES = [\n \"user\",\n \"service\",\n \"send\",\n \"receive\",\n \"manual\",\n \"businessRule\",\n \"script\",\n] as const;\n\nexport const PROCESS_FLOW_GATEWAY_SUBTYPES = [\n \"exclusive\",\n \"parallel\",\n \"inclusive\",\n] as const;\n\n// Legacy types for backward compat with existing stored analyses\nexport const PROCESS_FLOW_LEGACY_NODE_TYPES = [\n \"step\",\n \"decision\",\n \"inform\",\n \"escalation\",\n \"wait\",\n] as const;\n\nexport type ProcessFlowNodeType = (typeof PROCESS_FLOW_NODE_TYPES)[number];\nexport type ProcessFlowLegacyNodeType =\n (typeof PROCESS_FLOW_LEGACY_NODE_TYPES)[number];\nexport type ProcessFlowEventSubtype =\n (typeof PROCESS_FLOW_EVENT_SUBTYPES)[number];\nexport type ProcessFlowTaskSubtype =\n (typeof PROCESS_FLOW_TASK_SUBTYPES)[number];\nexport type ProcessFlowGatewaySubtype =\n (typeof PROCESS_FLOW_GATEWAY_SUBTYPES)[number];\n\nexport const processFlowNodeSchema = z.object({\n id: z.string(),\n type: z.enum([...PROCESS_FLOW_NODE_TYPES, ...PROCESS_FLOW_LEGACY_NODE_TYPES]),\n subtype: z\n .enum([\n ...PROCESS_FLOW_EVENT_SUBTYPES,\n ...PROCESS_FLOW_TASK_SUBTYPES,\n ...PROCESS_FLOW_GATEWAY_SUBTYPES,\n ])\n .optional(),\n label: z.string(),\n performer: z.string().optional(),\n description: z.string().optional(),\n});\nexport type ProcessFlowNode = z.infer<typeof processFlowNodeSchema>;\n\nexport const processFlowEdgeSchema = z.object({\n source: z.string(),\n target: z.string(),\n label: z.string().optional(),\n isDefault: z.boolean().optional(),\n});\nexport type ProcessFlowEdge = z.infer<typeof processFlowEdgeSchema>;\n\nexport const processFlowSchema = z.object({\n nodes: z.array(processFlowNodeSchema),\n edges: z.array(processFlowEdgeSchema),\n});\nexport type ProcessFlow = z.infer<typeof processFlowSchema>;\n\nexport const CLARITY_STEPS_SOURCES = [\"ai\", \"human\"] as const;\nexport type ClarityStepsSource = (typeof CLARITY_STEPS_SOURCES)[number];\n\nexport type ClarityAnalysis = {\n summary: string | null;\n steps: ClarityStep[] | null;\n /** Tracks whether current steps were last set by AI or a human edit. Null/undefined for legacy analyses. */\n stepsSource?: ClarityStepsSource | null;\n /** Top 5 highest-priority insights ordered by business impact */\n insights: ClarityInsight[] | null;\n /** Visual flow representation of the current process. Null for legacy analyses. */\n processFlow: ProcessFlow | null;\n /** Financial impact narrative estimating costs of inefficiencies. Null if team context not provided. */\n financialImpactNarrative: string | null;\n /** Full process transformation proposal - redesign from scratch. Null for legacy analyses. */\n transformation: ProcessTransformation | null;\n /** BPMN 2.0 process flow for the proposed/transformed process. Null for legacy analyses. */\n proposedProcessFlow: ProcessFlow | null;\n /** Ordered steps describing the proposed process. Null for legacy analyses. */\n proposedSteps: ClarityStep[] | null;\n /** Tracks whether proposed steps were last set by AI or a human edit. Null/undefined for legacy analyses. */\n proposedStepsSource?: ClarityStepsSource | null;\n /** Risk & resilience analysis - vulnerabilities. Null for legacy analyses or trivial processes. */\n riskResilience: ProcessRiskResilience | null;\n generated_at: string;\n};\n\nexport const clarityAnalysisSchema = z.object({\n summary: z.string().min(1).nullable(),\n steps: z.array(editableClarityStepSchema).nullable(),\n stepsSource: z.enum(CLARITY_STEPS_SOURCES).nullable().optional(),\n insights: z.array(clarityInsightSchema).max(5).nullable(),\n processFlow: processFlowSchema.nullable(),\n financialImpactNarrative: z.string().nullable(),\n transformation: processTransformationSchema.nullable(),\n proposedProcessFlow: processFlowSchema.nullable().default(null),\n proposedSteps: z.array(editableClarityStepSchema).nullable().default(null),\n proposedStepsSource: z.enum(CLARITY_STEPS_SOURCES).nullable().optional(),\n riskResilience: processRiskResilienceSchema.nullable().default(null),\n generated_at: z.string(),\n});\n\nexport const clarityAnalysisResponseSchema = z.object({\n summary: z.string().min(1).nullable(),\n steps: z.array(clarityStepSchema).nullable(),\n stepsSource: z.enum(CLARITY_STEPS_SOURCES).nullable().optional(),\n insights: z.array(clarityInsightSchema).max(5).nullable(),\n processFlow: processFlowSchema.nullable(),\n financialImpactNarrative: z.string().nullable(),\n transformation: processTransformationSchema.nullable(),\n proposedProcessFlow: processFlowSchema.nullable().default(null),\n proposedSteps: z.array(clarityStepSchema).nullable().default(null),\n proposedStepsSource: z.enum(CLARITY_STEPS_SOURCES).nullable().optional(),\n riskResilience: processRiskResilienceSchema.nullable().default(null),\n generated_at: z.string(),\n});\n\nexport type ClarityAnalysisResponse = z.infer<\n typeof clarityAnalysisResponseSchema\n>;\n\nexport const teamClaritySettingsSchema = z.object({\n teamId: z.guid(),\n teamSize: z.int().positive(),\n averageHourlyRate: z.number().positive(),\n currency: z.enum([\"USD\"]),\n emailReportsEnabled: z.boolean(),\n emailReportIncludeSummary: z.boolean(),\n emailReportIncludeCaptures: z.boolean(),\n updatedAt: z.coerce.date(),\n updatedBy: z.guid().nullable(),\n companyName: z.string().nullable().optional(),\n industry: z.string().nullable().optional(),\n annualRevenue: z.number().nullable().optional(),\n isUserConfigured: z.boolean(),\n});\n\nexport type TeamClaritySettings = z.infer<typeof teamClaritySettingsSchema>;\n\nexport const DEFAULT_TEAM_CLARITY_SETTINGS = {\n teamSize: 5,\n averageHourlyRate: 75,\n currency: \"USD\" as const,\n emailReportsEnabled: true,\n emailReportIncludeSummary: true,\n emailReportIncludeCaptures: false,\n companyName: null,\n industry: null,\n annualRevenue: null,\n};\n\nexport const clarityCaptureSchema = z.object({\n id: z.guid(),\n processId: z.guid(),\n userId: z.guid(),\n userName: z.string().optional(),\n type: clarityCaptureTypeSchema,\n videoUrl: z.string().nullable(),\n videoTranscript: z.string().nullable(),\n transcript: z.array(conversationMessageSchema).nullable(),\n status: clarityCaptureStatusSchema,\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n});\n\nexport type ClarityCapture = z.infer<typeof clarityCaptureSchema>;\n\n/**\n * Narrow architecture version. Applied at the repository boundary; wire\n * schemas stay `z.number().int()` so the OpenAPI contract doesn't break.\n */\nexport const clarityProcessVersionSchema = z.union([\n z.literal(1),\n z.literal(2),\n]);\n\nexport type ClarityProcessVersion = z.infer<typeof clarityProcessVersionSchema>;\n\nexport const clarityProcessSchema = z.object({\n id: z.guid(),\n teamId: z.guid(),\n userId: z.guid(),\n name: z.string(),\n status: clarityProcessStatusSchema,\n /** 1 = legacy, 2 = v2. */\n version: z.number().int(),\n analysis: clarityAnalysisResponseSchema.nullable(),\n generationError: z.string().nullable(),\n customPrompt: z.string().nullable().optional(),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n});\n\nexport type ClarityProcess = z.infer<typeof clarityProcessSchema>;\n\nexport const clarityProcessListItemSchema = z.object({\n id: z.guid(),\n teamId: z.guid().optional(),\n teamName: z.string().optional(),\n name: z.string(),\n status: clarityProcessStatusSchema,\n version: z.number().int(),\n captureCount: z.number(),\n captureCounts: z\n .object({\n video: z.number(),\n interview: z.number(),\n document: z.number(),\n })\n .optional(),\n insightsCount: z.number(),\n hasAnalysis: z.boolean(),\n pendingInvitationCount: z.number().optional(),\n summary: z.string().nullable().optional(),\n vulnerabilityCount: z.number().optional(),\n contributors: z\n .array(z.object({ userId: z.string(), userName: z.string() }))\n .optional(),\n createdAt: z.coerce.date(),\n createdByName: z.string().optional(),\n});\n\nexport type ClarityProcessListItem = z.infer<\n typeof clarityProcessListItemSchema\n>;\n\n// Generation progress types for async clarity\n\nconst GENERATION_STEP_STATUSES = [\n \"pending\",\n \"in_progress\",\n \"complete\",\n] as const;\n\nexport type GenerationStepStatus = (typeof GENERATION_STEP_STATUSES)[number];\n\nexport const generationStepStatusSchema = z.enum(GENERATION_STEP_STATUSES);\n\nexport const generationStepProgressSchema = z.object({\n key: z.string(),\n label: z.string(),\n status: generationStepStatusSchema,\n order: z.number(),\n count: z.number().optional(),\n});\n\nexport type GenerationStepProgress = z.infer<\n typeof generationStepProgressSchema\n>;\n\nexport const generationProgressSchema = z.object({\n steps: z.array(generationStepProgressSchema),\n});\n\nexport type GenerationProgress = z.infer<typeof generationProgressSchema>;\n\nexport const usedGuidanceMessageSchema = z.object({\n content: z.string(),\n author: z.string().nullable(),\n date: z.string().nullable(),\n});\n\nexport type UsedGuidanceMessage = z.infer<typeof usedGuidanceMessageSchema>;\n\nexport const clarityProcessDetailSchema = clarityProcessSchema.extend({\n captures: z.array(clarityCaptureSchema),\n createdByName: z.string().optional(),\n creatorUserId: z.guid(),\n generationProgress: generationProgressSchema.nullable(),\n transformationGuidance: z.string().nullable(),\n transformationGuidanceAuthor: z.string().nullable(),\n transformationGuidanceDate: z.string().nullable(),\n usedGuidanceMessages: z.array(usedGuidanceMessageSchema),\n});\n\nexport type ClarityProcessDetail = z.infer<typeof clarityProcessDetailSchema>;\n\nexport type ClarityProcessClient = Omit<\n ClarityProcessDetail,\n \"teamId\" | \"userId\"\n>;\n\nexport const createClarityProcessSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n});\n\nexport type CreateClarityProcess = z.infer<typeof createClarityProcessSchema>;\n\nexport const updateClarityProcessSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n customPrompt: z.string().max(5000).nullable().optional(),\n});\n\nexport type UpdateClarityProcess = z.infer<typeof updateClarityProcessSchema>;\n\nexport const saveClarityCaptureInterviewSchema = z.object({\n captureId: z.guid().optional(),\n extraCaptureRequestId: z.guid().optional(),\n transcript: z.array(conversationMessageSchema).min(1),\n});\n\nexport const startClarityCaptureInterviewQuerySchema = z.object({\n extraCaptureRequestId: z.guid().optional(),\n});\n\nexport type StartClarityCaptureInterviewQuery = z.infer<\n typeof startClarityCaptureInterviewQuerySchema\n>;\n\nexport type SaveClarityCaptureInterview = z.infer<\n typeof saveClarityCaptureInterviewSchema\n>;\n\nexport const INTERVIEW_LANGUAGES = [\n \"en\",\n \"cs\",\n \"de\",\n \"es\",\n \"fr\",\n \"pl\",\n] as const;\n\nexport type InterviewLanguage = (typeof INTERVIEW_LANGUAGES)[number];\n\nexport const initiateClarityPhoneInterviewSchema = z.object({\n phoneNumber: z.string().regex(/^\\+\\d{7,15}$/, \"Must be E.164 format\"),\n language: z.enum(INTERVIEW_LANGUAGES).optional().default(\"en\"),\n extraCaptureRequestId: z.guid().optional(),\n});\n\nexport type InitiateClarityPhoneInterview = z.infer<\n typeof initiateClarityPhoneInterviewSchema\n>;\n\nexport const initiateClarityPhoneInterviewResponseSchema = z.object({\n captureId: z.string().uuid(),\n status: z.literal(\"calling\"),\n});\n\nexport type InitiateClarityPhoneInterviewResponse = z.infer<\n typeof initiateClarityPhoneInterviewResponseSchema\n>;\n\n// Public sharing types\n\n/**\n * Public view of a clarity process (limited data for unauthenticated access).\n * Excludes team info, user info, and captures.\n */\nexport const publicClarityProcessSchema = z.object({\n id: z.guid(),\n name: z.string(),\n status: clarityProcessStatusSchema,\n analysis: clarityAnalysisResponseSchema.nullable(),\n createdAt: z.coerce.date(),\n});\n\nexport type PublicClarityProcess = z.infer<typeof publicClarityProcessSchema>;\n\n/**\n * Sharing status for a clarity process.\n */\nexport const claritySharingStatusSchema = z.object({\n shareEnabled: z.boolean(),\n shareToken: z.string().nullable(),\n shareUrl: z.string().nullable(),\n});\n\nexport type ClaritySharingStatus = z.infer<typeof claritySharingStatusSchema>;\n\n// Portfolio Intelligence types\n\nexport const PORTFOLIO_INTELLIGENCE_STATUSES = [\n \"idle\",\n \"generating\",\n \"complete\",\n \"generation_failed\",\n] as const;\n\nexport type PortfolioIntelligenceStatus =\n (typeof PORTFOLIO_INTELLIGENCE_STATUSES)[number];\n\nexport const portfolioIntelligenceStatusSchema = z.enum(\n PORTFOLIO_INTELLIGENCE_STATUSES\n);\n\nexport const RECOMMENDATION_CATEGORIES = [\n \"automation\",\n \"process-redesign\",\n \"governance\",\n \"tooling\",\n] as const;\n\nexport type RecommendationCategory = (typeof RECOMMENDATION_CATEGORIES)[number];\n\nexport const RECOMMENDATION_PRIORITIES = [\"P1\", \"P2\", \"P3\"] as const;\n\nexport type RecommendationPriority = (typeof RECOMMENDATION_PRIORITIES)[number];\n\nexport const RECOMMENDATION_EFFORTS = [\n \"Low (days)\",\n \"Medium (weeks)\",\n \"High (months)\",\n] as const;\n\nexport type RecommendationEffort = (typeof RECOMMENDATION_EFFORTS)[number];\n\nexport const portfolioRecommendationSchema = z.object({\n title: z.string().min(1),\n category: z.enum(RECOMMENDATION_CATEGORIES),\n priority: z.enum(RECOMMENDATION_PRIORITIES).optional().default(\"P2\"),\n rationale: z.string().min(1),\n impact: z.string().min(1),\n effort: z.enum(RECOMMENDATION_EFFORTS),\n processIds: z.array(z.guid()).min(1),\n});\n\nexport type PortfolioRecommendation = z.infer<\n typeof portfolioRecommendationSchema\n>;\n\nexport const portfolioAnalysisSchema = z.object({\n executiveSummary: z.string().min(1),\n recommendations: z.array(portfolioRecommendationSchema).min(1),\n aggregateFinancialImpact: z.string().nullable(),\n generatedAt: z.string(),\n});\n\nexport type PortfolioAnalysis = z.infer<typeof portfolioAnalysisSchema>;\n\nexport const portfolioIntelligenceResponseSchema = z.object({\n id: z.guid(),\n status: portfolioIntelligenceStatusSchema,\n generationError: z.string().nullable(),\n analysis: portfolioAnalysisSchema.nullable(),\n generatedAt: z.string().nullable(),\n processCount: z.number(),\n completedProcessCount: z.number(),\n generationProgress: generationProgressSchema.nullable(),\n});\n\nexport type PortfolioIntelligenceResponse = z.infer<\n typeof portfolioIntelligenceResponseSchema\n>;\n\nexport const PORTFOLIO_MIN_PROCESSES_REQUIRED = 2;\n", "import { z } from \"zod\";\n\nimport {\n PROCESS_FLOW_EVENT_SUBTYPES,\n PROCESS_FLOW_GATEWAY_SUBTYPES,\n PROCESS_FLOW_NODE_TYPES,\n PROCESS_FLOW_TASK_SUBTYPES,\n} from \"../types/clarity\";\nimport { refineStepGraph } from \"./validators\";\n\nexport const CLARITY_V2_SNAPSHOT_VERSION = 1;\n\nconst stepSourceSchema = z.object({\n attribution: z\n .string()\n .min(1)\n .describe(\n 'Human-readable source label identifying who or what the evidence comes from. Examples: \"Anna (sales interview)\", \"Onboarding SOP \u00A73.2\", \"Slack #ops 2024-06-12\"'\n ),\n excerpt: z\n .string()\n .min(1)\n .describe(\n 'Verbatim supporting text quoted from the capture, document, or transcript. Example: \"We always wait for finance to sign off before sending the invoice.\"'\n ),\n});\n\nconst stepEdgeSchema = z.object({\n stepId: z\n .string()\n .min(1)\n .describe(\n 'Id of the step this edge points to. Must match an existing step.id in the same steps array. Example: \"step-review-invoice\"'\n ),\n label: z\n .string()\n .nullable()\n .describe(\n 'Human-readable label shown on the BPMN edge. For gateways, the outcome answer; for default flows, \"Otherwise\". Examples: \"Approved\", \"> $5k\", \"Otherwise\"'\n ),\n isDefault: z\n .boolean()\n .describe(\n \"True on exactly one outgoing edge of an exclusive or inclusive gateway, marking the fallback taken when no other condition matches. False on all other edges.\"\n ),\n});\n\nexport const clarityStepBaseSchema = z.object({\n id: z\n .string()\n .min(1)\n .describe(\n 'Stable identifier for the step. Referenced by targetSteps[].stepId and by postprocessing agents annotating specific steps. Example: \"step-review-invoice\"'\n ),\n\n nodeType: z\n .enum(PROCESS_FLOW_NODE_TYPES)\n .describe(\n 'BPMN top-level category. \"event\" for things that happen (start/end/timer/message/escalation), \"task\" for work performed, \"gateway\" for branching decisions.'\n ),\n nodeSubtype: z\n .enum([\n ...PROCESS_FLOW_EVENT_SUBTYPES,\n ...PROCESS_FLOW_TASK_SUBTYPES,\n ...PROCESS_FLOW_GATEWAY_SUBTYPES,\n ])\n .describe(\n 'Specific BPMN element. Events: \"start\", \"end\", \"timer\", \"message\", \"escalation\". Tasks: \"user\", \"service\", \"send\", \"receive\", \"manual\", \"businessRule\", \"script\". Gateways: \"exclusive\", \"parallel\", \"inclusive\".'\n ),\n\n targetSteps: z\n .array(stepEdgeSchema)\n .describe(\n \"Outgoing BPMN edges from this step. Empty array only on end events. Exclusive and inclusive gateways must have \u22652 entries with exactly one isDefault: true.\"\n ),\n\n title: z\n .string()\n .min(1)\n .describe(\n 'Short action-oriented heading, 2-5 words. Used as the step\\'s name in lists and BPMN node labels. Example: \"Review invoice\"'\n ),\n description: z\n .string()\n .min(1)\n .describe(\n 'Full prose paragraph describing what happens in this step in natural language. Used for documentation reconstruction. Example: \"Finance reviews the invoice in NetSuite, checking line item accuracy and matching against the purchase order before flagging for approval.\"'\n ),\n action: z\n .string()\n .min(1)\n .nullable()\n .describe(\n 'Verb-led one-liner summarizing the concrete action performed. Example: \"Reviews invoice line items in NetSuite against the purchase order.\"'\n ),\n rationale: z\n .string()\n .min(1)\n .describe(\n 'Why this step exists in the process \u2014 its purpose or business reason. Used by downstream agents to assess whether the step is essential or removable. Example: \"Catches mispriced line items before they reach the customer and prevents downstream credit notes.\"'\n ),\n role: z\n .string()\n .min(1)\n .nullable()\n .describe(\n 'Performer of this step \u2014 the specific job title, team, or system. Use \"Duvo\" for automated actions and \"System\" for system-triggered steps. Examples: \"Finance Analyst\", \"Sales Operations\", \"Duvo\", \"System\"'\n ),\n sources: z\n .array(stepSourceSchema)\n .min(1)\n .describe(\n \"Evidence supporting this step's existence and details. At least one source is required \u2014 every step must trace back to something in the captures.\"\n ),\n\n system: z\n .string()\n .nullable()\n .describe(\n 'System, tool, or application used to perform this step. Null when the step is purely manual or is a decision/event with no associated tool. Examples: \"NetSuite\", \"Gmail\", \"Excel\", null'\n ),\n input: z\n .string()\n .nullable()\n .describe(\n 'Information or artifacts required to start this step. Null on start events or steps with no preconditions. Example: \"Invoice PDF and matching purchase order number\"'\n ),\n output: z\n .string()\n .nullable()\n .describe(\n 'What this step produces or updates. Null on pure waits or events that emit nothing. Example: \"Approved invoice record in NetSuite with reviewer signature\"'\n ),\n condition: z\n .string()\n .nullable()\n .describe(\n 'Decision criteria or precondition that gates this step. Null when the step is unconditional. For gateway nodes, this is the question being evaluated. Example: \"Only when invoice total exceeds $10,000\"'\n ),\n exception: z\n .string()\n .nullable()\n .describe(\n 'Known exceptions, errors, or failure modes observed in the captures for this step. Null when none were mentioned. Example: \"Customer disputes line items or PO number does not match\"'\n ),\n handling: z\n .string()\n .nullable()\n .describe(\n 'How exceptions or escalations are handled \u2014 escalation path, fallback action, or retry strategy. Null when no exception or no handling described. Example: \"Escalate to AP manager via email and pause processing until resolved\"'\n ),\n assumptions: z\n .array(z.string())\n .nullable()\n .describe(\n 'Assumptions the LLM made when extracting this step that were not directly stated in captures. Null if none. Used by verification agents to flag risky inferences. Example: [\"Invoices are reviewed within 24 hours of receipt\"]'\n ),\n openQuestions: z\n .array(z.string())\n .nullable()\n .describe(\n 'Specific gaps in understanding that a follow-up capture should address. Null if none. Drives the next interview or document request. Example: [\"Is there a backup approver when the AP manager is out of office?\"]'\n ),\n confidence: z\n .enum([\"low\", \"medium\", \"high\"])\n .describe(\n 'Confidence in the accuracy of this step given evidence quality and completeness. \"high\" = directly stated by multiple sources, \"medium\" = stated by one source or inferred from strong signals, \"low\" = inferred with significant assumptions.'\n ),\n});\n\nexport type ClarityStepBase = z.infer<typeof clarityStepBaseSchema>;\n\n/* ===========================================================================\n * Postprocessing-agent extension chain\n * ---------------------------------------------------------------------------\n *\n * Postprocessing agents enrich snapshots after the pipeline writes them. Each\n * agent owns a small, optional slice of the snapshot. The schemas below are\n * the registry: every agent that touches the snapshot data shape MUST\n *\n * 1. declare its own slice schema (per-step or root-level) in this file,\n * 2. chain it onto the relevant `postprocess<Kind>Schema.extend(...)` call,\n *\n * so the canonical postprocess schemas always reflect every registered agent.\n *\n * Hard rules for any registered slice schema:\n *\n * - Every field MUST be optional (`.optional()`). Pipeline output predates\n * all agents, so snapshots must be valid before any agent has run.\n * - `undefined` = \"agent has not yet run\". `null` = \"agent ran, no output\".\n * - An agent owns its fields exclusively. Never reuse a field across two\n * agents and never let one agent write into another agent's slice.\n *\n * The slice schemas live here (and not next to each agent) so the postprocess\n * schemas can be assembled in one place. The agent runtime imports the\n * postprocess schemas; the agent files themselves only need to re-export the\n * slice schema for prompt-time validation of their own LLM output.\n * ========================================================================= */\n\n/* --- Per-step agent slice schemas ----------------------------------------- */\nexport const extraCaptureNeededValueSchema = z.object({\n id: z\n .guid()\n .describe(\n \"Id of the `clarity_proposal_extra_capture_request` row this slot points at. Created server-side by the agent after the LLM call; the LLM never produces this value.\"\n ),\n gap: z\n .string()\n .min(1)\n .describe(\n 'Plain-language description of what about this step is unknown or under-specified, blocking automation. One short sentence. Example: \"We don\\'t know which fields the AP analyst copies from the invoice into NetSuite.\"'\n ),\n proposal: z\n .string()\n .min(1)\n .nullable()\n .optional()\n .describe(\n 'What the new capture should include in order to resolve the gap \u2014 concrete actions, screens, or decisions the user should walk through. Optional: omit when no specific proposal can be inferred. Example: \"Walk through reviewing one invoice in NetSuite end-to-end while narrating each field you check.\"'\n ),\n});\n\nexport type ExtraCaptureNeededValue = z.infer<\n typeof extraCaptureNeededValueSchema\n>;\n\n/**\n * Slice schema owned by the `extra-capture-needed` agent. Adds an optional\n * per-step `extraCaptureNeeded` field on transformation-proposal steps that\n * cannot be automated without an additional deep-dive capture.\n *\n * - `undefined`: the agent has not yet run for this step.\n * - `null`: the agent ran and the step is automation-ready (no extra needed).\n * - `{ id, gap, proposal? }`: the agent flagged this step. The same value is\n * mirrored into a `clarity_proposal_extra_capture_request` row by the\n * agent so the L3 \u2192 L4 capture loop can pick it up.\n */\nexport const extraCaptureNeededAgentStepSchema = z.object({\n extraCaptureNeeded: extraCaptureNeededValueSchema.nullable().optional(),\n});\n\nexport const STEP_READINESS_LEVELS = [\"low\", \"medium\", \"high\"] as const;\n\nexport type StepReadinessLevel = (typeof STEP_READINESS_LEVELS)[number];\n\nexport const bpmnStepReadinessAgentStepSchema = z.object({\n readiness: z\n .enum(STEP_READINESS_LEVELS)\n .nullable()\n .optional()\n .describe(\n 'Automation-readiness rating for this step. \"high\" = fully automatable today, \"medium\" = partially automatable or needs minor changes, \"low\" = blocked by manual review, judgement, or missing data.'\n ),\n readinessRationale: z\n .string()\n .nullable()\n .optional()\n .describe(\n 'One-sentence justification for the readiness rating, citing the specific signals that drove the choice. Example: \"Requires human judgement on edge cases that are not documented in the captures.\"'\n ),\n});\n\nexport const postprocessClarityStepBaseSchema = clarityStepBaseSchema\n .extend(extraCaptureNeededAgentStepSchema.shape)\n .extend(bpmnStepReadinessAgentStepSchema.shape)\n .extend({});\n\nexport type PostprocessClarityStepBase = z.infer<\n typeof postprocessClarityStepBaseSchema\n>;\n\nconst clarityCurrentProcessDataObjectSchema = z.object({\n version: z\n .number()\n .int()\n .describe(\n \"Schema version for the current process data payload. Increment on breaking changes to the data shape so consumers can branch on the version field.\"\n ),\n steps: z\n .array(postprocessClarityStepBaseSchema)\n .describe(\n \"Ordered steps describing how the process works today, extracted from captures. Array position is the canonical order; BPMN topology is encoded by each step's targetSteps[] edges.\"\n )\n .superRefine(refineStepGraph),\n});\n\nexport const processSummaryAgentCurrentProcessSchema = z.object({\n summary: z\n .string()\n .min(1)\n .nullable()\n .optional()\n .describe(\n 'One short paragraph (3-5 sentences) describing the captured process at a glance. Surfaced at the top of the current-process tab so reviewers can orient themselves before scanning the steps. Example: \"Customers order beer at the bar; the bartender greets them, picks an option matching their preference, pours and garnishes the glass, then rings the order through the POS before serving.\"'\n ),\n});\n\nexport type ProcessSummaryAgentCurrentProcess = z.infer<\n typeof processSummaryAgentCurrentProcessSchema\n>;\n\nexport const swotAnalysisSchema = z.object({\n strengths: z\n .array(z.string().min(1))\n .describe(\n 'Internal advantages of the current process \u2014 capabilities, resources, or design choices that work in its favour today. Phrase each as a short, evidence-backed statement. Example: \"Bartenders know regulars by name, which keeps service personal during peak hours.\"'\n ),\n weaknesses: z\n .array(z.string().min(1))\n .describe(\n 'Internal limitations of the current process \u2014 gaps, inefficiencies, or fragile assumptions visible in how it runs today. Phrase each as a short, evidence-backed statement. Example: \"Manual pour times balloon during rushes because there is only one tap.\"'\n ),\n opportunities: z\n .array(z.string().min(1))\n .describe(\n 'External openings the current process could exploit \u2014 adjacent automations, scale effects, or unmet needs surfaced by the captures. Example: \"POS data could feed dynamic pricing for slow hours.\"'\n ),\n threats: z\n .array(z.string().min(1))\n .describe(\n 'External risks that could degrade the current process \u2014 regulatory, operational, technological, or human factors visible in the captures. Example: \"New ID-check legislation will require staff to interrupt every order.\"'\n ),\n});\n\nexport type SwotAnalysis = z.infer<typeof swotAnalysisSchema>;\n\nexport const swotAnalysisAgentCurrentProcessSchema = z.object({\n swot: swotAnalysisSchema\n .nullable()\n .optional()\n .describe(\n \"SWOT analysis produced by the swot-analysis postprocessing agent. `undefined` = agent has not yet run; `null` = agent ran and produced no analysis.\"\n ),\n});\n\n/**\n * Current-process data as stored on disk after agents have written. This is\n * the schema repositories use for `parse` / `safeParse` and the schema the\n * read model exposes to the frontend.\n */\nexport const postprocessClarityCurrentProcessDataSchema =\n clarityCurrentProcessDataObjectSchema\n .extend(swotAnalysisAgentCurrentProcessSchema.shape)\n .extend(processSummaryAgentCurrentProcessSchema.shape)\n .extend({});\n\nexport type PostprocessClarityCurrentProcessData = z.infer<\n typeof postprocessClarityCurrentProcessDataSchema\n>;\n\n/* --- Transformation-proposal data ----------------------------------------- */\n\nconst clarityTransformationProposalDataObjectSchema = z.object({\n version: z\n .number()\n .int()\n .describe(\n \"Schema version for the transformation proposal data payload. Increment on breaking changes to the data shape so consumers can branch on the version field.\"\n ),\n steps: z\n .array(postprocessClarityStepBaseSchema)\n .describe(\n \"Ordered steps describing the proposed redesigned process. Same shape as the current process steps; BPMN topology is encoded by each step's targetSteps[] edges.\"\n )\n .superRefine(refineStepGraph),\n});\n\nexport const proposalSummaryAgentTransformationProposalSchema = z.object({\n summary: z\n .string()\n .min(1)\n .nullable()\n .optional()\n .describe(\n 'One short paragraph (3-5 sentences) describing the proposed transformed process at a glance. Surfaced at the top of the transformation-proposal tab so reviewers can orient themselves before scanning the steps. Example: \"Customers self-order on a tablet at the bar; a smart tap auto-pours the chosen beer into a labelled glass, which the customer collects from the pickup counter once payment clears.\"'\n ),\n});\n\nexport type ProposalSummaryAgentTransformationProposal = z.infer<\n typeof proposalSummaryAgentTransformationProposalSchema\n>;\n\nexport const postprocessClarityTransformationProposalDataSchema =\n clarityTransformationProposalDataObjectSchema\n .extend(proposalSummaryAgentTransformationProposalSchema.shape)\n .extend({});\n\nexport type PostprocessClarityTransformationProposalData = z.infer<\n typeof postprocessClarityTransformationProposalDataSchema\n>;\n\n/**\n * Versioning + audit fields shared by both clarity-v2 snapshot tables. The\n * `status` field replaces the implicit \"latest non-deleted\" convention with\n * an explicit live/historic flag that the picker UI can read.\n *\n * The internal \"snapshot\" types used to live here in camelCase form and\n * were re-mapped to snake_case at the wire boundary by serializers. That\n * mapping was redundant \u2014 DB columns are snake_case, the API is\n * snake_case, only the in-memory wrapper differed. The wire-format\n * snapshot types in `./api-schema.ts` (`clarityCurrentProcessSnapshotApiSchema`\n * + `clarityTransformationProposalSnapshotApiSchema`) are now used\n * end-to-end. The repos return rows in their natural snake_case shape with\n * `data` parsed through the postprocess schemas (still camelCase, since\n * `data` is an opaque LLM payload).\n */\nexport const clarityV2SnapshotStatusSchema = z.enum([\"live\", \"historic\"]);\nexport type ClarityV2SnapshotStatus = z.infer<\n typeof clarityV2SnapshotStatusSchema\n>;\n\nexport const clarityV2SnapshotCreatorTypeSchema = z.enum([\"human\", \"ai\"]);\nexport type ClarityV2SnapshotCreatorType = z.infer<\n typeof clarityV2SnapshotCreatorTypeSchema\n>;\n", "import type { z } from \"zod\";\n\nimport type { ClarityStepBase } from \"./process-data\";\n\nexport type StepGraphValidationIssueCode =\n | \"duplicate-step-id\"\n | \"missing-start\"\n | \"multiple-starts\"\n | \"missing-end\"\n | \"missing-target\"\n | \"end-has-outgoing-edges\"\n | \"gateway-too-few-outgoing-edges\"\n | \"gateway-default-count\";\n\nexport interface StepGraphValidationIssue {\n code: StepGraphValidationIssueCode;\n message: string;\n path: readonly (string | number)[];\n stepIds: readonly string[];\n}\n\nfunction isStartStep(step: ClarityStepBase): boolean {\n return step.nodeType === \"event\" && step.nodeSubtype === \"start\";\n}\n\nfunction isEndStep(step: ClarityStepBase): boolean {\n return step.nodeType === \"event\" && step.nodeSubtype === \"end\";\n}\n\nfunction isBranchingGateway(step: ClarityStepBase): boolean {\n return (\n step.nodeType === \"gateway\" &&\n (step.nodeSubtype === \"exclusive\" || step.nodeSubtype === \"inclusive\")\n );\n}\n\nexport function validateStepGraph(\n steps: readonly ClarityStepBase[]\n): StepGraphValidationIssue[] {\n const issues: StepGraphValidationIssue[] = [];\n const idToIndex = new Map<string, number>();\n const duplicateIds = new Set<string>();\n\n steps.forEach((step, index) => {\n const existingIndex = idToIndex.get(step.id);\n if (existingIndex !== undefined) {\n duplicateIds.add(step.id);\n issues.push({\n code: \"duplicate-step-id\",\n path: [\"steps\", index, \"id\"],\n stepIds: [step.id],\n message: `Duplicate step id \"${step.id}\"`,\n });\n return;\n }\n\n idToIndex.set(step.id, index);\n });\n\n const startSteps = steps.filter(isStartStep);\n if (startSteps.length === 0) {\n issues.push({\n code: \"missing-start\",\n path: [\"steps\"],\n stepIds: [],\n message: \"Exactly one event/start node is required (found 0)\",\n });\n } else if (startSteps.length > 1) {\n issues.push({\n code: \"multiple-starts\",\n path: [\"steps\"],\n stepIds: startSteps.map((step) => step.id),\n message: `Exactly one event/start node is required (found ${startSteps.length})`,\n });\n }\n\n const endSteps = steps.filter(isEndStep);\n if (endSteps.length === 0) {\n issues.push({\n code: \"missing-end\",\n path: [\"steps\"],\n stepIds: [],\n message: \"At least one event/end node is required\",\n });\n }\n\n steps.forEach((step, index) => {\n step.targetSteps.forEach((edge, edgeIndex) => {\n if (!idToIndex.has(edge.stepId) || duplicateIds.has(edge.stepId)) {\n issues.push({\n code: \"missing-target\",\n path: [\"steps\", index, \"targetSteps\", edgeIndex, \"stepId\"],\n stepIds: [step.id],\n message: `targetSteps[].stepId \"${edge.stepId}\" does not match any step.id`,\n });\n }\n });\n\n if (isEndStep(step) && step.targetSteps.length > 0) {\n issues.push({\n code: \"end-has-outgoing-edges\",\n path: [\"steps\", index, \"targetSteps\"],\n stepIds: [step.id],\n message: \"End events must have no outgoing edges\",\n });\n }\n\n if (!isBranchingGateway(step)) {\n return;\n }\n\n if (step.targetSteps.length < 2) {\n issues.push({\n code: \"gateway-too-few-outgoing-edges\",\n path: [\"steps\", index, \"targetSteps\"],\n stepIds: [step.id],\n message: `${step.nodeSubtype} gateway must have at least 2 outgoing edges`,\n });\n }\n\n const defaultCount = step.targetSteps.filter(\n (edge) => edge.isDefault\n ).length;\n if (defaultCount !== 1) {\n issues.push({\n code: \"gateway-default-count\",\n path: [\"steps\", index, \"targetSteps\"],\n stepIds: [step.id],\n message: `${step.nodeSubtype} gateway must have exactly one outgoing edge with isDefault: true (found ${defaultCount})`,\n });\n }\n });\n\n return issues;\n}\n\n/**\n * Graph-level invariants that the per-step Zod schema cannot express:\n * unique step ids, exactly one start, at least one end, every targetSteps[]\n * edge resolves to an existing step, end events have no outgoing edges,\n * exclusive and inclusive gateways have at least two outgoing edges with\n * exactly one default. Mirrors the rules the prompt asks the LLM to\n * follow; validating server-side prevents an off-spec hallucination from\n * being persisted as a snapshot.\n */\nexport function refineStepGraph(\n steps: ClarityStepBase[],\n ctx: z.RefinementCtx\n): void {\n for (const issue of validateStepGraph(steps)) {\n ctx.addIssue({\n code: \"custom\",\n path: [...issue.path],\n message: issue.message,\n });\n }\n}\n", "import { z } from \"zod\";\n\n/**\n * Typed lifecycle events broadcast over the user socket while a\n * clarity-v2 generation is in flight. The FE reduces these into a\n * `useClarityV2Lifecycle` state machine; every event is stamped with the\n * `sandboxId` of the run that produced it so stale events from a\n * superseded generation can be dropped without ambiguity.\n *\n * The legacy `clarity:process-updated` event still fires alongside these\n * to invalidate cache for non-generation mutations (rename, delete,\n * captures-added). It will be retired once every consumer subscribes to\n * the typed events.\n */\nexport const CLARITY_V2_SNAPSHOT_KINDS = [\n \"current_process\",\n \"transformation_proposal\",\n] as const;\n\nexport const claritySnapshotKindSchema = z.enum(CLARITY_V2_SNAPSHOT_KINDS);\n\nexport type ClaritySnapshotKind = z.infer<typeof claritySnapshotKindSchema>;\n\nconst baseEventDataSchema = z.object({\n processId: z.guid(),\n sandboxId: z.string(),\n snapshotKind: claritySnapshotKindSchema,\n});\n\nexport const clarityGenerationStartedEventDataSchema = baseEventDataSchema;\n\nexport const CLARITY_AGENT_PROGRESS_STATUSES = [\n \"started\",\n \"completed\",\n] as const;\n\nexport const clarityAgentProgressStatusSchema = z.enum(\n CLARITY_AGENT_PROGRESS_STATUSES\n);\n\nexport const clarityAgentProgressEventDataSchema = baseEventDataSchema.extend({\n agent: z.string().describe(\"Postprocessing agent name (machine-readable)\"),\n status: clarityAgentProgressStatusSchema,\n});\n\nexport const clarityGenerationCompletedEventDataSchema =\n baseEventDataSchema.extend({\n snapshotId: z.guid().describe(\"ID of the snapshot row that was finalised\"),\n });\n\nexport const clarityGenerationFailedEventDataSchema =\n baseEventDataSchema.extend({\n error: z.string().describe(\"Human-readable failure reason\"),\n });\n\nexport const clarityGenerationStoppedEventDataSchema = baseEventDataSchema;\n\nexport type ClarityGenerationStartedEventData = z.infer<\n typeof clarityGenerationStartedEventDataSchema\n>;\nexport type ClarityAgentProgressEventData = z.infer<\n typeof clarityAgentProgressEventDataSchema\n>;\nexport type ClarityGenerationCompletedEventData = z.infer<\n typeof clarityGenerationCompletedEventDataSchema\n>;\nexport type ClarityGenerationFailedEventData = z.infer<\n typeof clarityGenerationFailedEventDataSchema\n>;\nexport type ClarityGenerationStoppedEventData = z.infer<\n typeof clarityGenerationStoppedEventDataSchema\n>;\n\n/**\n * Wire-format event names. Centralised so emit and listen sites can not\n * drift. The values match the legacy `clarity:*` namespace already in\n * use for `clarity:process-updated`.\n */\nexport const CLARITY_GENERATION_EVENT_NAMES = {\n started: \"clarity:generation-started\",\n agentProgress: \"clarity:agent-progress\",\n completed: \"clarity:generation-completed\",\n failed: \"clarity:generation-failed\",\n stopped: \"clarity:generation-stopped\",\n} as const;\n\nexport type ClarityGenerationEventName =\n (typeof CLARITY_GENERATION_EVENT_NAMES)[keyof typeof CLARITY_GENERATION_EVENT_NAMES];\n\n/**\n * Discriminated union of every typed clarity generation event. Emitted as\n * `{ event, data }` so the FE can route on `event` without inspecting\n * data shape first.\n */\nexport type ClarityGenerationEvent =\n | {\n event: typeof CLARITY_GENERATION_EVENT_NAMES.started;\n data: ClarityGenerationStartedEventData;\n }\n | {\n event: typeof CLARITY_GENERATION_EVENT_NAMES.agentProgress;\n data: ClarityAgentProgressEventData;\n }\n | {\n event: typeof CLARITY_GENERATION_EVENT_NAMES.completed;\n data: ClarityGenerationCompletedEventData;\n }\n | {\n event: typeof CLARITY_GENERATION_EVENT_NAMES.failed;\n data: ClarityGenerationFailedEventData;\n }\n | {\n event: typeof CLARITY_GENERATION_EVENT_NAMES.stopped;\n data: ClarityGenerationStoppedEventData;\n };\n", "export function stringifyError(err: unknown): string {\n if (err instanceof Error) {\n if (err.message) {\n return err.message;\n }\n\n // The error has no message \u2014 try to extract meaning from its own\n // enumerable properties (e.g. Puppeteer / network errors that omit message).\n try {\n const ownProps = JSON.stringify(err, Object.getOwnPropertyNames(err));\n if (ownProps && ownProps !== \"{}\" && ownProps !== \"null\") {\n return ownProps;\n }\n } catch {\n // ignore serialization errors and fall through\n }\n\n return String(err);\n }\n\n try {\n return JSON.stringify(err) ?? String(err);\n } catch {\n return String(err);\n }\n}\n", "import { stringifyError } from \"./stringify-error\";\n\nexport type SeverityLevel =\n | \"fatal\"\n | \"error\"\n | \"warning\"\n | \"log\"\n | \"info\"\n | \"debug\"\n | \"critical\";\n\nexport type SentryLike = {\n captureException(err: unknown): void;\n withScope(cb: (scope: ScopeLike) => void): void;\n};\n\ntype ScopeLike = {\n setExtras(extras: Record<string, unknown>): void;\n setLevel(level: SeverityLevel): void;\n setTag(key: string, value: string): void;\n};\n\n// Keys that should be set as tags (searchable in Sentry) rather than just extras\nconst SEARCHABLE_KEYS = [\n \"agentRunId\",\n \"runId\",\n \"buildId\",\n \"sandboxId\",\n \"agentId\",\n \"teamId\",\n \"userId\",\n \"sessionId\",\n] as const;\n\nexport function makeSentryReporter(sentry: SentryLike) {\n return function reportToSentry(\n error: unknown,\n severity: SeverityLevel = \"error\",\n extras: Record<string, unknown> = {}\n ) {\n const errorWithStack =\n error instanceof Error && error.stack\n ? error\n : new Error(stringifyError(error));\n\n if (severity === \"warning\") {\n console.warn(errorWithStack, extras);\n } else {\n console.error(errorWithStack, extras);\n }\n\n try {\n sentry.withScope((scope) => {\n // Set searchable tags for key identifiers\n // These make errors searchable by agent_run_id, build_id, etc. in Sentry Issues\n for (const key of SEARCHABLE_KEYS) {\n const value = extras[key];\n if (value !== undefined && value !== null) {\n // Convert camelCase to snake_case for Sentry tag naming convention\n const tagKey = key.replace(/([A-Z])/g, \"_$1\").toLowerCase();\n scope.setTag(tagKey, String(value));\n }\n }\n\n scope.setExtras(extras);\n scope.setLevel(severity);\n sentry.captureException(errorWithStack);\n });\n } catch {\n try {\n sentry.captureException(errorWithStack);\n } catch {\n console.error(errorWithStack);\n }\n }\n };\n}\n", "export const ORG_ROLE = {\n EXECUTIVE: \"organization:executive\",\n OWNER: \"organization:owner\",\n ADMIN: \"organization:admin\",\n MEMBER: \"organization:member\",\n} as const;\n\nexport type OrgRole = (typeof ORG_ROLE)[keyof typeof ORG_ROLE];\n\nexport const ORG_ROLE_CONFIG: Record<OrgRole, { parentRole: OrgRole | null }> =\n {\n [ORG_ROLE.EXECUTIVE]: { parentRole: null },\n [ORG_ROLE.OWNER]: { parentRole: ORG_ROLE.EXECUTIVE },\n [ORG_ROLE.ADMIN]: { parentRole: ORG_ROLE.OWNER },\n [ORG_ROLE.MEMBER]: { parentRole: ORG_ROLE.ADMIN },\n };\n\nexport const ORG_ROLES = {\n EXECUTIVE_ONLY: [ORG_ROLE.EXECUTIVE] as const,\n OWNER_AND_ABOVE: [ORG_ROLE.EXECUTIVE, ORG_ROLE.OWNER] as const,\n ADMIN_AND_ABOVE: [\n ORG_ROLE.EXECUTIVE,\n ORG_ROLE.OWNER,\n ORG_ROLE.ADMIN,\n ] as const,\n ALL: [\n ORG_ROLE.EXECUTIVE,\n ORG_ROLE.OWNER,\n ORG_ROLE.ADMIN,\n ORG_ROLE.MEMBER,\n ] as const,\n} as const;\n\nexport function isValidOrgRole(role: string): role is OrgRole {\n return Object.values(ORG_ROLE).includes(role as OrgRole);\n}\n\nexport function hasMinimumOrgRole(\n userRole: string,\n minimumRole: OrgRole\n): boolean {\n if (!isValidOrgRole(userRole)) {\n return false;\n }\n let current: OrgRole | null = minimumRole;\n while (current) {\n if (current === userRole) {\n return true;\n }\n current = ORG_ROLE_CONFIG[current].parentRole;\n }\n return false;\n}\n\nexport function canAssignOrgRole(\n callerRole: string,\n targetRole: string\n): boolean {\n if (!isValidOrgRole(callerRole) || !isValidOrgRole(targetRole)) {\n return false;\n }\n return hasMinimumOrgRole(callerRole, targetRole);\n}\n", "export const TEAM_ROLE = {\n OWNER: \"team:owner\",\n SUPERADMIN: \"team:superadmin\",\n ADMIN: \"team:admin\",\n MANAGER: \"team:manager\",\n BUILDER: \"team:builder\",\n MEMBER: \"team:member\",\n CLARITY_MEMBER: \"team:clarity-member\",\n} as const;\n\nexport type TeamRole = (typeof TEAM_ROLE)[keyof typeof TEAM_ROLE];\n\nexport const TEAM_ROLE_CONFIG = {\n [TEAM_ROLE.OWNER]: {\n displayName: \"Owner\",\n parentRole: null,\n },\n [TEAM_ROLE.SUPERADMIN]: {\n displayName: \"Administrator\",\n parentRole: TEAM_ROLE.OWNER,\n },\n [TEAM_ROLE.ADMIN]: {\n displayName: \"Manager\",\n parentRole: TEAM_ROLE.SUPERADMIN,\n },\n [TEAM_ROLE.MANAGER]: {\n displayName: \"Manager\",\n parentRole: TEAM_ROLE.ADMIN,\n },\n [TEAM_ROLE.BUILDER]: {\n displayName: \"Builder\",\n parentRole: TEAM_ROLE.MANAGER,\n },\n [TEAM_ROLE.MEMBER]: {\n displayName: \"Member\",\n parentRole: TEAM_ROLE.BUILDER,\n },\n [TEAM_ROLE.CLARITY_MEMBER]: {\n displayName: \"Clarity Member\",\n parentRole: TEAM_ROLE.MEMBER,\n },\n} as const;\n\nexport const TEAM_ROLES = {\n OWNER_ONLY: [TEAM_ROLE.OWNER] as const,\n SUPERADMIN_AND_ABOVE: [TEAM_ROLE.OWNER, TEAM_ROLE.SUPERADMIN] as const,\n ADMIN_AND_ABOVE: [\n TEAM_ROLE.OWNER,\n TEAM_ROLE.SUPERADMIN,\n TEAM_ROLE.ADMIN,\n ] as const,\n MANAGER_AND_ABOVE: [\n TEAM_ROLE.OWNER,\n TEAM_ROLE.SUPERADMIN,\n TEAM_ROLE.ADMIN,\n TEAM_ROLE.MANAGER,\n ] as const,\n BUILDER_AND_ABOVE: [\n TEAM_ROLE.OWNER,\n TEAM_ROLE.SUPERADMIN,\n TEAM_ROLE.ADMIN,\n TEAM_ROLE.MANAGER,\n TEAM_ROLE.BUILDER,\n ] as const,\n MEMBER_AND_ABOVE: [\n TEAM_ROLE.OWNER,\n TEAM_ROLE.SUPERADMIN,\n TEAM_ROLE.ADMIN,\n TEAM_ROLE.MANAGER,\n TEAM_ROLE.BUILDER,\n TEAM_ROLE.MEMBER,\n ] as const,\n ALL: [\n TEAM_ROLE.OWNER,\n TEAM_ROLE.SUPERADMIN,\n TEAM_ROLE.ADMIN,\n TEAM_ROLE.MANAGER,\n TEAM_ROLE.BUILDER,\n TEAM_ROLE.MEMBER,\n TEAM_ROLE.CLARITY_MEMBER,\n ] as const,\n} as const;\n\nexport function hasMinimumRole(\n userRole: string,\n minimumRole: TeamRole\n): boolean {\n if (!isValidTeamRole(userRole)) {\n return false;\n }\n\n let current: TeamRole | null = minimumRole;\n while (current) {\n if (current === userRole) {\n return true;\n }\n current = TEAM_ROLE_CONFIG[current].parentRole;\n }\n return false;\n}\n\nexport function isValidTeamRole(role: string): role is TeamRole {\n return Object.values(TEAM_ROLE).includes(role as TeamRole);\n}\n", "import { z } from \"zod\";\n\nexport const apiKeySchema = z.object({\n id: z.guid(),\n name: z.string(),\n key_prefix: z.string(),\n user_id: z.guid(),\n user_name: z.string().nullable(),\n user_email: z.string().nullable(),\n last_used_at: z.string().nullable(),\n expires_at: z.string().nullable(),\n revoked_at: z.string().nullable(),\n created_at: z.string(),\n});\n\nexport type ApiKey = z.infer<typeof apiKeySchema>;\n\nexport const apiKeyListResponseSchema = z.object({\n apiKeys: z.array(apiKeySchema),\n});\n\nexport type ApiKeyListResponse = z.infer<typeof apiKeyListResponseSchema>;\n\nexport const createApiKeyBodySchema = z.object({\n name: z.string().trim().min(1).max(100),\n expires_in_days: z.int().min(1).max(365).optional(),\n});\n\nexport type CreateApiKeyBody = z.infer<typeof createApiKeyBodySchema>;\n\nexport const createApiKeyResponseSchema = z.object({\n id: z.guid(),\n name: z.string(),\n key: z.string(),\n key_prefix: z.string(),\n expires_at: z.string().nullable(),\n created_at: z.string(),\n});\n\nexport type CreateApiKeyResponse = z.infer<typeof createApiKeyResponseSchema>;\n\nexport const deleteApiKeyParamsSchema = z.object({\n keyId: z.guid(),\n});\n\nexport const deleteApiKeyResponseSchema = z.object({\n success: z.boolean(),\n});\n\nexport type DeleteApiKeyResponse = z.infer<typeof deleteApiKeyResponseSchema>;\n", "import { z } from \"zod\";\n\nexport const askUserQuestionOptionSchema = z.object({\n label: z.string(),\n description: z.string().optional().default(\"\"),\n});\n\nexport const askUserQuestionSchema = z.object({\n question: z.string(),\n header: z.string().optional().default(\"\"),\n options: z.array(askUserQuestionOptionSchema).optional().default([]),\n multiSelect: z.boolean().optional().default(false),\n});\n\nexport const askUserQuestionInputSchema = z.object({\n questions: z.array(askUserQuestionSchema).min(1),\n});\n\nexport type AskUserQuestionOption = z.infer<typeof askUserQuestionOptionSchema>;\nexport type AskUserQuestion = z.infer<typeof askUserQuestionSchema>;\nexport type AskUserQuestionInput = z.infer<typeof askUserQuestionInputSchema>;\n\nexport function parseAskUserQuestionInput(\n raw: unknown\n): AskUserQuestionInput | null {\n if (!raw || typeof raw !== \"object\") {\n return null;\n }\n\n const obj = raw as Record<string, unknown>;\n if (!Array.isArray(obj.questions)) {\n return null;\n }\n\n const validQuestions = obj.questions\n .map((q: unknown) => askUserQuestionSchema.safeParse(q))\n .filter((r) => r.success)\n .map((r) => r.data);\n\n if (validQuestions.length === 0) {\n return null;\n }\n\n return { questions: validQuestions } satisfies AskUserQuestionInput;\n}\n", "import { z } from \"zod\";\n\nexport const browserReplayScreenshotSchema = z.object({\n id: z.guid(),\n agent_run_id: z.guid(),\n tool_execution_id: z.string(),\n tool_name: z.string(),\n timing: z.string(),\n created_at: z.coerce.date(),\n signedUrl: z.string().nullable(),\n});\n\nexport const toolExecutionPairSchema = z.object({\n executionId: z.string(),\n toolName: z.string(),\n beforeScreenshot: browserReplayScreenshotSchema.nullable(),\n afterScreenshot: browserReplayScreenshotSchema.nullable(),\n});\n\nexport const screenshotsTimelineResponseSchema = z.object({\n toolExecutions: z.array(toolExecutionPairSchema),\n});\n\nexport type BrowserReplayScreenshot = z.infer<\n typeof browserReplayScreenshotSchema\n>;\n\nexport type ToolExecutionPair = z.infer<typeof toolExecutionPairSchema>;\n\nexport type ScreenshotsTimelineResponse = z.infer<\n typeof screenshotsTimelineResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport {\n clarityScreenshareTranscriptEntrySchema,\n clarityScreenshareTurnBodySchema,\n} from \"../clarity-screenshare/types\";\nimport {\n clarityCaptureSchema,\n clarityProcessStatusSchema,\n conversationMessageSchema,\n} from \"../types/clarity\";\n\nexport const voiceConfigSchema = z.object({\n method: z.literal(\"openAiRTC\"),\n rtcUrl: z.string(),\n clientSecretToken: z.string(),\n});\n\nexport type VoiceConfig = z.infer<typeof voiceConfigSchema>;\n\nexport const getClarityScreenshareSessionResponseSchema = z.object({\n sessionId: z.guid(),\n name: z.string(),\n status: clarityProcessStatusSchema,\n messages: z.array(conversationMessageSchema),\n lastError: z.string().nullable(),\n lastFrameBase64Data: z.string().nullable(),\n});\n\nexport type GetClarityScreenshareSessionResponse = z.infer<\n typeof getClarityScreenshareSessionResponseSchema\n>;\n\n/**\n * Per-interview guidance derived from a `clarity_proposal_extra_capture_request`\n * row when the capture is started to fulfil that request. The voice agent uses\n * `gap` and `suggestedPrompt` to focus the interview on the missing information\n * rather than re-walking the full process. Null when the capture has no linked\n * extra-capture-request.\n */\nexport const screenshareExtraCaptureGuidanceSchema = z.object({\n gap: z.string(),\n suggestedPrompt: z.string().nullable(),\n});\n\nexport type ScreenshareExtraCaptureGuidance = z.infer<\n typeof screenshareExtraCaptureGuidanceSchema\n>;\n\nexport const startScreenshareCaptureResponseSchema =\n clarityCaptureSchema.extend({\n createdAt: z.string(),\n updatedAt: z.string(),\n openaiToken: z.string(),\n openaiTokenExpiresAt: z.string(),\n /**\n * Process-level guidance authored by the process owner via the \"Process\n * guidance\" dialog (`clarity_process.custom_prompt`). Applies to every\n * interview on this process. Null when the owner has not set guidance.\n */\n processGuidance: z.string().nullable(),\n extraCaptureGuidance: screenshareExtraCaptureGuidanceSchema.nullable(),\n });\n\nexport type StartScreenshareCaptureResponse = z.infer<\n typeof startScreenshareCaptureResponseSchema\n>;\n\nexport const MAX_SCREENSHARE_FRAMES_PER_CAPTURE = 300;\n\nexport const screenshareUploadUrlsBodySchema = z.object({\n screenshareStartTime: z.int().nonnegative(),\n frameTimestamps: z\n .array(z.int().nonnegative())\n .max(MAX_SCREENSHARE_FRAMES_PER_CAPTURE),\n});\n\nexport type ScreenshareUploadUrlsBody = z.infer<\n typeof screenshareUploadUrlsBodySchema\n>;\n\nexport const screenshareFrameUploadSchema = z.object({\n timestamp: z.int().nonnegative(),\n url: z.string(),\n gcsPath: z.string(),\n});\n\nexport type ScreenshareFrameUpload = z.infer<\n typeof screenshareFrameUploadSchema\n>;\n\nexport const screenshareUploadUrlsResponseSchema = z.object({\n videoUploadUrl: z.string(),\n videoGcsPath: z.string(),\n frameUploadUrls: z.array(screenshareFrameUploadSchema),\n expiresAt: z.string(),\n});\n\nexport type ScreenshareUploadUrlsResponse = z.infer<\n typeof screenshareUploadUrlsResponseSchema\n>;\n\nexport const completeScreenshareCaptureBodySchema =\n screenshareUploadUrlsBodySchema.extend({\n transcript: z.array(conversationMessageSchema).min(1),\n });\n\nexport type CompleteScreenshareCaptureBody = z.infer<\n typeof completeScreenshareCaptureBodySchema\n>;\n\nexport const completeScreenshareCaptureResponseSchema =\n clarityCaptureSchema.extend({\n createdAt: z.string(),\n updatedAt: z.string(),\n });\n\nexport type CompleteScreenshareCaptureResponse = z.infer<\n typeof completeScreenshareCaptureResponseSchema\n>;\n\nexport const autoSaveScreenshareCaptureBodySchema =\n clarityScreenshareTurnBodySchema.pick({ images: true }).extend({\n transcript: z.array(\n clarityScreenshareTranscriptEntrySchema.extend({\n role: z.enum([\"user\", \"assistant\", \"interviewer\"]),\n })\n ),\n });\n\nexport type AutoSaveScreenshareCaptureBody = z.infer<\n typeof autoSaveScreenshareCaptureBodySchema\n>;\n", "import { z } from \"zod\";\n\nexport const errorSchema = z.object({\n error: z.string(),\n});\n", "import { z } from \"zod\";\n\nexport const HUMAN_REQUEST_MIN_OPTIONS = 2;\nexport const HUMAN_REQUEST_MAX_OPTIONS = 6;\nconst HUMAN_REQUEST_OPTION_LABEL_MAX = 80;\nconst HUMAN_REQUEST_OPTION_DESCRIPTION_MAX = 200;\nconst HUMAN_REQUEST_FREE_TEXT_MAX = 1000;\n\nexport const humanRequestOptionSchema = z.object({\n label: z.string().min(1).max(HUMAN_REQUEST_OPTION_LABEL_MAX),\n description: z.string().max(HUMAN_REQUEST_OPTION_DESCRIPTION_MAX).optional(),\n});\n\nexport const humanRequestOptionsSchema = z\n .array(humanRequestOptionSchema)\n .min(HUMAN_REQUEST_MIN_OPTIONS)\n .max(HUMAN_REQUEST_MAX_OPTIONS);\n\nexport const humanRequestResponseSchema = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"free_text\"),\n text: z.string().min(1).max(HUMAN_REQUEST_FREE_TEXT_MAX),\n }),\n z.object({\n kind: z.literal(\"single_select\"),\n optionLabel: z.string().min(1).max(HUMAN_REQUEST_OPTION_LABEL_MAX),\n }),\n z.object({\n kind: z.literal(\"multi_select\"),\n optionLabels: z\n .array(z.string().min(1).max(HUMAN_REQUEST_OPTION_LABEL_MAX))\n .min(1)\n .max(HUMAN_REQUEST_MAX_OPTIONS),\n }),\n z.object({\n kind: z.literal(\"approval\"),\n approved: z.boolean(),\n }),\n]);\n\nexport type HumanRequestOption = z.infer<typeof humanRequestOptionSchema>;\nexport type HumanRequestOptions = z.infer<typeof humanRequestOptionsSchema>;\nexport type HumanRequestResponse = z.infer<typeof humanRequestResponseSchema>;\n\nexport function formatHumanRequestResponseForDisplay(\n response: HumanRequestResponse\n): string {\n switch (response.kind) {\n case \"free_text\": {\n return response.text;\n }\n case \"single_select\": {\n return response.optionLabel;\n }\n case \"multi_select\": {\n return response.optionLabels.join(\", \");\n }\n case \"approval\": {\n return response.approved ? \"Approved\" : \"Rejected\";\n }\n }\n}\n", "import { z } from \"zod\";\n\nexport const logoUploadUrlBodySchema = z.object({\n fileName: z.string().min(1),\n contentType: z.string().min(1),\n});\nexport type LogoUploadUrlBody = z.infer<typeof logoUploadUrlBodySchema>;\n\nexport const logoUploadUrlResponseSchema = z.object({\n signedUrl: z.string(),\n expiresAt: z.string(),\n});\nexport type LogoUploadUrlResponse = z.infer<typeof logoUploadUrlResponseSchema>;\n\nexport const logoUrlResponseSchema = z.object({\n url: z.string(),\n expiresAt: z.string(),\n});\nexport type LogoUrlResponse = z.infer<typeof logoUrlResponseSchema>;\n", "import { z } from \"zod\";\n\nexport const successSchema = z.object({\n success: z.boolean(),\n});\n\nexport type SuccessResponse = z.infer<typeof successSchema>;\n", "import { z } from \"zod\";\n\nimport { ORG_ROLES } from \"../organization-roles\";\nimport { DISCOVERY_MODES } from \"./organization\";\n\nexport const adminOrgSummarySchema = z.object({\n id: z.guid(),\n name: z.string(),\n discoveryMode: z.string(),\n enterpriseBillingEnabled: z.boolean(),\n createdAt: z.string().nullable(),\n deletedAt: z.string().nullable(),\n teamCount: z.number().int().nonnegative(),\n memberCount: z.number().int().nonnegative(),\n domainCount: z.number().int().nonnegative(),\n});\nexport type AdminOrgSummary = z.infer<typeof adminOrgSummarySchema>;\n\nexport const adminOrgListResponseSchema = z.object({\n organizations: z.array(adminOrgSummarySchema),\n total: z.number().int().nonnegative(),\n});\nexport type AdminOrgListResponse = z.infer<typeof adminOrgListResponseSchema>;\n\nexport const ADMIN_ORG_SORT_FIELDS = [\n \"name\",\n \"teamCount\",\n \"memberCount\",\n \"domainCount\",\n \"createdAt\",\n] as const;\nexport type AdminOrgSortField = (typeof ADMIN_ORG_SORT_FIELDS)[number];\n\nexport const adminOrgListQuerySchema = z.object({\n q: z.string().trim().optional(),\n limit: z.coerce.number().int().min(1).max(100).prefault(25),\n offset: z.coerce.number().int().min(0).prefault(0),\n includeDeleted: z\n .enum([\"true\", \"false\"])\n .prefault(\"false\")\n .transform((v) => v === \"true\"),\n sortBy: z.enum(ADMIN_ORG_SORT_FIELDS).prefault(\"createdAt\"),\n sortDir: z.enum([\"asc\", \"desc\"]).prefault(\"desc\"),\n discoveryMode: z.enum(DISCOVERY_MODES).optional(),\n});\nexport type AdminOrgListQuery = z.infer<typeof adminOrgListQuerySchema>;\n\nexport const adminOrgTeamSchema = z.object({\n id: z.guid(),\n name: z.string(),\n createdAt: z.string().nullable(),\n discoveryMode: z.string().nullable(),\n memberCount: z.number().int().nonnegative(),\n pendingInvitationCount: z.number().int().nonnegative(),\n pendingJoinRequestCount: z.number().int().nonnegative(),\n});\nexport type AdminOrgTeam = z.infer<typeof adminOrgTeamSchema>;\n\nexport const adminOrgMemberSchema = z.object({\n userId: z.guid(),\n name: z.string().nullable(),\n email: z.string(),\n role: z.string(),\n});\nexport type AdminOrgMember = z.infer<typeof adminOrgMemberSchema>;\n\nexport const adminOrgDomainSchema = z.object({\n id: z.guid(),\n domain: z.string(),\n createdAt: z.string().nullable(),\n});\nexport type AdminOrgDomain = z.infer<typeof adminOrgDomainSchema>;\n\nexport const adminOrgDetailResponseSchema = z.object({\n organization: adminOrgSummarySchema,\n teams: z.array(adminOrgTeamSchema),\n members: z.array(adminOrgMemberSchema),\n membersTotal: z.number().int().nonnegative(),\n membersTruncated: z.boolean(),\n domains: z.array(adminOrgDomainSchema),\n});\nexport type AdminOrgDetailResponse = z.infer<\n typeof adminOrgDetailResponseSchema\n>;\n\nexport const adminOrgCreateRequestSchema = z.object({\n name: z.string().trim().min(1).max(200),\n discoveryMode: z.enum(DISCOVERY_MODES).optional(),\n});\nexport type AdminOrgCreateRequest = z.infer<typeof adminOrgCreateRequestSchema>;\n\nexport const adminOrgUpdateRequestSchema = z\n .object({\n name: z.string().trim().min(1).max(200).optional(),\n discoveryMode: z.enum(DISCOVERY_MODES).optional(),\n enterpriseBillingEnabled: z.boolean().optional(),\n })\n .refine(\n (val) => Object.values(val).some((v) => v !== undefined),\n \"At least one field must be provided\"\n );\nexport type AdminOrgUpdateRequest = z.infer<typeof adminOrgUpdateRequestSchema>;\n\nexport const adminOrgMutationResponseSchema = z.object({\n organization: adminOrgSummarySchema,\n});\nexport type AdminOrgMutationResponse = z.infer<\n typeof adminOrgMutationResponseSchema\n>;\n\nexport const adminOrgAddDomainRequestSchema = z.object({\n domain: z\n .string()\n .trim()\n .toLowerCase()\n .min(3)\n .max(253)\n .regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/),\n});\nexport type AdminOrgAddDomainRequest = z.infer<\n typeof adminOrgAddDomainRequestSchema\n>;\n\nexport const adminOrgAddDomainResponseSchema = z.object({\n domain: adminOrgDomainSchema,\n});\nexport type AdminOrgAddDomainResponse = z.infer<\n typeof adminOrgAddDomainResponseSchema\n>;\n\nexport const adminOrgAssignTeamRequestSchema = z.object({\n teamId: z.guid(),\n});\nexport type AdminOrgAssignTeamRequest = z.infer<\n typeof adminOrgAssignTeamRequestSchema\n>;\n\nexport const adminOrgAddMemberRequestSchema = z.object({\n userId: z.guid(),\n role: z.enum(ORG_ROLES.ALL),\n});\nexport type AdminOrgAddMemberRequest = z.infer<\n typeof adminOrgAddMemberRequestSchema\n>;\n\nexport const adminOrgAddMemberResponseSchema = z.object({\n member: adminOrgMemberSchema,\n});\nexport type AdminOrgAddMemberResponse = z.infer<\n typeof adminOrgAddMemberResponseSchema\n>;\n\nexport const adminOrgSuccessResponseSchema = z.object({\n success: z.literal(true),\n});\nexport type AdminOrgSuccessResponse = z.infer<\n typeof adminOrgSuccessResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport { ORG_ROLES } from \"../organization-roles\";\n\nconst orgRoleEnum = z.enum(ORG_ROLES.ALL);\n\nexport const organizationApiSchema = z.object({\n id: z.guid(),\n name: z.string(),\n discoveryMode: z.string(),\n createdAt: z.string(),\n});\nexport type OrganizationApi = z.infer<typeof organizationApiSchema>;\n\nexport const orgMemberApiSchema = z.object({\n id: z.guid(),\n name: z.string().nullable(),\n email: z.email(),\n role: z.string(),\n teams: z\n .array(\n z.object({\n teamId: z.guid(),\n teamName: z.string(),\n teamRole: z.string(),\n })\n )\n .default([]),\n});\nexport type OrgMemberApi = z.infer<typeof orgMemberApiSchema>;\n\nexport const organizationDomainApiSchema = z.object({\n id: z.guid(),\n domain: z.string(),\n createdAt: z.string(),\n});\nexport type OrganizationDomainApi = z.infer<typeof organizationDomainApiSchema>;\n\nconst joinRequestStatusSchema = z.enum([\"pending\", \"approved\", \"denied\"]);\n\nexport const orgJoinRequestApiSchema = z.object({\n id: z.guid(),\n organizationId: z.guid(),\n userId: z.guid(),\n userName: z.string().nullable().optional(),\n userEmail: z.email().optional(),\n status: joinRequestStatusSchema,\n createdAt: z.string(),\n resolvedAt: z.string().nullable(),\n resolvedBy: z.guid().nullable(),\n});\nexport type OrgJoinRequestApi = z.infer<typeof orgJoinRequestApiSchema>;\n\nexport const teamJoinRequestApiSchema = z.object({\n id: z.guid(),\n teamId: z.guid(),\n userId: z.guid(),\n userName: z.string().nullable().optional(),\n userEmail: z.email().optional(),\n status: joinRequestStatusSchema,\n createdAt: z.string(),\n resolvedAt: z.string().nullable(),\n resolvedBy: z.guid().nullable(),\n});\nexport type TeamJoinRequestApi = z.infer<typeof teamJoinRequestApiSchema>;\n\nexport const createOrganizationRequestSchema = z.object({\n name: z.string().min(1),\n});\nexport type CreateOrganizationRequest = z.infer<\n typeof createOrganizationRequestSchema\n>;\n\nexport const DISCOVERY_MODES = [\"request\", \"auto\"] as const;\nexport type DiscoveryMode = (typeof DISCOVERY_MODES)[number];\n\nexport const discoveryModeSchema = z.enum(DISCOVERY_MODES);\n\nexport const updateOrganizationRequestSchema = z.object({\n name: z.string().min(1).optional(),\n discoveryMode: discoveryModeSchema.optional(),\n});\nexport type UpdateOrganizationRequest = z.infer<\n typeof updateOrganizationRequestSchema\n>;\n\nexport const inviteOrgMemberRequestSchema = z.object({\n email: z.email(),\n role: z.enum([\n \"organization:executive\",\n \"organization:owner\",\n \"organization:admin\",\n \"organization:member\",\n ]),\n frontendUrl: z.url().optional(),\n teamId: z.guid().optional(),\n});\nexport type InviteOrgMemberRequest = z.infer<\n typeof inviteOrgMemberRequestSchema\n>;\n\nexport const inviteOrgMemberResponseSchema = z.object({\n success: z.boolean(),\n invitationId: z.guid(),\n emailSent: z.boolean(),\n});\nexport type InviteOrgMemberResponse = z.infer<\n typeof inviteOrgMemberResponseSchema\n>;\n\nexport const updateOrgMemberRoleRequestSchema = z.object({\n role: z.enum([\n \"organization:executive\",\n \"organization:owner\",\n \"organization:admin\",\n \"organization:member\",\n ]),\n});\nexport type UpdateOrgMemberRoleRequest = z.infer<\n typeof updateOrgMemberRoleRequestSchema\n>;\n\nexport const addOrgDomainRequestSchema = z.object({\n domain: z\n .string()\n .min(3)\n .regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/),\n});\nexport type AddOrgDomainRequest = z.infer<typeof addOrgDomainRequestSchema>;\n\nexport const resolveJoinRequestSchema = z.object({\n status: z.enum([\"approved\", \"denied\"]),\n});\nexport type ResolveJoinRequest = z.infer<typeof resolveJoinRequestSchema>;\n\nexport const discoverOrganizationResponseSchema = z.object({\n found: z.boolean(),\n organization: organizationApiSchema.nullable(),\n});\nexport type DiscoverOrganizationResponse = z.infer<\n typeof discoverOrganizationResponseSchema\n>;\n\nexport const listOrgMembersResponseSchema = z.object({\n members: z.array(orgMemberApiSchema),\n total: z.number(),\n});\nexport type ListOrgMembersResponse = z.infer<\n typeof listOrgMembersResponseSchema\n>;\n\nexport const listOrgDomainsResponseSchema = z.object({\n domains: z.array(organizationDomainApiSchema),\n});\nexport type ListOrgDomainsResponse = z.infer<\n typeof listOrgDomainsResponseSchema\n>;\n\nexport const listOrgJoinRequestsResponseSchema = z.object({\n requests: z.array(orgJoinRequestApiSchema),\n});\nexport type ListOrgJoinRequestsResponse = z.infer<\n typeof listOrgJoinRequestsResponseSchema\n>;\n\nexport const listTeamJoinRequestsResponseSchema = z.object({\n requests: z.array(teamJoinRequestApiSchema),\n});\nexport type ListTeamJoinRequestsResponse = z.infer<\n typeof listTeamJoinRequestsResponseSchema\n>;\n\nexport const teamJoinRequestWithTeamApiSchema = teamJoinRequestApiSchema.extend(\n {\n teamName: z.string(),\n }\n);\nexport type TeamJoinRequestWithTeamApi = z.infer<\n typeof teamJoinRequestWithTeamApiSchema\n>;\n\nexport const listOrgTeamJoinRequestsResponseSchema = z.object({\n requests: z.array(teamJoinRequestWithTeamApiSchema),\n total: z.number().int().nonnegative(),\n});\nexport type ListOrgTeamJoinRequestsResponse = z.infer<\n typeof listOrgTeamJoinRequestsResponseSchema\n>;\n\nexport const userOrganizationResponseSchema = z.object({\n organization: organizationApiSchema.nullable(),\n role: z.string().nullable(),\n});\nexport type UserOrganizationResponse = z.infer<\n typeof userOrganizationResponseSchema\n>;\n\nexport const orgMembershipApiSchema = z.object({\n organization: organizationApiSchema,\n role: z.string(),\n memberCount: z.number(),\n});\nexport type OrgMembershipApi = z.infer<typeof orgMembershipApiSchema>;\n\nexport const userOrganizationsResponseSchema = z.object({\n memberships: z.array(orgMembershipApiSchema),\n});\nexport type UserOrganizationsResponse = z.infer<\n typeof userOrganizationsResponseSchema\n>;\n\nexport const createOrgTeamRequestSchema = z.object({\n name: z.string().min(1),\n});\nexport type CreateOrgTeamRequest = z.infer<typeof createOrgTeamRequestSchema>;\n\nexport const orgInvitationApiSchema = z.object({\n id: z.guid(),\n email: z.email(),\n role: z.string(),\n teamId: z.guid().nullable().optional(),\n createdAt: z.string(),\n invitedByName: z.string().nullable().optional(),\n});\nexport type OrgInvitationApi = z.infer<typeof orgInvitationApiSchema>;\n\nexport const listOrgInvitationsResponseSchema = z.object({\n invitations: z.array(orgInvitationApiSchema),\n});\nexport type ListOrgInvitationsResponse = z.infer<\n typeof listOrgInvitationsResponseSchema\n>;\n\nexport const orgInvitationDetailApiSchema = z.object({\n id: z.guid(),\n email: z.email(),\n role: orgRoleEnum,\n createdAt: z.string(),\n resolvedAt: z.string().nullable(),\n invitedByName: z.string().nullable(),\n invitedByEmail: z.email().nullable(),\n organization: z.object({\n id: z.guid(),\n name: z.string(),\n }),\n});\nexport type OrgInvitationDetailApi = z.infer<\n typeof orgInvitationDetailApiSchema\n>;\n\nexport const acceptOrgInvitationResponseSchema = z.object({\n success: z.boolean(),\n orgId: z.guid(),\n});\nexport type AcceptOrgInvitationResponse = z.infer<\n typeof acceptOrgInvitationResponseSchema\n>;\n\nexport const createOrganizationInviteLinkRequestSchema = z.object({\n frontendUrl: z.url(),\n});\nexport type CreateOrganizationInviteLinkRequest = z.infer<\n typeof createOrganizationInviteLinkRequestSchema\n>;\n\nexport const getOrganizationInviteLinkQuerySchema = z.object({\n frontendUrl: z.url(),\n});\nexport type GetOrganizationInviteLinkQuery = z.infer<\n typeof getOrganizationInviteLinkQuerySchema\n>;\n\nexport const organizationInviteLinkCreatorSchema = z.object({\n id: z.guid(),\n name: z.string().nullable(),\n email: z.email(),\n});\n\nexport const organizationInviteLinkSchema = z.object({\n id: z.guid(),\n url: z.url().optional(),\n createdAt: z.string(),\n createdBy: organizationInviteLinkCreatorSchema,\n});\nexport type OrganizationInviteLink = z.infer<\n typeof organizationInviteLinkSchema\n>;\n\nexport const getOrganizationInviteLinkResponseSchema = z.object({\n hasLink: z.boolean(),\n link: organizationInviteLinkSchema.optional(),\n});\nexport type GetOrganizationInviteLinkResponse = z.infer<\n typeof getOrganizationInviteLinkResponseSchema\n>;\n\nexport const createOrganizationInviteLinkResponseSchema =\n organizationInviteLinkSchema;\nexport type CreateOrganizationInviteLinkResponse = z.infer<\n typeof createOrganizationInviteLinkResponseSchema\n>;\n\nexport const orgJoinLinkInfoResponseSchema = z.object({\n valid: z.boolean(),\n orgName: z.string().optional(),\n orgId: z.guid().optional(),\n reason: z.enum([\"invalid\", \"expired\"]).optional(),\n});\nexport type OrgJoinLinkInfoResponse = z.infer<\n typeof orgJoinLinkInfoResponseSchema\n>;\n\nexport const acceptOrgJoinLinkResponseSchema = z.object({\n success: z.boolean(),\n orgId: z.guid(),\n});\nexport type AcceptOrgJoinLinkResponse = z.infer<\n typeof acceptOrgJoinLinkResponseSchema\n>;\n\nexport const pendingCountsResponseSchema = z.object({\n joinRequests: z.number(),\n invitations: z.number(),\n});\nexport type PendingCountsResponse = z.infer<typeof pendingCountsResponseSchema>;\n", "import { z } from \"zod\";\n\nimport { StoredAgentConfigSchema } from \"./agent-config\";\n\n/**\n * Zod schemas for agent API responses\n * These schemas are used for both backend validation and frontend type inference\n */\n\n/**\n * Schedule frequency enum schema\n */\nexport const scheduleFrequencySchema = z.enum([\n \"every_5_minutes\",\n \"every_15_minutes\",\n \"hourly\",\n \"daily\",\n \"workday\",\n \"weekly\",\n \"monthly\",\n \"custom\",\n]);\n\n/**\n * Schedule day enum schema\n */\nexport const scheduleDaySchema = z.enum([\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n \"sunday\",\n]);\n\n/**\n * Schedule as returned over the wire.\n *\n * Frequency-dependent fields are nullable on this shape; the per-frequency\n * required-fields contract is:\n *\n * - `cron` set iff `frequency === \"custom\"`.\n * - `time` required for `daily`, `workday`, `weekly`, `monthly`.\n * - `day` required for `weekly`; `day_of_month` required for `monthly`.\n *\n * Writes are validated by `scheduleUpsertRequestSchema.superRefine`; cron\n * evaluation is in `shouldRunSchedule`.\n */\nexport const scheduleApiSchema = z.object({\n id: z.string(),\n build_id: z.string(),\n agent_id: z.string(),\n user_id: z.string(),\n enabled: z.boolean(),\n frequency: scheduleFrequencySchema,\n time: z.string().nullable(),\n timezone: z.string(),\n day: z.string().nullable(),\n day_of_month: z.number().nullable(),\n /** Cron expression. Set iff `frequency === \"custom\"`; null otherwise. */\n cron: z.string().nullable(),\n /** Who authored the schedule. `\"user\"` for user-driven upserts; `null` on legacy rows. */\n source: z.string().nullable(),\n /** Optional prompt appended to the run when the schedule fires. */\n task: z.string().nullable(),\n /** `false` for one-shot schedules, which are retired after the first fire. `null` is treated as recurring. */\n recurring: z.boolean().nullable(),\n created_at: z.string(),\n updated_at: z.string(),\n /** Populated only by the all-users admin endpoint; undefined on per-user responses. */\n user_name: z.string().nullable().optional(),\n /** Populated only by the all-users admin endpoint; undefined on per-user responses. */\n user_email: z.string().nullable().optional(),\n});\n\nexport const integrationConfigApiSchema = z.object({\n id: z.string(),\n integration_id: z.string(),\n integration_type: z.string(),\n integration_name: z.string(),\n created_at: z.string(),\n icon_url: z.string().nullish(),\n is_connected: z.boolean().optional(),\n});\n\n/**\n * Per-user blocker entry for the all-users schedule view (superadmin).\n * Lists missing integration connections for one schedule owner so the UI\n * can flag whether that user can edit or run their own schedules.\n */\nexport const userScheduleBlockersSchema = z.object({\n user_id: z.string(),\n missing_integrations: z.array(\n z.object({\n integration_id: z.string().nullable(),\n integration_type: z.string(),\n })\n ),\n});\n\nconst FREQUENCIES_REQUIRING_TIME = [\n \"daily\",\n \"workday\",\n \"weekly\",\n \"monthly\",\n] as const;\n\n/** Maximum schedules one `(agent_id, user_id)` pair can own. Enforced on create. */\nexport const MAX_SCHEDULES_PER_AGENT = 5;\n\n/**\n * Schedule upsert request schema\n */\nexport const scheduleUpsertRequestSchema = z\n .object({\n agent_id: z.string(),\n enabled: z.boolean(),\n frequency: scheduleFrequencySchema,\n time: z.string().nullable().optional(),\n timezone: z.string(),\n day: scheduleDaySchema.nullable().optional(),\n day_of_month: z.int().min(1).max(31).nullable().optional(),\n cron: z.string().nullable().optional(),\n recurring: z.boolean().nullable().optional(),\n })\n .superRefine((data, ctx) => {\n // Only validate required fields when schedule is enabled\n if (!data.enabled) {\n return;\n }\n\n if (data.frequency === \"custom\" && !data.cron) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Cron expression is required for custom schedules\",\n path: [\"cron\"],\n });\n }\n\n if (data.frequency === \"weekly\" && !data.day) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Day of week is required for weekly schedules\",\n path: [\"day\"],\n });\n }\n\n if (data.frequency === \"monthly\" && data.day_of_month == null) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Day of month is required for monthly schedules\",\n path: [\"day_of_month\"],\n });\n }\n\n if (\n FREQUENCIES_REQUIRING_TIME.includes(\n data.frequency as (typeof FREQUENCIES_REQUIRING_TIME)[number]\n ) &&\n !data.time\n ) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Time is required for this schedule frequency\",\n path: [\"time\"],\n });\n }\n });\n\n/**\n * Build schema for API responses (with ISO string dates).\n *\n * `agent_id` mirrors `copilot_id` for public consumers that pre-date\n * the rename; keep both populated in every response.\n */\nexport const buildApiSchema = z.strictObject({\n id: z.guid(),\n copilot_id: z.guid(),\n agent_id: z.guid(),\n name: z.string(),\n config: StoredAgentConfigSchema.nullable(),\n status: z.string().nullable(),\n revision_number: z.number().nullable(),\n parent_build_id: z.string().nullable(),\n created_by: z.string().nullable(),\n created_by_name: z.string().nullable().optional(),\n created_at: z.string().nullable(),\n updated_at: z.string().nullable(),\n schedules: z.array(scheduleApiSchema).optional(),\n});\n\n/**\n * Schema for a conflicting agent in case trigger conflict detection\n */\nexport const conflictingAgentSchema = z.object({\n id: z.string(),\n name: z.string(),\n});\n\nexport type ConflictingAgent = z.infer<typeof conflictingAgentSchema>;\n\n/**\n * Agent schema for API responses (with ISO string dates)\n */\nexport const agentApiSchema = z.object({\n id: z.guid(),\n name: z.string(),\n slack_enabled: z.boolean().nullable(),\n microsoft_teams_enabled: z.boolean().nullable(),\n agentic_memory_enabled: z.boolean().nullable(),\n team_id: z.string().nullable(),\n thread_id: z.string().nullable(),\n folder_id: z.string().nullable().optional(),\n created_at: z.string().nullable(),\n updated_at: z.string().nullable(),\n last_run_at: z.string().nullable(),\n created_by: z\n .object({\n id: z.string(),\n name: z.string().nullable(),\n email: z.string(),\n })\n .nullable()\n .optional(),\n updated_by: z\n .object({\n id: z.string(),\n name: z.string().nullable(),\n email: z.string(),\n })\n .nullable()\n .optional(),\n latest_build: buildApiSchema.nullable(),\n integration_configs: z.array(integrationConfigApiSchema),\n user_triggers: z\n .object({\n slack_mention: z.boolean(),\n slack_channel: z.boolean(),\n teams_mention: z.boolean(),\n })\n .optional(),\n case_trigger_enabled: z.boolean().optional(),\n case_trigger_has_conflict: z.boolean().optional(),\n case_trigger_conflicting_agents: z.array(conflictingAgentSchema).optional(),\n case_queue_name: z.string().nullable().optional(),\n});\n\n/**\n * Paginated list of agents for the GET /v1/agents response.\n */\nexport const agentsListApiSchema = z.object({\n agents: z.array(agentApiSchema),\n total: z.int(),\n limit: z.int(),\n offset: z.int(),\n});\n\n/**\n * Wrapper for single-agent responses (GET /v1/agents/:agent_id).\n */\nexport const agentResponseApiSchema = z.object({\n agent: agentApiSchema,\n});\n\n/**\n * Response for POST /v1/agents.\n *\n * When an inline `build` is supplied in the request body, the first build\n * is returned alongside the agent. Otherwise `build` is omitted.\n */\nexport const createAgentResponseApiSchema = z.object({\n agent: agentApiSchema,\n build: buildApiSchema.optional(),\n});\n\n/**\n * Agent run schema for API responses (with ISO string dates)\n */\nexport const agentRunApiSchema = z.object({\n id: z.string(),\n agent_id: z.string(),\n build_id: z.string(),\n status: z.string(),\n user_id: z.string().nullable(),\n source: z.string().nullable(),\n sandbox_id: z.string().nullable(),\n bb_session_id: z.string().nullable(),\n last_session_id: z.string().nullable(),\n created_at: z.string(),\n updated_at: z.string(),\n started_at: z.string().nullable(),\n completed_at: z.string().nullable(),\n});\n\n/**\n * Agent with runs schema - used when including run statistics\n */\nexport const agentWithRunsApiSchema = z.object({\n id: z.string(),\n name: z.string(),\n slack_enabled: z.boolean().nullable(),\n team_id: z.string().nullable(),\n thread_id: z.string().nullable(),\n created_at: z.string().nullable(),\n updated_at: z.string().nullable(),\n agent_run: z.array(agentRunApiSchema),\n});\n\n/**\n * Array of agents with runs schema for list endpoints\n */\nexport const agentsWithRunsListApiSchema = z.array(agentWithRunsApiSchema);\n\n/**\n * Active run counts grouped by agent\n */\nexport const activeRunCountByAgentApiSchema = z.object({\n agent: z.object({\n id: z.string(),\n name: z.string(),\n }),\n run_count: z.int(),\n});\n\nexport const activeRunsListApiSchema = z.array(activeRunCountByAgentApiSchema);\n\n/**\n * Schema for an agent's per-build integration slot row.\n * Returned by GET /v1/agents/:agent_id/builds/:build_id/integrations.\n */\nexport const buildIntegrationConfigSchema = z.object({\n id: z.guid(),\n integration_id: z.guid().nullable(),\n custom_integration_id: z.guid().nullable(),\n integration_type: z.string(),\n integration_name: z.string(),\n created_at: z.string(),\n});\n\nexport const listBuildIntegrationsResponseSchema = z.object({\n integrations: z.array(buildIntegrationConfigSchema),\n});\n\n/**\n * Schema for a queue summary linked to a build integration slot. Used by\n * GET /v1/agents/:agent_id/builds/:build_id/integrations/:integration_id/queues.\n */\nexport const buildIntegrationCaseQueueSchema = z.object({\n id: z.guid(),\n name: z.string(),\n});\n\nexport const buildIntegrationQueuesResponseSchema = z.object({\n queues: z.array(buildIntegrationCaseQueueSchema),\n});\n\n/**\n * TypeScript types for API responses\n * Inferred from Zod schemas to ensure they stay in sync\n */\nexport type ScheduleFrequency = z.infer<typeof scheduleFrequencySchema>;\nexport type ScheduleDay = z.infer<typeof scheduleDaySchema>;\nexport type ScheduleApi = z.infer<typeof scheduleApiSchema>;\nexport type UserScheduleBlockers = z.infer<typeof userScheduleBlockersSchema>;\nexport type ScheduleUpsertRequest = z.infer<typeof scheduleUpsertRequestSchema>;\nexport type BuildApi = z.infer<typeof buildApiSchema>;\nexport type IntegrationConfigApi = z.infer<typeof integrationConfigApiSchema>;\nexport type BuildIntegrationConfig = z.infer<\n typeof buildIntegrationConfigSchema\n>;\nexport type ListBuildIntegrationsResponse = z.infer<\n typeof listBuildIntegrationsResponseSchema\n>;\nexport type BuildIntegrationCaseQueue = z.infer<\n typeof buildIntegrationCaseQueueSchema\n>;\nexport type BuildIntegrationQueuesResponse = z.infer<\n typeof buildIntegrationQueuesResponseSchema\n>;\nexport type AgentApi = z.infer<typeof agentApiSchema>;\nexport type AgentsListApi = z.infer<typeof agentsListApiSchema>;\nexport type AgentResponseApi = z.infer<typeof agentResponseApiSchema>;\nexport type CreateAgentResponseApi = z.infer<\n typeof createAgentResponseApiSchema\n>;\nexport type AgentRunApi = z.infer<typeof agentRunApiSchema>;\nexport type AgentWithRunsApi = z.infer<typeof agentWithRunsApiSchema>;\nexport type AgentsWithRunsListApi = z.infer<typeof agentsWithRunsListApiSchema>;\nexport type ActiveRunCountByAgentApi = z.infer<\n typeof activeRunCountByAgentApiSchema\n>;\nexport type ActiveRunsListApi = z.infer<typeof activeRunsListApiSchema>;\n", "import type {\n ResponseIncludable,\n Tool,\n} from \"openai/resources/responses/responses\";\nimport { z } from \"zod\";\n\nimport {\n BrowsingModelIdSchema,\n BrowsingProviderSchema,\n ClaudeModelIdSchema,\n} from \"../constants/models\";\n\n// Schema for MCP tool approval filter\nconst McpToolApprovalFilterSchema = z.object({\n always: z\n .object({\n tool_names: z.array(z.string()).nullable().optional(),\n })\n .nullable()\n .optional(),\n never: z\n .object({\n tool_names: z.array(z.string()).nullable().optional(),\n })\n .nullable()\n .optional(),\n});\n\n// Schema for MCP allowed tools filter\nconst McpAllowedToolsFilterSchema = z.object({\n tool_names: z.array(z.string()).nullable().optional(),\n});\n\n// Schema for MCP tool definition\nexport const McpToolSchema = z.object({\n type: z.literal(\"mcp\"),\n server_label: z.string(),\n server_url: z.string(),\n allowed_tools: z\n .union([z.array(z.string()), McpAllowedToolsFilterSchema])\n .nullable()\n .optional(),\n headers: z.record(z.string(), z.string()).nullable().optional(),\n require_approval: z\n .union([\n z.literal(\"always\"),\n z.literal(\"never\"),\n McpToolApprovalFilterSchema,\n ])\n .nullable()\n .optional(),\n});\n\nexport type McpTool = z.infer<typeof McpToolSchema>;\n\n// Schema for input text content\nexport const InputTextSchema = z.object({\n type: z.literal(\"input_text\"),\n text: z.string(),\n});\n\nexport type InputText = z.infer<typeof InputTextSchema>;\n\n// Schema for input image content\nexport const InputImageSchema = z.object({\n type: z.literal(\"input_image\"),\n detail: z.enum([\"low\", \"high\", \"auto\"]).nullable().optional(),\n file_id: z.string().nullable().optional(),\n url: z.string().nullable().optional(),\n});\n\nexport type InputImage = z.infer<typeof InputImageSchema>;\n\n// Schema for input file content\nexport const InputFileSchema = z.object({\n type: z.literal(\"input_file\"),\n file_id: z.string(),\n});\n\nexport type InputFile = z.infer<typeof InputFileSchema>;\n\n// Union of all input content types\nexport const InputContentSchema = z.union([\n InputTextSchema,\n InputImageSchema,\n InputFileSchema,\n]);\n\nexport type InputContent = z.infer<typeof InputContentSchema>;\n\n// Schema for input messages\nexport const InputMessageSchema = z.object({\n role: z.enum([\"system\", \"user\", \"assistant\"]),\n content: z.union([z.string(), z.array(InputContentSchema)]),\n type: z.literal(\"message\").nullable().optional(),\n});\n\nexport type InputMessage = z.infer<typeof InputMessageSchema>;\n\n// Schema for OpenAI Responses API parameters (matches route.ts)\nexport const OpenAIResponseParamsSchema = z.object({\n // Required fields\n input: z.array(InputMessageSchema).describe(\"Instructions payload\"),\n model: z.string(),\n\n // Optional fields that OpenAI accepts\n background: z.boolean().nullable().optional(),\n include: z\n .array(z.string())\n .nullable()\n .optional()\n .transform((val) => val?.map((item) => item as ResponseIncludable)),\n instructions: z.string().nullable().optional(),\n max_output_tokens: z.number().positive().nullable().optional(),\n metadata: z.record(z.string(), z.string()).nullable().optional(),\n parallel_tool_calls: z.boolean().nullable().optional(),\n previous_response_id: z.string().nullable().optional(),\n reasoning: z.boolean().nullable().optional(),\n service_tier: z.enum([\"auto\", \"default\", \"flex\"]).nullable().optional(),\n store: z.boolean().nullable().optional(),\n stream: z.boolean().transform(() => true), // Always stream\n temperature: z.number().min(0).max(2).nullable().optional(),\n text: z\n .object({\n format: z\n .union([\n z.object({ type: z.literal(\"text\") }),\n z.object({ type: z.literal(\"json_object\") }),\n ])\n .nullable()\n .optional(),\n })\n .nullable()\n .optional(),\n tool_choice: z\n .union([\n z.string(),\n z.object({\n type: z.enum([\"tool\"]),\n name: z.string(),\n }),\n ])\n .nullable()\n .optional(),\n tools: z\n .array(McpToolSchema)\n .nullable()\n .optional()\n .transform((val) => val?.map((item) => item as Tool.Mcp)),\n top_p: z.number().min(0).max(1).nullable().optional(),\n truncation: z.enum([\"auto\", \"disabled\"]).nullable().optional(),\n user: z.string().nullable().optional(),\n});\n\nexport type OpenAIResponseParams = z.infer<typeof OpenAIResponseParamsSchema>;\n\n// Schema for incoming request (includes our custom conversation fields)\nexport const RequestParamsSchema = OpenAIResponseParamsSchema.extend({\n // Custom conversation handling fields\n messages: z\n .array(\n z.object({\n role: z.enum([\"user\", \"assistant\", \"system\"]),\n content: z.string(),\n })\n )\n .nullable()\n .optional(),\n conversationContext: z\n .array(\n z.object({\n role: z.enum([\"user\", \"assistant\", \"system\"]),\n content: z.string(),\n })\n )\n .nullable()\n .optional(),\n systemPrompt: z.string().nullable().optional(),\n});\n\n// v1 Schema (Legacy - OpenAI-based)\nexport const AgentConfigSchemaV1 = OpenAIResponseParamsSchema.pick({\n model: true,\n temperature: true,\n max_output_tokens: true,\n top_p: true,\n store: true,\n tools: true,\n input: true,\n text: true,\n}).extend({\n files: z.array(z.string()).nullable().optional().default([]),\n skills: z.array(z.string()).nullable().optional().default([]),\n input: z.union([z.string(), z.array(InputMessageSchema)]),\n});\n\nexport type AgentConfigV1 = z.infer<typeof AgentConfigSchemaV1>;\n\nexport const StoredAgentConfigSchemaV1 = z.object({\n version: z.literal(\"v1\"),\n data: AgentConfigSchemaV1,\n});\n\nexport type StoredAgentConfigV1 = z.infer<typeof StoredAgentConfigSchemaV1>;\n\n/**\n * Browser infrastructure provider types (where browser sessions run).\n */\nexport const BrowserProviderTypeSchema = z.enum([\"browserbase\", \"browser-use\"]);\nexport type BrowserProviderType = z.infer<typeof BrowserProviderTypeSchema>;\n\nexport const BenchmarkExpectedOutcomeSchema = z.object({\n description: z\n .string()\n .describe(\"Human-readable description of the expected outcome\"),\n criteria: z\n .string()\n .describe(\"Pass/fail criteria used to evaluate the outcome\"),\n});\n\nexport type BenchmarkExpectedOutcome = z.infer<\n typeof BenchmarkExpectedOutcomeSchema\n>;\n\n/**\n * Runtime options schema for agent execution.\n * Uses passthrough() to allow additional unknown keys for future extensibility.\n */\nexport const RuntimeOptionsSchema = z.looseObject({\n browserProvider: BrowserProviderTypeSchema.optional().describe(\n \"Browser infrastructure provider\"\n ),\n evaluationSchemaId: z\n .string()\n .optional()\n .describe(\"ID of the evaluation schema to apply to runs of this agent\"),\n benchmarkExpectedOutcomes: z\n .array(BenchmarkExpectedOutcomeSchema)\n .optional()\n .describe(\"Expected outcomes used when running benchmark scenarios\"),\n});\n\nexport type RuntimeOptions = z.infer<typeof RuntimeOptionsSchema>;\n\n// v2 Schema - nested models object matching PLATFORM_DEFAULT_MODELS structure\nexport const AgentConfigSchemaV2 = z.object({\n models: z\n .object({\n agent: z\n .object({\n model: ClaudeModelIdSchema.describe(\n \"Claude model identifier used for the primary agent loop\"\n ),\n })\n .describe(\"Primary Claude agent model configuration\"),\n browsing: z\n .object({\n provider: BrowsingProviderSchema.describe(\n \"Provider backing the browsing/computer-use model\"\n ),\n model: BrowsingModelIdSchema.describe(\n \"Model identifier for the browsing provider\"\n ),\n })\n .describe(\"Browsing/computer-use model configuration\"),\n })\n .describe(\"Model configuration for each capability the agent uses\"),\n\n // Core fields\n input: z\n .union([z.string(), z.array(InputMessageSchema)])\n .describe(\n \"Initial agent instructions \u2014 either a single system prompt string or a list of structured messages\"\n ),\n files: z\n .array(z.string())\n .nullable()\n .optional()\n .default([])\n .describe(\"IDs of team files that should be available to the agent\"),\n skills: z\n .array(z.string())\n .nullable()\n .optional()\n .default([])\n .describe(\n \"IDs of skills (team or system) that should be available to the agent\"\n ),\n // Plugins can be:\n // - Built-in plugin name: \"code-review\", \"commit-commands\"\n // - GitHub URL: \"https://github.com/owner/repo\"\n plugins: z\n .array(z.string())\n .nullable()\n .optional()\n .default([])\n .describe(\n 'Plugins to load \u2014 either a built-in plugin name (e.g. \"code-review\") or a GitHub URL (e.g. \"https://github.com/owner/repo\")'\n ),\n subAgents: z\n .array(z.uuid())\n .nullable()\n .optional()\n .default([])\n .describe(\n \"IDs of other assignments (agents in the same team) to expose to this assignment as Claude Code subagents. Each sub-assignment runs with its own SOP and connections; the parent can delegate to them via the Agent tool.\"\n ),\n\n // Runtime options (extensible)\n options: RuntimeOptionsSchema.optional().describe(\n \"Optional runtime options controlling how the agent executes\"\n ),\n});\n\nexport type AgentConfigV2 = z.infer<typeof AgentConfigSchemaV2>;\n\nexport const StoredAgentConfigSchemaV2 = z.object({\n version: z\n .literal(\"v2\")\n .describe(\n 'Schema version discriminator \u2014 must be \"v2\" for the current schema'\n ),\n data: AgentConfigSchemaV2.describe(\"Agent configuration payload\"),\n});\n\nexport type StoredAgentConfigV2 = z.infer<typeof StoredAgentConfigSchemaV2>;\n\nexport const AgentConfigSchema = AgentConfigSchemaV2;\nexport type AgentConfig = AgentConfigV2;\n\nexport const StoredAgentConfigSchema = z.union([\n StoredAgentConfigSchemaV1,\n StoredAgentConfigSchemaV2,\n]);\n\nexport type StoredAgentConfig = StoredAgentConfigV1 | StoredAgentConfigV2;\n\nexport const EditConfigParamsSchema = z.object({\n buildId: z.guid(),\n});\n\nexport type EditConfigParams = z.infer<typeof EditConfigParamsSchema>;\n\nexport const EditConfigBodySchema = z.object({\n prompt: z.union([z.string(), z.array(z.string())]),\n runId: z.guid().optional().describe(\"Optional run ID for context\"),\n conversation: z\n .array(z.object({ source: z.enum([\"ai\", \"user\"]), message: z.string() }))\n .optional()\n .describe(\"Optional voice conversation transcript\"),\n processId: z.guid().optional().describe(\"Optional process ID for context\"),\n insightIndex: z\n .number()\n .min(0)\n .optional()\n .describe(\"Optional insight index for context\"),\n previousBuildId: z\n .guid()\n .optional()\n .describe(\"Previous build ID for sandbox reuse\"),\n});\n\nexport type EditConfigBody = z.infer<typeof EditConfigBodySchema>;\n", "import { z } from \"zod\";\n\nexport const feedbackSentimentSchema = z.enum([\"positive\", \"negative\"]);\n\nexport type FeedbackSentiment = z.infer<typeof feedbackSentimentSchema>;\n\n/**\n * Maximum length for feedback comments in characters.\n */\nexport const MAX_FEEDBACK_COMMENT_LENGTH = 2000;\n\nexport const feedbackDataSchema = z.object({\n id: z.guid(),\n agent_id: z.guid(),\n build_id: z.guid(),\n run_id: z.guid(),\n user_id: z.guid(),\n sentiment: feedbackSentimentSchema,\n comment: z.string().max(MAX_FEEDBACK_COMMENT_LENGTH).nullable(),\n session_id: z.string().nullable(),\n created_at: z.string(),\n updated_at: z.string(),\n});\n\nexport type FeedbackData = z.infer<typeof feedbackDataSchema>;\n", "import { z } from \"zod\";\n\nexport const agentFolderResponseSchema = z.object({\n id: z.string(),\n name: z.string(),\n team_id: z.string(),\n parent_folder_id: z.string().nullable(),\n created_at: z.string(),\n updated_at: z.string(),\n agent_count: z.number(),\n subfolder_count: z.number(),\n});\n\nexport const agentFoldersListResponseSchema = z.array(\n agentFolderResponseSchema\n);\n\nexport const createAgentFolderRequestSchema = z.object({\n name: z.string().min(1).max(100),\n parent_folder_id: z.guid().nullable().optional(),\n});\n\nexport const updateAgentFolderRequestSchema = z.object({\n name: z.string().min(1).max(100).optional(),\n parent_folder_id: z.guid().nullable().optional(),\n});\n\nexport const moveAgentsRequestSchema = z.object({\n agent_ids: z.array(z.guid()).min(1),\n folder_id: z.guid().nullable(),\n});\n\nexport type AgentFolderResponse = z.infer<typeof agentFolderResponseSchema>;\nexport type AgentFoldersListResponse = z.infer<\n typeof agentFoldersListResponseSchema\n>;\nexport type CreateAgentFolderRequest = z.infer<\n typeof createAgentFolderRequestSchema\n>;\nexport type UpdateAgentFolderRequest = z.infer<\n typeof updateAgentFolderRequestSchema\n>;\nexport type MoveAgentsRequest = z.infer<typeof moveAgentsRequestSchema>;\n", "import { z } from \"zod\";\n\n/**\n * Zod schema for validating agent learning entities\n */\nexport const learningSchema = z.object({\n id: z.string(),\n content: z.string(),\n sourceRunId: z.string().nullable(),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\n\n/**\n * Type representing an agent learning entity\n */\nexport type Learning = z.infer<typeof learningSchema>;\n\n/**\n * Zod schema for API responses containing a learning entity\n */\nexport const getLearningsResponseSchema = z.object({\n learning: learningSchema.nullable(),\n});\n", "import { z } from \"zod\";\n\n// Page schema - all fields required (Browserbase provides full page data)\nexport const browserPageSchema = z.object({\n id: z.string().describe(\"Page ID\"),\n url: z.url().describe(\"Page URL\"),\n faviconUrl: z.string().describe(\"Page favicon URL\"),\n title: z.string().describe(\"Page title\"),\n debuggerUrl: z.url().describe(\"Page-specific debugger URL\"),\n debuggerFullscreenUrl: z\n .url()\n .describe(\"Page-specific full-screen debugger URL\"),\n});\n\n// Alias for backwards compatibility\nexport const browserbasePageSchema = browserPageSchema;\n\n// Session info response - includes session-level URLs + optional pages\n// Browser Use provides session-level URLs only, Browserbase provides both\nexport const browserSessionInfoSchema = z.object({\n // Session-level URLs (Browser Use provides these, Browserbase also has them)\n wsUrl: z.url().nullable(),\n liveUrl: z.url().nullable(),\n\n // Page-level data (Browserbase provides these, Browser Use returns empty array)\n pages: z.array(browserPageSchema),\n});\n\n// Zod schema for Browserbase debug API response\nexport const browserbaseDebugResponseSchema = z.object({\n debuggerFullscreenUrl: z.url().describe(\"Session full-screen debugger URL\"),\n debuggerUrl: z.url().describe(\"Session debugger URL\"),\n pages: z.array(browserPageSchema).describe(\"List of pages in the session\"),\n wsUrl: z.url().describe(\"WebSocket URL for the session\"),\n});\n\n// Zod schema for Browserbase session creation response\nexport const browserbaseSessionCreateResponseSchema = z.object({\n id: z.string().describe(\"Session ID\"),\n createdAt: z.iso.datetime().describe(\"Session creation timestamp\"),\n updatedAt: z.iso.datetime().describe(\"Session last update timestamp\"),\n projectId: z.string().describe(\"Project ID\"),\n startedAt: z.iso.datetime().describe(\"Session start timestamp\"),\n endedAt: z.iso.datetime().optional().describe(\"Session end timestamp\"),\n expiresAt: z.iso.datetime().describe(\"Session expiration timestamp\"),\n status: z.string().describe(\"Session status\"),\n proxyBytes: z.number().describe(\"Proxy bytes used\"),\n avgCpuUsage: z.number().describe(\"Average CPU usage\"),\n memoryUsage: z.number().describe(\"Memory usage\"),\n keepAlive: z.boolean().describe(\"Keep alive flag\"),\n contextId: z.string().describe(\"Context ID\"),\n region: z.string().describe(\"Region\"),\n userMetadata: z.record(z.string(), z.unknown()).describe(\"User metadata\"),\n connectUrl: z.string().describe(\"Connect URL\"),\n seleniumRemoteUrl: z.string().describe(\"Selenium remote URL\"),\n signingKey: z.string().describe(\"Signing key\"),\n});\n\n// TypeScript types derived from schemas\nexport type BrowserPage = z.infer<typeof browserPageSchema>;\nexport type BrowserbasePage = BrowserPage; // Alias for backwards compatibility\nexport type BrowserSessionInfo = z.infer<typeof browserSessionInfoSchema>;\nexport type BrowserbaseDebugResponse = z.infer<\n typeof browserbaseDebugResponseSchema\n>;\nexport type BrowserbaseSessionCreateResponse = z.infer<\n typeof browserbaseSessionCreateResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport { askUserQuestionInputSchema } from \"../schemas/ask-user-question\";\nimport { buildApiSchema } from \"./agent-api\";\nimport { StoredAgentConfigSchema } from \"./agent-config\";\n\n/**\n * Zod schemas for build API requests and responses\n * These schemas are used for both backend validation and frontend type inference\n */\n\n/**\n * Schema for get build params\n */\nexport const getBuildParamsSchema = z.object({\n buildId: z.guid(),\n});\n\n/**\n * Schema for list builds params\n */\nexport const listBuildsParamsSchema = z.object({\n copilotId: z.guid(),\n});\n\n/**\n * Schema for updating a build\n */\nexport const updateBuildBodySchema = z.object({\n config: z.record(z.string(), z.any()).describe(\"Build configuration object\"),\n handoverTargetIds: z\n .array(z.guid())\n .optional()\n .describe(\"Agent IDs that this agent can hand over work to\"),\n});\n\n/**\n * Schema for creating a new build\n */\nexport const createBuildBodySchema = z.object({\n copilot_id: z.guid().describe(\"Agent ID\"),\n name: z.string().describe(\"Build name\"),\n config: z\n .record(z.string(), z.any())\n .optional()\n .describe(\"Build configuration object\"),\n handoverTargetIds: z\n .array(z.guid())\n .optional()\n .describe(\"Agent IDs that this agent can hand over work to\"),\n source_build_id: z\n .guid()\n .optional()\n .describe(\"Build ID to copy integrations and case queue links from\"),\n});\n\n/**\n * TypeScript type for create build request body\n */\nexport type CreateBuildBody = z.infer<typeof createBuildBodySchema>;\n\n/**\n * Schema for build API response\n */\nexport const buildResponseSchema = z.object({\n build_id: z.string().describe(\"Build ID\"),\n name: z.string().describe(\"Build name\"),\n config: z\n .record(z.string(), z.any())\n .nullable()\n .describe(\"Build configuration\"),\n copilot_id: z.string().describe(\"Associated copilot ID\"),\n status: z.string().describe(\"Build status\"),\n created_at: z.coerce.date().describe(\"Creation timestamp\"),\n updated_at: z.coerce.date().nullable().describe(\"Last update timestamp\"),\n revision_number: z.number().nullable().describe(\"Revision number\"),\n parent_build_id: z.string().nullable().describe(\"Parent build ID\"),\n created_by: z.string().nullable().describe(\"User who created this build\"),\n created_by_name: z\n .string()\n .nullable()\n .optional()\n .describe(\"Display name of the user who created this build\"),\n});\n\n/**\n * Schema for list of builds response\n */\nexport const listBuildsResponseSchema = z.array(buildResponseSchema);\n\n/**\n * TypeScript types for build responses\n */\nexport type BuildResponse = z.infer<typeof buildResponseSchema>;\n\n/**\n * Wrapper for single-build responses (GET /v1/agents/:agent_id/builds/:build_id).\n */\nexport const buildResponseApiSchema = z.object({\n build: buildApiSchema,\n});\n\n/**\n * Paginated list of builds for GET /v1/agents/:agent_id/builds.\n */\nexport const buildsListApiSchema = z.object({\n builds: z.array(buildApiSchema),\n total: z.int(),\n limit: z.int(),\n offset: z.int(),\n});\n\n/**\n * Response for POST /v1/agents/:agent_id/builds.\n */\nexport const createBuildResponseApiSchema = z.object({\n build: buildApiSchema,\n agent: z.object({\n id: z.guid(),\n }),\n});\n\nexport type BuildResponseApi = z.infer<typeof buildResponseApiSchema>;\nexport type BuildsListApi = z.infer<typeof buildsListApiSchema>;\nexport type CreateBuildResponseApi = z.infer<\n typeof createBuildResponseApiSchema\n>;\n\nexport const builderRunGenerateResponseSchema = z.object({\n status: z.literal(\"generating\"),\n builderRunId: z.string(),\n buildId: z.string(),\n});\n\nexport type BuilderRunGenerateResponse = z.infer<\n typeof builderRunGenerateResponseSchema\n>;\n\nconst BUILDER_RUN_STATUSES = [\n \"not_started\",\n \"running\",\n \"completed\",\n \"failed\",\n \"cancelled\",\n \"waiting_for_input\",\n \"waiting_for_approve\",\n] as const;\n\nexport type BuilderRunStatusValue = (typeof BUILDER_RUN_STATUSES)[number];\n\nexport const builderRunStatusSchema = z.object({\n id: z.string(),\n status: z.enum(BUILDER_RUN_STATUSES),\n build_id: z.string(),\n started_at: z.string().nullable(),\n completed_at: z.string().nullable(),\n checkpoint_config: StoredAgentConfigSchema.nullable(),\n pending_user_questions: askUserQuestionInputSchema.nullable(),\n schedule_suggested: z.boolean().optional(),\n});\n\nexport type BuilderRunStatus = z.infer<typeof builderRunStatusSchema>;\n", "import { z } from \"zod\";\n\n/**\n * The two terminal decisions an approver can submit. Anything else is rejected\n * by both the route handler and the DB CHECK constraint on\n * `case_approval_request.decision`.\n */\nexport const CASE_APPROVAL_DECISION = {\n APPROVED: \"approved\",\n REJECTED: \"rejected\",\n} as const;\n\nexport type CaseApprovalDecision =\n (typeof CASE_APPROVAL_DECISION)[keyof typeof CASE_APPROVAL_DECISION];\n\nexport const caseApprovalDecisionSchema = z.enum([\n CASE_APPROVAL_DECISION.APPROVED,\n CASE_APPROVAL_DECISION.REJECTED,\n]);\n\n/**\n * Public-safe shape for an open or recently-resolved case approval request.\n * Mirrors `case_approval_request` 1:1 \u2014 including `cancellation_reason`,\n * which is bounded server-side and only set on cancellation paths.\n */\nexport const caseApprovalRequestSchema = z.object({\n id: z.string().uuid(),\n case_queue_item_id: z.string().uuid(),\n agent_run_id: z.string().uuid(),\n team_id: z.string().uuid(),\n approver_user_id: z.string().uuid(),\n title: z.string(),\n prompt: z.string(),\n created_at: z.string(),\n resolved_at: z.string().nullable(),\n resolved_by_user_id: z.string().uuid().nullable(),\n decision: caseApprovalDecisionSchema.nullable(),\n cancelled_at: z.string().nullable(),\n cancellation_reason: z.string().nullable(),\n});\n\nexport type CaseApprovalRequest = z.infer<typeof caseApprovalRequestSchema>;\n\n/**\n * One row in the case-detail Approvals section: covers both unresolved and\n * resolved/cancelled requests. The approver and resolver profiles are joined\n * server-side so the UI can render names without a follow-up fetch.\n */\nexport const caseApprovalListItemSchema = z.object({\n id: z.string().uuid(),\n agent_run_id: z.string().uuid(),\n title: z.string(),\n prompt: z.string(),\n created_at: z.string(),\n\n approver_user_id: z.string().uuid(),\n approver_name: z.string().nullable(),\n approver_email: z.string().nullable(),\n\n decision: caseApprovalDecisionSchema.nullable(),\n resolved_at: z.string().nullable(),\n resolved_by_user_id: z.string().uuid().nullable(),\n resolved_by_name: z.string().nullable(),\n resolved_by_email: z.string().nullable(),\n\n cancelled_at: z.string().nullable(),\n cancellation_reason: z.string().nullable(),\n});\n\nexport type CaseApprovalListItem = z.infer<typeof caseApprovalListItemSchema>;\n\nexport const createCaseApprovalRequestBodySchema = z.object({\n agentRunId: z.string().uuid(),\n approverUserId: z.string().uuid(),\n title: z.string().trim().min(1).max(200),\n prompt: z.string().trim().min(1).max(2000),\n});\n\nexport type CreateCaseApprovalRequestBody = z.infer<\n typeof createCaseApprovalRequestBodySchema\n>;\n\nexport const createCaseApprovalRequestResponseSchema = z.object({\n id: z.string().uuid(),\n created_at: z.string(),\n});\n\nexport type CreateCaseApprovalRequestResponse = z.infer<\n typeof createCaseApprovalRequestResponseSchema\n>;\n\nexport const respondCaseApprovalRequestBodySchema = z.object({\n decision: caseApprovalDecisionSchema,\n});\n\nexport type RespondCaseApprovalRequestBody = z.infer<\n typeof respondCaseApprovalRequestBodySchema\n>;\n\nexport const respondCaseApprovalRequestResponseSchema = z.object({\n id: z.string().uuid(),\n resolved_at: z.string(),\n resolved_by_user_id: z.string().uuid(),\n decision: caseApprovalDecisionSchema,\n});\n\nexport type RespondCaseApprovalRequestResponse = z.infer<\n typeof respondCaseApprovalRequestResponseSchema\n>;\n\n/**\n * Tool input/output for the agent-callable `request_case_approval`. The agent\n * picks `approverUserId` from the candidate set surfaced in the system\n * prompt; the backend rejects anything outside the candidate set.\n */\nexport const requestCaseApprovalToolInputSchema = z.object({\n approverUserId: z.string().uuid(),\n title: z.string().trim().min(1).max(200),\n prompt: z.string().trim().min(1).max(2000),\n});\n\nexport type RequestCaseApprovalToolInput = z.infer<\n typeof requestCaseApprovalToolInputSchema\n>;\n\nexport const requestCaseApprovalToolOutputSchema = z.object({\n status: caseApprovalDecisionSchema,\n resolvedByUserId: z.string().uuid(),\n});\n\nexport type RequestCaseApprovalToolOutput = z.infer<\n typeof requestCaseApprovalToolOutputSchema\n>;\n", "import { z } from \"zod\";\n\nexport const filterValueSchema = z.object({\n value: z.string().min(1),\n name: z.string().min(1),\n});\n\nexport type FilterValue = z.infer<typeof filterValueSchema>;\n\nexport const filterCategorySchema = z.object({\n key: z.string(),\n name: z.string().min(1),\n selectionMode: z.enum([\"single\", \"multi\"]),\n values: z.array(filterValueSchema),\n});\n\nexport type FilterCategory = z.infer<typeof filterCategorySchema>;\n\nexport const caseFiltersResponseSchema = z.object({\n filters: z.array(filterCategorySchema),\n});\n\nexport type CaseFiltersResponse = z.infer<typeof caseFiltersResponseSchema>;\n", "import { z } from \"zod\";\n\nexport const caseQueueFolderResponseSchema = z.object({\n id: z.string(),\n name: z.string(),\n team_id: z.string(),\n parent_folder_id: z.string().nullable(),\n created_at: z.string(),\n updated_at: z.string(),\n});\n\nexport const caseQueueFoldersListResponseSchema = z.object({\n folders: z.array(caseQueueFolderResponseSchema),\n});\n\nexport const createCaseQueueFolderRequestSchema = z.object({\n name: z.string().min(1).max(100),\n parent_folder_id: z.guid().nullable().optional(),\n});\n\nexport const updateCaseQueueFolderRequestSchema = z.object({\n name: z.string().min(1).max(100).optional(),\n parent_folder_id: z.guid().nullable().optional(),\n});\n\nexport const moveQueuesToFolderRequestSchema = z.object({\n queue_ids: z.array(z.guid()).min(1),\n folder_id: z.guid().nullable(),\n});\n\nexport type CaseQueueFolderResponse = z.infer<\n typeof caseQueueFolderResponseSchema\n>;\nexport type CaseQueueFoldersListResponse = z.infer<\n typeof caseQueueFoldersListResponseSchema\n>;\nexport type CreateCaseQueueFolderRequest = z.infer<\n typeof createCaseQueueFolderRequestSchema\n>;\nexport type UpdateCaseQueueFolderRequest = z.infer<\n typeof updateCaseQueueFolderRequestSchema\n>;\nexport type MoveQueuesToFolderRequest = z.infer<\n typeof moveQueuesToFolderRequestSchema\n>;\n", "import { z } from \"zod\";\n\nexport const caseQueueLabelSchema = z.object({\n id: z.guid(),\n key: z.string(), // Empty string key means a simple tag (value-only); non-empty key creates a key-value categorization\n value: z.string().min(1),\n color_hue: z.int().min(0).max(360),\n});\n\nexport type CaseQueueLabel = z.infer<typeof caseQueueLabelSchema>;\n\nexport const caseLabelsListResponseSchema = z.object({\n labels: z.array(caseQueueLabelSchema),\n});\n\nexport type CaseLabelsListResponse = z.infer<\n typeof caseLabelsListResponseSchema\n>;\n\nexport const caseLabelAssignInputSchema = z.object({\n labels: z\n .array(\n z.object({\n key: z.string().optional().default(\"\"),\n value: z.string().min(1),\n })\n )\n .min(1)\n .max(50),\n});\n\nexport type CaseLabelAssignInput = z.infer<typeof caseLabelAssignInputSchema>;\n\nexport const caseLabelAssignResponseSchema = z.object({\n labels: z.array(caseQueueLabelSchema),\n});\n\nexport type CaseLabelAssignResponse = z.infer<\n typeof caseLabelAssignResponseSchema\n>;\n\nexport const caseLabelUpdateInputSchema = z.object({\n // key is a partial-update field: omit to leave the existing key unchanged.\n // Do NOT add `.default(\"\")` \u2014 a missing key must not silently relocate the\n // label into the empty-key (\"Labels\") bucket when the caller only wants to\n // change color or value.\n key: z.string().optional(),\n value: z.string().min(1),\n color_hue: z.int().min(0).max(360).optional(),\n});\n\nexport type CaseLabelRenameInput = z.infer<typeof caseLabelUpdateInputSchema>;\n\nexport const caseLabelUpdateResponseSchema = z.object({\n label: caseQueueLabelSchema,\n});\n\nexport type CaseLabelRenameResponse = z.infer<\n typeof caseLabelUpdateResponseSchema\n>;\n\nexport const caseLabelUnlinkInputSchema = z.object({\n label_ids: z.array(z.guid()).min(1),\n});\n\nexport type CaseLabelUnlinkInput = z.infer<typeof caseLabelUnlinkInputSchema>;\n\nexport const caseLabelUnlinkResponseSchema = z.object({\n success: z.boolean(),\n});\n\nexport type CaseLabelUnlinkResponse = z.infer<\n typeof caseLabelUnlinkResponseSchema\n>;\n\nexport const caseLabelCreateInputSchema = z.object({\n key: z.string().optional().default(\"\"),\n value: z.string().min(1),\n color_hue: z.int().min(0).max(360).optional(),\n});\n\nexport type CaseLabelCreateInput = z.infer<typeof caseLabelCreateInputSchema>;\n\nexport const caseLabelCreateResponseSchema = z.object({\n label: caseQueueLabelSchema.extend({\n case_count: z.int().min(0),\n }),\n});\n\nexport type CaseLabelCreateResponse = z.infer<\n typeof caseLabelCreateResponseSchema\n>;\n\nexport const caseQueueLabelWithCountSchema = caseQueueLabelSchema.extend({\n case_count: z.int().min(0),\n});\n\nexport type CaseQueueLabelWithCount = z.infer<\n typeof caseQueueLabelWithCountSchema\n>;\n\nexport const caseLabelsWithCountsListResponseSchema = z.object({\n labels: z.array(caseQueueLabelWithCountSchema),\n});\n\nexport type CaseLabelsWithCountsListResponse = z.infer<\n typeof caseLabelsWithCountsListResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport { conflictingAgentSchema } from \"./agent-api\";\n\nexport const caseTriggerApiSchema = z.object({\n id: z.string(),\n agent_id: z.string(),\n case_queue_id: z.string(),\n case_queue_name: z.string(),\n user_id: z.string(),\n enabled: z.boolean(),\n concurrency: z.int().positive().nullable(),\n created_at: z.string(),\n updated_at: z.string(),\n creator_display_name: z.string().nullable(),\n can_disable: z.boolean(),\n has_conflict: z.boolean(),\n conflicting_agents: z.array(conflictingAgentSchema),\n});\n\nexport type CaseTriggerApi = z.infer<typeof caseTriggerApiSchema>;\n\nexport const caseTriggerResponseSchema = z.object({\n case_trigger: caseTriggerApiSchema,\n});\n\nexport type CaseTriggerResponse = z.infer<typeof caseTriggerResponseSchema>;\n\nexport const caseTriggersListResponseSchema = z.object({\n case_triggers: z.array(caseTriggerApiSchema),\n});\n\nexport type CaseTriggersListResponse = z.infer<\n typeof caseTriggersListResponseSchema\n>;\n\nexport const deleteCaseTriggerResponseSchema = z.object({\n success: z.literal(true),\n});\n\nexport type DeleteCaseTriggerResponse = z.infer<\n typeof deleteCaseTriggerResponseSchema\n>;\n\nconst integrationConfigMinSchema = z.object({\n id: z.string(),\n integration_id: z.guid().nullable(),\n integration_type: z.string(),\n});\n\nexport const integrationConfigsResponseSchema = z.object({\n integrations: z.array(integrationConfigMinSchema),\n});\n\nconst caseQueueMinSchema = z.object({\n id: z.string(),\n name: z.string(),\n});\n\nexport const caseQueuesForSlotResponseSchema = z.object({\n queues: z.array(caseQueueMinSchema),\n});\n\nexport type IntegrationConfigsResponse = z.infer<\n typeof integrationConfigsResponseSchema\n>;\n\nexport type CaseQueuesForSlotResponse = z.infer<\n typeof caseQueuesForSlotResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport { agentMessageSchema } from \"../schemas/automation-message\";\nimport { evalSummarySchema } from \"../schemas/run-evaluation\";\nimport { agentRunStatusSchema } from \"./agent-run\";\nimport { caseApprovalListItemSchema } from \"./case-approval\";\nimport { caseQueueLabelSchema } from \"./case-queue-labels\";\n\nexport const caseQueueItemSchema = z.object({\n id: z.guid(),\n queue_id: z.guid(),\n title: z.string(),\n data: z.string(),\n status: z.enum([\"pending\", \"claimed\", \"completed\", \"failed\"]),\n claimed_at: z.string().nullable(),\n claimed_by_run_id: z.string().nullable(),\n completed_at: z.string().nullable(),\n /** When the case is scheduled to be re-handled (null if not postponed) */\n postponed_to: z.string().nullable(),\n created_at: z.string(),\n updated_at: z.string(),\n created_by_user_id: z.guid().nullable(),\n created_by_user_name: z.string().nullable(),\n created_by_user_email: z.string().nullable(),\n /** Status of the associated agent run (running, waiting, etc.) - null if no active run */\n agent_run_status: z.string().nullable(),\n /** User ID of the owner of the active agent run - null if no active run */\n agent_run_user_id: z.guid().nullable(),\n /** ID of the pending human request for cases waiting for input */\n pending_human_request_id: z.guid().nullable(),\n /** ID of the open case_approval_request bound to this case, if any. Used to derive the `awaiting_approval` UI state. */\n pending_approval_request_id: z.guid().nullable(),\n /** User ID of the approver named on the open `case_approval_request`. Used to switch the badge to \"Awaiting your approval\" for the named approver. */\n pending_approval_approver_user_id: z.guid().nullable(),\n /** Number of resolved approval requests on this case with `decision = 'approved'`. */\n approval_approved_count: z.int().nonnegative(),\n /** Number of resolved approval requests on this case with `decision = 'rejected'`. */\n approval_rejected_count: z.int().nonnegative(),\n /** Snippet from the data field showing search match context. Only present when search matches data. */\n search_match_data_snippet: z\n .object({\n before: z.string(),\n match: z.string(),\n after: z.string(),\n })\n .optional(),\n labels: z.array(caseQueueLabelSchema),\n});\n\nexport type CaseQueueItem = z.infer<typeof caseQueueItemSchema>;\n\nexport const caseQueueItemEventSchema = z.object({\n id: z.guid(),\n case_queue_item_id: z.guid(),\n agent_run_id: z.guid().nullable(),\n human_request_id: z.guid().nullable(),\n type: z.string(),\n created_at: z.string(),\n agent_id: z.guid().nullable(),\n agent_name: z.string().nullable(),\n /**\n * Owner of the agent run referenced by this event (joined from\n * `agent_run.user_id`). The frontend mirrors the backend\n * `assertCanAccessRun` gate against this id + the viewer's team role to\n * decide whether the row should expose a click affordance.\n */\n user_id: z.guid().nullable(),\n user_name: z.string().nullable(),\n user_email: z.string().nullable(),\n human_request_title: z.string().nullable(),\n});\n\nexport type CaseQueueItemEvent = z.infer<typeof caseQueueItemEventSchema>;\n\nexport const casesListResponseSchema = z.object({\n cases: z.array(caseQueueItemSchema),\n total: z.number(),\n limit: z.int(),\n offset: z.int(),\n});\n\nexport type CasesListResponse = z.infer<typeof casesListResponseSchema>;\n\nexport const caseCreateInputSchema = z.object({\n title: z\n .string()\n .min(1)\n .max(500)\n .describe(\n \"Short title for the case (max 500 characters). Put long context in `data`.\"\n ),\n data: z\n .string()\n .optional()\n .describe(\n \"Additional data for the case. Free-form text or JSON; Assignments receive this on claim.\"\n ),\n labels: z\n .array(\n z.object({\n key: z\n .string()\n .optional()\n .default(\"\")\n .describe(\"Label key (omit for a simple tag).\"),\n value: z.string().min(1).describe(\"Label value (required).\"),\n })\n )\n .max(50)\n .optional()\n .describe(\n \"Optional labels to assign to the case at creation. Labels are created on the queue if they don't already exist.\"\n ),\n});\n\nexport type CaseCreateInput = z.infer<typeof caseCreateInputSchema>;\n\nexport const caseCreateRequestSchema = z\n .object({\n case: caseCreateInputSchema.optional(),\n cases: z.array(caseCreateInputSchema).min(1).max(100).optional(),\n })\n .superRefine((val, ctx) => {\n const hasCase = val.case !== undefined;\n const hasCases = val.cases !== undefined;\n if (hasCase && hasCases) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Provide either `case` or `cases`, not both.\",\n });\n return;\n }\n\n if (!hasCase && !hasCases) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Provide exactly one of `case` or `cases`.\",\n });\n }\n });\n\nexport type CaseCreateRequest = z.infer<typeof caseCreateRequestSchema>;\n\nexport const caseCreateResponseSchema = z.object({\n added_cases: z.array(caseQueueItemSchema),\n});\n\nexport type CaseCreateResponse = z.infer<typeof caseCreateResponseSchema>;\n\nexport const casesStatsSchema = z.object({\n total: z.number(),\n pending: z.number(),\n claimed: z.number(),\n /** Count of claimed cases waiting for human input (run status = waiting) */\n waiting: z.number(),\n /** Count of pending cases that are postponed for later */\n postponed: z.number(),\n completed: z.number(),\n failed: z.number(),\n});\n\nexport const casesStatsResponseSchema = z.object({\n stats: casesStatsSchema,\n});\n\nexport type CasesStatsResponse = z.infer<typeof casesStatsResponseSchema>;\n\nexport const caseDetailResponseSchema = z.object({\n case: caseQueueItemSchema,\n events: z.array(caseQueueItemEventSchema),\n /**\n * Every approval request ever created for this case \u2014 pending, resolved,\n * and cancelled \u2014 ordered by `created_at` ascending. The case-detail\n * Approvals section renders these inline; the unresolved row (if any) is\n * the only one with response affordances and matches\n * `case.pending_approval_request_id`.\n */\n case_approval_requests: z.array(caseApprovalListItemSchema),\n});\n\nexport type CaseDetailResponse = z.infer<typeof caseDetailResponseSchema>;\n\n/**\n * Summary of one Job (agent run) associated with a case, used by the\n * Activity timeline on the case detail page.\n *\n * `claimed_at` is the timestamp of the `claimed` case event that started\n * this run on this case \u2014 the timeline uses it as the Job card's anchor\n * so a single run that claims/releases multiple times renders as multiple\n * cards in correct chronological order.\n */\nexport const caseJobSummarySchema = z.object({\n id: z.string().uuid(),\n case_queue_item_id: z.string().uuid(),\n agent_id: z.string().uuid(),\n agent_name: z.string(),\n status: agentRunStatusSchema,\n source: z.string().nullable(),\n created_at: z.string(),\n started_at: z.string().nullable(),\n completed_at: z.string().nullable(),\n claimed_at: z.string(),\n has_pending_human_request: z.boolean(),\n pending_human_request_title: z.string().nullable(),\n evaluation: evalSummarySchema,\n /**\n * Owner of the agent run (from `agent_run.user_id`). The frontend mirrors\n * the backend `assertCanAccessRun` gate against this id + the viewer's\n * team role to decide whether the card is interactive (live messages,\n * HITL affordances, drawer link).\n */\n user_id: z.guid().nullable(),\n /**\n * Display name of the user who triggered the run, joined from `profiles`.\n * Falls back to `user_email` for the in-card user pill when null.\n */\n user_name: z.string().nullable(),\n user_email: z.string().nullable(),\n});\n\nexport type CaseJobSummary = z.infer<typeof caseJobSummarySchema>;\n\nexport const caseJobsResponseSchema = z.object({\n runs: z.array(caseJobSummarySchema),\n});\n\nexport type CaseJobsResponse = z.infer<typeof caseJobsResponseSchema>;\n\n/**\n * Latest qualifying messages (assistant text + tool calls) for a running\n * Job, streamed into the Activity timeline card body. Newest last so the\n * card reads top-to-bottom.\n */\nexport const caseJobRecentMessagesResponseSchema = z.object({\n messages: z.array(agentMessageSchema),\n});\n\nexport type CaseJobRecentMessagesResponse = z.infer<\n typeof caseJobRecentMessagesResponseSchema\n>;\n\nexport const adjacentCasesResponseSchema = z.object({\n previousId: z.guid().nullable(),\n nextId: z.guid().nullable(),\n position: z.number(),\n total: z.number(),\n});\n\nexport type AdjacentCasesResponse = z.infer<typeof adjacentCasesResponseSchema>;\n\nexport type CaseStatus = \"pending\" | \"claimed\" | \"completed\" | \"failed\";\n\nexport const caseDeleteResponseSchema = z.object({\n success: z.boolean(),\n interruptedRunIds: z.array(z.guid()),\n});\n\nexport type CaseDeleteResponse = z.infer<typeof caseDeleteResponseSchema>;\n\nexport const caseBulkDeleteResponseSchema = z.object({\n deletedCount: z.number(),\n interruptedRunIds: z.array(z.guid()),\n});\n\nexport const caseBulkRetryResponseSchema = z.object({\n retriedCount: z.number(),\n skippedCount: z.number(),\n});\n\nexport type CaseBulkRetryResponse = z.infer<typeof caseBulkRetryResponseSchema>;\n\nexport const caseBulkDelegateResponseSchema = z.object({\n delegatedCount: z.number(),\n skippedCount: z.number(),\n});\n\nexport type CaseBulkDelegateResponse = z.infer<\n typeof caseBulkDelegateResponseSchema\n>;\n\nexport const caseBulkStatusUpdateResponseSchema = z.object({\n updatedCount: z.number(),\n skippedCount: z.number(),\n interruptedRunIds: z.array(z.guid()),\n});\n\nexport type CaseBulkStatusUpdateResponse = z.infer<\n typeof caseBulkStatusUpdateResponseSchema\n>;\n\nexport const deleteQueueResponseSchema = z.object({\n success: z.boolean(),\n deleted_case_count: z.number(),\n interrupted_run_ids: z.array(z.guid()),\n});\n\nexport type DeleteQueueResponse = z.infer<typeof deleteQueueResponseSchema>;\n\nexport type CaseBulkDeleteResponse = z.infer<\n typeof caseBulkDeleteResponseSchema\n>;\n\nexport const caseClearQueueResponseSchema = z.object({\n success: z.boolean(),\n deletedCount: z.number(),\n interruptedRunIds: z.array(z.guid()),\n});\n\nexport type CaseClearQueueResponse = z.infer<\n typeof caseClearQueueResponseSchema\n>;\n\nexport const caseQueueSchema = z.object({\n id: z.guid(),\n name: z.string(),\n description: z.string().nullable(),\n folder_id: z.guid().nullable(),\n created_at: z.string(),\n /**\n * True when at least one case in this queue has ever had a\n * case_approval_request (pending, resolved, or cancelled). The frontend\n * uses this to relabel the \"Needs input\" filter to \"Needs input/approval\"\n * and to show the per-case approvals column.\n */\n has_approvals: z.boolean(),\n});\n\nexport type CaseQueue = z.infer<typeof caseQueueSchema>;\n\nexport const caseQueuesResponseSchema = z.object({\n queues: z.array(caseQueueSchema),\n total: z.number(),\n limit: z.number(),\n offset: z.number(),\n});\n\nexport type CaseQueuesResponse = z.infer<typeof caseQueuesResponseSchema>;\n\nexport const caseGetQueueResponseSchema = z.object({\n queue: caseQueueSchema,\n});\n\nexport type CaseGetQueueResponse = z.infer<typeof caseGetQueueResponseSchema>;\n\nexport const caseCreateQueueResponseSchema = z.object({\n queue: caseQueueSchema,\n});\n\nexport const caseUpdateQueueResponseSchema = z.object({\n queue: caseQueueSchema,\n});\n\nexport type CaseCreateQueueResponse = z.infer<\n typeof caseCreateQueueResponseSchema\n>;\n\nexport const caseQueueAgentProblemSchema = z.enum([\n \"multiple_triggers\",\n \"producer_consumer_mix\",\n]);\n\nexport type CaseQueueAgentProblem = z.infer<typeof caseQueueAgentProblemSchema>;\n\nexport const queueAgentProducerSchema = z.object({\n agent_id: z.guid(),\n agent_name: z.string(),\n case_trigger_enabled: z.boolean(),\n case_trigger_queue_name: z.string().nullable(),\n problems: z.array(caseQueueAgentProblemSchema),\n});\n\nexport const queueAgentConsumerSchema = z.object({\n agent_id: z.guid(),\n agent_name: z.string(),\n case_trigger_enabled: z.boolean(),\n is_handover_target: z.boolean(),\n problems: z.array(caseQueueAgentProblemSchema),\n});\n\nexport const queueAgentsResponseSchema = z.object({\n queue_name: z.string(),\n producers: z.array(queueAgentProducerSchema),\n consumers: z.array(queueAgentConsumerSchema),\n});\n\nexport type QueueAgentProducer = z.infer<typeof queueAgentProducerSchema>;\nexport type QueueAgentConsumer = z.infer<typeof queueAgentConsumerSchema>;\nexport type QueueAgentsResponse = z.infer<typeof queueAgentsResponseSchema>;\n\nexport const exportCasesResponseSchema = z.object({\n version: z.number(),\n queue_name: z.string(),\n exported_at: z.string(),\n cases: z.array(\n z.object({\n title: z.string(),\n data: z.string().optional(),\n })\n ),\n});\n\nexport type ExportCasesResponse = z.infer<typeof exportCasesResponseSchema>;\n\nexport const importCasesResponseSchema = z.object({\n imported_count: z.number(),\n});\n\nexport type ImportCasesResponse = z.infer<typeof importCasesResponseSchema>;\n\nexport const batchQueueStatsResponseSchema = z.object({\n stats: z.record(z.guid(), casesStatsSchema),\n});\n\nexport type BatchQueueStatsResponse = z.infer<\n typeof batchQueueStatsResponseSchema\n>;\n\nexport const batchQueueAgentsResponseSchema = z.object({\n agents: z.record(\n z.guid(),\n z.object({\n producers: z.array(queueAgentProducerSchema),\n consumers: z.array(queueAgentConsumerSchema),\n })\n ),\n});\n\nexport type BatchQueueAgentsResponse = z.infer<\n typeof batchQueueAgentsResponseSchema\n>;\n", "import { z } from \"zod\";\n\nimport { conversationMessageSchema } from \"./clarity\";\n\n// === Clarity Overview Status ===\n\nexport const CLARITY_OVERVIEW_STATUSES = [\n \"draft\",\n \"collecting\",\n \"generating\",\n \"review\",\n \"complete\",\n \"generation_failed\",\n] as const;\n\nexport type ClarityOverviewStatus = (typeof CLARITY_OVERVIEW_STATUSES)[number];\nexport const clarityOverviewStatusSchema = z.enum(CLARITY_OVERVIEW_STATUSES);\n\n// === Capture Status & Type ===\n\nexport const CLARITY_OVERVIEW_CAPTURE_STATUSES = [\n \"pending\",\n \"recording\",\n \"processing\",\n \"complete\",\n \"failed\",\n] as const;\n\nexport type ClarityOverviewCaptureStatus =\n (typeof CLARITY_OVERVIEW_CAPTURE_STATUSES)[number];\n\nexport const CLARITY_OVERVIEW_CAPTURE_TYPES = [\n \"video\",\n \"interview\",\n \"document\",\n \"screenshare\",\n] as const;\n\nexport type ClarityOverviewCaptureType =\n (typeof CLARITY_OVERVIEW_CAPTURE_TYPES)[number];\n\n// === Capture Schema ===\n\nexport const clarityOverviewCaptureSchema = z.object({\n id: z.guid(),\n overviewId: z.guid(),\n userId: z.guid(),\n userName: z.string().optional(),\n type: z.enum(CLARITY_OVERVIEW_CAPTURE_TYPES),\n videoUrl: z.string().nullable(),\n videoTranscript: z.string().nullable(),\n transcript: z.array(conversationMessageSchema).nullable(),\n status: z.enum(CLARITY_OVERVIEW_CAPTURE_STATUSES),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n});\n\nexport type ClarityOverviewCapture = z.infer<\n typeof clarityOverviewCaptureSchema\n>;\n\n// === Department Overview Sections ===\n\nconst OverviewKpi = z.object({\n id: z.guid(),\n name: z.string(),\n value: z.string(),\n description: z.string(),\n});\n\nconst OverviewHeadcount = z.object({\n approximate: z.int().nonnegative(),\n notes: z.string().optional(),\n});\n\nconst OverviewTeamMember = z.object({\n id: z.guid(),\n name: z.string(),\n role: z.string(),\n});\n\nconst OverviewTeam = z.object({\n id: z.guid(),\n name: z.string(),\n leadId: z.guid().nullable(),\n description: z.string(),\n memberCount: z.int().nonnegative().optional(),\n people: z.array(OverviewTeamMember),\n});\n\nconst OverviewInsight = z.object({\n id: z.guid(),\n title: z.string(),\n description: z.string(),\n});\n\nconst OverviewHelpNeeded = z.object({\n id: z.guid(),\n title: z.string(),\n description: z.string(),\n fromWhom: z.string(),\n});\n\nconst DepartmentOverview = z.object({\n mission: z.string().nullable(),\n kpis: z.array(OverviewKpi),\n headcount: OverviewHeadcount.nullable(),\n teams: z.array(OverviewTeam),\n worksWell: z.array(OverviewInsight),\n doesNotWorkWell: z.array(OverviewInsight),\n needsHelp: z.array(OverviewHelpNeeded),\n});\n\n// === Enums ===\n\nconst DocumentationStatus = z.enum([\"documented\", \"draft\", \"not_started\"]);\n\nconst VulnerabilitySeverity = z.enum([\"warning\", \"critical\"]);\n\n/**\n * Tags applied to people within a process to indicate their\n * accountability type. Rendered as colored badges in the UI.\n * A person with no tags is a regular participant.\n */\nconst AccountabilityTag = z.enum([\n \"owner\", // Decision-maker, shown with \"owner\" badge\n \"spof\", // Single point of failure \u2014 highlighted as risk\n \"external\", // Outside the org (e.g. Supplier)\n \"notified\", // Receives updates but doesn't act (e.g. Supply Chain)\n]);\n\n// === Systems ===\n\nconst SystemRef = z.object({\n /** Stable identifier for the system, used for deduplication across processes */\n id: z.string(),\n /** Display name as it appears in the UI: \"Product Pantry\", \"Rohlik Admin\", \"Google Sheets\" */\n name: z.string(),\n /** URL to the system's icon/logo. Null if we don't have one \u2014 FE shows a generic fallback */\n iconUrl: z.url().nullable(),\n});\n\n// === People & Roles ===\n\nconst PersonRole = z.object({\n id: z.guid(),\n /** Person's display name: \"Tereza\", \"Kristyna\" */\n name: z.string(),\n /**\n * Their role title within this process, not their org-wide job title.\n * e.g. \"Listing Specialist\", \"Senior Category Manager\"\n */\n role: z.string(),\n /**\n * Accountability tags for this person within THIS process.\n * Same person can be \"owner\" in one process and have no tags in another.\n */\n tags: z.array(AccountabilityTag).default([]),\n /**\n * Full-time equivalent headcount allocated to this role.\n * Optional \u2014 only set when the capture interview surfaced it.\n * e.g. 2.25 FTE for a Listing Specialist team of 3 part-timers.\n */\n fte: z.number().positive().optional(),\n});\n\n// === Vulnerabilities (rendered as \"risks\" on overview cards) ===\n\nconst Vulnerability = z.object({\n id: z.guid(),\n /** Warning = operational concern, Critical = structural/blocking risk */\n severity: VulnerabilitySeverity,\n /**\n * Human-readable description surfaced from the interview.\n * e.g. \"Tereza alone covers fresh listing\"\n * e.g. \"75-95% of obvious approvals still needs human\"\n */\n description: z.string(),\n /**\n * IDs of people directly tied to this vulnerability.\n * Enables FE to highlight affected people in the detail view.\n * e.g. SPOF vulnerability \u2192 [terezaId]\n */\n affectedPersonIds: z.array(z.string()).optional(),\n});\n\n// === Friction Signals ===\n\nconst FrictionSignal = z.object({\n id: z.guid(),\n /**\n * Operational pain point captured during interview.\n * e.g. \"40 unresolved bugs, periodic outages\"\n * These feed into the maturity score (future iteration) as penalties.\n */\n description: z.string(),\n /** Systems where this friction manifests \u2014 used for cross-referencing */\n relatedSystemIds: z.array(z.string()).optional(),\n});\n\n// === Process (full detail \u2014 returned by GET /processes/:id) ===\n\nconst Process = z.object({\n id: z.guid(),\n /** Process name as displayed in card headers: \"Product Listing\", \"Price Proposals\" */\n name: z.string(),\n /**\n * Tracks where this process is in the Clarity documentation pipeline.\n * - \"documented\": fully captured and reviewed\n * - \"draft\": interview done, output not yet validated\n * - \"not_started\": identified but not yet interviewed\n */\n documentationStatus: DocumentationStatus,\n clarityProcessId: z.guid().nullable().optional(),\n\n // --- Content ---\n\n /**\n * Short summary for overview cards (1-2 sentences).\n * e.g. \"End-to-end workflow of listing new products into the catalog...\"\n */\n summary: z.string(),\n /**\n * Rich description shown in the detail panel.\n * May include emphasized metrics (FE handles bold rendering).\n * e.g. \"Listing **660\u2013880 new SKUs every month** from the commercial decision...\"\n */\n description: z.string(),\n /**\n * Authored narrative describing the system flow / toolchain.\n * Comes from the Duvo capture output, not computed.\n * e.g. \"Product Pantry portal \u2192 Rohlik Admin backend \u2192 ChatGPT for description rewrites \u2192 ...\"\n */\n systemNarrative: z.string().optional(),\n /**\n * Authored narrative describing who does what and how accountability flows.\n * e.g. \"Senior CMs decide. Junior CMs configure. The Listing Specialist team finalizes everything.\"\n */\n accountabilityNarrative: z.string().optional(),\n /**\n * Free-text frequency because the real-world cadences are too varied to enumerate.\n * e.g. \"Continuous\", \"Weekly + monthly slowmover\", \"10\u201315 per CM / month\", \"Ad-hoc, no fixed cadence\"\n */\n frequency: z.string(),\n\n // --- Relations ---\n\n people: z.array(PersonRole),\n systems: z.array(SystemRef),\n vulnerabilities: z.array(Vulnerability),\n frictionSignals: z.array(FrictionSignal),\n});\n\n// === API Responses ===\n\n/**\n * GET /api/clarity/overview\n *\n * Returns everything needed to render the overview dashboard:\n * - Aggregate KPIs (processCount, singlePointOfFailureCount) computed on the fly\n * - Slim process cards with just enough data to render the grid\n *\n * The overview intentionally avoids sending full descriptions,\n * narratives, friction signals, and maturity breakdowns \u2014 those\n * are fetched on-demand via the detail endpoint.\n */\nconst ProcessOverviewItem = Process.extend({\n /**\n * Pre-computed count so FE doesn't need to re-count the people array.\n * Displayed as \"5 involved\" on overview cards.\n */\n peopleCount: z.int(),\n\n /**\n * First N systems (typically 4) to render the icon row.\n */\n systemPreviews: z.array(SystemRef),\n\n /**\n * How many systems beyond systemPreviews exist.\n * Rendered as \"+3\" badge after the icon row. 0 means all systems fit.\n */\n systemOverflowCount: z.int().default(0),\n});\n\nconst ClarityOverviewResponse = z.object({\n /** Explicit count for the \"Processes Captured\" KPI tile */\n processCount: z.int(),\n /**\n * Count of processes with at least one SPOF vulnerability.\n * Powers the \"Single point of failure\" KPI tile.\n */\n singlePointOfFailureCount: z.int(),\n processes: z.array(ProcessOverviewItem),\n\n // Department-level overview sections\n mission: z.string().nullable(),\n kpis: z.array(OverviewKpi),\n headcount: OverviewHeadcount.nullable(),\n teams: z.array(OverviewTeam),\n worksWell: z.array(OverviewInsight),\n doesNotWorkWell: z.array(OverviewInsight),\n needsHelp: z.array(OverviewHelpNeeded),\n});\n\n/**\n * GET /api/clarity/processes/:id\n *\n * Returns the full process detail for the side panel / detail view.\n */\nconst ProcessDetailResponse = Process;\n\nexport type ClarityOverviewResponse = z.infer<typeof ClarityOverviewResponse>;\nexport type ProcessDetailResponse = z.infer<typeof ProcessDetailResponse>;\nexport type ProcessOverviewItem = z.infer<typeof ProcessOverviewItem>;\n\n// === Detail Schema ===\n\nexport const clarityOverviewDetailSchema = z.object({\n id: z.guid(),\n teamId: z.guid(),\n userId: z.guid(),\n status: clarityOverviewStatusSchema,\n processCount: z.int(),\n singlePointOfFailureCount: z.int(),\n processes: z.array(ProcessOverviewItem),\n\n // Department-level overview sections\n mission: z.string().nullable(),\n kpis: z.array(OverviewKpi),\n headcount: OverviewHeadcount.nullable(),\n teams: z.array(OverviewTeam),\n worksWell: z.array(OverviewInsight),\n doesNotWorkWell: z.array(OverviewInsight),\n needsHelp: z.array(OverviewHelpNeeded),\n\n generationError: z.string().nullable(),\n captures: z.array(clarityOverviewCaptureSchema),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n});\n\nexport type ClarityOverviewDetail = z.infer<typeof clarityOverviewDetailSchema>;\n\nexport {\n AccountabilityTag,\n ClarityOverviewResponse,\n DepartmentOverview,\n DocumentationStatus,\n FrictionSignal,\n OverviewHeadcount,\n OverviewHelpNeeded,\n OverviewInsight,\n OverviewKpi,\n OverviewTeam,\n OverviewTeamMember,\n PersonRole,\n Process,\n ProcessDetailResponse,\n ProcessOverviewItem,\n SystemRef,\n Vulnerability,\n VulnerabilitySeverity,\n};\n", "import type { IntegrationSlug } from \"./integration\";\n\ntype ComposioAppSpec = {\n slug: IntegrationSlug;\n auth_config?: {\n type: string;\n credentials?: Record<string, string | boolean | number>;\n authScheme?: string;\n };\n};\n\nexport const COMPOSIO_AUTH_CONFIGS: ComposioAppSpec[] = [\n { slug: \"googledocs\" },\n { slug: \"googlesheets\" },\n { slug: \"googlecalendar\" },\n { slug: \"slack\" },\n { slug: \"googledrive\" },\n { slug: \"confluence\" },\n { slug: \"outlook\" },\n {\n slug: \"firecrawl\",\n auth_config: {\n type: \"use_custom_auth\",\n credentials: {},\n authScheme: \"API_KEY\",\n },\n },\n {\n slug: \"shopify\",\n auth_config: {\n type: \"use_custom_auth\",\n credentials: {},\n authScheme: \"API_KEY\",\n },\n },\n { slug: \"zendesk\" },\n { slug: \"intercom\" },\n];\n", "import { z } from \"zod\";\n\n// ============================================================================\n// Credential Preview - returned when listing credentials\n// ============================================================================\n\nexport const credentialPreviewSchema = z.object({\n id: z.guid().describe(\"Credential ID\"),\n domain: z.string().describe(\"Domain for the credential\"),\n username: z.string().nullable().describe(\"Username (if any)\"),\n hasEnabledTOTP: z.boolean().describe(\"Whether TOTP is enabled\"),\n hasPassword: z.boolean().describe(\"Whether a password is stored\"),\n user_id: z\n .string()\n .nullable()\n .describe(\"Owner user id; null when shared with the team\"),\n});\n\nexport type CredentialPreview = z.infer<typeof credentialPreviewSchema>;\n\n// ============================================================================\n// OTP Response - returned when generating a TOTP code\n// ============================================================================\n\nexport const otpResponseSchema = z.object({\n code: z.string().describe(\"The TOTP code\"),\n expiresAt: z.number().describe(\"Expiration timestamp in milliseconds\"),\n});\n\nexport type OtpResponse = z.infer<typeof otpResponseSchema>;\n\n// ============================================================================\n// Encrypted Data - used for storing encrypted passwords/secrets\n// ============================================================================\n\nexport const encryptedDataSchema = z.object({\n encrypted_data: z.string().describe(\"Base64-encoded encrypted data\"),\n key_version: z.string().describe(\"KMS key version or 'base64' for dev\"),\n});\n\nexport type EncryptedData = z.infer<typeof encryptedDataSchema>;\n\n// ============================================================================\n// Credential Detail - returned when fetching full credential details\n// ============================================================================\n\nexport const credentialDetailSchema = z.object({\n domain: z.string().describe(\"Domain for the credential\"),\n username: z.string().nullable().describe(\"Username (if any)\"),\n password: encryptedDataSchema.nullable().describe(\"Encrypted password data\"),\n});\n\nexport type CredentialDetail = z.infer<typeof credentialDetailSchema>;\n\n// ============================================================================\n// API Response types for credential endpoints\n// ============================================================================\n\n/**\n * Raw API response item from the credentials list endpoint.\n * Used for typing the JSON response before mapping to CredentialPreview.\n */\nexport type CredentialPreviewApiResponse = {\n id: string;\n domain: string;\n username: string | null;\n hasEnabledTOTP: boolean;\n hasPassword: boolean;\n user_id: string | null;\n};\n", "/**\n * Feature flag catalogue.\n *\n * Each entry maps an enum key to its database key, default value, and description.\n * The description should explain the flag's purpose and what it affects.\n *\n * Please keep this sorted alphabetically for easy scanning.\n */\n\ninterface FeatureFlagEntry {\n key: string;\n defaultValue: FeatureFlagValue;\n description: string;\n}\n\nexport const FEATURE_FLAG_CATALOGUE = {\n AGENTIC_MEMORY_TEAM_WIDE: {\n key: \"agentic_memory_team_wide\",\n defaultValue: false,\n description:\n \"Enables team-wide agentic memory. When active, newly created agents default to persistent memory and existing agents can also be enabled for persistent memory across runs.\",\n },\n AGENT_SELF_SCHEDULING: {\n key: \"agent_self_scheduling\",\n defaultValue: false,\n description:\n \"Injects the always-on scheduling MCP into agent runs so the agent can call CronCreate/CronList/CronUpdate/CronDelete to manage its own schedules. When off, the scheduling MCP is not injected and the agent cannot create or modify schedules from inside a run; user-created schedules and the cron dispatcher are unaffected.\",\n },\n BUILDER_ADVANCED_CONFIG: {\n key: \"builder_advanced_config\",\n defaultValue: false,\n description:\n \"Shows the Advanced configuration editor in the assignment builder, allowing raw JSON editing of the agent configuration.\",\n },\n BUILDER_BROWSER_LOGIN_NUDGE: {\n key: \"builder_browser_login_nudge\",\n defaultValue: false,\n description:\n \"Displays a nudge prompting users to add browser login credentials when their assignment uses browser integration but has no configured logins.\",\n },\n BUILDER_DRAFT_APPROVAL: {\n key: \"builder_draft_approval\",\n defaultValue: false,\n description:\n \"Enables the draft approval flow in the assignment builder. When enabled, AI-generated SOPs pause at waiting_for_approve for user review instead of auto-completing.\",\n },\n BUILDER_PLUGINS: {\n key: \"builder_plugins\",\n defaultValue: false,\n description:\n \"Enables the plugin selector UI in the assignment builder for managing plugins.\",\n },\n SUB_ASSIGNMENTS: {\n key: \"sub_assignments\",\n defaultValue: false,\n description:\n \"Enables the Sub-Assignments selector row in the assignment builder, letting an assignment delegate work to other assignments in the team.\",\n },\n BROWSING_PLUGIN_AUTO_SYNC: {\n key: \"browsing_plugin_auto_sync\",\n defaultValue: false,\n description:\n \"Automatically syncs browser integration connections from AI-generated tool recommendations during assignment generation and editing.\",\n },\n CASE_APPROVAL: {\n key: \"case_approval\",\n defaultValue: false,\n description:\n \"Enables the case approval feature end-to-end: SOP authors can @-mention team members in the assignment SOP textarea (serialized as <DUVO:USER> tags), agents can request human approval on cases via the request_case_approval tool, and approvers see and respond to pending requests on the case. Off-by-default for staged rollout.\",\n },\n CLARITY_ON_DISK_CAPTURES: {\n key: \"clarity_on_disk_captures\",\n defaultValue: false,\n description:\n \"When enabled, the Clarity generation agent receives capture content (transcripts, documents, video transcripts, screenshare frames) as files on the sandbox filesystem and is instructed to read them via a hard checklist, instead of having the content inlined into the prompt.\",\n },\n CLARITY_OVERVIEW: {\n key: \"clarity_overview\",\n defaultValue: false,\n description:\n \"Enables the Clarity Overview executive dashboard showing high-level process KPIs, maturity scores, and drill-down cards across all captured processes.\",\n },\n CLARITY_PROCESS_GUIDANCE: {\n key: \"clarity_process_guidance\",\n defaultValue: false,\n description:\n \"Enables the Process Guidance editor on Clarity processes, letting privileged users add custom context that steers the interview agent and documentation generation.\",\n },\n CLARITY_SCREENSHARE: {\n key: \"clarity_screenshare\",\n defaultValue: false,\n description:\n \"Enables the Clarity guided session flow (screen capture + voice + live preview). When on, the /clarity landing page routes Get Started / Document Process into the session flow at /clarity/start.\",\n },\n CLARITY_V2: {\n key: \"clarity_v2\",\n defaultValue: false,\n description:\n \"Enables the Clarity v2 architecture: typed snapshot tables (clarity_current_process, clarity_transformation_proposal), the P1-P4 pipelines, the v2 read model, and the v2 process page (/clarity/v2/[id]) with end-to-end use of /v1/clarity-v2/* endpoints.\",\n },\n DYNAMIC_BUILDER_ISLAND: {\n key: \"dynamic_builder_island\",\n defaultValue: false,\n description:\n \"Enables dynamic island-style UI in the assignment builder for contextual actions and status.\",\n },\n COMPUTER_USE: {\n key: \"computer_use\",\n defaultValue: false,\n description:\n \"Grants a team access to the Daytona-backed Computer Use beta. Tile is visible to all teams; when off, the tile shows a Request Access flow. When on, the tile enables the Duvo-managed Windows sandbox.\",\n },\n COMPUTER_USE_RDP: {\n key: \"computer_use_rdp\",\n defaultValue: true,\n description:\n \"Grants a team access to the Windows Remote Desktop beta. Default-on day-one (no known scaling limit); flip off to hide the Enable form and show a Request Access flow on the tile's detail page.\",\n },\n TEAM_ONTOLOGY: {\n key: \"team_ontology\",\n defaultValue: false,\n description:\n \"Enables ontology extraction during Clarity process generation, capturing structured domain knowledge (entities, relationships, business rules) into a team-wide knowledge base.\",\n },\n LEARNINGS: {\n key: \"learnings\",\n defaultValue: false,\n description:\n \"Enables the learnings feature, allowing users to record and reference learnings from assignment runs for continuous improvement.\",\n },\n LEARNINGS_UI: {\n key: \"learnings_ui\",\n defaultValue: false,\n description:\n \"Shows the Learnings, Automatic rating, and User feedback sections in the Evaluations tab.\",\n },\n MINUTE_SCHEDULING: {\n key: \"minute_scheduling\",\n defaultValue: false,\n description:\n \"Enables minute-level granularity for scheduling assignments, allowing sub-hour scheduling intervals for case queue postponement.\",\n },\n NEW_ORG_ONBOARDING: {\n key: \"new_org_onboarding\",\n defaultValue: false,\n description:\n \"Gates the entire organizations feature. When disabled, org UI is hidden and org API routes return 404 so the feature appears not to exist. When enabled, users can create organizations, invite members, manage teams under orgs, and go through the org-based onboarding flow.\",\n },\n PORTFOLIO_INTELLIGENCE: {\n key: \"portfolio_intelligence\",\n defaultValue: false,\n description:\n \"Enables portfolio intelligence analysis in the Clarity sidebar, providing cross-process insights and recommendations.\",\n },\n VISUAL_EDITING: {\n key: \"visual_editing\",\n defaultValue: false,\n description:\n \"Enables visual editing of Clarity process flow diagrams, including the Edit Diagram button, the edit toolbar (add/delete nodes, auto-layout), inline node/edge renaming, and right-click context menus.\",\n },\n} as const satisfies Record<string, FeatureFlagEntry>;\n\ntype FeatureFlagCatalogue = typeof FEATURE_FLAG_CATALOGUE;\n\n/**\n * Feature flag keys.\n * Derived from the catalogue \u2014 maps enum keys to database flag keys.\n */\nexport const FEATURE_FLAGS: {\n [K in keyof FeatureFlagCatalogue]: FeatureFlagCatalogue[K][\"key\"];\n} = Object.fromEntries(\n Object.entries(FEATURE_FLAG_CATALOGUE).map(([enumKey, entry]) => [\n enumKey,\n entry.key,\n ])\n) as { [K in keyof FeatureFlagCatalogue]: FeatureFlagCatalogue[K][\"key\"] };\n\nexport type FeatureFlagKey = (typeof FEATURE_FLAGS)[keyof typeof FEATURE_FLAGS];\n\n/**\n * Feature flag value type.\n * - boolean: for \"on\"/\"off\" flags (coerced to true/false)\n * - string: for variant flags with custom values\n */\nexport type FeatureFlagValue = boolean | string;\n\n/**\n * Default values for feature flags.\n * Derived from the catalogue.\n * Used as fallback when no database override exists or when the user is not logged in.\n */\nexport const FEATURE_FLAG_DEFAULTS: Record<FeatureFlagKey, FeatureFlagValue> =\n Object.fromEntries(\n Object.values(FEATURE_FLAG_CATALOGUE).map((entry) => [\n entry.key,\n entry.defaultValue,\n ])\n ) as Record<FeatureFlagKey, FeatureFlagValue>;\n\n/**\n * Descriptions for feature flags.\n * Derived from the catalogue. Keyed by database flag key.\n */\nexport const FEATURE_FLAG_DESCRIPTIONS: Record<FeatureFlagKey, string> =\n Object.fromEntries(\n Object.values(FEATURE_FLAG_CATALOGUE).map((entry) => [\n entry.key,\n entry.description,\n ])\n ) as Record<FeatureFlagKey, string>;\n\n/**\n * Type for feature flag values from the API.\n * Values are booleans (for on/off), strings (for variants), or undefined if not set.\n */\nexport type FeatureFlags = Record<string, FeatureFlagValue | undefined>;\n\n/**\n * Coerce a raw flag value to its appropriate type.\n * - \"on\" or \"true\" \u2192 true\n * - \"off\" or \"false\" \u2192 false\n * - other strings \u2192 kept as-is\n * - undefined \u2192 undefined\n */\nexport function coerceFlagValue(\n value: string | undefined\n): FeatureFlagValue | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (value === \"on\" || value === \"true\") {\n return true;\n }\n\n if (value === \"off\" || value === \"false\") {\n return false;\n }\n\n return value;\n}\n", "import { z } from \"zod\";\n\n/**\n * Zod schemas for the team files public API.\n * Used by the CLI; the backend routes still define their own (matching) inline\n * schemas. Importing from this file keeps the CLI in sync with the backend.\n */\n\nexport const teamFileItemSchema = z.object({\n id: z.string(),\n name: z.string(),\n path: z.string(),\n created_at: z.string().optional(),\n updated_at: z.string().optional(),\n metadata: z\n .object({\n mimetype: z.string().optional(),\n size: z.number().optional(),\n })\n .nullable()\n .optional(),\n});\n\nexport type TeamFileItem = z.infer<typeof teamFileItemSchema>;\n\nexport const listTeamFilesResponseSchema = z.object({\n files: z.array(teamFileItemSchema),\n});\n\nexport type ListTeamFilesResponse = z.infer<typeof listTeamFilesResponseSchema>;\n\nexport const createTeamFileUploadUrlBodySchema = z.object({\n fileName: z.string().min(1),\n contentType: z.string().min(1),\n});\n\nexport type CreateTeamFileUploadUrlBody = z.infer<\n typeof createTeamFileUploadUrlBodySchema\n>;\n\nexport const createTeamFileUploadUrlResponseSchema = z.object({\n signedUrl: z.url(),\n expiresAt: z.iso.datetime(),\n filePath: z.string(),\n});\n\nexport type CreateTeamFileUploadUrlResponse = z.infer<\n typeof createTeamFileUploadUrlResponseSchema\n>;\n\nexport const renameTeamFileBodySchema = z.object({\n relativePath: z.string().min(1),\n newFilenameOnly: z.string().min(1),\n});\n\nexport type RenameTeamFileBody = z.infer<typeof renameTeamFileBodySchema>;\n\nexport const teamFileSuccessResponseSchema = z.object({\n success: z.boolean(),\n});\n\nexport type TeamFileSuccessResponse = z.infer<\n typeof teamFileSuccessResponseSchema\n>;\n\nexport const teamFileDownloadUrlResponseSchema = z.object({\n url: z.url(),\n expiresAt: z.iso.datetime(),\n});\n\nexport type TeamFileDownloadUrlResponse = z.infer<\n typeof teamFileDownloadUrlResponseSchema\n>;\n\nexport const teamFileContentResponseSchema = z.object({\n content: z.string(),\n path: z.string(),\n contentType: z.string().optional(),\n});\n\nexport type TeamFileContentResponse = z.infer<\n typeof teamFileContentResponseSchema\n>;\n\nexport const updateTeamFileContentBodySchema = z.object({\n content: z.string(),\n});\n\nexport type UpdateTeamFileContentBody = z.infer<\n typeof updateTeamFileContentBodySchema\n>;\n", "import { z } from \"zod\";\n\nexport const globalAdminApiSchema = z.object({\n id: z.guid(),\n email: z.string(),\n userId: z.guid(),\n userName: z.string().nullable(),\n addedByUserId: z.guid().nullable(),\n createdAt: z.string(),\n});\nexport type GlobalAdminApi = z.infer<typeof globalAdminApiSchema>;\n\nexport const globalAdminListResponseSchema = z.object({\n admins: z.array(globalAdminApiSchema),\n});\nexport type GlobalAdminListResponse = z.infer<\n typeof globalAdminListResponseSchema\n>;\n\nexport const globalAdminSearchResponseSchema = z.object({\n users: z.array(\n z.object({\n id: z.guid(),\n name: z.string().nullable(),\n email: z.string(),\n createdAt: z.string().nullable(),\n })\n ),\n});\nexport type GlobalAdminSearchResponse = z.infer<\n typeof globalAdminSearchResponseSchema\n>;\n\nexport const globalAdminCreateRequestSchema = z.object({\n userId: z.guid(),\n});\nexport type GlobalAdminCreateRequest = z.infer<\n typeof globalAdminCreateRequestSchema\n>;\n\nexport const globalAdminCreateResponseSchema = z.object({\n admin: globalAdminApiSchema,\n});\nexport type GlobalAdminCreateResponse = z.infer<\n typeof globalAdminCreateResponseSchema\n>;\n\nexport const globalAdminDeleteResponseSchema = z.object({\n success: z.literal(true),\n});\nexport type GlobalAdminDeleteResponse = z.infer<\n typeof globalAdminDeleteResponseSchema\n>;\n\nexport const adminAccessCheckResponseSchema = z.object({\n isGlobalAdmin: z.boolean(),\n});\nexport type AdminAccessCheckResponse = z.infer<\n typeof adminAccessCheckResponseSchema\n>;\n", "import { z } from \"zod\";\n\nexport type IntegrationProvider = \"default\" | \"native\" | \"composio\" | \"user\";\nexport type IntegrationClass = \"platform\" | \"partner\" | \"custom\";\n\n/**\n * Integration category values.\n * Backend catalog uses kebab-case values; frontend may use display values for backward compatibility.\n */\nexport type IntegrationCategory =\n // Backend catalog (kebab-case)\n | \"google-workspace\"\n | \"ms-office-365\"\n | \"productivity\"\n | \"data-warehouses\"\n | \"duvo-platform\"\n | \"business-intelligence\"\n | \"custom\"\n // Frontend display values (legacy)\n | \"Google Workspace\"\n | \"MS Office 365\"\n | \"Productivity\"\n | \"Business Intelligence\"\n | \"Data Warehouses and Databases\"\n | \"Duvo Business Connections\"\n | \"ERP and Internal systems\";\n\n/**\n * MCP transport protocol types\n * Used to indicate how an MCP server communicates (computed field, not stored in database)\n */\nexport const TransportTypeSchema = z.enum([\"stdio\", \"sse\", \"http\"]);\nexport type TransportType = z.infer<typeof TransportTypeSchema>;\n\nexport const INTEGRATION_SLUGS = [\n \"googlecalendar\",\n \"google-calendar\",\n \"gmail\",\n \"slack\",\n \"googledocs\",\n \"googlesheets\",\n \"googledrive\",\n \"firecrawl\",\n \"exa\",\n \"exa-search\",\n \"exa-company-search\",\n \"exa-people-search\",\n \"deep-research\",\n \"system\",\n \"browser-agent\", // Deprecated: 368 teams still have catalog rows in the integration table\n \"browser-agent-devtools\",\n \"notion\",\n \"linear\",\n \"confluence\",\n \"custom_mcp\",\n \"user_mcp\",\n \"snowflake\",\n \"sharepoint\",\n \"teams\",\n \"onedrive\",\n \"bigquery\",\n \"databricks\",\n \"netsuite\",\n \"outlook\",\n \"microsoft-calendar\",\n \"excel\",\n \"word\",\n \"saps4hana\",\n \"md365\",\n \"businesscentral\",\n \"oraclefusion\",\n \"workday\",\n \"coupa\",\n \"msteams\",\n \"human-in-the-loop\",\n \"email-attachments-reader\",\n \"document-processor\",\n \"google-docs\",\n \"google-sheets\",\n \"google-drive\",\n \"outbound-call\",\n \"case-queue-producer\",\n \"case-queue-consumer\",\n \"handover\",\n \"shopify\",\n \"hubspot\",\n \"zendesk\",\n \"intercom\",\n \"powerbi\",\n \"salesforce\",\n \"pipedrive\",\n \"tableau\",\n \"image-generation\",\n \"forecasting\",\n \"supabase\",\n \"attio\",\n \"amplitude\",\n \"websets\",\n \"firecrawl-platform\",\n \"duvo-computer-use\",\n \"duvo-computer-use-rdp\",\n \"eu-commodity-prices\",\n \"asana\",\n \"ssh\",\n \"scheduling\",\n \"github\",\n \"linear-native\",\n \"notion-native\",\n \"granola\",\n] as const;\n\nexport const IntegrationSlugSchema = z.enum(INTEGRATION_SLUGS);\nexport type IntegrationSlug = z.infer<typeof IntegrationSlugSchema>;\n\nexport function isIntegrationSlug(value: string): value is IntegrationSlug {\n return (INTEGRATION_SLUGS as readonly string[]).includes(value);\n}\n\nexport interface Integration {\n slug: IntegrationSlug; // Used for MCP url backfilling, values must be in sync with the backend\n integrationName: string;\n icon: string;\n provider: IntegrationProvider;\n requires_instance?: boolean;\n integration_class?: IntegrationClass;\n description?: string;\n category?: IntegrationCategory;\n oauth_provider_id?: string | null;\n}\n\nexport const DEPRECATED_INTEGRATION_SLUGS: Set<IntegrationSlug> = new Set([\n \"browser-agent\",\n \"email-attachments-reader\",\n \"exa\",\n \"firecrawl\",\n \"linear\",\n \"notion\",\n]);\n\nexport interface IntegrationView extends Integration {\n id: string;\n name: string;\n}\n\nexport type CaseQueueIntegrationType =\n | \"case-queue-producer\"\n | \"case-queue-consumer\";\n\nexport const CASE_QUEUE_INTEGRATION_TYPES: readonly CaseQueueIntegrationType[] =\n [\"case-queue-producer\", \"case-queue-consumer\"];\n\nexport function isCaseQueueIntegrationType(\n type: string\n): type is CaseQueueIntegrationType {\n return type === \"case-queue-producer\" || type === \"case-queue-consumer\";\n}\n\n/**\n * Shared response schema for integration API objects.\n * Used by both backend routes and frontend API clients.\n *\n * Note on computed fields:\n * - server_url: Required in database, but optional in response for stdio MCP servers\n * - transport_type: NOT stored in database, computed from PRIVATE_MCP_SERVERS config\n * Only present for MCP-type integrations (undefined for OAuth/Composio integrations)\n */\nexport const integrationResponseSchema = z.object({\n id: z.string(),\n name: z.string(),\n type: z.string(),\n provider: z.string(),\n user_id: z.string().nullable(),\n team_id: z.string(),\n server_url: z.string().optional(),\n transport_type: TransportTypeSchema.optional(),\n auth_method: z.string().nullable().optional(),\n composio_mcp_id: z.string().nullable().default(null),\n custom_integration_id: z.string().nullable().optional(),\n icon_url: z.string().nullable().optional(),\n oauth_provider: z.string().nullable().optional(),\n oauth_scopes: z.array(z.string()).nullable().optional(),\n has_headers: z.boolean().optional(),\n has_oauth_tokens: z.boolean().optional(),\n /**\n * For connection rows (user instances), this is the FK to the team-level\n * integration this connection was created against. Null on catalog rows\n * (where `id` already represents the integration itself) and on\n * custom-integration-backed connections.\n */\n integration_id: z.string().nullable().optional(),\n created_at: z.iso.datetime(),\n updated_at: z.iso.datetime(),\n});\n\nexport type IntegrationApiResponse = z.infer<typeof integrationResponseSchema>;\n\nexport const integrationsListResponseSchema = z.object({\n integrations: z.array(integrationResponseSchema),\n total: z.int().min(0),\n limit: z.int().min(1),\n offset: z.int().min(0),\n});\n\nexport const integrationsListRequestQuerySchema = z.object({\n type: z.string().optional(),\n // Default high (100) because both the team integration catalog and the\n // user's connections are naturally small per team; existing dashboard\n // callers expect \"everything\" without explicit pagination.\n limit: z.coerce.number().int().min(1).max(100).prefault(100),\n offset: z.coerce.number().int().min(0).prefault(0),\n});\nexport type IntegrationsListRequestQuery = z.infer<\n typeof integrationsListRequestQuerySchema\n>;\n\nexport type IntegrationsListResponse = z.infer<\n typeof integrationsListResponseSchema\n>;\n\nexport const connectIntegrationResponseSchema = z.object({\n integration_id: z.string(),\n mcp_url: z.string(),\n});\n\nexport type ConnectIntegrationResponse = z.infer<\n typeof connectIntegrationResponseSchema\n>;\n\nexport const testIntegrationResponseSchema = z.object({\n success: z.boolean(),\n tools: z\n .array(\n z.object({\n name: z.string(),\n description: z.string().optional(),\n // Tool input schemas are JSON-Schema documents whose internal shape\n // varies per MCP server. Modeled as a record of unknowns (matching\n // the upstream MCP SDK's `{ [x: string]: unknown; type: \"object\" }`\n // typing) so that producers can pass `tool.inputSchema` straight\n // through without an unsafe cast \u2014 using `z.json()` here would force\n // every caller to cast since the SDK does not assert JSON-ness.\n input_schema: z.record(z.string(), z.unknown()).optional(),\n })\n )\n .optional(),\n error: z.string().optional(),\n});\n\nexport type TestIntegrationResponse = z.infer<\n typeof testIntegrationResponseSchema\n>;\n\nexport const integrationCredentialsResponseSchema = z.object({\n id: z.guid(),\n headers: z.record(z.string(), z.string()),\n});\n\nexport type IntegrationCredentialsResponse = z.infer<\n typeof integrationCredentialsResponseSchema\n>;\n\nexport const deleteIntegrationResponseSchema = z.object({\n success: z.boolean(),\n message: z.string(),\n});\n\nexport type DeleteIntegrationResponse = z.infer<\n typeof deleteIntegrationResponseSchema\n>;\n\nexport const checkDcrSupportResponseSchema = z.object({\n supports_dcr: z.boolean(),\n authorization_endpoint: z.string().optional(),\n scopes: z.array(z.string()).optional(),\n});\n\nexport type CheckDcrSupportResponse = z.infer<\n typeof checkDcrSupportResponseSchema\n>;\n\nexport const createCustomIntegrationRequestSchema = z\n .object({\n name: z.string().min(1, \"Name is required\"),\n auth_method: z.enum([\"url\", \"apikey\", \"headers\", \"oauth\"]),\n server_url: z.url(\"Must be a valid URL\"),\n oauth_client_id: z.string().min(1).optional(),\n oauth_client_secret: z.string().min(1).optional(),\n })\n .refine(\n (data) => {\n const hasClientId = !!data.oauth_client_id;\n const hasClientSecret = !!data.oauth_client_secret;\n return hasClientId === hasClientSecret;\n },\n {\n error:\n \"Both OAuth Client ID and Client Secret are required, or leave both empty for automatic registration\",\n }\n );\n\nexport type CreateCustomIntegrationRequest = z.infer<\n typeof createCustomIntegrationRequestSchema\n>;\n\n// Schema for creating a new integration.\n// Note: `composio_mcp_id` is intentionally *not* in this schema. It is a\n// foreign-system identifier that is set server-side by\n// `/v1/connections/composio/finalize` after Composio creates the MCP\n// server. Allowing callers to write it lets them bind a new instance to\n// any Composio MCP server they happen to know the ID of \u2014 a footgun.\nexport const createIntegrationRequestSchema = z.object({\n name: z.string().min(1, \"Name is required\"),\n server_url: z.url(\"Must be a valid URL\").optional(),\n type: z.string().default(\"custom_mcp\"),\n provider: z.literal(\"user\"),\n auth_method: z.enum([\"url\", \"apikey\", \"headers\", \"oauth\"]),\n custom_integration_id: z.guid().optional(),\n headers: z\n .object({\n plaintext: z.record(z.string(), z.string()).optional(),\n secret: z.record(z.string(), z.string()).optional(),\n })\n .optional(),\n});\n\nexport type CreateIntegrationRequest = z.infer<\n typeof createIntegrationRequestSchema\n>;\n\n// Schema for updating an integration - all fields optional.\n// Note: `composio_mcp_id` is intentionally *not* updatable via the public\n// API. It's a foreign-system identifier set during connect-flow finalize;\n// letting callers swap it points an existing instance at an arbitrary\n// Composio MCP server, which would silently break the connection or, if\n// IDs are guessable, point at a teammate's account.\nexport const updateIntegrationRequestSchema = z.object({\n name: z.string().min(1).optional(),\n server_url: z.url().optional(),\n auth_method: z.enum([\"url\", \"oauth\", \"apikey\", \"headers\"]).optional(),\n headers: z\n .object({\n plaintext: z.record(z.string(), z.string()).optional(),\n secret: z.record(z.string(), z.string()).optional(),\n })\n .nullable()\n .optional(),\n});\n\nexport type UpdateIntegrationRequest = z.infer<\n typeof updateIntegrationRequestSchema\n>;\n\nexport const testIntegrationRequestSchema = z.object({\n server_url: z.url().describe(\"MCP server URL to test\"),\n headers: z\n .record(z.string(), z.string())\n .optional()\n .describe(\"Optional HTTP headers for authentication\"),\n});\n\nexport type TestIntegrationRequest = z.infer<\n typeof testIntegrationRequestSchema\n>;\n", "import { z } from \"zod\";\n\nimport { evalSummarySchema } from \"../schemas/run-evaluation\";\nimport { agentRunStatusSchema } from \"./agent-run\";\n\nexport const JOB_LIST_SORT_COLUMNS = [\"created_at\"] as const;\n\nexport type JobListSortColumn = (typeof JOB_LIST_SORT_COLUMNS)[number];\n\nexport const jobListSortColumnSchema = z.enum(JOB_LIST_SORT_COLUMNS);\n\nexport const jobListItemSchema = z.object({\n id: z.guid(),\n created_at: z.coerce.date(),\n updated_at: z.coerce.date(),\n started_at: z.coerce.date().nullable(),\n completed_at: z.coerce.date().nullable(),\n status: agentRunStatusSchema,\n source: z.string().nullable(),\n title: z.string(),\n run_number: z.number(),\n // Assignment info\n agent_id: z.guid(),\n agent_name: z.string(),\n build_id: z.guid(),\n // User info\n user_id: z.guid().nullable(),\n // Case info\n case_queue_item_id: z.guid().nullable(),\n case_queue_id: z.guid().nullable(),\n case_queue_name: z.string().nullable(),\n case_title: z.string().nullable(),\n postponed_to: z.coerce.date().nullable(),\n submitted_prompt_count: z.number().int().min(0),\n eval_summaries: evalSummarySchema.nullable().optional(),\n});\n\nexport type JobListItem = z.infer<typeof jobListItemSchema>;\n\nexport const jobListResponseSchema = z.object({\n data: z.array(jobListItemSchema),\n total: z.number(),\n});\n\nexport type JobListResponse = z.infer<typeof jobListResponseSchema>;\n\nexport const jobFilterOptionsSchema = z.object({\n agents: z.array(\n z.object({\n id: z.string(),\n name: z.string(),\n folder_id: z.string().nullable(),\n })\n ),\n folders: z.array(\n z.object({\n id: z.string(),\n name: z.string(),\n parent_folder_id: z.string().nullable(),\n })\n ),\n users: z.array(\n z.object({\n id: z.string(),\n name: z.string().nullable(),\n email: z.string(),\n })\n ),\n caseQueues: z.array(z.object({ id: z.string(), name: z.string() })),\n});\n\nexport type JobFilterOptions = z.infer<typeof jobFilterOptionsSchema>;\n", "/**\n * MCP Workflow types for browser automation.\n * Represents recorded user workflows as sequences of MCP tool calls\n * that can be replayed by AI agents.\n */\n\nimport { z } from \"zod\";\n\n/**\n * Single step in an MCP workflow - represents one tool call.\n */\nexport const mcpStepSchema = z.object({\n tool: z.string().describe(\"MCP tool name (e.g., click, fill, navigate_page)\"),\n params: z\n .record(z.string(), z.unknown())\n .describe(\"Tool-specific parameters\"),\n fallbackSelectors: z\n .array(z.string())\n .optional()\n .describe(\"Alternative CSS selectors if primary fails\"),\n description: z\n .string()\n .optional()\n .describe(\"Human-readable step description\"),\n screenshot: z\n .string()\n .optional()\n .describe(\"Base64 screenshot at this step for visual context\"),\n snapshot: z\n .string()\n .optional()\n .describe(\"DOM snapshot in accessibility tree format at this step\"),\n framePath: z\n .array(z.number())\n .optional()\n .describe(\n \"Index-based path to the target iframe (e.g., [0] for first child iframe, [1, 0] for nested)\"\n ),\n});\n\nexport type McpStep = z.infer<typeof mcpStepSchema>;\n\n/**\n * MCP Workflow format - represents a recorded user workflow\n * as a sequence of MCP tool calls.\n */\nexport const mcpWorkflowSchema = z.object({\n name: z.string(),\n startUrl: z.string(),\n viewport: z.object({\n width: z.number(),\n height: z.number(),\n }),\n steps: z.array(mcpStepSchema),\n});\n\nexport type McpWorkflow = z.infer<typeof mcpWorkflowSchema>;\n\n/**\n * JSON Schema representation of the MCP workflow schema.\n * Auto-generated from Zod schemas to stay in sync.\n */\nexport const MCP_WORKFLOW_JSON_SCHEMA = z.toJSONSchema(mcpWorkflowSchema, {\n reused: \"inline\",\n});\n\n/**\n * Documentation string for the MCP workflow schema.\n * Used in generated skill files to document the workflow format.\n */\nexport const MCP_WORKFLOW_SCHEMA_DOCS = JSON.stringify(\n MCP_WORKFLOW_JSON_SCHEMA,\n null,\n 2\n);\n", "import { z } from \"zod\";\n\n/**\n * Zod schemas for the plugins public API.\n * Used by both backend validation and CLI/frontend type inference.\n */\n\nexport const catalogPluginSchema = z.object({\n name: z.string().describe(\"Identifier to pass in the build's plugins array.\"),\n type: z\n .enum([\"duvo-platform\", \"github\"])\n .describe(\n \"Plugin source. 'duvo-platform' plugins are pre-baked into the Duvo runtime; 'github' plugins are downloaded from a user-supplied repository URL at run time.\"\n ),\n description: z.string(),\n});\n\nexport type CatalogPlugin = z.infer<typeof catalogPluginSchema>;\n\nexport const pluginCatalogResponseSchema = z.object({\n plugins: z.array(catalogPluginSchema),\n});\n\nexport type PluginCatalogResponse = z.infer<typeof pluginCatalogResponseSchema>;\n", "import { z } from \"zod\";\n\nexport const publicProfileSchema = z.object({\n id: z.guid(),\n name: z.string().nullable(),\n email: z.email(),\n teamId: z.guid().nullable(),\n});\nexport type PublicProfile = z.infer<typeof publicProfileSchema>;\n\nexport const publicProfileResponseSchema = z.object({\n profile: publicProfileSchema,\n});\nexport type PublicProfileResponse = z.infer<typeof publicProfileResponseSchema>;\n", "/**\n * Types for headless workflow recording in Browserbase sessions.\n * Used by both the Chrome extension and backend API.\n */\n\nimport { z } from \"zod\";\n\n/**\n * Cookie name used to pass recording configuration to the extension.\n * The extension reads this cookie on initialization to determine if\n * it should run in headless mode with auto-start recording.\n */\nexport const RECORDING_CONFIG_COOKIE_NAME = \"__duvo_recording_config\";\n\n/**\n * Configuration passed to the extension via cookie for headless recording.\n */\nexport interface HeadlessRecordingConfig {\n /** Recording session ID (UUID) - used for API calls */\n sessionId: string;\n /** Browserbase session ID */\n browserbaseSessionId: string;\n /** Agent ID this recording is for */\n agentId: string;\n /** Team ID owning the agent */\n teamId: string;\n /** User ID who initiated the recording */\n userId: string;\n /** Optional name for the generated skill */\n skillName?: string;\n /** Optional description for the generated skill */\n skillDescription?: string;\n /** Backend streaming endpoint URL (e.g., https://api.duvo.ai/v1/recordings) */\n streamEndpoint: string;\n /** JWT or API key for authentication */\n authToken: string;\n}\n\n/**\n * Recording session status values.\n */\nexport type RecordingSessionStatus =\n | \"browsing\" // Browser open, not recording yet\n | \"recording\"\n | \"completing\"\n | \"completed\"\n | \"failed\";\n\n/**\n * Batch of recorded events sent from extension to backend.\n */\nexport interface RecordingEventBatch {\n /** Recording session ID */\n sessionId: string;\n /** Sequential batch number (1-indexed) */\n batchNumber: number;\n /** Array of recorded events - uses unknown to avoid circular dependency with extension types */\n events: unknown[];\n /** Timestamp when batch was created (Date.now()) */\n timestamp: number;\n}\n\n/**\n * Metadata about the recording session, sent on completion.\n */\nexport interface RecordingSessionMetadata {\n /** Starting URL of the recording */\n startUrl: string;\n /** Viewport dimensions during recording */\n viewport: {\n width: number;\n height: number;\n };\n /** Browser information */\n browserInfo: {\n name: string;\n version: string;\n userAgent: string;\n };\n}\n\n/**\n * Response from the stream events endpoint.\n */\nexport interface StreamEventsResponse {\n success: boolean;\n eventsReceived: number;\n}\n\n/**\n * Response from the complete recording endpoint.\n */\nexport interface CompleteRecordingResponse {\n success: boolean;\n skillId?: string;\n error?: string;\n}\n\n// =============================================================================\n// Recorded Event Schemas\n// =============================================================================\n\n/**\n * Element selector information captured from the DOM.\n */\nexport const elementSelectorsSchema = z.object({\n css: z.string().optional(),\n cssPath: z.string().optional(),\n xpath: z.string().optional(),\n testId: z.string().optional(),\n ariaSelector: z.string().optional(),\n text: z.string().optional(),\n});\n\nexport type ElementSelectors = z.infer<typeof elementSelectorsSchema>;\n\n/**\n * Element information captured from the DOM.\n */\nexport const elementInfoSchema = z.object({\n uid: z.string().optional(),\n selectors: elementSelectorsSchema,\n tagName: z.string(),\n textContent: z.string().optional(),\n ariaLabel: z.string().optional(),\n computedRole: z.string().optional(),\n attributes: z.record(z.string(), z.string()).optional(),\n framePath: z.array(z.number()).optional(),\n frameUrl: z.string().optional(),\n});\n\nexport type ElementInfo = z.infer<typeof elementInfoSchema>;\n\n/**\n * Base recorded event structure.\n */\nexport const recordedEventSchema = z.looseObject({\n id: z.string(),\n type: z.string(),\n timestamp: z.number(),\n url: z.string(),\n tabId: z.number().optional(),\n frameId: z.number().optional(),\n framePath: z.array(z.number()).optional(),\n element: elementInfoSchema.optional(),\n});\n\nexport type RecordedEvent = z.infer<typeof recordedEventSchema>;\n", "import { z } from \"zod\";\n\nimport { AgentConfigSchema } from \"./agent-config\";\nimport { IntegrationSlugSchema, TransportTypeSchema } from \"./integration\";\n\n/**\n * Redacted MCP server configuration that contains no secrets.\n * Stored in run_config at agent run creation time.\n * Secrets are resolved at execution time using instanceId lookups.\n */\nexport const RedactedMcpServerConfigSchema = z.object({\n type: TransportTypeSchema,\n integrationSlug: IntegrationSlugSchema,\n instanceId: z.string().nullable(),\n});\n\nexport type RedactedMcpServerConfig = z.infer<\n typeof RedactedMcpServerConfigSchema\n>;\n\n/**\n * Schema for thread context messages (e.g., from Slack threads).\n */\nexport const ThreadContextMessageSchema = z.object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string(),\n});\n\nexport type ThreadContextMessage = z.infer<typeof ThreadContextMessageSchema>;\n\n/**\n * Schema for chat platform file references attached to thread messages.\n * Stored in run_config so the runtime can download and upload them to the sandbox.\n *\n * Platform-specific fields:\n * - slack: workspaceId = Slack workspace ID, channelId = Slack channel ID\n * - teams: workspaceId = Teams tenant ID, channelId = Teams channel/conversation ID\n */\nexport const ChatFileReferenceSchema = z.object({\n id: z.string(),\n name: z.string(),\n mimetype: z.string(),\n size: z.number(),\n platform: z.enum([\"slack\", \"teams\"]),\n workspaceId: z.string(),\n channelId: z.string(),\n});\n\nexport type ChatFileReference = z.infer<typeof ChatFileReferenceSchema>;\n\nexport type SlackFileReference = ChatFileReference & { platform: \"slack\" };\nexport type TeamsFileReference = ChatFileReference & { platform: \"teams\" };\n\n/**\n * A sub-assignment resolved at run-creation time.\n *\n * Frozen entry that captures everything needed to run another assignment as\n * a Claude Code subagent: the live build that was current at run creation,\n * a stable slug used as the SDK agent name, the system prompt to give the\n * subagent, and redacted MCP servers (secrets resolved at execution time).\n * Replays consume this directly without re-resolving live builds.\n *\n * NOTE on resource inheritance: a child's `files`, `skills`, and `plugins`\n * are NOT carried on this entry. They are unioned into the parent run's own\n * `files`, `skills`, and `plugins` at config-build time (see\n * `resolveSubAgents` + `buildRunConfig`). Because the sandbox FS is shared\n * and plugins load once at session start, those resources are visible to the\n * parent's main loop and to sibling subagents \u2014 accepted trade-off for\n * letting authors compose existing assignments.\n */\nexport const ResolvedSubAgentSchema = z.object({\n agentId: z.string().uuid(),\n buildId: z.string().uuid(),\n name: z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-z0-9-]+$/)\n .describe(\n \"Stable slug used as the Claude Code subagent name (kebab-case, \u226464 chars)\"\n ),\n description: z\n .string()\n .describe(\n \"Routing description Claude uses to decide when to delegate to this subagent\"\n ),\n prompt: z.string().describe(\"System prompt (SOP) for this subagent\"),\n model: z\n .string()\n .optional()\n .describe(\"Optional Claude model identifier override for this subagent\"),\n mcpServers: z\n .record(z.string(), RedactedMcpServerConfigSchema)\n .default({})\n .describe(\n \"Redacted MCP server configs scoped to this subagent. Secrets resolved at execution time.\"\n ),\n});\n\nexport type ResolvedSubAgent = z.infer<typeof ResolvedSubAgentSchema>;\n\n/**\n * Run configuration data (the actual config payload).\n * Extends AgentConfig with runtime-specific additions (task, mcpServers).\n *\n * Contains all data needed to execute the run, decoupled from build state.\n * MCP server secrets are resolved at execution time using instanceId lookups.\n *\n * NOTE: `subAgents` is overridden here. AgentConfigSchema stores it as a list\n * of agent IDs (the user's selection at edit time); RunConfigSchema replaces\n * those IDs with frozen ResolvedSubAgent entries at run-creation time so\n * downstream execution does not need to re-resolve live builds.\n */\nexport const RunConfigSchema = AgentConfigSchema.extend({\n task: z.string(),\n mcpServers: z.record(z.string(), RedactedMcpServerConfigSchema),\n subAgents: z.array(ResolvedSubAgentSchema).optional().default([]),\n conversationHistory: z.array(ThreadContextMessageSchema).optional(),\n chatFiles: z.array(ChatFileReferenceSchema).optional(),\n /** IANA timezone (e.g. `\"Europe/Prague\"`). Consumers should fall back to UTC when absent. */\n timezone: z.string().optional(),\n});\n\nexport type RunConfig = z.infer<typeof RunConfigSchema>;\n\n/**\n * V0: Empty placeholder for legacy runs (pre-dispatcher).\n * Used for runs created before run_config was implemented.\n */\nexport const StoredRunConfigV0Schema = z.object({\n version: z.literal(\"v0\"),\n});\n\nexport type StoredRunConfigV0 = z.infer<typeof StoredRunConfigV0Schema>;\n\n/**\n * V1: Full frozen run configuration with version wrapper.\n */\nexport const StoredRunConfigV1Schema = z.object({\n version: z.literal(\"v1\"),\n data: RunConfigSchema,\n});\n\nexport type StoredRunConfigV1 = z.infer<typeof StoredRunConfigV1Schema>;\n\n/**\n * Union of all stored run config formats.\n */\nexport const StoredRunConfigSchema = z.union([\n StoredRunConfigV0Schema,\n StoredRunConfigV1Schema,\n]);\n\nexport type StoredRunConfig = z.infer<typeof StoredRunConfigSchema>;\n\n/**\n * Type guard to check if stored config is V0 format.\n */\nexport function isStoredRunConfigV0(\n config: unknown\n): config is StoredRunConfigV0 {\n return StoredRunConfigV0Schema.safeParse(config).success;\n}\n\n/**\n * Type guard to check if stored config is V1 format.\n */\nexport function isStoredRunConfigV1(\n config: unknown\n): config is StoredRunConfigV1 {\n return StoredRunConfigV1Schema.safeParse(config).success;\n}\n\n/**\n * Type guard to check if a value is a RunConfig (the inner data, not the wrapper).\n */\nexport function isRunConfig(config: unknown): config is RunConfig {\n return RunConfigSchema.safeParse(config).success;\n}\n", "import { z } from \"zod\";\n\n/**\n * Zod schemas for the skills public API.\n * Used by the CLI; the backend routes still define their own (matching) inline\n * schemas, but importing from this file keeps the CLI in sync with the backend.\n */\n\nexport const skillApiSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n // System skills have null team_id.\n team_id: z.string().nullable(),\n});\n\nexport type SkillApi = z.infer<typeof skillApiSchema>;\n\nexport const listSkillsResponseSchema = z.object({\n skills: z.array(skillApiSchema),\n});\n\nexport type ListSkillsResponse = z.infer<typeof listSkillsResponseSchema>;\n\nexport const systemSkillSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n});\n\nexport type SystemSkill = z.infer<typeof systemSkillSchema>;\n\nexport const listSystemSkillsResponseSchema = z.object({\n skills: z.array(systemSkillSchema),\n});\n\nexport type ListSystemSkillsResponse = z.infer<\n typeof listSystemSkillsResponseSchema\n>;\n\nexport const skillFileItemSchema = z.object({\n name: z.string(),\n path: z.string(),\n size: z.number().optional(),\n contentType: z.string().optional(),\n updatedAt: z.string().optional(),\n});\n\nexport type SkillFileItem = z.infer<typeof skillFileItemSchema>;\n\nexport const listSkillFilesResponseSchema = z.object({\n files: z.array(skillFileItemSchema),\n});\n\nexport type ListSkillFilesResponse = z.infer<\n typeof listSkillFilesResponseSchema\n>;\n\nexport const getSkillFileContentResponseSchema = z.object({\n content: z.string(),\n path: z.string(),\n contentType: z.string().optional(),\n});\n\nexport type GetSkillFileContentResponse = z.infer<\n typeof getSkillFileContentResponseSchema\n>;\n\nexport const updateSkillFileBodySchema = z.object({\n content: z.string(),\n});\n\nexport type UpdateSkillFileBody = z.infer<typeof updateSkillFileBodySchema>;\n\nexport const updateSkillFileResponseSchema = z.object({\n success: z.boolean(),\n message: z.string(),\n skill: z\n .object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n })\n .optional(),\n});\n\nexport type UpdateSkillFileResponse = z.infer<\n typeof updateSkillFileResponseSchema\n>;\n\nexport const deleteSkillResponseSchema = z.object({\n success: z.boolean(),\n message: z.string(),\n});\n\nexport type DeleteSkillResponse = z.infer<typeof deleteSkillResponseSchema>;\n\nexport const generateSkillBodySchema = z.object({\n prompt: z.string().min(1).max(2000),\n existingContent: z.string().max(20000).optional(),\n});\n\nexport type GenerateSkillBody = z.infer<typeof generateSkillBodySchema>;\n\nexport const generateSkillResponseSchema = z.object({\n content: z.string(),\n});\n\nexport type GenerateSkillResponse = z.infer<typeof generateSkillResponseSchema>;\n", "import { z } from \"zod\";\n\nimport { BrowserProviderTypeSchema } from \"./agent-config\";\nimport { teamInvitationApiSchema } from \"./team-invitation\";\n\nconst teamDiscoveryModeSchema = z.enum([\"request\", \"auto\"]);\nexport type TeamDiscoveryMode = z.infer<typeof teamDiscoveryModeSchema>;\n\nexport const BrowserLocationSchema = z.union([\n z.literal(\"cz\"),\n z.literal(\"de\"),\n z.literal(\"fr\"),\n z.literal(\"gb\"),\n z.literal(\"it\"),\n z.literal(\"pl\"),\n z.literal(\"sk\"),\n]);\nexport type BrowserLocation = z.infer<typeof BrowserLocationSchema>;\n\n// Team member schema\nexport const teamMemberApiSchema = z.object({\n id: z.guid(),\n name: z.string().nullable(),\n email: z.email(),\n role: z.string(),\n inheritedFromOrg: z.boolean().default(false),\n});\nexport type TeamMemberApi = z.infer<typeof teamMemberApiSchema>;\n\n// List members response\nexport const listTeamMembersResponseSchema = z.object({\n members: z.array(teamMemberApiSchema),\n total: z.number().int().nonnegative(),\n limit: z.number().int().positive(),\n offset: z.number().int().nonnegative(),\n});\nexport type ListTeamMembersResponse = z.infer<\n typeof listTeamMembersResponseSchema\n>;\n\n// Update member role request\nexport const updateMemberRoleRequestSchema = z.object({\n role: z.string(),\n});\nexport type UpdateMemberRoleRequest = z.infer<\n typeof updateMemberRoleRequestSchema\n>;\n\n// Remove member response\nexport const removeMemberResponseSchema = z.object({\n success: z.literal(true),\n nextTeamId: z.guid().nullable(),\n planType: z.enum([\"pro\", \"enterprise\"]).nullable(),\n});\nexport type RemoveMemberResponse = z.infer<typeof removeMemberResponseSchema>;\n\n// Get current user role response\nexport const getMemberMeResponseSchema = z.object({\n role: z.string().nullable(),\n});\nexport type GetMemberMeResponse = z.infer<typeof getMemberMeResponseSchema>;\n\n// Add user to team request\nexport const addTeamMemberRequestSchema = z.object({\n userId: z.guid(),\n role: z.string(),\n});\nexport type AddTeamMemberRequest = z.infer<typeof addTeamMemberRequestSchema>;\n\n// Update team request\nexport const updateTeamRequestSchema = z.object({\n name: z.string().min(1).optional(),\n slack_team_id: z.string().optional(),\n discovery_mode: teamDiscoveryModeSchema.optional(),\n});\nexport type UpdateTeamRequest = z.infer<typeof updateTeamRequestSchema>;\n\n// Team response schema\nexport const teamApiSchema = z.object({\n id: z.guid(),\n name: z.string(),\n created_at: z.string(),\n organization_id: z.guid().nullable(),\n slack_team_id: z.string().nullable(),\n discovery_mode: teamDiscoveryModeSchema,\n});\nexport type TeamApi = z.infer<typeof teamApiSchema>;\n\n// Team config schema (versioned envelope)\nexport const TEAM_CONFIG_VERSION = 1;\n\nexport const teamConfigDataSchema = z.object({\n browserProviderOverride: BrowserProviderTypeSchema.nullable().optional(),\n browserLocationOverride: BrowserLocationSchema.nullable().optional(),\n});\nexport type TeamConfigData = z.infer<typeof teamConfigDataSchema>;\n\nexport const teamConfigSchema = z.object({\n version: z.literal(TEAM_CONFIG_VERSION),\n data: teamConfigDataSchema,\n});\nexport type TeamConfig = z.infer<typeof teamConfigSchema>;\n\n// List team invites response\nexport const listTeamInvitesResponseSchema = z.object({\n invitations: z.array(teamInvitationApiSchema),\n});\nexport type ListTeamInvitesResponse = z.infer<\n typeof listTeamInvitesResponseSchema\n>;\n", "import { z } from \"zod\";\n\n// Base invite schema matching the database table\nexport const teamInvitationApiSchema = z.object({\n id: z.string(),\n team_id: z.string(),\n email: z.email(),\n invited_by: z.string(),\n role: z.string(),\n status: z.string(),\n name: z.string().nullable(),\n created_at: z.string(),\n process_id: z.guid().nullable().optional(),\n});\n\nexport type TeamInvitationApi = z.infer<typeof teamInvitationApiSchema>;\n\n// Detailed invite schema with relationships\nexport const teamInvitationDetailApiSchema = z.object({\n id: z.string(),\n team_id: z.string(),\n email: z.email(),\n invited_by: z.string(),\n role: z.string(),\n status: z.string(),\n name: z.string().nullable(),\n created_at: z.string(),\n process_id: z.guid().nullable().optional(),\n team: z.object({\n id: z.string(),\n name: z.string(),\n }),\n invitedBy: z.object({\n id: z.string(),\n name: z.string().nullable(),\n email: z.email(),\n }),\n process: z\n .object({\n id: z.string(),\n name: z.string(),\n })\n .optional(),\n});\n\nexport type TeamInvitationDetailApi = z.infer<\n typeof teamInvitationDetailApiSchema\n>;\n\n// Request schemas for API endpoints\nexport const createTeamInvitationRequestSchema = z.object({\n email: z.email(),\n role: z.string(),\n processId: z.guid().optional(),\n});\n\nexport type CreateTeamInvitationRequest = z.infer<\n typeof createTeamInvitationRequestSchema\n>;\n\nexport const acceptTeamInvitationRequestSchema = z.object({\n name: z.string().optional(),\n});\n\nexport type AcceptTeamInvitationRequest = z.infer<\n typeof acceptTeamInvitationRequestSchema\n>;\n\n// Response schemas\nexport const bulkInviteResponseSchema = z.object({\n succeeded: z.number(),\n skipped: z.number(),\n failed: z.number(),\n});\nexport type BulkInviteResponse = z.infer<typeof bulkInviteResponseSchema>;\n\nexport const createTeamInvitationResponseSchema = teamInvitationDetailApiSchema;\nexport type CreateTeamInvitationResponse = TeamInvitationDetailApi;\n\nexport const getTeamInvitationResponseSchema = teamInvitationDetailApiSchema;\nexport type GetTeamInvitationResponse = TeamInvitationDetailApi;\n", "import { z } from \"zod\";\n\nimport { agentRunSourceSchema } from \"./agent-run\";\n\n// --- Agents-run endpoint schemas ---\n\nexport const teamInsightsCopilotSchema = z.object({\n id: z.guid(),\n name: z.string(),\n teamName: z.string().nullable().optional(),\n created_at: z.string().nullable(),\n updated_at: z.string().nullable(),\n team_id: z.string().nullable(),\n thread_id: z.string().nullable(),\n slack_enabled: z.boolean().nullable(),\n});\n\nexport const teamInsightsUserProfileSchema = z.object({\n id: z.guid(),\n name: z.string().nullable(),\n email: z.string(),\n});\n\nexport const teamInsightsUserUsageSchema = teamInsightsUserProfileSchema.extend(\n {\n runCount: z.number(),\n lastRun: z.string().nullable(),\n }\n);\n\nexport const teamInsightsMetricSourceSchema = z.object({\n source: agentRunSourceSchema,\n runsTotal: z.number(),\n completedRuns: z.number(),\n});\n\nexport const teamInsightsCopilotWithRunsSchema =\n teamInsightsCopilotSchema.extend({\n integrations: z.array(z.string()),\n uniqueUsersCount: z.number(),\n users: z.array(teamInsightsUserUsageSchema),\n totalRuns: z.number(),\n completedRuns: z.number(),\n totalTimeSpentMs: z.number(),\n averageTimeSpentMs: z.number(),\n completedRunsWithTiming: z.number(),\n sources: z.array(teamInsightsMetricSourceSchema),\n });\n\nexport const teamInsightsAgentsRunResponseSchema = z.object({\n data: z.array(teamInsightsCopilotWithRunsSchema),\n total: z.number(),\n});\n\nexport type TeamInsightsAgentsRunResponse = z.infer<\n typeof teamInsightsAgentsRunResponseSchema\n>;\n\n// --- Metrics endpoint schemas ---\n\nexport const teamInsightsMetricsResponseSchema = z.object({\n runsTotal: z.number(),\n completedRuns: z.number(),\n sources: z.array(teamInsightsMetricSourceSchema),\n});\n\nexport type TeamInsightsMetricsResponse = z.infer<\n typeof teamInsightsMetricsResponseSchema\n>;\n\nexport type TeamInsightsMetricSource = z.infer<\n typeof teamInsightsMetricSourceSchema\n>[\"source\"];\n\n// --- Users endpoint schemas ---\n\nexport const teamInsightsUserAgentRunSchema = z.object({\n id: z.guid(),\n created_at: z.string(),\n updated_at: z.string(),\n agent_id: z.guid(),\n agent_name: z.string(),\n build_id: z.guid(),\n source: z.string().nullable(),\n started_at: z.string().nullable(),\n completed_at: z.string().nullable(),\n});\n\nexport const teamInsightsAgentSchema = z.object({\n id: z.guid(),\n name: z.string(),\n teamName: z.string().nullable().optional(),\n runs: z.array(teamInsightsUserAgentRunSchema),\n});\n\nexport const teamInsightsUserWithAgentsAndRunsSchema =\n teamInsightsUserProfileSchema.extend({\n agents: z.array(teamInsightsAgentSchema),\n runs: z.array(teamInsightsUserAgentRunSchema),\n totalRuns: z.number(),\n });\n\nexport const teamInsightsUsersResponseSchema = z.object({\n data: z.array(teamInsightsUserWithAgentsAndRunsSchema),\n total: z.number(),\n});\n\nexport type TeamInsightsUsersResponse = z.infer<\n typeof teamInsightsUsersResponseSchema\n>;\n", "import { z } from \"zod\";\n\n// Request schemas\nexport const createTeamInviteLinkRequestSchema = z.object({\n frontendUrl: z.url(),\n});\n\nexport type CreateTeamInviteLinkRequest = z.infer<\n typeof createTeamInviteLinkRequestSchema\n>;\n\nexport const getTeamInviteLinkQuerySchema = z.object({\n frontendUrl: z.url(),\n});\n\nexport type GetTeamInviteLinkQuery = z.infer<\n typeof getTeamInviteLinkQuerySchema\n>;\n\n// Response schemas\nexport const teamInviteLinkCreatorSchema = z.object({\n id: z.guid(),\n name: z.string().nullable(),\n email: z.email(),\n});\n\nexport const teamInviteLinkSchema = z.object({\n id: z.guid(),\n url: z.url().optional(),\n createdAt: z.string(),\n createdBy: teamInviteLinkCreatorSchema,\n});\n\nexport type TeamInviteLink = z.infer<typeof teamInviteLinkSchema>;\n\nexport const getTeamInviteLinkResponseSchema = z.object({\n hasLink: z.boolean(),\n link: teamInviteLinkSchema.optional(),\n});\n\nexport type GetTeamInviteLinkResponse = z.infer<\n typeof getTeamInviteLinkResponseSchema\n>;\n\nexport const createTeamInviteLinkResponseSchema = teamInviteLinkSchema;\n\nexport type CreateTeamInviteLinkResponse = z.infer<\n typeof createTeamInviteLinkResponseSchema\n>;\n\n// Join link public info (no auth required)\nexport const joinLinkInfoResponseSchema = z.object({\n valid: z.boolean(),\n teamName: z.string().optional(),\n teamId: z.guid().optional(),\n reason: z.enum([\"invalid\", \"expired\"]).optional(),\n});\n\nexport type JoinLinkInfoResponse = z.infer<typeof joinLinkInfoResponseSchema>;\n\n// Accept join link response\nexport const acceptJoinLinkResponseSchema = z.object({\n success: z.boolean(),\n teamId: z.guid(),\n});\n\nexport type AcceptJoinLinkResponse = z.infer<\n typeof acceptJoinLinkResponseSchema\n>;\n", "/**\n * Utilities for the x-agent-run-api-key header.\n *\n * The header format is \"{runId}:{apiKey}\" and is used to authenticate\n * requests from the agent runtime to MCP servers.\n */\n\n/**\n * The header name for agent run API key authentication.\n */\nexport const AGENT_RUN_API_KEY_HEADER = \"x-agent-run-api-key\";\n\n/**\n * Result of parsing the x-agent-run-api-key header.\n */\nexport interface ParsedAgentRunApiKey {\n runId: string;\n apiKey: string;\n}\n\n/**\n * Parses the x-agent-run-api-key header format: \"{runId}:{apiKey}\"\n * Returns null if the header is missing or malformed.\n */\nexport const parseAgentRunApiKeyHeader = (\n agentRunApiKey: string | undefined\n): ParsedAgentRunApiKey | null => {\n if (!agentRunApiKey) {\n return null;\n }\n\n const parts = agentRunApiKey.split(\":\");\n if (parts.length !== 2) {\n return null;\n }\n\n const [runId, apiKey] = parts.map((s) => s.trim());\n if (!runId || !apiKey) {\n return null;\n }\n\n return { runId, apiKey };\n};\n\n/**\n * Builds the x-agent-run-api-key header value from runId and apiKey.\n * Format: \"{runId}:{apiKey}\"\n */\nexport const buildAgentRunApiKeyHeader = (\n runId: string,\n apiKey: string\n): string => {\n return `${runId}:${apiKey}`;\n};\n", "import { z } from \"zod\";\n\nexport type LabelFilters = Record<string, string[]>;\n\nexport const caseFilterStatusSchema = z.enum([\n \"pending\",\n \"claimed\",\n \"completed\",\n \"failed\",\n \"needs_input\",\n \"postponed\",\n]);\n\nexport type CaseFilterStatus = z.infer<typeof caseFilterStatusSchema>;\n\nexport const casesFiltersSchema = z.object({\n status: z.array(caseFilterStatusSchema).optional(),\n created_at_from: z.string().optional(),\n updated_at_from: z.string().optional(),\n labels: z.record(z.string(), z.array(z.string())).optional(),\n});\n\nexport type CasesFilters = z.infer<typeof casesFiltersSchema>;\n\nexport const casesListRequestBodySchema = z.object({\n filters: casesFiltersSchema.default({}),\n limit: z.int().min(1).max(100).default(25),\n offset: z.int().min(0).default(0),\n sort_by: z\n .enum([\"created_at\", \"updated_at\", \"postponed_to\"])\n .default(\"created_at\"),\n sort_order: z.enum([\"asc\", \"desc\"]).default(\"desc\"),\n search: z.string().optional(),\n});\n\nexport type CasesListRequestBody = z.infer<typeof casesListRequestBodySchema>;\n\nexport interface CasesListRequestOptions {\n limit: number;\n offset: number;\n sort_by: \"created_at\" | \"updated_at\" | \"postponed_to\";\n sort_order: \"asc\" | \"desc\";\n search?: string;\n}\n\nfunction toBase64(input: string): string {\n if (typeof btoa === \"function\") {\n return btoa(unescape(encodeURIComponent(input)));\n }\n return Buffer.from(input, \"utf-8\").toString(\"base64\");\n}\n\nfunction fromBase64(input: string): string {\n if (typeof atob === \"function\") {\n return decodeURIComponent(escape(atob(input)));\n }\n return Buffer.from(input, \"base64\").toString(\"utf-8\");\n}\n\nexport function parseLabelsFromUrlParam(\n param: string | null | undefined\n): LabelFilters {\n if (!param) {\n return {};\n }\n try {\n const parsed: unknown = JSON.parse(fromBase64(param));\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return {};\n }\n const result: LabelFilters = {};\n for (const [key, values] of Object.entries(parsed)) {\n if (Array.isArray(values) && values.every((v) => typeof v === \"string\")) {\n result[key] = values as string[];\n }\n }\n return result;\n } catch {\n return {};\n }\n}\n\nexport function serializeLabelsToUrlParam(labels: LabelFilters): string {\n return toBase64(JSON.stringify(labels));\n}\n\n/**\n * All filters serialize into a single `f` URL param as base64-encoded JSON.\n */\nexport const FILTERS_URL_PARAM = \"f\";\n\nexport function serializeCasesFiltersToUrlParam(filters: CasesFilters): string {\n if (isCasesFiltersEmpty(filters)) {\n return \"\";\n }\n return toBase64(JSON.stringify(filters));\n}\n\nexport function parseCasesFiltersFromUrlParam(\n value: string | null | undefined\n): CasesFilters {\n if (!value) {\n return {};\n }\n try {\n const parsed: unknown = JSON.parse(fromBase64(value));\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return {};\n }\n const result = casesFiltersSchema.safeParse(parsed);\n return result.success ? result.data : {};\n } catch {\n return {};\n }\n}\n\nconst LABEL_PREFIX = \"label:\";\n\n/** Read the values for a dropdown category key from typed CasesFilters. */\nexport function getFilterValuesByCategoryKey(\n filters: CasesFilters,\n categoryKey: string\n): string[] {\n if (categoryKey === \"status\") {\n return filters.status ?? [];\n }\n if (categoryKey === \"created_at_from\") {\n return filters.created_at_from ? [filters.created_at_from] : [];\n }\n if (categoryKey === \"updated_at_from\") {\n return filters.updated_at_from ? [filters.updated_at_from] : [];\n }\n if (categoryKey.startsWith(LABEL_PREFIX)) {\n const labelKey = categoryKey.slice(LABEL_PREFIX.length);\n return filters.labels?.[labelKey] ?? [];\n }\n return [];\n}\n\n/** Update a category's values, returning a new CasesFilters. Empty clears. */\nexport function setFilterValuesByCategoryKey(\n filters: CasesFilters,\n categoryKey: string,\n values: string[]\n): CasesFilters {\n if (categoryKey === \"status\") {\n if (values.length === 0) {\n const { status: _, ...rest } = filters;\n return rest;\n }\n const parsed = z.array(caseFilterStatusSchema).safeParse(values);\n if (!parsed.success) {\n return filters;\n }\n return { ...filters, status: parsed.data };\n }\n if (categoryKey === \"created_at_from\") {\n if (values.length === 0 || !values[0]) {\n const { created_at_from: _, ...rest } = filters;\n return rest;\n }\n return { ...filters, created_at_from: values[0] };\n }\n if (categoryKey === \"updated_at_from\") {\n if (values.length === 0 || !values[0]) {\n const { updated_at_from: _, ...rest } = filters;\n return rest;\n }\n return { ...filters, updated_at_from: values[0] };\n }\n if (categoryKey.startsWith(LABEL_PREFIX)) {\n const labelKey = categoryKey.slice(LABEL_PREFIX.length);\n const nextLabels = { ...(filters.labels ?? {}) };\n if (values.length === 0) {\n delete nextLabels[labelKey];\n } else {\n nextLabels[labelKey] = values;\n }\n if (Object.keys(nextLabels).length === 0) {\n const { labels: _, ...rest } = filters;\n return rest;\n }\n return { ...filters, labels: nextLabels };\n }\n return filters;\n}\n\nexport function removeFilterByCategoryKey(\n filters: CasesFilters,\n categoryKey: string\n): CasesFilters {\n return setFilterValuesByCategoryKey(filters, categoryKey, []);\n}\n\nexport function isCasesFiltersEmpty(filters: CasesFilters): boolean {\n return (\n !filters.status?.length &&\n !filters.created_at_from &&\n !filters.updated_at_from &&\n (!filters.labels || Object.keys(filters.labels).length === 0)\n );\n}\n\nexport function countCasesFilters(filters: CasesFilters): number {\n let count = 0;\n if (filters.status?.length) {\n count += 1;\n }\n if (filters.created_at_from) {\n count += 1;\n }\n if (filters.updated_at_from) {\n count += 1;\n }\n if (filters.labels) {\n count += Object.keys(filters.labels).length;\n }\n return count;\n}\n", "import { COMPOSIO_AUTH_CONFIGS } from \"../types/composio\";\nimport { IntegrationSlug } from \"../types/integration\";\n\nexport const getAppSpecBySlug = (slug: string) =>\n COMPOSIO_AUTH_CONFIGS.find((a) => a.slug === (slug as IntegrationSlug));\n", "export function normalizeDomain(value: string): string {\n return (value || \"\")\n .trim()\n .toLowerCase()\n .replace(/^www\\./, \"\");\n}\n\nexport function deriveDomain(input: string): string {\n let value = (input || \"\").trim().toLowerCase();\n if (!value) {\n return value;\n }\n const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\//.test(value);\n if (hasScheme) {\n try {\n const u = new URL(value);\n value = u.hostname;\n } catch {\n // fall back to original value on parse failure\n }\n } else {\n const stopIdx = [\"/\", \"?\", \"#\"].reduce((idx, ch) => {\n const i = value.indexOf(ch);\n return i !== -1 && (idx === -1 || i < idx) ? i : idx;\n }, -1);\n if (stopIdx !== -1) {\n value = value.slice(0, stopIdx);\n }\n const colon = value.indexOf(\":\");\n if (colon > -1) {\n value = value.slice(0, colon);\n }\n }\n return normalizeDomain(value);\n}\n\n/**\n * Server-compatible variant that returns undefined for empty input\n */\nexport function deriveHostnameFromInput(input?: string): string | undefined {\n if (!input) {\n return undefined;\n }\n const value = deriveDomain(input);\n return value ? value : undefined;\n}\n", "// Matches the on-disk `<DUVO:AGENT id=\"...\" name=\"...\">` tag shape produced\n// by the agent-instructions textarea. The escape pair `\\\\.` lets `\\\"` and\n// `\\\\` round-trip through the attribute values.\nconst AGENT_MENTION_REGEX_SOURCE = `<DUVO:AGENT\\\\s+id=\"((?:[^\"\\\\\\\\]|\\\\\\\\.)*)\"\\\\s+name=\"((?:[^\"\\\\\\\\]|\\\\\\\\.)*)\">`;\n\nfunction unescapeAttrValue(value: string): string {\n return value.replace(/\\\\(.)/g, \"$1\");\n}\n\n/**\n * Extracts unique agent IDs referenced by `<DUVO:AGENT>` mentions in SOP\n * text. Used to keep a build's handover target list in sync with the agents\n * mentioned in the SOP \u2014 the source of truth for which agents are valid\n * handover targets.\n */\nexport function extractAgentMentionIds(text: string): string[] {\n if (!text) {\n return [];\n }\n\n const regex = new RegExp(AGENT_MENTION_REGEX_SOURCE, \"g\");\n const ids = new Set<string>();\n for (const match of text.matchAll(regex)) {\n ids.add(unescapeAttrValue(match[1]));\n }\n\n return Array.from(ids);\n}\n", "import type { InputContent } from \"../types/agent-config\";\nimport type { EditableAgentConfig } from \"./normalize-agent-config\";\n\n/**\n * Extracts the system prompt text from an agent config's input field.\n *\n * Handles all input shapes:\n * - A plain string (legacy configs)\n * - An array of messages where the system role message contains the SOP\n * - Content can be a string or an array of typed content blocks\n */\nexport function extractSystemPromptText(\n input: EditableAgentConfig[\"input\"] | undefined | null\n): string {\n if (!input) {\n return \"\";\n }\n\n if (typeof input === \"string\") {\n return input;\n }\n\n if (!Array.isArray(input) || input.length === 0) {\n return \"\";\n }\n\n const systemMessage = input.find((msg) => msg.role === \"system\");\n if (!systemMessage?.content) {\n return \"\";\n }\n\n if (typeof systemMessage.content === \"string\") {\n return systemMessage.content;\n }\n\n if (Array.isArray(systemMessage.content)) {\n const textContent = systemMessage.content.find(\n (c): c is Extract<InputContent, { type: \"input_text\" }> =>\n c.type === \"input_text\"\n );\n return textContent?.text ?? \"\";\n }\n\n return \"\";\n}\n", "export type SentryEnvironment = \"development\" | \"staging\" | \"production\";\n\nconst VALID_ENVIRONMENTS: Record<SentryEnvironment, SentryEnvironment> = {\n development: \"development\",\n staging: \"staging\",\n production: \"production\",\n};\n\nconst ALIAS_MAP: Record<string, SentryEnvironment> = {\n \"vercel-preview\": \"staging\",\n \"vercel-production\": \"production\",\n};\n\nfunction normalize(value: string | undefined | null) {\n return value?.toLowerCase().trim();\n}\n\n/**\n * Restrict Sentry environment values to the canonical trio the team expects.\n * Only the exact names development/staging/production are retained, with\n * vercel-preview mapped to staging and vercel-production mapped to production.\n * The first match is used; fallback is development.\n */\nexport function getSentryEnvironment(\n ...candidates: Array<string | undefined | null>\n): SentryEnvironment {\n for (const candidate of candidates) {\n const normalized = normalize(candidate);\n\n if (!normalized) {\n continue;\n }\n\n if (normalized in ALIAS_MAP) {\n return ALIAS_MAP[normalized];\n }\n\n if (normalized in VALID_ENVIRONMENTS) {\n return VALID_ENVIRONMENTS[normalized as SentryEnvironment];\n }\n }\n\n return \"development\";\n}\n", "import type { InputContent } from \"../types/agent-config\";\nimport type { EditableAgentConfig } from \"./normalize-agent-config\";\n\n/**\n * Checks if an agent config has non-empty instructions (SOP content).\n *\n * Instructions can be:\n * - A non-empty string\n * - An array with a system message containing non-empty text content\n */\nexport function hasInstructions(\n input: EditableAgentConfig[\"input\"] | undefined | null\n): boolean {\n if (!input) {\n return false;\n }\n\n if (typeof input === \"string\") {\n return Boolean(input.trim());\n }\n\n if (!Array.isArray(input) || input.length === 0) {\n return false;\n }\n\n const systemMessage = input.find((msg) => msg.role === \"system\");\n if (!systemMessage?.content) {\n return false;\n }\n\n if (typeof systemMessage.content === \"string\") {\n return Boolean(systemMessage.content.trim());\n }\n\n if (Array.isArray(systemMessage.content)) {\n const textContent = systemMessage.content.find(\n (c): c is Extract<InputContent, { type: \"input_text\" }> =>\n c.type === \"input_text\"\n );\n return Boolean(textContent?.text?.trim());\n }\n\n return false;\n}\n", "import { jsonrepair } from \"jsonrepair\";\nimport type { z, ZodType } from \"zod\";\n\ninterface Logger {\n warn: (obj: Record<string, unknown>, msg: string) => void;\n}\n\nexport function safeParseJson<S extends ZodType>(\n input: string,\n log: Logger,\n schema: S\n): z.output<S> {\n let raw: unknown;\n try {\n raw = JSON.parse(input);\n } catch (parseError) {\n log.warn(\n { error: parseError },\n \"Input contains invalid JSON, attempting repair\"\n );\n try {\n const repaired = jsonrepair(input);\n raw = JSON.parse(repaired);\n } catch (repairError) {\n throw new Error(\n `Failed to parse input even after repair: ${repairError instanceof Error ? repairError.message : String(repairError)}`\n );\n }\n }\n\n return schema.parse(raw);\n}\n", "export const BASE_HUES = [0, 30, 50, 90, 145, 175, 215, 270, 330] as const;\n\nexport type LabelHue = (typeof BASE_HUES)[number];\n\nexport function isLabelHue(value: number): value is LabelHue {\n return (BASE_HUES as readonly number[]).includes(value);\n}\n", "/**\n * MCP Server Label Utilities\n *\n * Unified functions for generating and parsing MCP server labels across\n * backend and frontend. Ensures consistent format for tool identification.\n *\n * Server label formats:\n * - Default integrations: \"{integration_type}\" (e.g., \"browser-agent-devtools\")\n * - Integrations with instances: \"{integration_type}_{instance_id_uuid}\" (e.g., \"gmail_2bf44658-....\", \"custom_mcp_bb92426d-....\")\n */\n\n/**\n * Generates a unique MCP server label for an integration instance.\n *\n * @param integrationType - The integration type slug (e.g., \"gmail\", \"custom_mcp\")\n * @param instanceId - The integration instance UUID (null for default integrations)\n * @returns The generated server label\n *\n * @example\n * // Default integration (no instance)\n * generateMcpServerLabel(\"browser-agent-devtools\", null) // \"browser-agent-devtools\"\n *\n * @example\n * // OAuth integration\n * generateMcpServerLabel(\"gmail\", \"2bf44658-...\") // \"gmail_2bf44658-...\"\n *\n * @example\n * // Custom MCP\n * generateMcpServerLabel(\"custom_mcp\", \"bb92426d-...\") // \"custom_mcp_bb92426d-...\"\n */\nexport function generateMcpServerLabel(\n integrationType: string,\n instanceId: string | null\n): string {\n if (!instanceId) {\n // Default integrations (browser-agent-devtools, exa, etc.) have no instances\n return integrationType;\n }\n\n // Append full instance UUID for unambiguous lookup\n return `${integrationType}_${instanceId}`;\n}\n\nexport interface ParsedMcpServerLabel {\n /** The base integration type slug (e.g., \"custom_mcp\", \"gmail\", \"browser-agent-devtools\") */\n integrationType: string;\n /** The full instance UUID (preferred) or legacy 8-char prefix, or null for default integrations */\n instanceId: string | null;\n}\n\n/**\n * Parses an MCP server label to extract its components.\n *\n * @param serverLabel - The server label to parse\n * @returns Parsed components including integration type and instance ID\n *\n * @example\n * // Default integration\n * parseMcpServerLabel(\"browser-agent-devtools\")\n * // { integrationType: \"browser-agent-devtools\", instanceId: null }\n *\n * @example\n * // OAuth integration\n * parseMcpServerLabel(\"gmail_2bf44658-6dbd-4c39-8ad1-7f4a0d2dcb2a\")\n * // { integrationType: \"gmail\", instanceId: \"2bf44658-6dbd-4c39-8ad1-7f4a0d2dcb2a\" }\n *\n * @example\n * // Custom MCP\n * parseMcpServerLabel(\"custom_mcp_bb92426d-6dbd-4c39-8ad1-7f4a0d2dcb2a\")\n * // { integrationType: \"custom_mcp\", instanceId: \"bb92426d-6dbd-4c39-8ad1-7f4a0d2dcb2a\" }\n */\nexport function parseMcpServerLabel(serverLabel: string): ParsedMcpServerLabel {\n // Prefer full UUIDs (supports optional trailing suffixes like `_1` when names\n // need to be disambiguated by the runtime).\n const uuidPattern =\n /_([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})(?=$|_)/gi;\n let uuidMatch: RegExpExecArray | null = null;\n for (let match = uuidPattern.exec(serverLabel); match; ) {\n uuidMatch = match;\n match = uuidPattern.exec(serverLabel);\n }\n\n if (uuidMatch) {\n const instanceId = uuidMatch[1] ?? null;\n const integrationType = serverLabel.slice(0, uuidMatch.index);\n return { integrationType, instanceId };\n }\n\n // Legacy format: _[8 hex chars] (also supports optional trailing suffixes).\n const legacyPattern = /_([a-f0-9]{8})(?=$|_)/gi;\n let legacyMatch: RegExpExecArray | null = null;\n for (let match = legacyPattern.exec(serverLabel); match; ) {\n legacyMatch = match;\n match = legacyPattern.exec(serverLabel);\n }\n\n if (legacyMatch) {\n const instanceId = legacyMatch[1] ?? null;\n const integrationType = serverLabel.slice(0, legacyMatch.index);\n return { integrationType, instanceId };\n }\n\n // No instance ID suffix - this is a default integration\n return {\n integrationType: serverLabel,\n instanceId: null,\n };\n}\n\n/**\n * Extracts only the integration type slug from a server label.\n * Convenience wrapper around parseMcpServerLabel.\n *\n * @param serverLabel - The server label to parse\n * @returns The integration type slug\n *\n * @example\n * extractIntegrationTypeFromServerLabel(\"gmail_2bf44658-...\") // \"gmail\"\n * extractIntegrationTypeFromServerLabel(\"custom_mcp_bb92426d-...\") // \"custom_mcp\"\n */\nexport function extractIntegrationTypeFromServerLabel(\n serverLabel: string\n): string {\n return parseMcpServerLabel(serverLabel).integrationType;\n}\n", "import {\n type BrowsingModelId,\n type BrowsingProvider,\n CLAUDE_MODEL_IDS,\n type ClaudeModelId,\n type CoreClaudeModelId,\n LEGACY_DEFAULT_MODEL,\n PLATFORM_DEFAULT_MODELS,\n} from \"../constants/models\";\nimport type {\n AgentConfigV1,\n AgentConfigV2,\n RuntimeOptions,\n} from \"../types/agent-config\";\n\ntype InputMessage = Extract<AgentConfigV2[\"input\"], Array<unknown>>[number];\n\n/**\n * Normalized config format for UI editing\n */\nexport interface EditableAgentConfig {\n models: {\n agent: {\n model: ClaudeModelId;\n };\n browsing: {\n provider: BrowsingProvider;\n model: BrowsingModelId;\n };\n };\n input: string | InputMessage[];\n files?: string[];\n skills?: string[];\n plugins?: string[];\n subAgents?: string[];\n options?: RuntimeOptions;\n}\n\nexport function normalizeToEditableConfig(\n config: AgentConfigV1 | AgentConfigV2 | EditableAgentConfig\n): EditableAgentConfig {\n // Check if config has v2 nested models structure\n const hasNestedModels =\n \"models\" in config && config.models?.agent !== undefined;\n\n if (hasNestedModels && config.models) {\n // v2 config with nested structure\n const rawModel = config.models.agent.model;\n const isValidCoreModel =\n !!rawModel && CLAUDE_MODEL_IDS.includes(rawModel as CoreClaudeModelId);\n\n return {\n models: {\n agent: {\n model: isValidCoreModel ? rawModel : LEGACY_DEFAULT_MODEL,\n },\n browsing: {\n provider:\n config.models.browsing?.provider ??\n PLATFORM_DEFAULT_MODELS.browsing.provider,\n model:\n config.models.browsing?.model ??\n PLATFORM_DEFAULT_MODELS.browsing.model,\n },\n },\n input: config.input ?? \"\",\n files: config.files ?? [],\n skills: config.skills ?? [],\n plugins: (\"plugins\" in config ? config.plugins : undefined) ?? [],\n subAgents: (\"subAgents\" in config ? config.subAgents : undefined) ?? [],\n options: config.options,\n };\n }\n\n // v1 config with flat structure \u2014 any stored model (including missing) resolves\n // to LEGACY_DEFAULT_MODEL. Browsing uses platform defaults since v1 never\n // carried a browsing provider/model.\n return {\n models: {\n agent: { model: LEGACY_DEFAULT_MODEL },\n browsing: {\n provider: PLATFORM_DEFAULT_MODELS.browsing.provider,\n model: PLATFORM_DEFAULT_MODELS.browsing.model,\n },\n },\n input: config.input ?? \"\",\n files: config.files ?? [],\n skills: config.skills ?? [],\n plugins: [], // v1 configs don't have plugins\n subAgents: [], // v1 configs don't have subAgents\n };\n}\n\nexport function normalizeForDatabase(\n config: EditableAgentConfig\n): AgentConfigV2 {\n return {\n ...config,\n files: config.files ?? [],\n skills: config.skills ?? [],\n plugins: config.plugins ?? [],\n subAgents: config.subAgents ?? [],\n };\n}\n", "/** Throw this inside a pRetry callback to abort immediately without retrying. */\nexport class AbortError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AbortError\";\n }\n}\n\n/**\n * Retries a promise-returning function with exponential backoff.\n * Throw AbortError to stop retrying immediately.\n *\n * @param fn - The async function to retry\n * @param retries - Maximum number of retry attempts (default: 3)\n * @returns The resolved value of `fn`\n */\nexport async function pRetry<T>(fn: () => Promise<T>, retries = 3): Promise<T> {\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n // eslint-disable-next-line no-await-in-loop\n return await fn();\n } catch (err) {\n if (err instanceof AbortError || attempt === retries) {\n throw err;\n }\n // eslint-disable-next-line no-await-in-loop\n await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 100));\n }\n }\n throw new Error(\"pRetry: unreachable\");\n}\n", "import {\n mapModelToClaudeModel,\n PLATFORM_DEFAULT_MODELS,\n} from \"../constants/models\";\nimport {\n AgentConfigSchema,\n type AgentConfigV2,\n StoredAgentConfigSchemaV1,\n StoredAgentConfigSchemaV2,\n} from \"../types/agent-config\";\n\nexport interface ParseAgentConfigOptions {\n buildId?: string;\n expectedVersion?: string;\n}\n\nexport interface ParseAgentConfigResult {\n config: AgentConfigV2 | null;\n error?: string;\n isLegacyFormat?: boolean;\n versionMismatch?: boolean;\n version?: \"v1\" | \"v2\";\n}\n\nexport function parseAgentConfig(\n configJson: unknown,\n options: ParseAgentConfigOptions = {}\n): ParseAgentConfigResult {\n if (!configJson) {\n return { config: null };\n }\n\n try {\n const parsed =\n typeof configJson === \"string\" ? JSON.parse(configJson) : configJson;\n\n // Check if this is a versioned config\n if (parsed.version && parsed.data) {\n // Try v2 first\n const v2Result = StoredAgentConfigSchemaV2.safeParse(parsed);\n if (v2Result.success) {\n const data = v2Result.data.data;\n\n // v2 always has nested models structure\n // Normalize legacy model IDs (gpt-*, duvo-1-max) to Claude model IDs\n const resolvedConfig: AgentConfigV2 = {\n ...data,\n models: {\n agent: {\n model: mapModelToClaudeModel(data.models.agent.model),\n },\n browsing: {\n provider:\n data.models.browsing.provider ??\n PLATFORM_DEFAULT_MODELS.browsing.provider,\n model:\n data.models.browsing.model ??\n PLATFORM_DEFAULT_MODELS.browsing.model,\n },\n },\n };\n\n // Check version compatibility\n const versionMismatch = options.expectedVersion\n ? v2Result.data.version !== options.expectedVersion\n : undefined;\n\n return {\n config: resolvedConfig,\n version: \"v2\",\n versionMismatch,\n };\n }\n\n // Try v1 and convert to v2 format\n const v1Result = StoredAgentConfigSchemaV1.safeParse(parsed);\n if (v1Result.success) {\n const storedConfig = v1Result.data;\n const v1Data = storedConfig.data;\n\n // Convert v1 flat structure to v2 nested structure\n // Map legacy model IDs (gpt-*, duvo-1-max) to Claude model IDs\n const convertedConfig: AgentConfigV2 = {\n models: {\n agent: {\n model: mapModelToClaudeModel(v1Data.model),\n },\n browsing: {\n provider: PLATFORM_DEFAULT_MODELS.browsing.provider,\n model: PLATFORM_DEFAULT_MODELS.browsing.model,\n },\n },\n input: v1Data.input ?? \"\",\n files: v1Data.files ?? [],\n skills: v1Data.skills ?? [],\n plugins: [],\n subAgents: [],\n };\n\n // Check version compatibility\n const versionMismatch = options.expectedVersion\n ? storedConfig.version !== options.expectedVersion\n : undefined;\n\n return {\n config: convertedConfig,\n version: \"v1\",\n versionMismatch,\n };\n }\n\n // Both failed\n const errorMessage = options.buildId\n ? `Invalid versioned config format for build ${options.buildId}: ${v2Result.error.message}`\n : `Invalid versioned config format: ${v2Result.error.message}`;\n\n return {\n config: null,\n error: errorMessage,\n };\n } else {\n // Legacy format - validate config directly with Zod\n const result = AgentConfigSchema.safeParse(parsed);\n if (!result.success) {\n const errorMessage = options.buildId\n ? `Invalid legacy config format for build ${options.buildId}: ${result.error.message}`\n : `Invalid legacy config format: ${result.error.message}`;\n\n return {\n config: null,\n error: errorMessage,\n isLegacyFormat: true,\n };\n }\n\n return {\n config: result.data,\n isLegacyFormat: true,\n };\n }\n } catch (error) {\n const errorMessage = options.buildId\n ? `Failed to parse config for build ${options.buildId}: ${error}`\n : `Failed to parse config: ${error}`;\n\n return {\n config: null,\n error: errorMessage,\n };\n }\n}\n", "import { LEGACY_DEFAULT_BROWSER_PROVIDER } from \"../constants/agent\";\nimport { BrowserProviderType } from \"../types/agent-config\";\nimport {\n isStoredRunConfigV0,\n isStoredRunConfigV1,\n RunConfig,\n StoredRunConfigSchema,\n StoredRunConfigV1,\n} from \"../types/run-config\";\n\nexport interface ParseRunConfigResult {\n config: RunConfig | null;\n version: \"v0\" | \"v1\" | null;\n error?: string;\n}\n\n/**\n * Parses a stored run config from JSON (string or object).\n * Returns the inner RunConfig for v1, null for v0.\n *\n * Handles:\n * - V1: {version: \"v1\", data: RunConfig} \u2192 returns data\n * - V0: {version: \"v0\"} \u2192 returns null (legacy placeholder)\n * - null/undefined \u2192 returns null\n * - Invalid format \u2192 returns null with error\n */\nexport function parseRunConfig(configJson: unknown): ParseRunConfigResult {\n if (configJson == null) {\n return { config: null, version: null };\n }\n\n try {\n const parsed =\n typeof configJson === \"string\" ? JSON.parse(configJson) : configJson;\n\n const result = StoredRunConfigSchema.safeParse(parsed);\n\n if (result.success) {\n if (isStoredRunConfigV1(result.data)) {\n return { config: result.data.data, version: \"v1\" };\n }\n if (isStoredRunConfigV0(result.data)) {\n return { config: null, version: \"v0\" };\n }\n }\n\n return {\n config: null,\n version: null,\n error: `Invalid run config format: ${result.error?.message ?? \"unknown error\"}`,\n };\n } catch (error) {\n return {\n config: null,\n version: null,\n error: `Failed to parse run config JSON: ${error}`,\n };\n }\n}\n\n/**\n * Convenience function to check if a stored config has dispatchable data.\n * Returns true only for V1 configs (which have the full RunConfig data).\n */\nexport function hasDispatchableRunConfig(configJson: unknown): boolean {\n const { config } = parseRunConfig(configJson);\n return config !== null;\n}\n\n/**\n * Creates a StoredRunConfigV1 wrapper around a RunConfig.\n */\nexport function wrapRunConfig(config: RunConfig): StoredRunConfigV1 {\n return { version: \"v1\", data: config };\n}\n\n/**\n * Extracts browser provider from a parsed RunConfig.\n *\n * Resolution order:\n * 1. config.options.browserProvider (if set)\n * 2. LEGACY_DEFAULT_BROWSER_PROVIDER (browserbase)\n *\n * This ensures backward compatibility for legacy runs that were created\n * before browserProvider was added to the config.\n *\n * @param config - The parsed RunConfig from parseRunConfig()\n * @returns The browser provider type to use for this run\n */\nexport function getBrowserProviderFromRunConfig(\n config: RunConfig | null\n): BrowserProviderType {\n if (config?.options?.browserProvider) {\n return config.options.browserProvider;\n }\n return LEGACY_DEFAULT_BROWSER_PROVIDER;\n}\n", "export class JSONRepairError extends Error {\n position: number\n\n constructor(message: string, position: number) {\n super(`${message} at position ${position}`)\n\n this.position = position\n }\n}\n", "const codeSpace = 0x20 // \" \"\nconst codeNewline = 0xa // \"\\n\"\nconst codeTab = 0x9 // \"\\t\"\nconst codeReturn = 0xd // \"\\r\"\nconst codeNonBreakingSpace = 0xa0\nconst codeEnQuad = 0x2000\nconst codeHairSpace = 0x200a\nconst codeNarrowNoBreakSpace = 0x202f\nconst codeMediumMathematicalSpace = 0x205f\nconst codeIdeographicSpace = 0x3000\n\nexport function isHex(char: string): boolean {\n return /^[0-9A-Fa-f]$/.test(char)\n}\n\nexport function isDigit(char: string): boolean {\n return char >= '0' && char <= '9'\n}\n\nexport function isValidStringCharacter(char: string): boolean {\n // note that the valid range is between \\u{0020} and \\u{10ffff},\n // but in JavaScript it is not possible to create a code point larger than\n // \\u{10ffff}, so there is no need to test for that here.\n return char >= '\\u0020'\n}\n\nexport function isDelimiter(char: string): boolean {\n return ',:[]/{}()\\n+'.includes(char)\n}\n\nexport function isFunctionNameCharStart(char: string) {\n return (\n (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || char === '_' || char === '$'\n )\n}\n\nexport function isFunctionNameChar(char: string) {\n return (\n (char >= 'a' && char <= 'z') ||\n (char >= 'A' && char <= 'Z') ||\n char === '_' ||\n char === '$' ||\n (char >= '0' && char <= '9')\n )\n}\n\n// matches \"https://\" and other schemas\nexport const regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\\/\\/$/\n\n// matches all valid URL characters EXCEPT \"[\", \"]\", and \",\", since that are important JSON delimiters\nexport const regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/\n\nexport function isUnquotedStringDelimiter(char: string): boolean {\n return ',[]/{}\\n+'.includes(char)\n}\n\nexport function isStartOfValue(char: string): boolean {\n return isQuote(char) || regexStartOfValue.test(char)\n}\n\n// alpha, number, minus, or opening bracket or brace\nconst regexStartOfValue = /^[[{\\w-]$/\n\nexport function isControlCharacter(char: string) {\n return char === '\\n' || char === '\\r' || char === '\\t' || char === '\\b' || char === '\\f'\n}\n\nexport interface Text {\n charCodeAt: (index: number) => number\n}\n\n/**\n * Check if the given character is a whitespace character like space, tab, or\n * newline\n */\nexport function isWhitespace(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn\n}\n\n/**\n * Check if the given character is a whitespace character like space or tab,\n * but NOT a newline\n */\nexport function isWhitespaceExceptNewline(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return code === codeSpace || code === codeTab || code === codeReturn\n}\n\n/**\n * Check if the given character is a special whitespace character, some\n * unicode variant\n */\nexport function isSpecialWhitespace(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return (\n code === codeNonBreakingSpace ||\n (code >= codeEnQuad && code <= codeHairSpace) ||\n code === codeNarrowNoBreakSpace ||\n code === codeMediumMathematicalSpace ||\n code === codeIdeographicSpace\n )\n}\n\n/**\n * Test whether the given character is a quote or double quote character.\n * Also tests for special variants of quotes.\n */\nexport function isQuote(char: string): boolean {\n // the first check double quotes, since that occurs most often\n return isDoubleQuoteLike(char) || isSingleQuoteLike(char)\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Also tests for special variants of double quotes.\n */\nexport function isDoubleQuoteLike(char: string): boolean {\n return char === '\"' || char === '\\u201c' || char === '\\u201d'\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Does NOT test for special variants of double quotes.\n */\nexport function isDoubleQuote(char: string): boolean {\n return char === '\"'\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Also tests for special variants of single quotes.\n */\nexport function isSingleQuoteLike(char: string): boolean {\n return (\n char === \"'\" || char === '\\u2018' || char === '\\u2019' || char === '\\u0060' || char === '\\u00b4'\n )\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Does NOT test for special variants of single quotes.\n */\nexport function isSingleQuote(char: string): boolean {\n return char === \"'\"\n}\n\n/**\n * Strip last occurrence of textToStrip from text\n */\nexport function stripLastOccurrence(\n text: string,\n textToStrip: string,\n stripRemainingText = false\n): string {\n const index = text.lastIndexOf(textToStrip)\n return index !== -1\n ? text.substring(0, index) + (stripRemainingText ? '' : text.substring(index + 1))\n : text\n}\n\nexport function insertBeforeLastWhitespace(text: string, textToInsert: string): string {\n let index = text.length\n\n if (!isWhitespace(text, index - 1)) {\n // no trailing whitespaces\n return text + textToInsert\n }\n\n while (isWhitespace(text, index - 1)) {\n index--\n }\n\n return text.substring(0, index) + textToInsert + text.substring(index)\n}\n\nexport function removeAtIndex(text: string, start: number, count: number) {\n return text.substring(0, start) + text.substring(start + count)\n}\n\n/**\n * Test whether a string ends with a newline or comma character and optional whitespace\n */\nexport function endsWithCommaOrNewline(text: string): boolean {\n return /[,\\n][ \\t\\r]*$/.test(text)\n}\n", "import { JSONRepairError } from '../utils/JSONRepairError.js'\nimport {\n endsWithCommaOrNewline,\n insertBeforeLastWhitespace,\n isControlCharacter,\n isDelimiter,\n isDigit,\n isDoubleQuote,\n isDoubleQuoteLike,\n isFunctionNameChar,\n isFunctionNameCharStart,\n isHex,\n isQuote,\n isSingleQuote,\n isSingleQuoteLike,\n isSpecialWhitespace,\n isStartOfValue,\n isUnquotedStringDelimiter,\n isValidStringCharacter,\n isWhitespace,\n isWhitespaceExceptNewline,\n regexUrlChar,\n regexUrlStart,\n removeAtIndex,\n stripLastOccurrence\n} from '../utils/stringUtils.js'\n\nconst controlCharacters: { [key: string]: string } = {\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t'\n}\n\n// map with all escape characters\nconst escapeCharacters: { [key: string]: string } = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t'\n // note that \\u is handled separately in parseString()\n}\n\n/**\n * Repair a string containing an invalid JSON document.\n * For example changes JavaScript notation into JSON notation.\n *\n * Example:\n *\n * try {\n * const json = \"{name: 'John'}\"\n * const repaired = jsonrepair(json)\n * console.log(repaired)\n * // '{\"name\": \"John\"}'\n * } catch (err) {\n * console.error(err)\n * }\n *\n */\nexport function jsonrepair(text: string): string {\n let i = 0 // current index in text\n let output = '' // generated output\n\n parseMarkdownCodeBlock(['```', '[```', '{```'])\n\n const processed = parseValue()\n if (!processed) {\n throwUnexpectedEnd()\n }\n\n parseMarkdownCodeBlock(['```', '```]', '```}'])\n\n const processedComma = parseCharacter(',')\n if (processedComma) {\n parseWhitespaceAndSkipComments()\n }\n\n if (isStartOfValue(text[i]) && endsWithCommaOrNewline(output)) {\n // start of a new value after end of the root level object: looks like\n // newline delimited JSON -> turn into a root level array\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n\n parseNewlineDelimitedJSON()\n } else if (processedComma) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',')\n }\n\n // repair redundant end quotes\n while (text[i] === '}' || text[i] === ']') {\n i++\n parseWhitespaceAndSkipComments()\n }\n\n if (i >= text.length) {\n // reached the end of the document properly\n return output\n }\n\n throwUnexpectedCharacter()\n\n function parseValue(): boolean {\n parseWhitespaceAndSkipComments()\n const processed =\n parseObject() ||\n parseArray() ||\n parseString() ||\n parseNumber() ||\n parseKeywords() ||\n parseUnquotedString(false) ||\n parseRegex()\n parseWhitespaceAndSkipComments()\n\n return processed\n }\n\n function parseWhitespaceAndSkipComments(skipNewline = true): boolean {\n const start = i\n\n let changed = parseWhitespace(skipNewline)\n do {\n changed = parseComment()\n if (changed) {\n changed = parseWhitespace(skipNewline)\n }\n } while (changed)\n\n return i > start\n }\n\n function parseWhitespace(skipNewline: boolean): boolean {\n const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline\n let whitespace = ''\n\n while (true) {\n if (_isWhiteSpace(text, i)) {\n whitespace += text[i]\n i++\n } else if (isSpecialWhitespace(text, i)) {\n // repair special whitespace\n whitespace += ' '\n i++\n } else {\n break\n }\n }\n\n if (whitespace.length > 0) {\n output += whitespace\n return true\n }\n\n return false\n }\n\n function parseComment(): boolean {\n // find a block comment '/* ... */'\n if (text[i] === '/' && text[i + 1] === '*') {\n // repair block comment by skipping it\n while (i < text.length && !atEndOfBlockComment(text, i)) {\n i++\n }\n i += 2\n\n return true\n }\n\n // find a line comment '// ...'\n if (text[i] === '/' && text[i + 1] === '/') {\n // repair line comment by skipping it\n while (i < text.length && text[i] !== '\\n') {\n i++\n }\n\n return true\n }\n\n return false\n }\n\n function parseMarkdownCodeBlock(blocks: string[]): boolean {\n // find and skip over a Markdown fenced code block:\n // ``` ... ```\n // or\n // ```json ... ```\n if (skipMarkdownCodeBlock(blocks)) {\n if (isFunctionNameCharStart(text[i])) {\n // strip the optional language specifier like \"json\"\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++\n }\n }\n\n parseWhitespaceAndSkipComments()\n\n return true\n }\n\n return false\n }\n\n function skipMarkdownCodeBlock(blocks: string[]): boolean {\n parseWhitespace(true)\n\n for (const block of blocks) {\n const end = i + block.length\n if (text.slice(i, end) === block) {\n i = end\n return true\n }\n }\n\n return false\n }\n\n function parseCharacter(char: string): boolean {\n if (text[i] === char) {\n output += text[i]\n i++\n return true\n }\n\n return false\n }\n\n function skipCharacter(char: string): boolean {\n if (text[i] === char) {\n i++\n return true\n }\n\n return false\n }\n\n function skipEscapeCharacter(): boolean {\n return skipCharacter('\\\\')\n }\n\n /**\n * Skip ellipsis like \"[1,2,3,...]\" or \"[1,2,3,...,9]\" or \"[...,7,8,9]\"\n * or a similar construct in objects.\n */\n function skipEllipsis(): boolean {\n parseWhitespaceAndSkipComments()\n\n if (text[i] === '.' && text[i + 1] === '.' && text[i + 2] === '.') {\n // repair: remove the ellipsis (three dots) and optionally a comma\n i += 3\n parseWhitespaceAndSkipComments()\n skipCharacter(',')\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse an object like '{\"key\": \"value\"}'\n */\n function parseObject(): boolean {\n if (text[i] === '{') {\n output += '{'\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: skip leading comma like in {, message: \"hi\"}\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n let initial = true\n while (i < text.length && text[i] !== '}') {\n let processedComma: boolean\n if (!initial) {\n processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n parseWhitespaceAndSkipComments()\n } else {\n processedComma = true\n initial = false\n }\n\n skipEllipsis()\n\n const processedKey = parseString() || parseUnquotedString(true)\n if (!processedKey) {\n if (\n text[i] === '}' ||\n text[i] === '{' ||\n text[i] === ']' ||\n text[i] === '[' ||\n text[i] === undefined\n ) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',')\n } else {\n throwObjectKeyExpected()\n }\n break\n }\n\n parseWhitespaceAndSkipComments()\n const processedColon = parseCharacter(':')\n const truncatedText = i >= text.length\n if (!processedColon) {\n if (isStartOfValue(text[i]) || truncatedText) {\n // repair missing colon\n output = insertBeforeLastWhitespace(output, ':')\n } else {\n throwColonExpected()\n }\n }\n const processedValue = parseValue()\n if (!processedValue) {\n if (processedColon || truncatedText) {\n // repair missing object value\n output += 'null'\n } else {\n throwColonExpected()\n }\n }\n }\n\n if (text[i] === '}') {\n output += '}'\n i++\n } else {\n // repair missing end bracket\n output = insertBeforeLastWhitespace(output, '}')\n }\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse an array like '[\"item1\", \"item2\", ...]'\n */\n function parseArray(): boolean {\n if (text[i] === '[') {\n output += '['\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: skip leading comma like in [,1,2,3]\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n let initial = true\n while (i < text.length && text[i] !== ']') {\n if (!initial) {\n const processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n } else {\n initial = false\n }\n\n skipEllipsis()\n\n const processedValue = parseValue()\n if (!processedValue) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',')\n break\n }\n }\n\n if (text[i] === ']') {\n output += ']'\n i++\n } else {\n // repair missing closing array bracket\n output = insertBeforeLastWhitespace(output, ']')\n }\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse and repair Newline Delimited JSON (NDJSON):\n * multiple JSON objects separated by a newline character\n */\n function parseNewlineDelimitedJSON() {\n // repair NDJSON\n let initial = true\n let processedValue = true\n while (processedValue) {\n if (!initial) {\n // parse optional comma, insert when missing\n const processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair: add missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n } else {\n initial = false\n }\n\n processedValue = parseValue()\n }\n\n if (!processedValue) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',')\n }\n\n // repair: wrap the output inside array brackets\n output = `[\\n${output}\\n]`\n }\n\n /**\n * Parse a string enclosed by double quotes \"...\". Can contain escaped quotes\n * Repair strings enclosed in single quotes or special quotes\n * Repair an escaped string\n *\n * The function can run in two stages:\n * - First, it assumes the string has a valid end quote\n * - If it turns out that the string does not have a valid end quote followed\n * by a delimiter (which should be the case), the function runs again in a\n * more conservative way, stopping the string at the first next delimiter\n * and fixing the string by inserting a quote there, or stopping at a\n * stop index detected in the first iteration.\n */\n function parseString(stopAtDelimiter = false, stopAtIndex = -1): boolean {\n let skipEscapeChars = text[i] === '\\\\'\n if (skipEscapeChars) {\n // repair: remove the first escape character\n i++\n skipEscapeChars = true\n }\n\n if (isQuote(text[i])) {\n // double quotes are correct JSON,\n // single quotes come from JavaScript for example, we assume it will have a correct single end quote too\n // otherwise, we will match any double-quote-like start with a double-quote-like end,\n // or any single-quote-like start with a single-quote-like end\n const isEndQuote = isDoubleQuote(text[i])\n ? isDoubleQuote\n : isSingleQuote(text[i])\n ? isSingleQuote\n : isSingleQuoteLike(text[i])\n ? isSingleQuoteLike\n : isDoubleQuoteLike\n\n const iBefore = i\n const oBefore = output.length\n\n let str = '\"'\n i++\n\n while (true) {\n if (i >= text.length) {\n // end of text, we are missing an end quote\n\n const iPrev = prevNonWhitespaceIndex(i - 1)\n if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) {\n // if the text ends with a delimiter, like [\"hello],\n // so the missing end quote should be inserted before this delimiter\n // retry parsing the string, stopping at the first next delimiter\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(true)\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n return true\n }\n\n if (i === stopAtIndex) {\n // use the stop index detected in the first iteration, and repair end quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n return true\n }\n\n if (isEndQuote(text[i])) {\n // end quote\n // let us check what is before and after the quote to verify whether this is a legit end quote\n const iQuote = i\n const oQuote = str.length\n str += '\"'\n i++\n output += str\n\n parseWhitespaceAndSkipComments(false)\n\n if (\n stopAtDelimiter ||\n i >= text.length ||\n isDelimiter(text[i]) ||\n isQuote(text[i]) ||\n isDigit(text[i])\n ) {\n // The quote is followed by the end of the text, a delimiter,\n // or a next value. So the quote is indeed the end of the string.\n parseConcatenatedString()\n\n return true\n }\n\n const iPrevChar = prevNonWhitespaceIndex(iQuote - 1)\n const prevChar = text.charAt(iPrevChar)\n\n if (prevChar === ',') {\n // A comma followed by a quote, like '{\"a\":\"b,c,\"d\":\"e\"}'.\n // We assume that the quote is a start quote, and that the end quote\n // should have been located right before the comma but is missing.\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(false, iPrevChar)\n }\n\n if (isDelimiter(prevChar)) {\n // This is not the right end quote: it is preceded by a delimiter,\n // and NOT followed by a delimiter. So, there is an end quote missing\n // parse the string again and then stop at the first next delimiter\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(true)\n }\n\n // revert to right after the quote but before any whitespace, and continue parsing the string\n output = output.substring(0, oBefore)\n i = iQuote + 1\n\n // repair unescaped quote\n str = `${str.substring(0, oQuote)}\\\\${str.substring(oQuote)}`\n } else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i])) {\n // we're in the mode to stop the string at the first delimiter\n // because there is an end quote missing\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(iBefore + 1, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n str += text[i]\n i++\n }\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n parseConcatenatedString()\n\n return true\n } else if (text[i] === '\\\\') {\n // handle escaped content like \\n or \\u2605\n const char = text.charAt(i + 1)\n const escapeChar = escapeCharacters[char]\n if (escapeChar !== undefined) {\n str += text.slice(i, i + 2)\n i += 2\n } else if (char === 'u') {\n let j = 2\n while (j < 6 && isHex(text[i + j])) {\n j++\n }\n\n if (j === 6) {\n str += text.slice(i, i + 6)\n i += 6\n } else if (i + j >= text.length) {\n // repair invalid or truncated unicode char at the end of the text\n // by removing the unicode char and ending the string here\n i = text.length\n } else {\n throwInvalidUnicodeCharacter()\n }\n } else {\n // repair invalid escape character: remove it\n str += char\n i += 2\n }\n } else {\n // handle regular characters\n const char = text.charAt(i)\n\n if (char === '\"' && text[i - 1] !== '\\\\') {\n // repair unescaped double quote\n str += `\\\\${char}`\n i++\n } else if (isControlCharacter(char)) {\n // unescaped control character\n str += controlCharacters[char]\n i++\n } else {\n if (!isValidStringCharacter(char)) {\n throwInvalidCharacter(char)\n }\n str += char\n i++\n }\n }\n\n if (skipEscapeChars) {\n // repair: skipped escape character (nothing to do)\n skipEscapeCharacter()\n }\n }\n }\n\n return false\n }\n\n /**\n * Repair concatenated strings like \"hello\" + \"world\", change this into \"helloworld\"\n */\n function parseConcatenatedString(): boolean {\n let processed = false\n\n parseWhitespaceAndSkipComments()\n while (text[i] === '+') {\n processed = true\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: remove the end quote of the first string\n output = stripLastOccurrence(output, '\"', true)\n const start = output.length\n const parsedStr = parseString()\n if (parsedStr) {\n // repair: remove the start quote of the second string\n output = removeAtIndex(output, start, 1)\n } else {\n // repair: remove the + because it is not followed by a string\n output = insertBeforeLastWhitespace(output, '\"')\n }\n }\n\n return processed\n }\n\n /**\n * Parse a number like 2.4 or 2.4e6\n */\n function parseNumber(): boolean {\n const start = i\n if (text[i] === '-') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n }\n\n // Note that in JSON leading zeros like \"00789\" are not allowed.\n // We will allow all leading zeros here though and at the end of parseNumber\n // check against trailing zeros and repair that if needed.\n // Leading zeros can have meaning, so we should not clear them.\n while (isDigit(text[i])) {\n i++\n }\n\n if (text[i] === '.') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n while (isDigit(text[i])) {\n i++\n }\n }\n\n if (text[i] === 'e' || text[i] === 'E') {\n i++\n if (text[i] === '-' || text[i] === '+') {\n i++\n }\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n while (isDigit(text[i])) {\n i++\n }\n }\n\n // if we're not at the end of the number by this point, allow this to be parsed as another type\n if (!atEndOfNumber()) {\n i = start\n return false\n }\n\n if (i > start) {\n // repair a number with leading zeros like \"00789\"\n const num = text.slice(start, i)\n const hasInvalidLeadingZero = /^0\\d/.test(num)\n\n output += hasInvalidLeadingZero ? `\"${num}\"` : num\n return true\n }\n\n return false\n }\n\n /**\n * Parse keywords true, false, null\n * Repair Python keywords True, False, None\n */\n function parseKeywords(): boolean {\n return (\n parseKeyword('true', 'true') ||\n parseKeyword('false', 'false') ||\n parseKeyword('null', 'null') ||\n // repair Python keywords True, False, None\n parseKeyword('True', 'true') ||\n parseKeyword('False', 'false') ||\n parseKeyword('None', 'null')\n )\n }\n\n function parseKeyword(name: string, value: string): boolean {\n if (text.slice(i, i + name.length) === name) {\n output += value\n i += name.length\n return true\n }\n\n return false\n }\n\n /**\n * Repair an unquoted string by adding quotes around it\n * Repair a MongoDB function call like NumberLong(\"2\")\n * Repair a JSONP function call like callback({...});\n */\n function parseUnquotedString(isKey: boolean) {\n // note that the symbol can end with whitespaces: we stop at the next delimiter\n // also, note that we allow strings to contain a slash / in order to support repairing regular expressions\n const start = i\n\n if (isFunctionNameCharStart(text[i])) {\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++\n }\n\n let j = i\n while (isWhitespace(text, j)) {\n j++\n }\n\n if (text[j] === '(') {\n // repair a MongoDB function call like NumberLong(\"2\")\n // repair a JSONP function call like callback({...});\n i = j + 1\n\n parseValue()\n\n if (text[i] === ')') {\n // repair: skip close bracket of function call\n i++\n if (text[i] === ';') {\n // repair: skip semicolon after JSONP call\n i++\n }\n }\n\n return true\n }\n }\n\n while (\n i < text.length &&\n !isUnquotedStringDelimiter(text[i]) &&\n !isQuote(text[i]) &&\n (!isKey || text[i] !== ':')\n ) {\n i++\n }\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(start, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n i++\n }\n }\n\n if (i > start) {\n // repair unquoted string\n // also, repair undefined into null\n\n // first, go back to prevent getting trailing whitespaces in the string\n while (isWhitespace(text, i - 1) && i > 0) {\n i--\n }\n\n const symbol = text.slice(start, i)\n output += symbol === 'undefined' ? 'null' : JSON.stringify(symbol)\n\n if (text[i] === '\"') {\n // we had a missing start quote, but now we encountered the end quote, so we can skip that one\n i++\n }\n\n return true\n }\n }\n\n function parseRegex() {\n if (text[i] === '/') {\n const start = i\n i++\n\n while (i < text.length && (text[i] !== '/' || text[i - 1] === '\\\\')) {\n i++\n }\n i++\n\n output += JSON.stringify(text.substring(start, i))\n\n return true\n }\n }\n\n function prevNonWhitespaceIndex(start: number): number {\n let prev = start\n\n while (prev > 0 && isWhitespace(text, prev)) {\n prev--\n }\n\n return prev\n }\n\n function atEndOfNumber() {\n return i >= text.length || isDelimiter(text[i]) || isWhitespace(text, i)\n }\n\n function repairNumberEndingWithNumericSymbol(start: number) {\n // repair numbers cut off at the end\n // this will only be called when we end after a '.', '-', or 'e' and does not\n // change the number more than it needs to make it valid JSON\n output += `${text.slice(start, i)}0`\n }\n\n function throwInvalidCharacter(char: string) {\n throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i)\n }\n\n function throwUnexpectedCharacter() {\n throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i])}`, i)\n }\n\n function throwUnexpectedEnd() {\n throw new JSONRepairError('Unexpected end of json string', text.length)\n }\n\n function throwObjectKeyExpected() {\n throw new JSONRepairError('Object key expected', i)\n }\n\n function throwColonExpected() {\n throw new JSONRepairError('Colon expected', i)\n }\n\n function throwInvalidUnicodeCharacter() {\n const chars = text.slice(i, i + 6)\n throw new JSONRepairError(`Invalid unicode character \"${chars}\"`, i)\n }\n}\n\nfunction atEndOfBlockComment(text: string, i: number) {\n return text[i] === '*' && text[i + 1] === '/'\n}\n", "import {\n AGENT_CONFIG_VERSION,\n DEFAULT_AGENT_CONFIG,\n DEFAULT_AGENT_NAME,\n StoredAgentConfigSchemaV2,\n} from \"@taskcrew/shared\";\nimport { z } from \"zod\";\n\nconst publicAgentSchema = z.object({\n id: z.string(),\n name: z.string(),\n slack_enabled: z.boolean().nullish(),\n microsoft_teams_enabled: z.boolean().nullish(),\n agentic_memory_enabled: z.boolean().nullish(),\n thread_id: z.string().nullish(),\n created_at: z.string().nullish(),\n updated_at: z.string().nullish(),\n});\n\nexport type PublicAgent = z.infer<typeof publicAgentSchema>;\n\nconst publicBuildSchema = z.object({\n id: z.string(),\n agent_id: z.string(),\n name: z.string(),\n revision_number: z.number().nullish(),\n created_at: z.string().nullish(),\n updated_at: z.string().nullish(),\n});\n\nexport type PublicBuild = z.infer<typeof publicBuildSchema>;\n\nexport const listAgentsResponseSchema = z.object({\n agents: z.array(publicAgentSchema),\n total: z.number().nullish(),\n limit: z.number().nullish(),\n offset: z.number().nullish(),\n});\n\nexport type ListAgentsResponse = z.infer<typeof listAgentsResponseSchema>;\n\nexport const getAgentResponseSchema = z.object({\n agent: publicAgentSchema,\n});\n\nexport type GetAgentResponse = z.infer<typeof getAgentResponseSchema>;\n\nexport const createAgentResponseSchema = z.object({\n agent: publicAgentSchema,\n build: publicBuildSchema.optional(),\n});\n\nexport type CreateAgentResponse = z.infer<typeof createAgentResponseSchema>;\n\nexport const buildConfigSchema = StoredAgentConfigSchemaV2;\n\nexport type BuildConfig = z.input<typeof buildConfigSchema>;\n\nexport const DEFAULT_NEW_AGENT_NAME = DEFAULT_AGENT_NAME;\nexport const DEFAULT_BUILD_NAME = \"Initial build\";\n\nexport const DEFAULT_BUILD_CONFIG: BuildConfig = {\n version: AGENT_CONFIG_VERSION,\n data: DEFAULT_AGENT_CONFIG,\n};\n", "import { type Command } from \"commander\";\n\nimport { getAgentResponseSchema } from \"@/api/agent-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype GetOptions = {\n json?: boolean;\n};\n\nexport function registerAgentsGet(agents: Command): void {\n agents\n .command(\"get <id>\")\n .description(\"Get an agent by ID\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function getAction(\n this: Command,\n id: string,\n options: GetOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/agents/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = getAgentResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { agent } = parsed.data;\n\n console.log(\n renderKeyValue([\n { label: \"ID\", value: agent.id },\n { label: \"Name\", value: agent.name },\n { label: \"Created\", value: agent.created_at ?? \"\" },\n { label: \"Updated\", value: agent.updated_at ?? \"\" },\n ])\n );\n });\n}\n", "import { CliError } from \"@/errors.js\";\n\nconst POSITIVE_INT = /^\\d+$/;\n\ntype ParseLimitOptions = {\n defaultValue: number;\n min: number;\n max: number;\n};\n\nexport function parseLimit(\n raw: string | undefined,\n { defaultValue, min, max }: ParseLimitOptions\n): number {\n if (raw === undefined) {\n return defaultValue;\n }\n\n if (!POSITIVE_INT.test(raw)) {\n throw new CliError(`--limit must be an integer between ${min} and ${max}`);\n }\n\n const n = Number(raw);\n if (n < min || n > max) {\n throw new CliError(`--limit must be an integer between ${min} and ${max}`);\n }\n\n return n;\n}\n\nexport function parseOffset(raw: string | undefined): number {\n if (raw === undefined) {\n return 0;\n }\n\n if (!POSITIVE_INT.test(raw)) {\n throw new CliError(\"--offset must be a non-negative integer\");\n }\n\n return Number(raw);\n}\n", "import { type Command } from \"commander\";\n\nimport {\n listAgentsResponseSchema,\n type PublicAgent,\n} from \"@/api/agent-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { parseLimit, parseOffset } from \"../shared/pagination.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n limit?: string;\n offset?: string;\n json?: boolean;\n};\n\nconst DEFAULT_LIMIT = 20;\nconst MIN_LIMIT = 1;\nconst MAX_LIMIT = 100;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: PublicAgent) => row.id },\n { header: \"NAME\", cell: (row: PublicAgent) => row.name },\n { header: \"CREATED\", cell: (row: PublicAgent) => row.created_at ?? \"\" },\n] as const;\n\nexport function registerAgentsList(agents: Command): void {\n agents\n .command(\"list\", { isDefault: true })\n .description(\"List agents for your team\")\n .option(\"--limit <n>\", `page size (${MIN_LIMIT}-${MAX_LIMIT})`)\n .option(\"--offset <n>\", \"number of agents to skip\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const limit = parseLimit(options.limit, {\n defaultValue: DEFAULT_LIMIT,\n min: MIN_LIMIT,\n max: MAX_LIMIT,\n });\n const offset = parseOffset(options.offset);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", String(limit));\n searchParams.append(\"offset\", String(offset));\n\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/agents\",\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listAgentsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const response = parsed.data;\n\n if (response.agents.length === 0) {\n console.log(\"No agents found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, response.agents));\n const resolvedOffset = response.offset ?? offset;\n const summary =\n response.total === null || response.total === undefined\n ? `Showing ${response.agents.length} \u00B7 offset ${resolvedOffset}`\n : `Showing ${response.agents.length} of ${response.total} \u00B7 offset ${resolvedOffset}`;\n console.log(summary);\n });\n}\n", "import { z } from \"zod\";\n\nconst publicScheduleSchema = z.object({\n id: z.string(),\n build_id: z.string(),\n agent_id: z.string(),\n user_id: z.string(),\n enabled: z.boolean(),\n frequency: z.string(),\n time: z.string().nullish(),\n timezone: z.string(),\n day: z.string().nullish(),\n day_of_month: z.number().nullish(),\n cron: z.string().nullish(),\n source: z.string().nullish(),\n task: z.string().nullish(),\n recurring: z.boolean().nullish(),\n created_at: z.string(),\n updated_at: z.string(),\n});\n\nexport type PublicSchedule = z.infer<typeof publicScheduleSchema>;\n\nexport const listSchedulesResponseSchema = z.object({\n schedules: z.array(publicScheduleSchema),\n});\n\nexport type ListSchedulesResponse = z.infer<typeof listSchedulesResponseSchema>;\n", "import { type Command } from \"commander\";\n\nimport {\n listSchedulesResponseSchema,\n type PublicSchedule,\n} from \"@/api/schedule-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype SchedulesOptions = {\n json?: boolean;\n};\n\nconst TASK_PREVIEW_WIDTH = 40;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: PublicSchedule) => row.id },\n {\n header: \"ENABLED\",\n cell: (row: PublicSchedule) => (row.enabled ? \"yes\" : \"no\"),\n },\n { header: \"FREQUENCY\", cell: (row: PublicSchedule) => row.frequency },\n { header: \"WHEN\", cell: whenCell },\n { header: \"TIMEZONE\", cell: (row: PublicSchedule) => row.timezone },\n {\n header: \"RECURRING\",\n cell: (row: PublicSchedule) => (row.recurring === false ? \"no\" : \"yes\"),\n },\n {\n header: \"TASK\",\n cell: (row: PublicSchedule) =>\n row.task ? row.task.replace(/\\s+/g, \" \").trim() : \"\",\n maxWidth: TASK_PREVIEW_WIDTH,\n },\n] as const;\n\nfunction whenCell(row: PublicSchedule): string {\n if (row.frequency === \"custom\") {\n return row.cron ?? \"\";\n }\n\n if (row.frequency === \"weekly\" && row.day) {\n return `${row.day} ${row.time ?? \"\"}`.trim();\n }\n\n if (\n row.frequency === \"monthly\" &&\n row.day_of_month !== null &&\n row.day_of_month !== undefined\n ) {\n return `day ${row.day_of_month} ${row.time ?? \"\"}`.trim();\n }\n\n return row.time ?? \"\";\n}\n\nexport function registerAgentsSchedules(agents: Command): void {\n agents\n .command(\"schedules <agent-id>\")\n .description(\"List schedules you own for an agent\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function schedulesAction(\n this: Command,\n agentId: string,\n options: SchedulesOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/agents/${encodeURIComponent(agentId)}/schedules`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listSchedulesResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { schedules } = parsed.data;\n\n if (schedules.length === 0) {\n console.log(\"No schedules found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, schedules));\n console.log(`Showing ${schedules.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { getAgentResponseSchema } from \"@/api/agent-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { trimRequired } from \"../shared/trim-required.js\";\n\ntype UpdateOptions = {\n name?: string;\n enableSlack?: boolean;\n disableSlack?: boolean;\n enableMicrosoftTeams?: boolean;\n disableMicrosoftTeams?: boolean;\n enableAgenticMemory?: boolean;\n disableAgenticMemory?: boolean;\n threadId?: string;\n clearThread?: boolean;\n json?: boolean;\n};\n\ntype RequestBody = {\n name?: string;\n slack_enabled?: boolean;\n microsoft_teams_enabled?: boolean;\n agentic_memory_enabled?: boolean;\n thread_id?: string | null;\n};\n\nfunction parseBoolPair(\n enable: boolean | undefined,\n disable: boolean | undefined,\n enableFlag: string,\n disableFlag: string\n): boolean | undefined {\n if (enable === true && disable === true) {\n throw new CliError(\n `Pass either --${enableFlag} or --${disableFlag}, not both.`\n );\n }\n\n if (enable === true) {\n return true;\n }\n\n if (disable === true) {\n return false;\n }\n\n return undefined;\n}\n\nfunction buildBody(options: UpdateOptions): RequestBody {\n const body: RequestBody = {};\n\n if (options.name !== undefined) {\n body.name = trimRequired(options.name, \"--name\");\n }\n\n const slack = parseBoolPair(\n options.enableSlack,\n options.disableSlack,\n \"enable-slack\",\n \"disable-slack\"\n );\n if (slack !== undefined) {\n body.slack_enabled = slack;\n }\n\n const teams = parseBoolPair(\n options.enableMicrosoftTeams,\n options.disableMicrosoftTeams,\n \"enable-microsoft-teams\",\n \"disable-microsoft-teams\"\n );\n if (teams !== undefined) {\n body.microsoft_teams_enabled = teams;\n }\n\n const memory = parseBoolPair(\n options.enableAgenticMemory,\n options.disableAgenticMemory,\n \"enable-agentic-memory\",\n \"disable-agentic-memory\"\n );\n if (memory !== undefined) {\n body.agentic_memory_enabled = memory;\n }\n\n if (options.threadId !== undefined && options.clearThread === true) {\n throw new CliError(\"Pass either --thread-id or --clear-thread, not both.\");\n }\n\n if (options.threadId !== undefined) {\n body.thread_id = trimRequired(options.threadId, \"--thread-id\");\n }\n\n if (options.clearThread === true) {\n body.thread_id = null;\n }\n\n if (Object.keys(body).length === 0) {\n throw new CliError(\n \"Provide at least one field to update (e.g. --name, --enable-slack).\"\n );\n }\n\n return body;\n}\n\nexport function registerAgentsUpdate(agents: Command): void {\n agents\n .command(\"update <id>\")\n .description(\"Update an agent's display name or delivery settings\")\n .option(\"--name <name>\", \"new display name\")\n .option(\"--enable-slack\", \"enable Slack delivery\")\n .option(\"--disable-slack\", \"disable Slack delivery\")\n .option(\"--enable-microsoft-teams\", \"enable Microsoft Teams delivery\")\n .option(\"--disable-microsoft-teams\", \"disable Microsoft Teams delivery\")\n .option(\"--enable-agentic-memory\", \"enable agentic memory\")\n .option(\"--disable-agentic-memory\", \"disable agentic memory\")\n .option(\"--thread-id <id>\", \"associate the agent with a thread\")\n .option(\n \"--clear-thread\",\n \"clear the agent's associated thread (sets thread_id to null)\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function updateAction(\n this: Command,\n id: string,\n options: UpdateOptions\n ) {\n const agentId = trimRequired(id, \"<id>\");\n const body = buildBody(options);\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"PATCH\",\n path: `/v1/agents/${encodeURIComponent(agentId)}`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = getAgentResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { agent } = parsed.data;\n\n console.log(green(\"Agent updated!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: agent.id },\n { label: \"Name\", value: agent.name },\n { label: \"Slack\", value: formatBool(agent.slack_enabled) },\n {\n label: \"Microsoft Teams\",\n value: formatBool(agent.microsoft_teams_enabled),\n },\n {\n label: \"Agentic memory\",\n value: formatBool(agent.agentic_memory_enabled),\n },\n { label: \"Thread\", value: agent.thread_id ?? \"(none)\" },\n { label: \"Created\", value: agent.created_at ?? \"\" },\n { label: \"Updated\", value: agent.updated_at ?? \"\" },\n ])\n );\n });\n}\n\nfunction formatBool(value: boolean | null | undefined): string {\n if (value === true) {\n return \"enabled\";\n }\n\n if (value === false) {\n return \"disabled\";\n }\n\n return \"(unset)\";\n}\n", "import { type Command } from \"commander\";\n\nimport { registerAgentsCreate } from \"./create.js\";\nimport { registerAgentsGet } from \"./get.js\";\nimport { registerAgentsList } from \"./list.js\";\nimport { registerAgentsSchedules } from \"./schedules.js\";\nimport { registerAgentsUpdate } from \"./update.js\";\n\nexport function registerAgents(program: Command): void {\n const agents = program\n .command(\"agents\")\n .description(\"Manage agents in the Duvo public API\");\n\n registerAgentsList(agents);\n registerAgentsGet(agents);\n registerAgentsCreate(agents);\n registerAgentsUpdate(agents);\n registerAgentsSchedules(agents);\n}\n", "import { readFileSync } from \"node:fs\";\n\ntype Field = {\n key: string;\n value: unknown;\n};\n\nconst INTEGER_OR_DECIMAL = /^-?\\d+(\\.\\d+)?$/;\n\n/**\n * Parses a `-f key=value` pair. The value is always kept as a string,\n * matching the `gh api` convention.\n */\nexport function parseStringField(input: string): Field {\n const eq = input.indexOf(\"=\");\n if (eq === -1) {\n throw new Error(\n `Invalid field \"${input}\". Expected \"key=value\" (e.g. -f name=\"Bot\").`\n );\n }\n\n const key = input.slice(0, eq);\n if (key.length === 0) {\n throw new Error(\n `Invalid field \"${input}\". Key cannot be empty (e.g. -f name=\"Bot\").`\n );\n }\n\n return { key, value: input.slice(eq + 1) };\n}\n\n/**\n * Parses a `-F key=value` pair. The value is coerced to a typed value\n * when it matches one of: `null`, `true`, `false`, a number, or\n * `@path/to/file.json` (inlines the file's parsed JSON). Anything else\n * falls through as a string.\n */\nexport function parseTypedField(input: string): Field {\n const eq = input.indexOf(\"=\");\n if (eq === -1) {\n throw new Error(\n `Invalid field \"${input}\". Expected \"key=value\" (e.g. -F count=42).`\n );\n }\n\n const key = input.slice(0, eq);\n if (key.length === 0) {\n throw new Error(\n `Invalid field \"${input}\". Key cannot be empty (e.g. -F count=42).`\n );\n }\n\n const raw = input.slice(eq + 1);\n\n if (raw.startsWith(\"@\")) {\n const path = raw.slice(1);\n return { key, value: readJsonFile(path) };\n }\n\n if (raw === \"null\") {\n return { key, value: null };\n }\n\n if (raw === \"true\") {\n return { key, value: true };\n }\n\n if (raw === \"false\") {\n return { key, value: false };\n }\n\n if (INTEGER_OR_DECIMAL.test(raw)) {\n return { key, value: Number(raw) };\n }\n\n return { key, value: raw };\n}\n\n/**\n * Combines repeated `-f` and `-F` flag values into a single object.\n * String fields (`-f`) are applied first, then typed fields (`-F`), so\n * typed fields win on key collision regardless of CLI argument order.\n * Commander collects the two flags into separate arrays, so the original\n * interleaved order is lost by the time we get here.\n */\nexport function buildFieldObject(\n stringFields: readonly string[] = [],\n typedFields: readonly string[] = []\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const input of stringFields) {\n const { key, value } = parseStringField(input);\n result[key] = value;\n }\n\n for (const input of typedFields) {\n const { key, value } = parseTypedField(input);\n result[key] = value;\n }\n\n return result;\n}\n\nfunction readJsonFile(path: string): unknown {\n let contents: string;\n try {\n contents = readFileSync(path, \"utf8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Cannot read \"${path}\": ${message}`);\n }\n\n try {\n return JSON.parse(contents);\n } catch {\n throw new Error(`File \"${path}\" is not valid JSON.`);\n }\n}\n", "import { readFileSync } from \"node:fs\";\n\nimport { CliError } from \"@/errors.js\";\n\n/**\n * Reads a raw JSON body from a file path or from stdin (when path is\n * `\"-\"`). Returns the parsed JSON value. Throws `CliError` if the input\n * is not valid JSON or the file cannot be read.\n */\nexport function readInputJson(path: string): unknown {\n const contents = path === \"-\" ? readStdin() : readFile(path);\n try {\n return JSON.parse(contents);\n } catch {\n const source = path === \"-\" ? \"stdin\" : `\"${path}\"`;\n throw new CliError(`Input from ${source} is not valid JSON.`);\n }\n}\n\nfunction readFile(path: string): string {\n try {\n return readFileSync(path, \"utf8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Cannot read \"${path}\": ${message}`);\n }\n}\n\nfunction readStdin(): string {\n return readFileSync(0, \"utf8\");\n}\n", "import { printJson } from \"@/output/json.js\";\nimport { type Column, renderTable } from \"@/output/table.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nconst FALLBACK_TERMINAL_WIDTH = 120;\nconst MIN_COLUMN_WIDTH = 8;\nconst COLUMN_GUTTER = 2;\n\n/**\n * Routes the response through the shared output pipeline per GUIDE.md:\n * collections render as a table, single objects as a key/value block,\n * everything else (and `--json`) falls back to pretty JSON. `duvo api`\n * has no schema, so columns and labels come straight from the response\n * keys.\n */\nexport function renderApiResponse(response: unknown, asJson: boolean): void {\n if (asJson) {\n printJson(response);\n return;\n }\n\n if (Array.isArray(response)) {\n if (response.length === 0) {\n console.log(\"No results.\");\n return;\n }\n\n if (response.every(isRecord)) {\n renderTableResponse(response);\n return;\n }\n }\n\n if (isRecord(response)) {\n const entries = Object.entries(response).map(([key, value]) => {\n return { label: key, value: formatScalar(value) };\n });\n console.log(renderKeyValue(entries));\n return;\n }\n\n printJson(response);\n}\n\nfunction renderTableResponse(rows: readonly Record<string, unknown>[]): void {\n const keys = Array.from(new Set(rows.flatMap((row) => Object.keys(row))));\n const maxWidth = perColumnMaxWidth(keys.length);\n const columns: Column<Record<string, unknown>>[] = keys.map((key) => {\n return {\n header: key.toUpperCase(),\n cell: (row) => formatScalar(row[key]),\n maxWidth,\n };\n });\n console.log(renderTable(columns, rows));\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction perColumnMaxWidth(columnCount: number): number {\n if (columnCount === 0) {\n return MIN_COLUMN_WIDTH;\n }\n\n const terminalWidth = process.stdout.columns ?? FALLBACK_TERMINAL_WIDTH;\n const budget = terminalWidth - COLUMN_GUTTER * (columnCount - 1);\n return Math.max(MIN_COLUMN_WIDTH, Math.floor(budget / columnCount));\n}\n\nfunction formatScalar(value: unknown): string {\n if (value === null || value === undefined) {\n return \"\";\n }\n\n if (typeof value === \"string\") {\n return value;\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n\n return JSON.stringify(value);\n}\n", "import { type Command } from \"commander\";\n\nimport { buildFieldObject } from \"@/api/parse-fields.js\";\nimport { readInputJson } from \"@/api/read-input.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\n\nimport { renderApiResponse } from \"./api-render.js\";\nimport {\n type AuthenticatedConfig,\n requireAuthenticatedConfig,\n} from \"./shared/require-auth.js\";\n\ntype ApiOptions = {\n field?: string[];\n rawField?: string[];\n input?: string;\n json?: boolean;\n};\n\ntype RequestData = {\n body: unknown;\n searchParams: URLSearchParams | undefined;\n};\n\nconst METHODS_WITH_BODY = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\nconst VALID_METHODS = new Set([\n \"GET\",\n \"HEAD\",\n \"POST\",\n \"PUT\",\n \"PATCH\",\n \"DELETE\",\n]);\n\nexport function registerApi(program: Command): void {\n program\n .command(\"api <method> <path>\")\n .description(\"Make an authenticated request to the Duvo public API\")\n .option(\n \"-f, --field <key=value>\",\n \"string field; repeat for multiple (body on POST/PUT/PATCH/DELETE, query on GET/HEAD)\",\n collect,\n []\n )\n .option(\n \"-F, --raw-field <key=value>\",\n \"typed field (boolean, number, null, or @file for JSON); repeat for multiple\",\n collect,\n []\n )\n .option(\n \"--input <path>\",\n 'raw JSON body from a file, or \"-\" for stdin (mutually exclusive with -f / -F)'\n )\n .option(\"--json\", \"output raw JSON instead of the formatted view\")\n .action(async function apiAction(\n this: Command,\n method: string,\n path: string,\n options: ApiOptions\n ) {\n const resolved = await requireAuthenticatedConfig(this);\n await runApi({ method, path, options }, resolved);\n });\n}\n\nasync function runApi(\n args: { method: string; path: string; options: ApiOptions },\n resolved: AuthenticatedConfig\n): Promise<void> {\n const method = args.method.toUpperCase();\n if (!VALID_METHODS.has(method)) {\n throw new CliError(\n `Invalid HTTP method \"${args.method}\". Expected one of: ${[...VALID_METHODS].join(\", \")}.`\n );\n }\n\n const { body, searchParams } = prepareRequestData(method, args.options);\n\n const response = await httpRequest({\n method,\n path: args.path,\n apiKey: resolved.apiKey,\n apiBaseUrl: resolved.apiBaseUrl,\n body,\n searchParams,\n });\n\n renderApiResponse(response, args.options.json ?? false);\n}\n\nfunction prepareRequestData(method: string, options: ApiOptions): RequestData {\n const hasFieldArgs =\n (options.field?.length ?? 0) > 0 || (options.rawField?.length ?? 0) > 0;\n\n if (options.input !== undefined && hasFieldArgs) {\n throw new CliError(\"Cannot combine --input with -f / -F flags.\");\n }\n\n if (options.input !== undefined) {\n if (!METHODS_WITH_BODY.has(method)) {\n throw new CliError(\n `--input is only supported for ${[...METHODS_WITH_BODY].join(\", \")} requests.`\n );\n }\n\n return { body: readInputJson(options.input), searchParams: undefined };\n }\n\n if (!hasFieldArgs) {\n return { body: undefined, searchParams: undefined };\n }\n\n const fields = buildFieldObject(options.field, options.rawField);\n if (METHODS_WITH_BODY.has(method)) {\n return { body: fields, searchParams: undefined };\n }\n\n return { body: undefined, searchParams: fieldsToSearchParams(fields) };\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\n/**\n * Encodes typed fields as query string values. Scalars pass through as\n * their string form; objects and arrays are JSON-stringified so an\n * `-F filter=@file.json` round-trips to a usable `?filter=\u2026` rather\n * than `[object Object]`. `null` / `undefined` keys are dropped \u2014 query\n * strings have no native null encoding.\n */\nfunction fieldsToSearchParams(\n fields: Record<string, unknown>\n): URLSearchParams {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(fields)) {\n if (value === null || value === undefined) {\n continue;\n }\n\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n params.append(key, String(value));\n continue;\n }\n\n params.append(key, JSON.stringify(value));\n }\n\n return params;\n}\n", "import { z } from \"zod\";\n\nconst integrationSchema = z.object({\n id: z.string(),\n name: z.string(),\n type: z.string(),\n provider: z.string(),\n user_id: z.string().nullable(),\n team_id: z.string(),\n server_url: z.string().optional(),\n transport_type: z.string().optional(),\n auth_method: z.string().nullish(),\n composio_mcp_id: z.string().nullish(),\n custom_integration_id: z.string().nullish(),\n icon_url: z.string().nullish(),\n oauth_provider: z.string().nullish(),\n oauth_scopes: z.array(z.string()).nullish(),\n integration_id: z.string().nullish(),\n created_at: z.string(),\n updated_at: z.string(),\n});\n\nexport type Integration = z.infer<typeof integrationSchema>;\n\nexport const integrationsListResponseSchema = z.object({\n integrations: z.array(integrationSchema),\n});\n\nexport type IntegrationsListResponse = z.infer<\n typeof integrationsListResponseSchema\n>;\n\nexport const connectionResponseSchema = integrationSchema;\n\nexport type Connection = z.infer<typeof connectionResponseSchema>;\n\nconst buildIntegrationConfigSchema = z.object({\n id: z.string(),\n integration_id: z.string().nullable(),\n custom_integration_id: z.string().nullable(),\n integration_type: z.string(),\n integration_name: z.string(),\n created_at: z.string(),\n});\n\nexport type BuildIntegrationConfig = z.infer<\n typeof buildIntegrationConfigSchema\n>;\n\nexport const listBuildIntegrationsResponseSchema = z.object({\n integrations: z.array(buildIntegrationConfigSchema),\n});\n\nexport type ListBuildIntegrationsResponse = z.infer<\n typeof listBuildIntegrationsResponseSchema\n>;\n\nexport const attachBuildIntegrationsResponseSchema = z.object({\n success: z.boolean(),\n count: z.number(),\n});\n\nexport type AttachBuildIntegrationsResponse = z.infer<\n typeof attachBuildIntegrationsResponseSchema\n>;\n\nconst buildIntegrationConnectionSchema = z.object({\n connection_id: z.string(),\n created_at: z.string(),\n});\n\nexport type BuildIntegrationConnection = z.infer<\n typeof buildIntegrationConnectionSchema\n>;\n\nexport const listBuildIntegrationConnectionsResponseSchema = z.object({\n connections: z.array(buildIntegrationConnectionSchema),\n});\n\nexport type ListBuildIntegrationConnectionsResponse = z.infer<\n typeof listBuildIntegrationConnectionsResponseSchema\n>;\n\nexport const successResponseSchema = z.object({\n success: z.boolean(),\n});\n", "import { type Command } from \"commander\";\n\nimport { attachBuildIntegrationsResponseSchema } from \"@/api/integration-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype AttachOptions = {\n agent: string;\n revision: string;\n integration: string[];\n json?: boolean;\n};\n\nfunction collectMultiOption(\n value: string,\n previous: readonly string[] | undefined\n): string[] {\n return [...(previous ?? []), value];\n}\n\nexport function registerBuildIntegrationsAttach(\n buildIntegrations: Command\n): void {\n buildIntegrations\n .command(\"attach\")\n .description(\"Attach one or more integrations to a revision\")\n .requiredOption(\"--agent <id>\", \"ID of the agent the revision belongs to\")\n .requiredOption(\"--revision <id>\", \"ID of the revision\")\n .requiredOption(\n \"--integration <id>\",\n \"integration (or custom integration) ID to attach (repeat for multiple)\",\n collectMultiOption,\n [] as string[]\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function attachAction(this: Command, options: AttachOptions) {\n if (options.integration.length === 0) {\n throw new CliError(\"Pass at least one --integration <id>\");\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/agents/${encodeURIComponent(options.agent)}/revisions/${encodeURIComponent(options.revision)}/integrations`,\n apiKey,\n apiBaseUrl,\n body: { integration_ids: options.integration },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = attachBuildIntegrationsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { count } = parsed.data;\n console.log(green(`Attached ${count} integration(s) to the revision.`));\n });\n}\n", "import { type Command } from \"commander\";\n\nimport {\n type BuildIntegrationConnection,\n listBuildIntegrationConnectionsResponseSchema,\n} from \"@/api/integration-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ConnectionsListOptions = {\n agent: string;\n revision: string;\n integration: string;\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n {\n header: \"CONNECTION ID\",\n cell: (row: BuildIntegrationConnection) => row.connection_id,\n },\n {\n header: \"PINNED AT\",\n cell: (row: BuildIntegrationConnection) => row.created_at,\n },\n] as const;\n\nexport function registerBuildIntegrationsConnectionsList(\n connections: Command\n): void {\n connections\n .command(\"list\", { isDefault: true })\n .description(\n \"List your pinned connections for a revision's integration slot\"\n )\n .requiredOption(\"--agent <id>\", \"ID of the agent the revision belongs to\")\n .requiredOption(\"--revision <id>\", \"ID of the revision\")\n .requiredOption(\"--integration <id>\", \"ID of the integration slot\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(\n this: Command,\n options: ConnectionsListOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/agents/${encodeURIComponent(options.agent)}/revisions/${encodeURIComponent(options.revision)}/integrations/${encodeURIComponent(options.integration)}/connections`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed =\n listBuildIntegrationConnectionsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { connections: rows } = parsed.data;\n\n if (rows.length === 0) {\n console.log(\"No connections pinned to this slot.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, rows));\n console.log(`Showing ${rows.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { successResponseSchema } from \"@/api/integration-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype PinOptions = {\n agent: string;\n revision: string;\n integration: string;\n json?: boolean;\n};\n\nexport function registerBuildIntegrationsConnectionsPin(\n connections: Command\n): void {\n connections\n .command(\"pin <connection-id>\")\n .description(\"Pin one of your connections to a revision's integration slot\")\n .requiredOption(\"--agent <id>\", \"ID of the agent the revision belongs to\")\n .requiredOption(\"--revision <id>\", \"ID of the revision\")\n .requiredOption(\"--integration <id>\", \"ID of the integration slot\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function pinAction(\n this: Command,\n connectionId: string,\n options: PinOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/agents/${encodeURIComponent(options.agent)}/revisions/${encodeURIComponent(options.revision)}/integrations/${encodeURIComponent(options.integration)}/connections`,\n apiKey,\n apiBaseUrl,\n body: { connection_id: connectionId },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = successResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n console.log(green(\"Connection pinned to integration slot.\"));\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { successResponseSchema } from \"@/api/integration-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype UnpinOptions = {\n agent: string;\n revision: string;\n integration: string;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerBuildIntegrationsConnectionsUnpin(\n connections: Command\n): void {\n connections\n .command(\"unpin <connection-id>\")\n .description(\n \"Unpin one of your connections from a revision's integration slot\"\n )\n .requiredOption(\"--agent <id>\", \"ID of the agent the revision belongs to\")\n .requiredOption(\"--revision <id>\", \"ID of the revision\")\n .requiredOption(\"--integration <id>\", \"ID of the integration slot\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function unpinAction(\n this: Command,\n connectionId: string,\n options: UnpinOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Unpin connection \"${connectionId}\" from integration slot \"${options.integration}\"?`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/agents/${encodeURIComponent(options.agent)}/revisions/${encodeURIComponent(options.revision)}/integrations/${encodeURIComponent(options.integration)}/connections/${encodeURIComponent(connectionId)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = successResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n console.log(green(\"Connection unpinned from integration slot.\"));\n });\n}\n", "import { type Command } from \"commander\";\n\nimport {\n type BuildIntegrationConfig,\n listBuildIntegrationsResponseSchema,\n} from \"@/api/integration-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n agent: string;\n revision: string;\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"SLOT ID\", cell: (row: BuildIntegrationConfig) => row.id },\n {\n header: \"INTEGRATION ID\",\n cell: (row: BuildIntegrationConfig) =>\n row.integration_id ?? row.custom_integration_id ?? \"\",\n },\n {\n header: \"TYPE\",\n cell: (row: BuildIntegrationConfig) => row.integration_type,\n },\n {\n header: \"NAME\",\n cell: (row: BuildIntegrationConfig) => row.integration_name,\n },\n { header: \"CREATED\", cell: (row: BuildIntegrationConfig) => row.created_at },\n] as const;\n\nexport function registerBuildIntegrationsList(\n buildIntegrations: Command\n): void {\n buildIntegrations\n .command(\"list\", { isDefault: true })\n .description(\"List integrations attached to a revision\")\n .requiredOption(\"--agent <id>\", \"ID of the agent the revision belongs to\")\n .requiredOption(\"--revision <id>\", \"ID of the revision\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/agents/${encodeURIComponent(options.agent)}/revisions/${encodeURIComponent(options.revision)}/integrations`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listBuildIntegrationsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { integrations } = parsed.data;\n\n if (integrations.length === 0) {\n console.log(\"No integrations attached to this revision.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, integrations));\n console.log(`Showing ${integrations.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { successResponseSchema } from \"@/api/integration-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype RemoveOptions = {\n agent: string;\n revision: string;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerBuildIntegrationsRemove(\n buildIntegrations: Command\n): void {\n buildIntegrations\n .command(\"remove <integration-id>\")\n .description(\n \"Remove an integration from a revision. Removes the slot for everyone on the revision.\"\n )\n .requiredOption(\"--agent <id>\", \"ID of the agent the revision belongs to\")\n .requiredOption(\"--revision <id>\", \"ID of the revision\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function removeAction(\n this: Command,\n integrationId: string,\n options: RemoveOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Remove integration \"${integrationId}\" from revision \"${options.revision}\"?`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/agents/${encodeURIComponent(options.agent)}/revisions/${encodeURIComponent(options.revision)}/integrations/${encodeURIComponent(integrationId)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = successResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n console.log(green(\"Integration removed from revision.\"));\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerBuildIntegrationsAttach } from \"./attach.js\";\nimport { registerBuildIntegrationsConnectionsList } from \"./connections-list.js\";\nimport { registerBuildIntegrationsConnectionsPin } from \"./connections-pin.js\";\nimport { registerBuildIntegrationsConnectionsUnpin } from \"./connections-unpin.js\";\nimport { registerBuildIntegrationsList } from \"./list.js\";\nimport { registerBuildIntegrationsRemove } from \"./remove.js\";\n\nexport function registerBuildIntegrations(program: Command): void {\n const buildIntegrations = program\n .command(\"revision-integrations\")\n .description(\"Manage integrations attached to an agent revision\");\n\n registerBuildIntegrationsList(buildIntegrations);\n registerBuildIntegrationsAttach(buildIntegrations);\n registerBuildIntegrationsRemove(buildIntegrations);\n\n const connections = buildIntegrations\n .command(\"connections\")\n .description(\n \"Manage your pinned connections for a revision's integration slot\"\n );\n\n registerBuildIntegrationsConnectionsList(connections);\n registerBuildIntegrationsConnectionsPin(connections);\n registerBuildIntegrationsConnectionsUnpin(connections);\n}\n", "import { z } from \"zod\";\n\nimport { jsonValueSchema } from \"./json-value.js\";\n\nconst publicBuildSchema = z.object({\n id: z.string(),\n agent_id: z.string(),\n name: z.string(),\n config: jsonValueSchema.nullish(),\n revision_number: z.number().nullish(),\n created_at: z.string().nullish(),\n updated_at: z.string().nullish(),\n});\n\nexport type PublicBuild = z.infer<typeof publicBuildSchema>;\n\nexport const listBuildsResponseSchema = z.object({\n builds: z.array(publicBuildSchema),\n total: z.number().nullish(),\n limit: z.number().nullish(),\n offset: z.number().nullish(),\n});\n\nexport type ListBuildsResponse = z.infer<typeof listBuildsResponseSchema>;\n\nexport const getBuildResponseSchema = z.object({\n build: publicBuildSchema,\n});\n\nexport type GetBuildResponse = z.infer<typeof getBuildResponseSchema>;\n\nexport const createBuildResponseSchema = z.object({\n build: publicBuildSchema,\n agent: z.object({ id: z.string() }),\n});\n\nexport type CreateBuildResponse = z.infer<typeof createBuildResponseSchema>;\n", "import { z } from \"zod\";\n\nexport type JsonPrimitive = boolean | number | string | null;\nexport type JsonArray = JsonValue[];\nexport type JsonObject = { [key: string]: JsonValue | undefined };\nexport type JsonValue = JsonPrimitive | JsonArray | JsonObject;\n\nexport const jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>\n z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(jsonValueSchema),\n z.record(z.string(), jsonValueSchema),\n ])\n);\n", "import { type Command } from \"commander\";\n\nimport { createBuildResponseSchema } from \"@/api/build-schemas.js\";\nimport { type JsonValue, jsonValueSchema } from \"@/api/json-value.js\";\nimport { readInputJson } from \"@/api/read-input.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype CreateOptions = {\n agent: string;\n name: string;\n configFile: string;\n json?: boolean;\n};\n\ntype RequestBody = {\n name: string;\n config: JsonValue;\n};\n\nexport function registerBuildsCreate(builds: Command): void {\n builds\n .command(\"create\")\n .description(\"Create a new revision for an existing agent\")\n .requiredOption(\"--agent <id>\", \"ID of the agent this revision belongs to\")\n .requiredOption(\"--name <text>\", \"revision name\")\n .requiredOption(\n \"--config-file <path>\",\n 'path to a JSON file with the revision config, or \"-\" for stdin'\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function createAction(this: Command, options: CreateOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const parsedConfig = jsonValueSchema.safeParse(\n readInputJson(options.configFile)\n );\n if (!parsedConfig.success) {\n throw new CliError(`Invalid config: ${parsedConfig.error.message}`);\n }\n\n const config = parsedConfig.data;\n\n const body: RequestBody = {\n name: options.name,\n config,\n };\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/agents/${encodeURIComponent(options.agent)}/revisions`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = createBuildResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { build } = parsed.data;\n\n const revision = String(build.revision_number ?? \"\");\n\n console.log(green(\"Revision created!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: build.id },\n { label: \"Agent\", value: build.agent_id },\n { label: \"Name\", value: build.name },\n { label: \"Revision\", value: revision },\n { label: \"Created\", value: build.created_at ?? \"\" },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { getBuildResponseSchema } from \"@/api/build-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype GetOptions = {\n agent: string;\n json?: boolean;\n};\n\nexport function registerBuildsGet(builds: Command): void {\n builds\n .command(\"get <id>\")\n .description(\"Get a revision by ID\")\n .requiredOption(\"--agent <id>\", \"ID of the agent this revision belongs to\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function getAction(\n this: Command,\n id: string,\n options: GetOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/agents/${encodeURIComponent(options.agent)}/revisions/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = getBuildResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { build } = parsed.data;\n\n const revision = String(build.revision_number ?? \"\");\n\n console.log(\n renderKeyValue([\n { label: \"ID\", value: build.id },\n { label: \"Agent\", value: build.agent_id },\n { label: \"Name\", value: build.name },\n { label: \"Revision\", value: revision },\n { label: \"Created\", value: build.created_at ?? \"\" },\n { label: \"Updated\", value: build.updated_at ?? \"\" },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport {\n listBuildsResponseSchema,\n type PublicBuild,\n} from \"@/api/build-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { parseLimit, parseOffset } from \"../shared/pagination.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n agent: string;\n limit?: string;\n offset?: string;\n json?: boolean;\n};\n\nconst DEFAULT_LIMIT = 20;\nconst MIN_LIMIT = 1;\nconst MAX_LIMIT = 100;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: PublicBuild) => row.id },\n { header: \"NAME\", cell: (row: PublicBuild) => row.name },\n {\n header: \"REVISION\",\n cell: (row: PublicBuild) => String(row.revision_number ?? \"\"),\n },\n { header: \"CREATED\", cell: (row: PublicBuild) => row.created_at ?? \"\" },\n] as const;\n\nexport function registerBuildsList(builds: Command): void {\n builds\n .command(\"list\", { isDefault: true })\n .description(\"List revisions for an agent\")\n .requiredOption(\"--agent <id>\", \"ID of the agent to list revisions for\")\n .option(\"--limit <n>\", `page size (${MIN_LIMIT}-${MAX_LIMIT})`)\n .option(\"--offset <n>\", \"number of revisions to skip\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const limit = parseLimit(options.limit, {\n defaultValue: DEFAULT_LIMIT,\n min: MIN_LIMIT,\n max: MAX_LIMIT,\n });\n const offset = parseOffset(options.offset);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", String(limit));\n searchParams.append(\"offset\", String(offset));\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/agents/${encodeURIComponent(options.agent)}/revisions`,\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listBuildsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const response = parsed.data;\n\n if (response.builds.length === 0) {\n console.log(\"No revisions found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, response.builds));\n const resolvedOffset = response.offset ?? offset;\n const total = response.total ?? null;\n const summary =\n total === null\n ? `Showing ${response.builds.length} \u00B7 offset ${resolvedOffset}`\n : `Showing ${response.builds.length} of ${total} \u00B7 offset ${resolvedOffset}`;\n console.log(summary);\n });\n}\n", "import {\n buildResponseApiSchema,\n extractAgentMentionIds,\n extractSystemPromptText,\n parseAgentConfig,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { type JsonValue, jsonValueSchema } from \"@/api/json-value.js\";\nimport { readInputJson } from \"@/api/read-input.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype UpdateOptions = {\n configFile: string;\n json?: boolean;\n};\n\ntype RequestBody = {\n config: JsonValue;\n handoverTargetIds: string[];\n};\n\nexport function registerBuildsUpdate(builds: Command): void {\n builds\n .command(\"update <revision-id>\")\n .description(\n \"Update a revision's config (and handover targets, derived from it)\"\n )\n .requiredOption(\n \"--config-file <path>\",\n 'path to a JSON file with the new revision config, or \"-\" for stdin'\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function updateAction(\n this: Command,\n buildId: string,\n options: UpdateOptions\n ) {\n const parsedConfig = jsonValueSchema.safeParse(\n readInputJson(options.configFile)\n );\n if (!parsedConfig.success) {\n throw new CliError(`Invalid config: ${parsedConfig.error.message}`);\n }\n\n const body: RequestBody = {\n config: parsedConfig.data,\n handoverTargetIds: deriveHandoverTargetIds(parsedConfig.data),\n };\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"PATCH\",\n path: `/v1/revisions/${encodeURIComponent(buildId)}`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = buildResponseApiSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { build } = parsed.data;\n console.log(green(\"Revision updated!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: build.id },\n { label: \"Agent\", value: build.agent_id },\n { label: \"Name\", value: build.name },\n {\n label: \"Revision\",\n value: String(build.revision_number ?? \"\"),\n },\n { label: \"Updated\", value: build.updated_at ?? \"\" },\n ])\n );\n });\n}\n\nfunction deriveHandoverTargetIds(config: JsonValue): string[] {\n const { config: parsedConfig } = parseAgentConfig(config);\n const sopText = extractSystemPromptText(parsedConfig?.input);\n return extractAgentMentionIds(sopText);\n}\n", "import { type Command } from \"commander\";\n\nimport { registerBuildsCreate } from \"./create.js\";\nimport { registerBuildsGet } from \"./get.js\";\nimport { registerBuildsList } from \"./list.js\";\nimport { registerBuildsUpdate } from \"./update.js\";\n\nexport function registerBuilds(program: Command): void {\n const builds = program\n .command(\"revisions\")\n .description(\"Manage agent revisions in the Duvo public API\");\n\n registerBuildsList(builds);\n registerBuildsGet(builds);\n registerBuildsCreate(builds);\n registerBuildsUpdate(builds);\n}\n", "import { CliError } from \"@/errors.js\";\n\nexport function parseCaseIds(raw: string): string[] {\n const ids = raw\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (ids.length === 0) {\n throw new CliError(\"--ids must contain at least one case ID.\");\n }\n\n if (ids.length > 100) {\n throw new CliError(\"--ids must contain at most 100 case IDs.\");\n }\n\n return ids;\n}\n", "import { caseBulkDelegateResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { parseCaseIds } from \"./parse-case-ids.js\";\n\ntype BulkDelegateOptions = {\n queue: string;\n agent: string;\n ids: string;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerCasesBulkDelegate(cases: Command): void {\n cases\n .command(\"bulk-delegate\")\n .description(\n \"Delegate multiple cases to a chosen agent (1-100). Interrupts any active runs.\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue the cases belong to\")\n .requiredOption(\n \"--agent <id>\",\n \"agent ID to delegate to (must be a queue consumer; list via `duvo queues agents <queue-id>`)\"\n )\n .requiredOption(\"--ids <list>\", \"comma-separated case IDs (1-100)\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function bulkDelegateAction(\n this: Command,\n options: BulkDelegateOptions\n ) {\n const caseIds = parseCaseIds(options.ids);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Delegate ${caseIds.length} case(s) in queue \"${options.queue}\" to agent \"${options.agent}\"?`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases/bulk-delegate`,\n apiKey,\n apiBaseUrl,\n body: { case_ids: caseIds, agent_id: options.agent },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseBulkDelegateResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const result = parsed.data;\n\n console.log(green(\"Bulk delegate complete.\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"Delegated\", value: String(result.delegatedCount) },\n { label: \"Skipped\", value: String(result.skippedCount) },\n ])\n );\n });\n}\n", "import {\n caseBulkDeleteResponseSchema,\n caseDetailResponseSchema,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { parseCaseIds } from \"./parse-case-ids.js\";\n\ntype BulkDeleteOptions = {\n queue: string;\n ids: string;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerCasesBulkDelete(cases: Command): void {\n cases\n .command(\"bulk-delete\")\n .description(\n \"Delete multiple cases from a queue (1-100). Interrupts any running jobs first.\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue the cases belong to\")\n .requiredOption(\"--ids <list>\", \"comma-separated case IDs (1-100)\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function bulkDeleteAction(\n this: Command,\n options: BulkDeleteOptions\n ) {\n const caseIds = parseCaseIds(options.ids);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const message = await buildConfirmMessage({\n caseIds,\n queue: options.queue,\n skip: Boolean(options.yes),\n apiKey,\n apiBaseUrl,\n });\n\n await confirmDestructive({\n message,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases/bulk-delete`,\n apiKey,\n apiBaseUrl,\n body: { case_ids: caseIds },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseBulkDeleteResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const result = parsed.data;\n\n console.log(green(\"Bulk delete complete.\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"Deleted cases\", value: String(result.deletedCount) },\n {\n label: \"Interrupted runs\",\n value: String(result.interruptedRunIds.length),\n },\n ])\n );\n });\n}\n\nasync function buildConfirmMessage(args: {\n caseIds: string[];\n queue: string;\n skip: boolean;\n apiKey: string;\n apiBaseUrl: string;\n}): Promise<string> {\n const baseMessage = `Delete ${args.caseIds.length} case(s) from queue \"${args.queue}\"?`;\n if (args.skip || !process.stdin.isTTY) {\n return baseMessage;\n }\n\n const titles = await fetchCaseTitles(\n args.caseIds,\n args.apiKey,\n args.apiBaseUrl\n );\n const lines = titles.map((line) => ` - ${line}`).join(\"\\n\");\n return `Delete the following ${args.caseIds.length} case(s) from queue \"${args.queue}\"?\\n${lines}`;\n}\n\nconst FETCH_TITLES_CONCURRENCY = 10;\n\nasync function fetchCaseTitles(\n ids: readonly string[],\n apiKey: string,\n apiBaseUrl: string\n): Promise<string[]> {\n const chunks: string[][] = [];\n for (let i = 0; i < ids.length; i += FETCH_TITLES_CONCURRENCY) {\n chunks.push([...ids.slice(i, i + FETCH_TITLES_CONCURRENCY)]);\n }\n\n // Batches must run sequentially so we cap concurrent in-flight requests at\n // FETCH_TITLES_CONCURRENCY.\n const results: PromiseSettledResult<unknown>[] = [];\n for (const chunk of chunks) {\n // eslint-disable-next-line no-await-in-loop\n const batch = await Promise.allSettled(\n chunk.map((id) =>\n httpRequest({\n method: \"GET\",\n path: `/v1/cases/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n })\n )\n );\n results.push(...batch);\n }\n\n return results.map((result, i) => {\n const id = ids[i];\n if (result.status === \"rejected\") {\n return `${id} (could not fetch)`;\n }\n\n const parsed = caseDetailResponseSchema.safeParse(result.value);\n if (!parsed.success) {\n return `${id} (could not parse)`;\n }\n\n return `${id} \u2014 ${parsed.data.case.title}`;\n });\n}\n", "import { caseBulkRetryResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { parseCaseIds } from \"./parse-case-ids.js\";\n\ntype BulkRetryOptions = {\n queue: string;\n ids: string;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerCasesBulkRetry(cases: Command): void {\n cases\n .command(\"bulk-retry\")\n .description(\n \"Retry multiple cases by resetting them to pending (1-100). Interrupts any active runs.\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue the cases belong to\")\n .requiredOption(\"--ids <list>\", \"comma-separated case IDs (1-100)\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function bulkRetryAction(\n this: Command,\n options: BulkRetryOptions\n ) {\n const caseIds = parseCaseIds(options.ids);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Retry ${caseIds.length} case(s) in queue \"${options.queue}\"?`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases/bulk-retry`,\n apiKey,\n apiBaseUrl,\n body: { case_ids: caseIds },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseBulkRetryResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const result = parsed.data;\n\n console.log(green(\"Bulk retry complete.\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"Retried\", value: String(result.retriedCount) },\n { label: \"Skipped\", value: String(result.skippedCount) },\n ])\n );\n });\n}\n", "import { caseBulkStatusUpdateResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\nimport { parseCaseIds } from \"./parse-case-ids.js\";\n\nconst CASE_TERMINAL_STATUSES = [\"completed\", \"failed\"] as const;\ntype CaseTerminalStatus = (typeof CASE_TERMINAL_STATUSES)[number];\n\ntype BulkUpdateStatusOptions = {\n queue: string;\n ids: string;\n status: string;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerCasesBulkUpdateStatus(cases: Command): void {\n cases\n .command(\"bulk-update-status\")\n .description(\n \"Update the status of multiple cases to completed or failed (1-100). Interrupts any active runs.\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue the cases belong to\")\n .requiredOption(\"--ids <list>\", \"comma-separated case IDs (1-100)\")\n .requiredOption(\n \"--status <status>\",\n `terminal status (${CASE_TERMINAL_STATUSES.join(\", \")})`\n )\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function bulkUpdateStatusAction(\n this: Command,\n options: BulkUpdateStatusOptions\n ) {\n const caseIds = parseCaseIds(options.ids);\n const status = parseStatus(options.status);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Set ${caseIds.length} case(s) in queue \"${options.queue}\" to \"${status}\"?`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases/bulk-update-status`,\n apiKey,\n apiBaseUrl,\n body: { case_ids: caseIds, status },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseBulkStatusUpdateResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const result = parsed.data;\n\n console.log(green(\"Bulk status update complete.\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"Updated\", value: String(result.updatedCount) },\n { label: \"Skipped\", value: String(result.skippedCount) },\n {\n label: \"Interrupted runs\",\n value: String(result.interruptedRunIds.length),\n },\n ])\n );\n });\n}\n\nfunction parseStatus(raw: string): CaseTerminalStatus {\n if (!CASE_TERMINAL_STATUSES.includes(raw as CaseTerminalStatus)) {\n throw new CliError(\n `Invalid --status value \"${raw}\". Allowed: ${CASE_TERMINAL_STATUSES.join(\", \")}.`\n );\n }\n\n return raw as CaseTerminalStatus;\n}\n", "import {\n caseClearQueueResponseSchema,\n casesListResponseSchema,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ClearOptions = {\n queue: string;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerCasesClear(cases: Command): void {\n cases\n .command(\"clear\")\n .description(\n \"Delete every case in a queue. Interrupts any running jobs first.\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue to clear\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function clearAction(this: Command, options: ClearOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const message = await buildConfirmMessage({\n queue: options.queue,\n skip: Boolean(options.yes),\n apiKey,\n apiBaseUrl,\n });\n\n await confirmDestructive({\n message,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseClearQueueResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const result = parsed.data;\n if (!result.success) {\n throw new CliError(\"Failed to clear queue cases.\");\n }\n\n console.log(green(\"Queue cleared!\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"Deleted cases\", value: String(result.deletedCount) },\n {\n label: \"Interrupted runs\",\n value: String(result.interruptedRunIds.length),\n },\n ])\n );\n });\n}\n\nasync function buildConfirmMessage(args: {\n queue: string;\n skip: boolean;\n apiKey: string;\n apiBaseUrl: string;\n}): Promise<string> {\n if (args.skip || !process.stdin.isTTY) {\n return `Delete every case in queue \"${args.queue}\"?`;\n }\n\n const total = await fetchQueueCaseCount(\n args.queue,\n args.apiKey,\n args.apiBaseUrl\n );\n if (total === null) {\n return `Delete every case in queue \"${args.queue}\"?`;\n }\n\n return `Delete every case (${total}) in queue \"${args.queue}\"?`;\n}\n\nasync function fetchQueueCaseCount(\n queueId: string,\n apiKey: string,\n apiBaseUrl: string\n): Promise<number | null> {\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", \"1\");\n searchParams.append(\"offset\", \"0\");\n\n try {\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/queues/${encodeURIComponent(queueId)}/cases`,\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n const parsed = casesListResponseSchema.safeParse(raw);\n if (!parsed.success) {\n return null;\n }\n\n return parsed.data.total ?? null;\n } catch {\n return null;\n }\n}\n", "import { readFile } from \"node:fs/promises\";\n\nimport { caseCreateResponseSchema, type CaseQueueItem } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype CreateOptions = {\n queue: string;\n title?: string;\n data?: string;\n label?: string[];\n fromFile?: string;\n json?: boolean;\n};\n\ntype CaseInput = {\n title: string;\n data?: string;\n labels?: { key: string; value: string }[];\n};\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: CaseQueueItem) => row.id },\n { header: \"TITLE\", cell: (row: CaseQueueItem) => row.title, maxWidth: 50 },\n { header: \"STATUS\", cell: (row: CaseQueueItem) => row.status },\n] as const;\n\nexport function registerCasesCreate(cases: Command): void {\n cases\n .command(\"create\")\n .description(\n \"Create one or more cases in a queue. Provide --title for one case or --from-file with a JSON array for many.\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue to create cases in\")\n .option(\"--title <text>\", \"case title (max 500 chars)\")\n .option(\"--data <text>\", \"free-form data passed to the assignment on claim\")\n .option(\n \"--label <key=value>\",\n \"label to assign to the case (omit key for a simple tag, repeat for multiple)\",\n collectLabel,\n [] as string[]\n )\n .option(\n \"--from-file <path>\",\n 'JSON file with a single case object or an array of cases (max 100). \"-\" reads from stdin.'\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function createAction(this: Command, options: CreateOptions) {\n const body = await buildRequestBody(options);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseCreateResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { added_cases: addedCases } = parsed.data;\n\n console.log(\n green(\n addedCases.length === 1\n ? \"Case created!\"\n : `${addedCases.length} cases created!`\n )\n );\n console.log();\n console.log(renderTable(TABLE_COLUMNS, addedCases));\n });\n}\n\nfunction collectLabel(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nasync function buildRequestBody(\n options: CreateOptions\n): Promise<{ case?: CaseInput; cases?: CaseInput[] }> {\n if (options.fromFile !== undefined) {\n if (\n options.title !== undefined ||\n options.data !== undefined ||\n (options.label?.length ?? 0) > 0\n ) {\n throw new CliError(\n \"--from-file cannot be combined with --title, --data, or --label.\"\n );\n }\n\n return readCasesFromFile(options.fromFile);\n }\n\n if (options.title === undefined || options.title.trim().length === 0) {\n throw new CliError(\"--title is required (or use --from-file).\");\n }\n\n const labels = parseLabels(options.label);\n const single: CaseInput = { title: options.title };\n if (options.data !== undefined) {\n single.data = options.data;\n }\n\n if (labels) {\n single.labels = labels;\n }\n\n return { case: single };\n}\n\nasync function readCasesFromFile(\n path: string\n): Promise<{ case?: CaseInput; cases?: CaseInput[] }> {\n let raw: string;\n try {\n raw = path === \"-\" ? await readStdin() : await readFile(path, \"utf8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Could not read cases file \"${path}\": ${message}`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Cases file \"${path}\" is not valid JSON: ${message}`);\n }\n\n if (Array.isArray(parsed)) {\n if (parsed.length === 0) {\n throw new CliError(\"Cases file must contain at least one case.\");\n }\n\n if (parsed.length > 100) {\n throw new CliError(\"Cases file must contain at most 100 cases.\");\n }\n\n return { cases: parsed.map((c, i) => coerceCase(c, `cases[${i}]`)) };\n }\n\n return { case: coerceCase(parsed, \"case\") };\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction coerceCase(value: unknown, location: string): CaseInput {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new CliError(`${location} must be a JSON object.`);\n }\n\n const obj = value as Record<string, unknown>;\n const title = obj.title;\n if (typeof title !== \"string\" || title.trim().length === 0) {\n throw new CliError(`${location}.title must be a non-empty string.`);\n }\n\n const out: CaseInput = { title };\n if (obj.data !== undefined) {\n if (typeof obj.data !== \"string\") {\n throw new CliError(`${location}.data must be a string when present.`);\n }\n\n out.data = obj.data;\n }\n\n if (obj.labels !== undefined) {\n if (!Array.isArray(obj.labels)) {\n throw new CliError(`${location}.labels must be an array when present.`);\n }\n\n out.labels = obj.labels.map((l, i) =>\n coerceLabel(l, `${location}.labels[${i}]`)\n );\n }\n\n return out;\n}\n\nfunction coerceLabel(\n value: unknown,\n location: string\n): { key: string; value: string } {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new CliError(`${location} must be a JSON object.`);\n }\n\n const obj = value as Record<string, unknown>;\n const labelValue = obj.value;\n if (typeof labelValue !== \"string\" || labelValue.length === 0) {\n throw new CliError(`${location}.value must be a non-empty string.`);\n }\n\n const key = obj.key === undefined ? \"\" : obj.key;\n if (typeof key !== \"string\") {\n throw new CliError(`${location}.key must be a string when present.`);\n }\n\n return { key, value: labelValue };\n}\n\nfunction parseLabels(\n raw: string[] | undefined\n): { key: string; value: string }[] | undefined {\n if (!raw || raw.length === 0) {\n return undefined;\n }\n\n return raw.map((entry) => {\n const eq = entry.indexOf(\"=\");\n if (eq === -1) {\n const trimmed = entry.trim();\n if (trimmed.length === 0) {\n throw new CliError(\"Label value must be a non-empty string.\");\n }\n\n return { key: \"\", value: trimmed };\n }\n\n if (eq === 0) {\n throw new CliError(\n `Invalid label \"${entry}\": omit the leading \"=\" for a simple tag (use \"value\") or provide a non-empty key (use \"key=value\").`\n );\n }\n\n const key = entry.slice(0, eq).trim();\n if (key.length === 0) {\n throw new CliError(\n `Invalid label \"${entry}\": omit the leading \"=\" for a simple tag (use \"value\") or provide a non-empty key (use \"key=value\").`\n );\n }\n\n const value = entry.slice(eq + 1).trim();\n if (value.length === 0) {\n throw new CliError(`Label \"${entry}\" has an empty value.`);\n }\n\n return { key, value };\n });\n}\n", "import { caseDeleteResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype DeleteOptions = {\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerCasesDelete(cases: Command): void {\n cases\n .command(\"delete <id>\")\n .description(\"Delete a case. Interrupts any associated running jobs.\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function deleteAction(\n this: Command,\n id: string,\n options: DeleteOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Delete case \"${id}\"?`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/cases/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseDeleteResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const result = parsed.data;\n if (!result.success) {\n throw new CliError(\"Failed to delete case.\");\n }\n\n console.log(green(\"Case deleted!\"));\n console.log();\n console.log(\n renderKeyValue([\n {\n label: \"Interrupted runs\",\n value: String(result.interruptedRunIds.length),\n },\n ])\n );\n });\n}\n", "import { caseDetailResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype GetOptions = {\n json?: boolean;\n};\n\nexport function registerCasesGet(cases: Command): void {\n cases\n .command(\"get <id>\")\n .description(\"Get a case by ID with its event history\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function getAction(\n this: Command,\n id: string,\n options: GetOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/cases/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseDetailResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { case: caseItem, events } = parsed.data;\n\n console.log(\n renderKeyValue([\n { label: \"ID\", value: caseItem.id },\n { label: \"Queue\", value: caseItem.queue_id },\n { label: \"Title\", value: caseItem.title },\n { label: \"Status\", value: caseItem.status },\n { label: \"Data\", value: caseItem.data ?? \"\" },\n { label: \"Claimed\", value: caseItem.claimed_at ?? \"\" },\n { label: \"Claimed by run\", value: caseItem.claimed_by_run_id ?? \"\" },\n { label: \"Completed\", value: caseItem.completed_at ?? \"\" },\n { label: \"Postponed to\", value: caseItem.postponed_to ?? \"\" },\n { label: \"Created\", value: caseItem.created_at ?? \"\" },\n { label: \"Updated\", value: caseItem.updated_at ?? \"\" },\n ])\n );\n\n if (events && events.length > 0) {\n console.log(\"\");\n console.log(`Events (${events.length}):`);\n for (const event of events) {\n console.log(` - ${event.created_at ?? \"\"} ${event.type}`);\n }\n }\n });\n}\n", "import {\n caseLabelAssignResponseSchema,\n caseLabelsListResponseSchema,\n caseLabelUnlinkResponseSchema,\n type CaseQueueLabel,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\nconst MAX_LABELS_PER_REQUEST = 50;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: CaseQueueLabel) => row.id },\n { header: \"KEY\", cell: (row: CaseQueueLabel) => row.key },\n { header: \"VALUE\", cell: (row: CaseQueueLabel) => row.value },\n { header: \"COLOR HUE\", cell: (row: CaseQueueLabel) => String(row.color_hue) },\n] as const;\n\ntype ListOptions = {\n queue: string;\n json?: boolean;\n};\n\ntype AssignOptions = {\n queue: string;\n label?: string[];\n json?: boolean;\n};\n\ntype UnlinkOptions = {\n queue: string;\n labelId?: string[];\n json?: boolean;\n};\n\nexport function registerCasesLabels(cases: Command): void {\n const labels = cases\n .command(\"labels\")\n .description(\"Manage labels assigned to a case\");\n\n labels\n .command(\"list <case-id>\")\n .description(\"List labels assigned to a case\")\n .requiredOption(\"--queue <id>\", \"ID of the queue the case belongs to\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(\n this: Command,\n caseId: string,\n options: ListOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases/${encodeURIComponent(caseId)}/labels`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseLabelsListResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.labels.length === 0) {\n console.log(\"No labels assigned.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, parsed.data.labels));\n console.log(`Showing ${parsed.data.labels.length}`);\n });\n\n labels\n .command(\"assign <case-id>\")\n .description(\n \"Assign one or more labels to a case (creates labels on the queue if they don't exist)\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue the case belongs to\")\n .requiredOption(\n \"--label <kv>\",\n 'label as \"key=value\" or \"value\" for tag-only (repeatable, 1-50)',\n collectRepeatable,\n [] as string[]\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function assignAction(\n this: Command,\n caseId: string,\n options: AssignOptions\n ) {\n const labelInputs = options.label ?? [];\n if (labelInputs.length === 0) {\n throw new CliError(\"Pass at least one --label\");\n }\n\n if (labelInputs.length > MAX_LABELS_PER_REQUEST) {\n throw new CliError(\n `Pass at most ${MAX_LABELS_PER_REQUEST} --label values per request`\n );\n }\n\n const labelEntries = labelInputs.map(parseLabel);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases/${encodeURIComponent(caseId)}/labels`,\n apiKey,\n apiBaseUrl,\n body: { labels: labelEntries },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseLabelAssignResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n console.log(green(\"Labels assigned!\"));\n console.log(renderTable(TABLE_COLUMNS, parsed.data.labels));\n });\n\n labels\n .command(\"unlink <case-id>\")\n .description(\"Remove one or more labels from a case\")\n .requiredOption(\"--queue <id>\", \"ID of the queue the case belongs to\")\n .requiredOption(\n \"--label-id <id>\",\n \"label ID to unlink (repeatable, at least one required)\",\n collectRepeatable,\n [] as string[]\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function unlinkAction(\n this: Command,\n caseId: string,\n options: UnlinkOptions\n ) {\n const labelIds = options.labelId ?? [];\n if (labelIds.length === 0) {\n throw new CliError(\"Pass at least one --label-id\");\n }\n\n if (labelIds.length > MAX_LABELS_PER_REQUEST) {\n throw new CliError(\n `Pass at most ${MAX_LABELS_PER_REQUEST} --label-id values per request`\n );\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases/${encodeURIComponent(caseId)}/labels/unlink`,\n apiKey,\n apiBaseUrl,\n body: { label_ids: labelIds },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseLabelUnlinkResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n throw new CliError(\"Failed to unlink labels.\");\n }\n\n console.log(green(`Unlinked ${labelIds.length} label(s).`));\n });\n}\n\nfunction collectRepeatable(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nfunction parseLabel(input: string): { key: string; value: string } {\n const eq = input.indexOf(\"=\");\n if (eq === -1) {\n const value = input.trim();\n if (value.length === 0) {\n throw new CliError(`--label \"${input}\" must have a non-empty value`);\n }\n\n return { key: \"\", value };\n }\n\n const key = input.slice(0, eq).trim();\n const value = input.slice(eq + 1).trim();\n if (key.length === 0) {\n throw new CliError(\n `--label \"${input}\" must have a non-empty key (drop the leading \\`=\\` for tag-only labels)`\n );\n }\n\n if (value.length === 0) {\n throw new CliError(`--label \"${input}\" must have a non-empty value`);\n }\n\n return { key, value };\n}\n", "import {\n type CaseFilterStatus,\n caseFilterStatusSchema,\n type CaseQueueItem,\n casesListResponseSchema,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { parseLimit, parseOffset } from \"../shared/pagination.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n queue: string;\n limit?: string;\n offset?: string;\n status?: string;\n search?: string;\n createdAtFrom?: string;\n updatedAtFrom?: string;\n sortBy?: string;\n sortOrder?: string;\n json?: boolean;\n};\n\nconst DEFAULT_LIMIT = 20;\nconst MIN_LIMIT = 1;\nconst MAX_LIMIT = 100;\nconst SORT_FIELDS = [\"created_at\", \"updated_at\", \"postponed_to\"] as const;\nconst SORT_ORDERS = [\"asc\", \"desc\"] as const;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: CaseQueueItem) => row.id },\n { header: \"TITLE\", cell: (row: CaseQueueItem) => row.title, maxWidth: 50 },\n { header: \"STATUS\", cell: (row: CaseQueueItem) => row.status },\n { header: \"CREATED\", cell: (row: CaseQueueItem) => row.created_at ?? \"\" },\n] as const;\n\nexport function registerCasesList(cases: Command): void {\n cases\n .command(\"list\", { isDefault: true })\n .description(\"List cases in a queue\")\n .requiredOption(\"--queue <id>\", \"ID of the queue to list cases for\")\n .option(\"--limit <n>\", `page size (${MIN_LIMIT}-${MAX_LIMIT})`)\n .option(\"--offset <n>\", \"number of cases to skip\")\n .option(\n \"--status <statuses>\",\n `comma-separated case statuses (${caseFilterStatusSchema.options.join(\", \")})`\n )\n .option(\"--search <text>\", \"full-text search across title and data\")\n .option(\n \"--created-at-from <iso>\",\n \"include cases created on or after this ISO-8601 timestamp\"\n )\n .option(\n \"--updated-at-from <iso>\",\n \"include cases updated on or after this ISO-8601 timestamp\"\n )\n .option(\"--sort-by <field>\", `sort field (${SORT_FIELDS.join(\", \")})`)\n .option(\n \"--sort-order <order>\",\n `sort direction (${SORT_ORDERS.join(\", \")})`\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const limit = parseLimit(options.limit, {\n defaultValue: DEFAULT_LIMIT,\n min: MIN_LIMIT,\n max: MAX_LIMIT,\n });\n const offset = parseOffset(options.offset);\n const statuses = parseStatuses(options.status);\n const sortBy = parseSortBy(options.sortBy);\n const sortOrder = parseSortOrder(options.sortOrder);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", String(limit));\n searchParams.append(\"offset\", String(offset));\n if (statuses) {\n searchParams.append(\"status\", statuses.join(\",\"));\n }\n\n if (options.search !== undefined) {\n searchParams.append(\"search\", options.search);\n }\n\n if (options.createdAtFrom !== undefined) {\n searchParams.append(\"created_at_from\", options.createdAtFrom);\n }\n\n if (options.updatedAtFrom !== undefined) {\n searchParams.append(\"updated_at_from\", options.updatedAtFrom);\n }\n\n if (sortBy !== undefined) {\n searchParams.append(\"sort_by\", sortBy);\n }\n\n if (sortOrder !== undefined) {\n searchParams.append(\"sort_order\", sortOrder);\n }\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/cases`,\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = casesListResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const response = parsed.data;\n\n if (response.cases.length === 0) {\n console.log(\"No cases found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, response.cases));\n const resolvedOffset = response.offset ?? offset;\n const total = response.total ?? null;\n const summary =\n total === null\n ? `Showing ${response.cases.length} \u00B7 offset ${resolvedOffset}`\n : `Showing ${response.cases.length} of ${total} \u00B7 offset ${resolvedOffset}`;\n console.log(summary);\n });\n}\n\nfunction parseStatuses(\n raw: string | undefined\n): CaseFilterStatus[] | undefined {\n if (raw === undefined) {\n return undefined;\n }\n\n const parts = raw\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n throw new CliError(\n `Invalid --status value \"${raw}\". Allowed: ${caseFilterStatusSchema.options.join(\", \")}.`\n );\n }\n\n const allowed = new Set<string>(caseFilterStatusSchema.options);\n const invalid = parts.filter((p) => !allowed.has(p));\n if (invalid.length > 0) {\n throw new CliError(\n `Invalid --status value(s): ${invalid.join(\", \")}. Allowed: ${caseFilterStatusSchema.options.join(\", \")}.`\n );\n }\n\n return parts as CaseFilterStatus[];\n}\n\nfunction parseSortBy(raw: string | undefined): string | undefined {\n if (raw === undefined) {\n return undefined;\n }\n\n if (!SORT_FIELDS.includes(raw as (typeof SORT_FIELDS)[number])) {\n throw new CliError(\n `Invalid --sort-by value \"${raw}\". Allowed: ${SORT_FIELDS.join(\", \")}.`\n );\n }\n\n return raw;\n}\n\nfunction parseSortOrder(raw: string | undefined): string | undefined {\n if (raw === undefined) {\n return undefined;\n }\n\n if (!SORT_ORDERS.includes(raw as (typeof SORT_ORDERS)[number])) {\n throw new CliError(\n `Invalid --sort-order value \"${raw}\". Allowed: ${SORT_ORDERS.join(\", \")}.`\n );\n }\n\n return raw;\n}\n", "import { caseJobsResponseSchema, type CaseJobSummary } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype RunsOptions = {\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"RUN ID\", cell: (row: CaseJobSummary) => row.id },\n { header: \"AGENT\", cell: (row: CaseJobSummary) => row.agent_name },\n { header: \"STATUS\", cell: (row: CaseJobSummary) => row.status },\n { header: \"CLAIMED\", cell: (row: CaseJobSummary) => row.claimed_at },\n {\n header: \"COMPLETED\",\n cell: (row: CaseJobSummary) => row.completed_at ?? \"\",\n },\n {\n header: \"PENDING REQUEST\",\n cell: (row: CaseJobSummary) =>\n row.has_pending_human_request\n ? (row.pending_human_request_title ?? \"(unknown)\")\n : \"\",\n },\n] as const;\n\nexport function registerCasesRuns(cases: Command): void {\n cases\n .command(\"runs <case-id>\")\n .description(\"List jobs (agent runs) that have worked on a case\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function runsAction(\n this: Command,\n caseId: string,\n options: RunsOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/cases/${encodeURIComponent(caseId)}/runs`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseJobsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.runs.length === 0) {\n console.log(\"No runs found for this case.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, parsed.data.runs));\n console.log(`Showing ${parsed.data.runs.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerCasesBulkDelegate } from \"./bulk-delegate.js\";\nimport { registerCasesBulkDelete } from \"./bulk-delete.js\";\nimport { registerCasesBulkRetry } from \"./bulk-retry.js\";\nimport { registerCasesBulkUpdateStatus } from \"./bulk-update-status.js\";\nimport { registerCasesClear } from \"./clear.js\";\nimport { registerCasesCreate } from \"./create.js\";\nimport { registerCasesDelete } from \"./delete.js\";\nimport { registerCasesGet } from \"./get.js\";\nimport { registerCasesLabels } from \"./labels.js\";\nimport { registerCasesList } from \"./list.js\";\nimport { registerCasesRuns } from \"./runs.js\";\n\nexport function registerCases(program: Command): void {\n const cases = program\n .command(\"cases\")\n .description(\"Manage cases in the Duvo public API\");\n\n registerCasesList(cases);\n registerCasesGet(cases);\n registerCasesCreate(cases);\n registerCasesDelete(cases);\n registerCasesClear(cases);\n registerCasesBulkDelete(cases);\n registerCasesBulkRetry(cases);\n registerCasesBulkUpdateStatus(cases);\n registerCasesBulkDelegate(cases);\n registerCasesRuns(cases);\n registerCasesLabels(cases);\n}\n", "import { type Command } from \"commander\";\n\nimport { connectionResponseSchema } from \"@/api/integration-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype GetOptions = {\n json?: boolean;\n};\n\nexport function registerConnectionsGet(connections: Command): void {\n connections\n .command(\"get <id>\")\n .description(\"Get one of your connections by ID\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function getAction(\n this: Command,\n id: string,\n options: GetOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/connections/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = connectionResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const connection = parsed.data;\n\n console.log(\n renderKeyValue([\n { label: \"ID\", value: connection.id },\n { label: \"Name\", value: connection.name },\n { label: \"Type\", value: connection.type },\n { label: \"Provider\", value: connection.provider },\n { label: \"Auth Method\", value: connection.auth_method ?? \"\" },\n { label: \"Server URL\", value: connection.server_url ?? \"\" },\n { label: \"Team\", value: connection.team_id },\n { label: \"User\", value: connection.user_id ?? \"\" },\n { label: \"Created\", value: connection.created_at },\n { label: \"Updated\", value: connection.updated_at },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport {\n type Integration,\n integrationsListResponseSchema,\n} from \"@/api/integration-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n type?: string;\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: Integration) => row.id },\n { header: \"NAME\", cell: (row: Integration) => row.name },\n { header: \"TYPE\", cell: (row: Integration) => row.type },\n { header: \"PROVIDER\", cell: (row: Integration) => row.provider },\n { header: \"CREATED\", cell: (row: Integration) => row.created_at },\n] as const;\n\nexport function registerConnectionsList(connections: Command): void {\n connections\n .command(\"list\", { isDefault: true })\n .description(\"List your connections (connected integration instances)\")\n .option(\"--type <type>\", \"filter by integration type\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n if (options.type) {\n searchParams.append(\"type\", options.type);\n }\n\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/connections\",\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = integrationsListResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { integrations: rows } = parsed.data;\n\n if (rows.length === 0) {\n console.log(\"No connections found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, rows));\n console.log(`Showing ${rows.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerConnectionsGet } from \"./get.js\";\nimport { registerConnectionsList } from \"./list.js\";\n\nexport function registerConnections(program: Command): void {\n const connections = program\n .command(\"connections\")\n .description(\"Manage your connections (connected integrations)\");\n\n registerConnectionsList(connections);\n registerConnectionsGet(connections);\n}\n", "import { teamFileContentResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ContentOptions = {\n json?: boolean;\n};\n\nexport function registerFilesContent(files: Command): void {\n files\n .command(\"content <path>\")\n .description(\"Get the content of a text file (binary files are rejected)\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function contentAction(\n this: Command,\n filePath: string,\n options: ContentOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const encodedPath = filePath\n .split(\"/\")\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/files/content/${encodedPath}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = teamFileContentResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n process.stdout.write(parsed.data.content);\n });\n}\n", "import { readFileSync } from \"node:fs\";\n\nimport { teamFileSuccessResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ContentSetOptions = {\n content?: string;\n contentFile?: string;\n json?: boolean;\n};\n\nexport function registerFilesContentSet(files: Command): void {\n files\n .command(\"content-set <path>\")\n .description(\"Update the content of a text file in team storage\")\n .option(\"--content <text>\", \"new content as a string\")\n .option(\n \"--content-file <path>\",\n 'path to a file with the new content, or \"-\" for stdin'\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function contentSetAction(\n this: Command,\n filePath: string,\n options: ContentSetOptions\n ) {\n if (options.content !== undefined && options.contentFile !== undefined) {\n throw new CliError(\n \"Pass either --content or --content-file, not both.\"\n );\n }\n\n const content = readContent(options);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const encodedPath = filePath\n .split(\"/\")\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n\n const raw = await httpRequest({\n method: \"PUT\",\n path: `/v1/files/content/${encodedPath}`,\n apiKey,\n apiBaseUrl,\n body: { content },\n });\n\n const parsed = teamFileSuccessResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n if (options.json) {\n printJson(raw);\n }\n\n throw new CliError(\"Failed to update file.\");\n }\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n console.log(green(\"File updated!\"));\n });\n}\n\nfunction readContent(options: ContentSetOptions): string {\n if (options.content !== undefined) {\n return options.content;\n }\n\n if (options.contentFile === undefined) {\n throw new CliError(\"Pass either --content or --content-file\");\n }\n\n if (options.contentFile === \"-\") {\n return readFileSync(0, \"utf8\");\n }\n\n try {\n return readFileSync(options.contentFile, \"utf8\");\n } catch (error) {\n throw new CliError(\n `Cannot read --content-file ${options.contentFile}: ${(error as Error).message}`\n );\n }\n}\n", "import { teamFileSuccessResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype DeleteOptions = {\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerFilesDelete(files: Command): void {\n files\n .command(\"delete <path>\")\n .description(\"Delete a team file\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function deleteAction(\n this: Command,\n filePath: string,\n options: DeleteOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Delete file \"${filePath}\"?`,\n skip: Boolean(options.yes),\n });\n\n const encodedPath = filePath\n .split(\"/\")\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/files/${encodedPath}`,\n apiKey,\n apiBaseUrl,\n });\n\n const parsed = teamFileSuccessResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n if (options.json) {\n printJson(raw);\n }\n\n throw new CliError(\"Failed to delete file.\");\n }\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n console.log(green(\"File deleted!\"));\n });\n}\n", "import { teamFileDownloadUrlResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype DownloadUrlOptions = {\n json?: boolean;\n};\n\nexport function registerFilesDownloadUrl(files: Command): void {\n files\n .command(\"download-url <path>\")\n .description(\"Get a presigned download URL for a team file\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function downloadUrlAction(\n this: Command,\n filePath: string,\n options: DownloadUrlOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const encodedPath = filePath\n .split(\"/\")\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/files/download-url/${encodedPath}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = teamFileDownloadUrlResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n console.log(\n renderKeyValue([\n { label: \"URL\", value: parsed.data.url },\n { label: \"Expires\", value: parsed.data.expiresAt },\n ])\n );\n });\n}\n", "import {\n listTeamFilesResponseSchema,\n type TeamFileItem,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"PATH\", cell: (row: TeamFileItem) => row.path },\n { header: \"NAME\", cell: (row: TeamFileItem) => row.name },\n {\n header: \"MIME\",\n cell: (row: TeamFileItem) => row.metadata?.mimetype ?? \"\",\n },\n {\n header: \"SIZE\",\n cell: (row: TeamFileItem) =>\n row.metadata?.size === undefined ? \"\" : String(row.metadata.size),\n },\n {\n header: \"UPDATED\",\n cell: (row: TeamFileItem) => row.updated_at ?? \"\",\n },\n] as const;\n\nexport function registerFilesList(files: Command): void {\n files\n .command(\"list\", { isDefault: true })\n .description(\"List team files\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/files\",\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listTeamFilesResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.files.length === 0) {\n console.log(\"No files found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, parsed.data.files));\n console.log(`Showing ${parsed.data.files.length}`);\n });\n}\n", "import { teamFileSuccessResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype RenameOptions = {\n path: string;\n newName: string;\n json?: boolean;\n};\n\nconst PATH_SEPARATOR = /[\\\\/]/;\n\nexport function registerFilesRename(files: Command): void {\n files\n .command(\"rename\")\n .description(\n \"Rename a team file (only the filename changes; extension is preserved)\"\n )\n .requiredOption(\"--path <path>\", \"current relative path of the file\")\n .requiredOption(\n \"--new-name <name>\",\n \"new filename without extension (extension is preserved automatically)\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function renameAction(this: Command, options: RenameOptions) {\n const newName = options.newName.trim();\n if (\n newName.length === 0 ||\n newName === \".\" ||\n newName === \"..\" ||\n PATH_SEPARATOR.test(newName)\n ) {\n throw new CliError(\n \"--new-name must be a filename only (no path separators, no `.` or `..`)\"\n );\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"PATCH\",\n path: \"/v1/files\",\n apiKey,\n apiBaseUrl,\n body: {\n relativePath: options.path,\n newFilenameOnly: newName,\n },\n });\n\n const parsed = teamFileSuccessResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n if (options.json) {\n printJson(raw);\n }\n\n throw new CliError(\"Failed to rename file.\");\n }\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n console.log(green(\"File renamed!\"));\n });\n}\n", "import { createTeamFileUploadUrlResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype UploadUrlOptions = {\n fileName: string;\n contentType: string;\n json?: boolean;\n};\n\nexport function registerFilesUploadUrl(files: Command): void {\n files\n .command(\"upload-url\")\n .description(\"Get a presigned upload URL for a team file\")\n .requiredOption(\"--file-name <name>\", \"name of the file to upload\")\n .requiredOption(\"--content-type <mime>\", \"MIME type of the file\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function uploadUrlAction(\n this: Command,\n options: UploadUrlOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/files/create-upload-url\",\n apiKey,\n apiBaseUrl,\n body: {\n fileName: options.fileName,\n contentType: options.contentType,\n },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = createTeamFileUploadUrlResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n console.log(\n renderKeyValue([\n { label: \"Path\", value: parsed.data.filePath },\n { label: \"Signed URL\", value: parsed.data.signedUrl },\n { label: \"Expires\", value: parsed.data.expiresAt },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerFilesContent } from \"./content.js\";\nimport { registerFilesContentSet } from \"./content-set.js\";\nimport { registerFilesDelete } from \"./delete.js\";\nimport { registerFilesDownloadUrl } from \"./download-url.js\";\nimport { registerFilesList } from \"./list.js\";\nimport { registerFilesRename } from \"./rename.js\";\nimport { registerFilesUploadUrl } from \"./upload-url.js\";\n\nexport function registerFiles(program: Command): void {\n const files = program\n .command(\"files\")\n .description(\"Manage team files exposed by the Duvo public API\");\n\n registerFilesList(files);\n registerFilesUploadUrl(files);\n registerFilesDownloadUrl(files);\n registerFilesRename(files);\n registerFilesDelete(files);\n registerFilesContent(files);\n registerFilesContentSet(files);\n}\n", "import { type Command } from \"commander\";\n\nimport {\n type Integration,\n integrationsListResponseSchema,\n} from \"@/api/integration-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: Integration) => row.id },\n { header: \"NAME\", cell: (row: Integration) => row.name },\n { header: \"TYPE\", cell: (row: Integration) => row.type },\n { header: \"PROVIDER\", cell: (row: Integration) => row.provider },\n {\n header: \"AUTH METHOD\",\n cell: (row: Integration) => row.auth_method ?? \"\",\n },\n] as const;\n\nexport function registerIntegrationsList(integrations: Command): void {\n integrations\n .command(\"list\", { isDefault: true })\n .description(\"List the team's integration catalog\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/integrations\",\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = integrationsListResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { integrations: rows } = parsed.data;\n\n if (rows.length === 0) {\n console.log(\"No integrations found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, rows));\n console.log(`Showing ${rows.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerIntegrationsList } from \"./list.js\";\n\nexport function registerIntegrations(program: Command): void {\n const integrations = program\n .command(\"integrations\")\n .description(\n \"List integrations available to your team. OAuth connections are created via the Duvo dashboard.\"\n );\n\n registerIntegrationsList(integrations);\n}\n", "import { isCancel, password, spinner, text } from \"@clack/prompts\";\nimport { type Command } from \"commander\";\n\nimport { DEFAULT_API_BASE_URL } from \"@/config/defaults.js\";\nimport { addProfile, isValidProfileName } from \"@/config/profiles.js\";\nimport { readConfig, writeConfig } from \"@/config/store.js\";\nimport { type OAuthProfile, type Profile } from \"@/config/types.js\";\nimport { CancelCliError, CliError } from \"@/errors.js\";\nimport {\n buildAuthorizationUrl,\n exchangeCodeForTokens,\n type TokenResponse,\n} from \"@/oauth/auth0-client.js\";\nimport { resolveAuth0Config } from \"@/oauth/auth0-config.js\";\nimport { startLoopbackServer } from \"@/oauth/loopback.js\";\nimport { openBrowser } from \"@/oauth/open-browser.js\";\nimport { generatePkcePair, generateState } from \"@/oauth/pkce.js\";\nimport { bold, cyan, green, red, yellow } from \"@/output/colors.js\";\n\nconst CALLBACK_TIMEOUT_MS = 120_000;\n\ntype LoginOptions = {\n name?: string;\n apiKey?: string;\n baseUrl?: string;\n};\n\nexport function registerLogin(program: Command): void {\n program\n .command(\"login\")\n .description(\"Sign in via OAuth (or store an API key with --api-key)\")\n .option(\n \"--name <profile>\",\n \"profile name to store this credential under (prompted if omitted)\"\n )\n .option(\n \"--api-key <key>\",\n \"API key (skips OAuth and stores the key directly)\"\n )\n .option(\n \"--base-url <url>\",\n `API base URL for this profile (default: ${DEFAULT_API_BASE_URL})`\n )\n .action(async (options: LoginOptions) => {\n await runLogin(options);\n });\n}\n\nasync function runLogin(options: LoginOptions): Promise<void> {\n const config = await readConfig();\n const existingCount = Object.keys(config.profiles).length;\n const name = await resolveProfileName(options.name, existingCount);\n const apiBaseUrl = options.baseUrl ?? DEFAULT_API_BASE_URL;\n const wasExisting = name in config.profiles;\n\n console.log(bold(yellow(\"Duvo CLI Authentication\")));\n console.log(\"\");\n\n let profile: Profile;\n try {\n profile = options.apiKey\n ? {\n type: \"api-key\",\n apiKey: await resolveApiKey(options.apiKey),\n apiBaseUrl,\n }\n : await runOAuthFlow(apiBaseUrl);\n } catch (err) {\n console.log(\"\");\n console.log(red(`\u2717 ${err instanceof Error ? err.message : String(err)}`));\n console.log(\"\");\n throw err;\n }\n\n const next = addProfile(config, name, profile);\n await writeConfig(next);\n\n console.log(\n green(`\u2713 ${wasExisting ? \"Updated\" : \"Saved\"} profile \"${name}\"`)\n );\n if (next.defaultProfile === name && config.defaultProfile !== name) {\n console.log(green(`\u2713 Default profile is now \"${name}\"`));\n }\n\n console.log(\"\");\n if (profile.type === \"oauth\" && profile.email) {\n console.log(\n `\uD83C\uDF89 Authentication successful. Welcome ${bold(profile.email)}`\n );\n } else {\n console.log(`Profile saved.`);\n }\n\n console.log(\"\");\n}\n\nasync function runOAuthFlow(apiBaseUrl: string): Promise<OAuthProfile> {\n const auth0 = resolveAuth0Config();\n const pkce = generatePkcePair();\n const state = generateState();\n const server = await startLoopbackServer();\n\n try {\n const authorizeUrl = buildAuthorizationUrl(auth0, {\n redirectUri: server.redirectUri,\n codeChallenge: pkce.challenge,\n state,\n });\n\n console.log(\"Opening your browser to complete Duvo sign-in...\");\n console.log(\"\");\n console.log(\n \"If the browser does not open or the login does not finish automatically, use this fallback URL:\"\n );\n console.log(cyan(authorizeUrl));\n console.log(\"\");\n\n openBrowser(authorizeUrl);\n\n const waiting = spinner();\n waiting.start(\"Waiting for browser approval\");\n\n let callback;\n try {\n callback = await server.waitForCallback(CALLBACK_TIMEOUT_MS);\n } catch (err) {\n waiting.stop(red(\"\u2717 Browser approval timed out\"), 2);\n throw err;\n }\n\n if (callback.state !== state) {\n waiting.stop(red(\"\u2717 Invalid state parameter\"), 2);\n throw new CliError(\n \"Invalid state parameter \u2014 possible CSRF attempt. Aborting login.\"\n );\n }\n\n waiting.stop(green(\"\u2713 Sign-in callback received\"));\n\n const exchanging = spinner();\n exchanging.start(\"Loading account\");\n\n let tokens;\n try {\n tokens = await exchangeCodeForTokens(auth0, {\n code: callback.code,\n codeVerifier: pkce.verifier,\n redirectUri: server.redirectUri,\n });\n } catch (err) {\n exchanging.stop(red(\"\u2717 Token exchange failed\"), 2);\n throw err;\n }\n\n const refreshToken = tokens.refresh_token;\n if (!refreshToken) {\n exchanging.stop(red(\"\u2717 Token exchange failed\"), 2);\n throw new CliError(\n \"Auth0 did not return a refresh token. Ensure `Allow Offline Access` is enabled on the Duvo API.\"\n );\n }\n\n exchanging.stop(green(\"\u2713 Account loaded\"));\n\n return profileFromTokens({ tokens, refreshToken, auth0, apiBaseUrl });\n } finally {\n await server.close();\n }\n}\n\nfunction profileFromTokens(args: {\n tokens: TokenResponse;\n refreshToken: string;\n auth0: ReturnType<typeof resolveAuth0Config>;\n apiBaseUrl: string;\n}): OAuthProfile {\n const { tokens, refreshToken, auth0, apiBaseUrl } = args;\n const expiresAt = Date.now() + tokens.expires_in * 1000;\n const claims = decodeJwtClaims(tokens.access_token);\n const idClaims = tokens.id_token\n ? decodeJwtClaims(tokens.id_token)\n : undefined;\n\n return {\n type: \"oauth\",\n apiBaseUrl,\n accessToken: tokens.access_token,\n refreshToken,\n expiresAt,\n issuer: auth0.issuer,\n clientId: auth0.clientId,\n userId: typeof claims?.sub === \"string\" ? claims.sub : undefined,\n email: typeof idClaims?.email === \"string\" ? idClaims.email : undefined,\n };\n}\n\nfunction decodeJwtClaims(token: string): Record<string, unknown> | null {\n const parts = token.split(\".\");\n if (parts.length !== 3) {\n return null;\n }\n\n try {\n const padded = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (padded.length % 4)) % 4);\n const json = Buffer.from(padded + padding, \"base64\").toString(\"utf8\");\n return JSON.parse(json) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\nasync function resolveProfileName(\n flag: string | undefined,\n existingCount: number\n): Promise<string> {\n if (flag !== undefined) {\n if (!isValidProfileName(flag)) {\n throw new CliError(\n `Invalid profile name \"${flag}\". Use lowercase letters, digits, ` +\n `\".\", \"-\" or \"_\", max 40 chars.`\n );\n }\n\n return flag;\n }\n\n const placeholder = existingCount === 0 ? \"default\" : \"\";\n const answer = await text({\n message: \"Profile name\",\n placeholder: placeholder || \"e.g. acme\",\n defaultValue: placeholder,\n validate: (value) => {\n if (!value || value.length === 0) {\n return \"Profile name is required.\";\n }\n\n if (!isValidProfileName(value)) {\n return 'Use lowercase letters, digits, \".\", \"-\" or \"_\" only (max 40 chars).';\n }\n\n return undefined;\n },\n });\n if (isCancel(answer)) {\n throw new CancelCliError(\"Login cancelled.\");\n }\n\n return answer;\n}\n\nasync function resolveApiKey(flag: string): Promise<string> {\n if (flag.length > 0) {\n return flag;\n }\n\n const answer = await password({\n message: \"API key\",\n validate: (value) => {\n if (!value || value.length === 0) {\n return \"API key is required.\";\n }\n\n return undefined;\n },\n });\n if (isCancel(answer)) {\n throw new CancelCliError(\"Login cancelled.\");\n }\n\n return answer;\n}\n", "/**\n * Auth0 configuration for the Duvo CLI.\n *\n * Values are baked into the published binary at build time. The CLI's Auth0\n * application is owned by Duvo \u2014 there is no per-user setup. The constants\n * below are the dev-tenant defaults; prod CI overrides them via esbuild's\n * `define` (see `scripts/build.mjs`).\n *\n * The `client_id` is the Auth0-generated opaque identifier for the static\n * `Duvo CLI` Native application. The literal string `duvo-cli` is the\n * human-readable name; never send it as a `client_id` value.\n */\nexport type Auth0Config = {\n domain: string;\n clientId: string;\n audience: string;\n issuer: string;\n};\n\ndeclare const __DUVO_CLI_DOMAIN__: string | undefined;\ndeclare const __DUVO_CLI_CLIENT_ID__: string | undefined;\ndeclare const __DUVO_CLI_AUDIENCE__: string | undefined;\n\nconst BAKED_DOMAIN =\n typeof __DUVO_CLI_DOMAIN__ !== \"undefined\" && __DUVO_CLI_DOMAIN__\n ? __DUVO_CLI_DOMAIN__\n : \"login.dev.duvo.ai\";\n\nconst BAKED_CLIENT_ID =\n typeof __DUVO_CLI_CLIENT_ID__ !== \"undefined\" && __DUVO_CLI_CLIENT_ID__\n ? __DUVO_CLI_CLIENT_ID__\n : \"mq4MhUUHRNKrzkqr1MnAJdcvv5MNfuBU\";\n\nconst BAKED_AUDIENCE =\n typeof __DUVO_CLI_AUDIENCE__ !== \"undefined\" && __DUVO_CLI_AUDIENCE__\n ? __DUVO_CLI_AUDIENCE__\n : \"https://api.dev.duvo.ai\";\n\nexport function resolveAuth0Config(): Auth0Config {\n return {\n domain: BAKED_DOMAIN,\n clientId: BAKED_CLIENT_ID,\n audience: BAKED_AUDIENCE,\n issuer: `https://${BAKED_DOMAIN}/`,\n };\n}\n", "import { createServer, type Server } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\n\nimport { CliError } from \"@/errors.js\";\n\nconst LOOPBACK_PORTS = [49152, 49153, 49154, 49155, 49156] as const;\nconst HOST = \"127.0.0.1\";\n\nexport type LoopbackResult = {\n code: string;\n state: string;\n};\n\nexport type LoopbackServer = {\n redirectUri: string;\n /** Resolves once Auth0 redirects to /callback (or rejects on timeout / error). */\n waitForCallback: (timeoutMs: number) => Promise<LoopbackResult>;\n close: () => Promise<void>;\n};\n\n/**\n * Start an HTTP server on the first bindable port from `LOOPBACK_PORTS`.\n * Auth0 does not honor RFC 8252 \u00A77.3 wildcard-port matching, so we register\n * five exact callbacks in the Auth0 application and try them in order.\n */\nexport async function startLoopbackServer(): Promise<LoopbackServer> {\n const result = await tryBindNext([...LOOPBACK_PORTS]);\n if (!result) {\n throw new CliError(\n `Could not bind to a local port \u2014 tried ${LOOPBACK_PORTS.join(\", \")}.`\n );\n }\n\n const redirectUri = `http://${HOST}:${result.port}/callback`;\n return wrapServer(result.server, redirectUri);\n}\n\nasync function tryBindNext(\n ports: number[]\n): Promise<{ server: Server; port: number } | null> {\n if (ports.length === 0) {\n return null;\n }\n\n const [port, ...rest] = ports;\n const server = await tryBind(port);\n if (server) {\n return { server, port };\n }\n\n return tryBindNext(rest);\n}\n\nasync function tryBind(port: number): Promise<Server | null> {\n return new Promise((resolve) => {\n const server = createServer();\n const onError = (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\" || err.code === \"EACCES\") {\n resolve(null);\n return;\n }\n\n server.close();\n resolve(null);\n };\n\n server.once(\"error\", onError);\n server.listen(port, HOST, () => {\n server.removeListener(\"error\", onError);\n const address = server.address() as AddressInfo | null;\n if (!address || address.port !== port) {\n server.close();\n resolve(null);\n return;\n }\n\n resolve(server);\n });\n });\n}\n\nfunction wrapServer(server: Server, redirectUri: string): LoopbackServer {\n let resolved = false;\n let resolver: ((value: LoopbackResult) => void) | null = null;\n let rejecter: ((error: Error) => void) | null = null;\n\n server.on(\"request\", (req, res) => {\n if (!req.url) {\n res.statusCode = 400;\n res.end(\"Bad Request\");\n return;\n }\n\n const url = new URL(req.url, redirectUri);\n if (url.pathname !== \"/callback\") {\n res.statusCode = 404;\n res.end(\"Not Found\");\n return;\n }\n\n const error = url.searchParams.get(\"error\");\n const code = url.searchParams.get(\"code\");\n const state = url.searchParams.get(\"state\");\n\n if (error) {\n const description = url.searchParams.get(\"error_description\") ?? error;\n res.statusCode = 400;\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.end(renderHtml(`Authorization failed: ${description}`));\n if (!resolved && rejecter) {\n resolved = true;\n rejecter(new CliError(`Authorization denied: ${description}`));\n }\n\n return;\n }\n\n if (!code || !state) {\n res.statusCode = 400;\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.end(renderHtml(\"Missing code or state.\"));\n if (!resolved && rejecter) {\n resolved = true;\n rejecter(new CliError(\"Callback missing code or state.\"));\n }\n\n return;\n }\n\n res.statusCode = 200;\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.end(renderHtml(\"You are now signed in. You can close this tab.\"));\n if (!resolved && resolver) {\n resolved = true;\n resolver({ code, state });\n }\n });\n\n return {\n redirectUri,\n waitForCallback(timeoutMs) {\n return new Promise<LoopbackResult>((resolve, reject) => {\n resolver = resolve;\n rejecter = reject;\n const timer = setTimeout(() => {\n if (!resolved) {\n resolved = true;\n reject(new CliError(\"Authorization timed out.\"));\n }\n }, timeoutMs);\n timer.unref();\n });\n },\n async close() {\n await new Promise<void>((resolve) => server.close(() => resolve()));\n },\n };\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n};\n\nfunction renderHtml(message: string): string {\n const safe = message.replace(/[&<>]/g, (c) => HTML_ESCAPES[c] ?? c);\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <title>Duvo CLI</title>\n <style>\n body { font-family: system-ui, sans-serif; padding: 4rem; text-align: center; }\n .card { display: inline-block; padding: 2rem 3rem; border-radius: 12px; background: #f6f8fa; }\n </style>\n </head>\n <body>\n <div class=\"card\">\n <h2>Duvo CLI</h2>\n <p>${safe}</p>\n </div>\n </body>\n</html>`;\n}\n", "import { spawn, type SpawnOptions } from \"node:child_process\";\nimport { platform } from \"node:os\";\n\ntype SpawnPlan = {\n command: string;\n args: readonly string[];\n options: SpawnOptions;\n};\n\nconst BASE_OPTIONS: SpawnOptions = {\n detached: true,\n stdio: \"ignore\",\n shell: false,\n};\n\nfunction spawnPlanFor(url: string): SpawnPlan {\n const os = platform();\n if (os === \"darwin\") {\n return { command: \"open\", args: [url], options: BASE_OPTIONS };\n }\n\n if (os === \"win32\") {\n // OAuth URLs always contain `&`. On Windows, libuv's quote_cmd_arg\n // only quotes args containing whitespace or double-quote, so a raw\n // URL is passed unquoted to cmd.exe and `&` is interpreted as a\n // command separator before `start` ever sees its argv. The fix is\n // `windowsVerbatimArguments: true` (Node skips its own quoting) plus\n // pre-quoting the URL ourselves. The empty `\"\"` is a placeholder\n // window title \u2014 without it `start` treats the first quoted argument\n // as the title and the URL never opens.\n return {\n command: \"cmd.exe\",\n args: [\"/c\", \"start\", '\"\"', `\"${url}\"`],\n options: { ...BASE_OPTIONS, windowsVerbatimArguments: true },\n };\n }\n\n return { command: \"xdg-open\", args: [url], options: BASE_OPTIONS };\n}\n\nexport function openBrowser(url: string): void {\n const { command, args, options } = spawnPlanFor(url);\n\n try {\n const child = spawn(command, args, options);\n child.on(\"error\", () => {\n // Browser launch failure is non-fatal \u2014 the URL is also printed.\n });\n child.unref();\n } catch {\n // Best-effort. The user can still copy the URL from the terminal.\n }\n}\n", "import { createHash, randomBytes } from \"node:crypto\";\n\nexport type PkcePair = {\n verifier: string;\n challenge: string;\n};\n\nfunction base64url(buffer: Buffer): string {\n return buffer\n .toString(\"base64\")\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/, \"\");\n}\n\nexport function generatePkcePair(): PkcePair {\n const verifier = base64url(randomBytes(32));\n const challenge = base64url(createHash(\"sha256\").update(verifier).digest());\n return { verifier, challenge };\n}\n\nexport function generateState(): string {\n return base64url(randomBytes(24));\n}\n", "import { type Command } from \"commander\";\n\nimport { removeProfile } from \"@/config/profiles.js\";\nimport { readConfig, writeConfig } from \"@/config/store.js\";\nimport { type OAuthProfile, type Profile } from \"@/config/types.js\";\nimport { revokeRefreshToken } from \"@/oauth/auth0-client.js\";\nimport { resolveAuth0Config } from \"@/oauth/auth0-config.js\";\n\nimport { confirmDestructive } from \"./shared/confirm.js\";\n\ntype LogoutOptions = {\n name?: string;\n yes?: boolean;\n all?: boolean;\n};\n\nexport function registerLogout(program: Command): void {\n program\n .command(\"logout\")\n .description(\n \"Sign out of a profile (revokes OAuth tokens server-side and removes the profile)\"\n )\n .option(\n \"--name <profile>\",\n \"profile to remove (defaults to the default profile)\"\n )\n .option(\"--all\", \"log out of every stored profile\")\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .action(async (options: LogoutOptions) => {\n await runLogout(options);\n });\n}\n\nasync function runLogout(options: LogoutOptions): Promise<void> {\n const config = await readConfig();\n\n if (options.all) {\n const names = Object.keys(config.profiles);\n if (names.length === 0) {\n console.log(\"No profiles to remove.\");\n return;\n }\n\n await confirmDestructive({\n message: `Remove ${names.length} profile(s)?`,\n skip: options.yes ?? false,\n });\n\n await Promise.all(\n names.map((name) => tryRevokeOAuth(config.profiles[name], name))\n );\n\n let next = config;\n for (const name of names) {\n next = removeProfile(next, name);\n }\n\n await writeConfig(next);\n console.log(\"Logged out of all profiles.\");\n return;\n }\n\n const target = options.name ?? config.defaultProfile;\n if (!target) {\n console.log(\"No profile to remove \u2014 you are not logged in.\");\n return;\n }\n\n if (!(target in config.profiles)) {\n console.log(`Profile \"${target}\" does not exist.`);\n return;\n }\n\n await confirmDestructive({\n message: `Remove profile \"${target}\"?`,\n skip: options.yes ?? false,\n });\n\n await tryRevokeOAuth(config.profiles[target], target);\n const next = removeProfile(config, target);\n await writeConfig(next);\n\n console.log(`Logged out of profile \"${target}\".`);\n if (next.defaultProfile && next.defaultProfile !== config.defaultProfile) {\n console.log(`Default profile is now \"${next.defaultProfile}\".`);\n } else if (!next.defaultProfile) {\n console.log(\"No profiles remaining.\");\n }\n}\n\nasync function tryRevokeOAuth(profile: Profile, name: string): Promise<void> {\n if (profile.type !== \"oauth\") {\n return;\n }\n\n try {\n await revokeOAuthProfile(profile);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.warn(\n `Local tokens cleared, but server-side revocation failed for \"${name}\": ${message}`\n );\n }\n}\n\nasync function revokeOAuthProfile(profile: OAuthProfile): Promise<void> {\n const auth0 = resolveAuth0Config();\n await revokeRefreshToken(\n {\n ...auth0,\n clientId: profile.clientId,\n issuer: profile.issuer,\n },\n profile.refreshToken\n );\n}\n", "import {\n type CatalogPlugin,\n pluginCatalogResponseSchema,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"NAME\", cell: (row: CatalogPlugin) => row.name },\n { header: \"TYPE\", cell: (row: CatalogPlugin) => row.type },\n {\n header: \"DESCRIPTION\",\n cell: (row: CatalogPlugin) => row.description,\n maxWidth: 60,\n },\n] as const;\n\nexport function registerPluginsList(plugins: Command): void {\n plugins\n .command(\"list\", { isDefault: true })\n .description(\n \"List plugins that can be referenced by name in a build's plugins array\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/plugins/catalog\",\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = pluginCatalogResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.plugins.length === 0) {\n console.log(\"No plugins found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, parsed.data.plugins));\n console.log(`Showing ${parsed.data.plugins.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerPluginsList } from \"./list.js\";\n\nexport function registerPlugins(program: Command): void {\n const plugins = program\n .command(\"plugins\")\n .description(\n \"Browse plugins that can be referenced in a build's plugins array\"\n );\n\n registerPluginsList(plugins);\n}\n", "const FALLBACK_PREFIX_LEN = 11;\n\n/**\n * Mask the secret portion of an API key, leaving the non-secret prefix\n * visible so users can distinguish keys in listings.\n *\n * Keys have the shape `dv_<prefix>-<secret>`. Everything up to and\n * including the first `-` is the public id; everything after is masked.\n * Keys without a dash (shouldn't happen in practice) fall back to a\n * fixed-length prefix so we never leak the tail regardless of format.\n */\nexport function truncateApiKey(key: string): string {\n const dashIdx = key.indexOf(\"-\");\n const visibleLen = dashIdx >= 0 ? dashIdx + 1 : FALLBACK_PREFIX_LEN;\n if (key.length <= visibleLen) {\n return key;\n }\n\n const visible = key.slice(0, visibleLen);\n const masked = \"*\".repeat(key.length - visibleLen);\n return `${visible}${masked}`;\n}\n\nexport function padRight(value: string, width: number): string {\n if (value.length >= width) {\n return value;\n }\n\n return value + \" \".repeat(width - value.length);\n}\n", "import { type ProfileSummary } from \"@/config/profiles.js\";\nimport { truncateApiKey } from \"@/output/format.js\";\nimport { type Column, renderTable } from \"@/output/table.js\";\n\nexport const DEFAULT_MARKER = \"\u25B6\";\nexport const NON_DEFAULT_MARKER = \" \";\n\nconst COLUMNS: readonly Column<ProfileSummary>[] = [\n {\n header: \"\",\n cell: (item) => (item.isDefault ? DEFAULT_MARKER : NON_DEFAULT_MARKER),\n },\n { header: \"NAME\", cell: (item) => item.name },\n {\n header: \"AUTH\",\n cell: (item) => (item.authType === \"oauth\" ? \"oauth\" : \"api-key\"),\n },\n { header: \"BASE URL\", cell: (item) => item.apiBaseUrl },\n];\n\n/**\n * Format the profile list as an aligned text table. The leading marker\n * column flags the active profile (\u25B6) and stays a single character wide\n * so non-default rows align cleanly. The masked API key is intentionally\n * omitted \u2014 `duvo whoami` shows it for the active profile, and including\n * the full masked key here forced an unhelpfully wide column.\n */\nexport function renderProfileTable(items: readonly ProfileSummary[]): string {\n return renderTable(COLUMNS, items);\n}\n\n/**\n * JSON output mirrors the text view's masked keys \u2014 never emit raw\n * credentials from a listing command.\n */\nexport function renderProfileJson(items: readonly ProfileSummary[]): string {\n const masked = items.map((item) => {\n return {\n ...item,\n apiKey: item.apiKey ? truncateApiKey(item.apiKey) : undefined,\n };\n });\n return JSON.stringify(masked, null, 2);\n}\n", "import { type Command } from \"commander\";\n\nimport { listProfiles } from \"@/config/profiles.js\";\nimport { readConfig } from \"@/config/store.js\";\n\nimport { renderProfileJson, renderProfileTable } from \"./render-list.js\";\n\ntype ListOptions = {\n json?: boolean;\n};\n\nexport function registerList(profiles: Command): void {\n profiles\n .command(\"list\", { isDefault: true })\n .description(\"List stored profiles; mark the default one with \u25B6\")\n .option(\"--json\", \"output raw JSON\")\n .action(async (options: ListOptions) => {\n const config = await readConfig();\n const items = listProfiles(config);\n\n if (options.json) {\n console.log(renderProfileJson(items));\n return;\n }\n\n if (items.length === 0) {\n console.log(\"No profiles stored. Run `duvo login` to add one.\");\n return;\n }\n\n console.log(renderProfileTable(items));\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { removeProfile } from \"@/config/profiles.js\";\nimport { readConfig, writeConfig } from \"@/config/store.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\n\ntype RemoveOptions = {\n yes?: boolean;\n};\n\nexport function registerRemove(profiles: Command): void {\n profiles\n .command(\"remove <name>\")\n .description(\"Remove a stored profile (alias of `duvo logout --name`)\")\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .action(async (name: string, options: RemoveOptions) => {\n const config = await readConfig();\n if (!(name in config.profiles)) {\n console.log(`Profile \"${name}\" does not exist.`);\n return;\n }\n\n await confirmDestructive({\n message: `Remove profile \"${name}\"?`,\n skip: options.yes ?? false,\n });\n\n const next = removeProfile(config, name);\n await writeConfig(next);\n console.log(`Removed profile \"${name}\".`);\n if (\n next.defaultProfile &&\n next.defaultProfile !== config.defaultProfile\n ) {\n console.log(`Default profile is now \"${next.defaultProfile}\".`);\n } else if (!next.defaultProfile) {\n console.log(\"No profiles remaining.\");\n }\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { renameProfile } from \"@/config/profiles.js\";\nimport { readConfig, writeConfig } from \"@/config/store.js\";\nimport { CliError, EXIT_CODE } from \"@/errors.js\";\n\nexport function registerRename(profiles: Command): void {\n profiles\n .command(\"rename <old> <new>\")\n .description(\"Rename a stored profile, preserving its credentials\")\n .action(async (oldName: string, newName: string) => {\n const config = await readConfig();\n try {\n const next = renameProfile(config, oldName, newName);\n await writeConfig(next);\n console.log(`Renamed profile \"${oldName}\" to \"${newName}\".`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(message, EXIT_CODE.GENERIC);\n }\n });\n}\n", "import { isCancel, select } from \"@clack/prompts\";\nimport { type Command } from \"commander\";\n\nimport {\n listProfiles,\n type ProfileSummary,\n setDefaultProfile,\n} from \"@/config/profiles.js\";\nimport { readConfig, writeConfig } from \"@/config/store.js\";\nimport { type Config } from \"@/config/types.js\";\nimport { AuthCliError, CancelCliError, CliError } from \"@/errors.js\";\nimport { padRight, truncateApiKey } from \"@/output/format.js\";\n\nimport { DEFAULT_MARKER, NON_DEFAULT_MARKER } from \"./render-list.js\";\n\nconst NAME_HEADER = \"NAME\";\n\nexport function registerUse(profiles: Command): void {\n profiles\n .command(\"use [name]\")\n .description(\n \"Switch the default profile (interactive picker when name is omitted)\"\n )\n .action(async (name: string | undefined) => {\n const target =\n name ?? (await pickProfileInteractively(await readConfig()));\n\n const config = await readConfig();\n if (!(target in config.profiles)) {\n throw new AuthCliError(\n `Profile \"${target}\" does not exist. Run \\`duvo profiles list\\` to see available profiles.`\n );\n }\n\n const next = setDefaultProfile(config, target);\n await writeConfig(next);\n console.log(`Default profile is now \"${target}\".`);\n });\n}\n\nasync function pickProfileInteractively(config: Config): Promise<string> {\n const profiles = listProfiles(config);\n if (profiles.length === 0) {\n throw new CliError(\n \"No profiles configured. Run `duvo login` to add one first.\"\n );\n }\n\n if (!process.stdin.isTTY) {\n throw new CliError(\n \"Profile name is required in non-interactive shells. \" +\n \"Run `duvo profiles use <name>`.\"\n );\n }\n\n const options = buildPickerOptions(profiles);\n\n const answer = await select({\n message: \"Select default profile\",\n initialValue: config.defaultProfile ?? profiles[0].name,\n options,\n });\n if (isCancel(answer)) {\n throw new CancelCliError(\"Profile switch cancelled.\");\n }\n\n return answer;\n}\n\ntype PickerOption = {\n value: string;\n label: string;\n};\n\nfunction buildPickerOptions(\n profiles: readonly ProfileSummary[]\n): PickerOption[] {\n const maskedKeys = profiles.map((profile) =>\n profile.apiKey\n ? truncateApiKey(profile.apiKey)\n : `oauth (${profile.email ?? \"\u2014\"})`\n );\n const nameWidth = Math.max(\n NAME_HEADER.length,\n ...profiles.map((profile) => profile.name.length)\n );\n\n return profiles.map((profile, index) => {\n const marker = profile.isDefault ? DEFAULT_MARKER : NON_DEFAULT_MARKER;\n const label = `${marker} ${padRight(profile.name, nameWidth)} ${maskedKeys[index]}`;\n return {\n value: profile.name,\n label,\n };\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerList } from \"./list.js\";\nimport { registerRemove } from \"./remove.js\";\nimport { registerRename } from \"./rename.js\";\nimport { registerUse } from \"./use.js\";\n\nexport function registerProfiles(program: Command): void {\n const profiles = program\n .command(\"profiles\")\n .description(\"Manage stored API-key profiles\");\n\n registerList(profiles);\n registerUse(profiles);\n registerRename(profiles);\n registerRemove(profiles);\n}\n", "import {\n type CaseLabelCreateResponse,\n caseLabelCreateResponseSchema,\n caseLabelsWithCountsListResponseSchema,\n caseLabelUnlinkResponseSchema,\n caseLabelUpdateResponseSchema,\n type CaseQueueLabelWithCount,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: CaseQueueLabelWithCount) => row.id },\n { header: \"KEY\", cell: (row: CaseQueueLabelWithCount) => row.key },\n { header: \"VALUE\", cell: (row: CaseQueueLabelWithCount) => row.value },\n {\n header: \"COLOR HUE\",\n cell: (row: CaseQueueLabelWithCount) => String(row.color_hue),\n },\n {\n header: \"CASES\",\n cell: (row: CaseQueueLabelWithCount) => String(row.case_count),\n },\n] as const;\n\ntype ListOptions = {\n queue: string;\n limit?: string;\n offset?: string;\n json?: boolean;\n};\n\ntype CreateOptions = {\n queue: string;\n key?: string;\n value: string;\n colorHue?: string;\n json?: boolean;\n};\n\ntype UpdateOptions = {\n queue: string;\n key?: string;\n value?: string;\n colorHue?: string;\n json?: boolean;\n};\n\ntype DeleteOptions = {\n queue: string;\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerQueueLabels(program: Command): void {\n const labels = program\n .command(\"queue-labels\")\n .description(\"Manage label vocabularies on a queue\");\n\n registerList(labels);\n registerCreate(labels);\n registerUpdate(labels);\n registerDelete(labels);\n}\n\nfunction registerList(labels: Command): void {\n labels\n .command(\"list\", { isDefault: true })\n .description(\n \"List labels defined on a queue along with the number of cases each is assigned to\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue\")\n .option(\"--limit <n>\", \"page size (1-1000, default 1000)\")\n .option(\"--offset <n>\", \"number of labels to skip\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n if (options.limit !== undefined) {\n searchParams.append(\"limit\", options.limit);\n }\n\n if (options.offset !== undefined) {\n searchParams.append(\"offset\", options.offset);\n }\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/labels`,\n apiKey,\n apiBaseUrl,\n searchParams: searchParams.size > 0 ? searchParams : undefined,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseLabelsWithCountsListResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.labels.length === 0) {\n console.log(\"No labels defined on this queue.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, parsed.data.labels));\n console.log(`Showing ${parsed.data.labels.length}`);\n });\n}\n\nfunction registerCreate(labels: Command): void {\n labels\n .command(\"create\")\n .description(\"Create a label on a queue without assigning it to a case\")\n .requiredOption(\"--queue <id>\", \"ID of the queue\")\n .option(\"--key <text>\", \"label key (omit for tag-only labels)\")\n .requiredOption(\"--value <text>\", \"label value (required, non-empty)\")\n .option(\"--color-hue <n>\", \"color hue 0-360 (auto-derived if omitted)\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function createAction(this: Command, options: CreateOptions) {\n if (options.value.trim().length === 0) {\n throw new CliError(\"--value must not be empty\");\n }\n\n const colorHue = parseColorHue(options.colorHue);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const body: Record<string, unknown> = { value: options.value };\n if (options.key !== undefined) {\n body.key = options.key;\n }\n\n if (colorHue !== undefined) {\n body.color_hue = colorHue;\n }\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/labels`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseLabelCreateResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { label } = parsed.data as CaseLabelCreateResponse;\n console.log(green(\"Label created!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: label.id },\n { label: \"Key\", value: label.key },\n { label: \"Value\", value: label.value },\n { label: \"Color hue\", value: String(label.color_hue) },\n { label: \"Cases\", value: String(label.case_count) },\n ])\n );\n });\n}\n\nfunction registerUpdate(labels: Command): void {\n labels\n .command(\"update <label-id>\")\n .description(\n \"Rename a label or change its color (affects every case it's assigned to)\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue the label belongs to\")\n .option(\"--key <text>\", \"new label key (omit to leave unchanged)\")\n .option(\"--value <text>\", \"new label value\")\n .option(\"--color-hue <n>\", \"new color hue 0-360\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function updateAction(\n this: Command,\n labelId: string,\n options: UpdateOptions\n ) {\n const colorHue = parseColorHue(options.colorHue);\n\n const body: Record<string, unknown> = {};\n if (options.key !== undefined) {\n body.key = options.key;\n }\n\n if (options.value !== undefined) {\n if (options.value.trim().length === 0) {\n throw new CliError(\"--value must not be empty\");\n }\n\n body.value = options.value;\n }\n\n if (colorHue !== undefined) {\n body.color_hue = colorHue;\n }\n\n // The schema requires `value`; the server will reject if missing. But\n // leaving body empty also makes no sense, so guard early.\n if (Object.keys(body).length === 0) {\n throw new CliError(\n \"Pass at least one of --key, --value, or --color-hue.\"\n );\n }\n\n if (body.value === undefined) {\n throw new CliError(\n \"--value is required by the API; pass --value <text> to keep or change it.\"\n );\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"PATCH\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/labels/${encodeURIComponent(labelId)}`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseLabelUpdateResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { label } = parsed.data;\n console.log(green(\"Label updated!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: label.id },\n { label: \"Key\", value: label.key },\n { label: \"Value\", value: label.value },\n { label: \"Color hue\", value: String(label.color_hue) },\n ])\n );\n });\n}\n\nfunction registerDelete(labels: Command): void {\n labels\n .command(\"delete <label-id>\")\n .description(\n \"Delete a label from a queue (cascade-removes from every case it was assigned to)\"\n )\n .requiredOption(\"--queue <id>\", \"ID of the queue the label belongs to\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function deleteAction(\n this: Command,\n labelId: string,\n options: DeleteOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Delete label \"${labelId}\" from queue \"${options.queue}\"? Cases assigned to this label will lose it.`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/queues/${encodeURIComponent(options.queue)}/labels/${encodeURIComponent(labelId)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseLabelUnlinkResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n throw new CliError(\"Failed to delete label.\");\n }\n\n console.log(green(\"Label deleted!\"));\n });\n}\n\nfunction parseColorHue(raw: string | undefined): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n\n const value = Number.parseInt(raw, 10);\n if (Number.isNaN(value) || value < 0 || value > 360) {\n throw new CliError(\"--color-hue must be an integer between 0 and 360\");\n }\n\n return value;\n}\n", "import {\n type QueueAgentConsumer,\n type QueueAgentProducer,\n queueAgentsResponseSchema,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype AgentsOptions = {\n json?: boolean;\n};\n\nconst PRODUCER_COLUMNS = [\n { header: \"AGENT ID\", cell: (row: QueueAgentProducer) => row.agent_id },\n { header: \"NAME\", cell: (row: QueueAgentProducer) => row.agent_name },\n {\n header: \"TRIGGER ENABLED\",\n cell: (row: QueueAgentProducer) =>\n row.case_trigger_enabled ? \"yes\" : \"no\",\n },\n {\n header: \"TRIGGER QUEUE\",\n cell: (row: QueueAgentProducer) => row.case_trigger_queue_name ?? \"\",\n },\n {\n header: \"PROBLEMS\",\n cell: (row: QueueAgentProducer) =>\n row.problems.length === 0 ? \"\" : row.problems.join(\", \"),\n },\n] as const;\n\nconst CONSUMER_COLUMNS = [\n { header: \"AGENT ID\", cell: (row: QueueAgentConsumer) => row.agent_id },\n { header: \"NAME\", cell: (row: QueueAgentConsumer) => row.agent_name },\n {\n header: \"TRIGGER ENABLED\",\n cell: (row: QueueAgentConsumer) =>\n row.case_trigger_enabled ? \"yes\" : \"no\",\n },\n {\n header: \"HANDOVER TARGET\",\n cell: (row: QueueAgentConsumer) => (row.is_handover_target ? \"yes\" : \"no\"),\n },\n {\n header: \"PROBLEMS\",\n cell: (row: QueueAgentConsumer) =>\n row.problems.length === 0 ? \"\" : row.problems.join(\", \"),\n },\n] as const;\n\nexport function registerQueuesAgents(queues: Command): void {\n queues\n .command(\"agents <queue-id>\")\n .description(\n \"List agents bound to a queue (producers push cases in; consumers are triggered by cases)\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function agentsAction(\n this: Command,\n queueId: string,\n options: AgentsOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/queues/${encodeURIComponent(queueId)}/agents`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = queueAgentsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { queue_name, producers, consumers } = parsed.data;\n console.log(`Queue: ${queue_name}`);\n console.log(\"\");\n\n console.log(`Producers (${producers.length})`);\n if (producers.length === 0) {\n console.log(\" (none)\");\n } else {\n console.log(renderTable(PRODUCER_COLUMNS, producers));\n }\n\n console.log(\"\");\n\n console.log(`Consumers (${consumers.length})`);\n if (consumers.length === 0) {\n console.log(\" (none)\");\n } else {\n console.log(renderTable(CONSUMER_COLUMNS, consumers));\n }\n });\n}\n", "import { caseCreateQueueResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype CreateOptions = {\n name?: string;\n description?: string;\n folderId?: string;\n json?: boolean;\n};\n\ntype RequestBody = {\n name: string;\n description?: string | null;\n folder_id?: string | null;\n};\n\nexport function registerQueuesCreate(queues: Command): void {\n queues\n .command(\"create\")\n .description(\"Create a new case queue\")\n .requiredOption(\"--name <name>\", \"queue name (must be unique within team)\")\n .option(\"--description <text>\", \"human-readable description\")\n .option(\"--folder-id <id>\", \"folder to nest the queue under\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function createAction(this: Command, options: CreateOptions) {\n if (options.name === undefined || options.name.trim().length === 0) {\n throw new CliError(\"--name must not be empty\");\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const body: RequestBody = { name: options.name.trim() };\n if (options.description !== undefined) {\n body.description = options.description;\n }\n\n if (options.folderId !== undefined) {\n const trimmedFolderId = options.folderId.trim();\n if (trimmedFolderId.length === 0) {\n throw new CliError(\"--folder-id must not be empty\");\n }\n\n body.folder_id = trimmedFolderId;\n }\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/queues\",\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseCreateQueueResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { queue } = parsed.data;\n\n console.log(green(\"Queue created!\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"ID\", value: queue.id },\n { label: \"Name\", value: queue.name },\n { label: \"Description\", value: queue.description ?? \"\" },\n { label: \"Folder\", value: queue.folder_id ?? \"\" },\n { label: \"Created\", value: queue.created_at ?? \"\" },\n ])\n );\n });\n}\n", "import { deleteQueueResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype DeleteOptions = {\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerQueuesDelete(queues: Command): void {\n queues\n .command(\"delete <id>\")\n .description(\n \"Delete a case queue. Interrupts running jobs and removes all cases.\"\n )\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function deleteAction(\n this: Command,\n id: string,\n options: DeleteOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Delete queue \"${id}\" and all of its cases?`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/queues/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = deleteQueueResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const result = parsed.data;\n if (!result.success) {\n throw new CliError(\"Failed to delete queue.\");\n }\n\n console.log(green(\"Queue deleted!\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"Deleted cases\", value: String(result.deleted_case_count) },\n {\n label: \"Interrupted runs\",\n value: String(result.interrupted_run_ids.length),\n },\n ])\n );\n });\n}\n", "import { caseGetQueueResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype GetOptions = {\n json?: boolean;\n};\n\nexport function registerQueuesGet(queues: Command): void {\n queues\n .command(\"get <id>\")\n .description(\"Get a case queue by ID\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function getAction(\n this: Command,\n id: string,\n options: GetOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/queues/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseGetQueueResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { queue } = parsed.data;\n\n console.log(\n renderKeyValue([\n { label: \"ID\", value: queue.id },\n { label: \"Name\", value: queue.name },\n { label: \"Description\", value: queue.description ?? \"\" },\n { label: \"Folder\", value: queue.folder_id ?? \"\" },\n { label: \"Created\", value: queue.created_at ?? \"\" },\n ])\n );\n });\n}\n", "import { type CaseQueue, caseQueuesResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { parseLimit, parseOffset } from \"../shared/pagination.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n limit?: string;\n offset?: string;\n json?: boolean;\n};\n\nconst DEFAULT_LIMIT = 20;\nconst MIN_LIMIT = 1;\nconst MAX_LIMIT = 100;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: CaseQueue) => row.id },\n { header: \"NAME\", cell: (row: CaseQueue) => row.name },\n {\n header: \"DESCRIPTION\",\n cell: (row: CaseQueue) => row.description ?? \"\",\n maxWidth: 40,\n },\n { header: \"CREATED\", cell: (row: CaseQueue) => row.created_at ?? \"\" },\n] as const;\n\nexport function registerQueuesList(queues: Command): void {\n queues\n .command(\"list\", { isDefault: true })\n .description(\"List case queues for your team\")\n .option(\"--limit <n>\", `page size (${MIN_LIMIT}-${MAX_LIMIT})`)\n .option(\"--offset <n>\", \"number of queues to skip\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const limit = parseLimit(options.limit, {\n defaultValue: DEFAULT_LIMIT,\n min: MIN_LIMIT,\n max: MAX_LIMIT,\n });\n const offset = parseOffset(options.offset);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", String(limit));\n searchParams.append(\"offset\", String(offset));\n\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/queues\",\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseQueuesResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const response = parsed.data;\n\n if (response.queues.length === 0) {\n console.log(\"No queues found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, response.queues));\n const resolvedOffset = response.offset ?? offset;\n const total = response.total ?? null;\n const summary =\n total === null\n ? `Showing ${response.queues.length} \u00B7 offset ${resolvedOffset}`\n : `Showing ${response.queues.length} of ${total} \u00B7 offset ${resolvedOffset}`;\n console.log(summary);\n });\n}\n", "import { caseUpdateQueueResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype UpdateOptions = {\n name?: string;\n description?: string;\n clearDescription?: boolean;\n folderId?: string;\n clearFolder?: boolean;\n json?: boolean;\n};\n\ntype RequestBody = {\n name?: string;\n description?: string | null;\n folder_id?: string | null;\n};\n\nexport function registerQueuesUpdate(queues: Command): void {\n queues\n .command(\"update <id>\")\n .description(\"Update a case queue\")\n .option(\"--name <name>\", \"new queue name\")\n .option(\"--description <text>\", \"new description\")\n .option(\"--clear-description\", \"clear the existing description\")\n .option(\"--folder-id <id>\", \"move queue under a folder\")\n .option(\"--clear-folder\", \"move queue out of any folder (root)\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function updateAction(\n this: Command,\n id: string,\n options: UpdateOptions\n ) {\n if (\n options.description !== undefined &&\n Boolean(options.clearDescription)\n ) {\n throw new CliError(\n \"Pass either --description or --clear-description, not both.\"\n );\n }\n\n if (options.folderId !== undefined && Boolean(options.clearFolder)) {\n throw new CliError(\n \"Pass either --folder-id or --clear-folder, not both.\"\n );\n }\n\n const body: RequestBody = {};\n if (options.name !== undefined) {\n const trimmed = options.name.trim();\n if (trimmed.length === 0) {\n throw new CliError(\"--name must not be empty\");\n }\n\n body.name = trimmed;\n }\n\n if (options.description !== undefined) {\n const trimmedDescription = options.description.trim();\n if (trimmedDescription.length === 0) {\n throw new CliError(\n \"--description must not be empty; use --clear-description to remove it.\"\n );\n }\n\n body.description = trimmedDescription;\n } else if (options.clearDescription) {\n body.description = null;\n }\n\n if (options.folderId !== undefined) {\n const trimmedFolderId = options.folderId.trim();\n if (trimmedFolderId.length === 0) {\n throw new CliError(\"--folder-id must not be empty\");\n }\n\n body.folder_id = trimmedFolderId;\n } else if (options.clearFolder) {\n body.folder_id = null;\n }\n\n if (Object.keys(body).length === 0) {\n throw new CliError(\n \"Provide at least one field to update (--name, --description, --clear-description, --folder-id, --clear-folder).\"\n );\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"PATCH\",\n path: `/v1/queues/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = caseUpdateQueueResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { queue } = parsed.data;\n\n console.log(green(\"Queue updated!\"));\n console.log();\n console.log(\n renderKeyValue([\n { label: \"ID\", value: queue.id },\n { label: \"Name\", value: queue.name },\n { label: \"Description\", value: queue.description ?? \"\" },\n { label: \"Folder\", value: queue.folder_id ?? \"\" },\n { label: \"Created\", value: queue.created_at ?? \"\" },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerQueuesAgents } from \"./agents.js\";\nimport { registerQueuesCreate } from \"./create.js\";\nimport { registerQueuesDelete } from \"./delete.js\";\nimport { registerQueuesGet } from \"./get.js\";\nimport { registerQueuesList } from \"./list.js\";\nimport { registerQueuesUpdate } from \"./update.js\";\n\nexport function registerQueues(program: Command): void {\n const queues = program\n .command(\"queues\")\n .description(\"Manage case queues in the Duvo public API\");\n\n registerQueuesList(queues);\n registerQueuesGet(queues);\n registerQueuesCreate(queues);\n registerQueuesUpdate(queues);\n registerQueuesDelete(queues);\n registerQueuesAgents(queues);\n}\n", "import { type JobListItem, jobListResponseSchema } from \"@taskcrew/shared\";\nimport { z } from \"zod\";\n\nexport { jobListResponseSchema as listRunsResponseSchema };\nexport type { JobListItem };\nexport type ListRunsResponse = z.infer<typeof jobListResponseSchema>;\n\nconst publicRunSchema = z.object({\n id: z.string(),\n agent_id: z.string(),\n build_id: z.string(),\n status: z.string(),\n source: z.string().nullish(),\n sandbox_id: z.string().nullish(),\n started_at: z.string().nullish(),\n completed_at: z.string().nullish(),\n created_at: z.string(),\n updated_at: z.string().nullish(),\n human_in_the_loop_enabled: z.boolean().nullish(),\n});\n\nexport type PublicRun = z.infer<typeof publicRunSchema>;\n\nexport const startRunResponseSchema = z.object({\n run: publicRunSchema,\n});\n\nexport type StartRunResponse = z.infer<typeof startRunResponseSchema>;\n\nconst questionOptionSchema = z.object({\n label: z.string(),\n description: z.string().nullish(),\n});\n\nconst questionSchema = z.object({\n question: z.string(),\n header: z.string().nullish(),\n options: z.array(questionOptionSchema).nullish(),\n multi_select: z.boolean().nullish(),\n});\n\nconst pendingHumanRequestSchema = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string().nullish(),\n created_at: z.string(),\n type: z.string(),\n questions: z.array(questionSchema).nullish(),\n});\n\nexport type PendingHumanRequest = z.infer<typeof pendingHumanRequestSchema>;\n\nexport const getRunResponseSchema = z.object({\n run: publicRunSchema.nullable(),\n pending_human_request: pendingHumanRequestSchema.nullish(),\n});\n\nexport type GetRunResponse = z.infer<typeof getRunResponseSchema>;\n\nexport const stopRunResponseSchema = z.object({\n success: z.boolean(),\n message: z.string().nullish(),\n});\n\nexport type StopRunResponse = z.infer<typeof stopRunResponseSchema>;\n\nconst runMessageSchema = z.object({\n id: z.string(),\n type: z.string(),\n role: z.string(),\n timestamp: z.string(),\n text_content: z.string().nullish(),\n tool_call: z\n .object({\n id: z.string(),\n name: z.string(),\n arguments: z.record(z.string(), z.unknown()).nullish(),\n })\n .nullish(),\n tool_result: z\n .object({\n tool_call_id: z.string(),\n result: z.unknown().nullish(),\n error: z.string().nullish(),\n })\n .nullish(),\n});\n\nexport type RunMessage = z.infer<typeof runMessageSchema>;\n\nexport const listRunMessagesResponseSchema = z.object({\n messages: z.array(runMessageSchema),\n total: z.number().nullish(),\n limit: z.number().nullish(),\n offset: z.number().nullish(),\n});\n\nexport type ListRunMessagesResponse = z.infer<\n typeof listRunMessagesResponseSchema\n>;\n\nconst postedMessageSchema = z.object({\n id: z.string(),\n type: z.string(),\n role: z.string(),\n timestamp: z.string(),\n text_content: z.string(),\n});\n\nexport const postRunMessageResponseSchema = z.object({\n message: postedMessageSchema,\n});\n\nexport type PostRunMessageResponse = z.infer<\n typeof postRunMessageResponseSchema\n>;\n\nexport const respondHumanRequestResponseSchema = z.object({\n human_request: z.object({\n id: z.string(),\n run_id: z.string(),\n title: z.string(),\n description: z.string().nullish(),\n response: z.string().nullish(),\n responded_at: z.string().nullish(),\n created_at: z.string(),\n }),\n});\n\nexport type RespondHumanRequestResponse = z.infer<\n typeof respondHumanRequestResponseSchema\n>;\n", "import { type Command } from \"commander\";\n\nimport { getRunResponseSchema } from \"@/api/run-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype GetOptions = {\n json?: boolean;\n};\n\nexport function registerRunsGet(runs: Command): void {\n runs\n .command(\"get <id>\")\n .description(\"Get an agent run by ID\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function getAction(\n this: Command,\n id: string,\n options: GetOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/runs/${encodeURIComponent(id)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = getRunResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { run, pending_human_request: pendingHumanRequest } = parsed.data;\n\n if (!run) {\n throw new CliError(`Run \"${id}\" not found.`);\n }\n\n console.log(\n renderKeyValue([\n { label: \"ID\", value: run.id },\n { label: \"Agent\", value: run.agent_id },\n { label: \"Build\", value: run.build_id },\n { label: \"Status\", value: run.status },\n { label: \"Source\", value: run.source ?? \"\" },\n { label: \"Sandbox\", value: run.sandbox_id ?? \"\" },\n { label: \"Started\", value: run.started_at ?? \"\" },\n { label: \"Completed\", value: run.completed_at ?? \"\" },\n { label: \"Created\", value: run.created_at },\n { label: \"Updated\", value: run.updated_at ?? \"\" },\n ])\n );\n\n if (pendingHumanRequest) {\n console.log(\"\");\n console.log(\"Pending human request:\");\n console.log(\n renderKeyValue([\n { label: \"ID\", value: pendingHumanRequest.id },\n { label: \"Type\", value: pendingHumanRequest.type },\n { label: \"Title\", value: pendingHumanRequest.title },\n {\n label: \"Description\",\n value: pendingHumanRequest.description ?? \"\",\n },\n { label: \"Created\", value: pendingHumanRequest.created_at },\n ])\n );\n }\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { type JobListItem, listRunsResponseSchema } from \"@/api/run-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { parseLimit, parseOffset } from \"../shared/pagination.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n limit?: string;\n offset?: string;\n sortOrder?: string;\n status?: string;\n agent?: string;\n user?: string;\n caseQueue?: string;\n source?: string;\n search?: string;\n hasIssues?: string;\n json?: boolean;\n};\n\nconst DEFAULT_LIMIT = 20;\nconst MIN_LIMIT = 1;\nconst MAX_LIMIT = 100;\n\nconst SORT_ORDERS = [\"asc\", \"desc\"] as const;\ntype SortOrder = (typeof SORT_ORDERS)[number];\n\nconst HAS_ISSUES_VALUES = [\"true\", \"false\"] as const;\ntype HasIssuesValue = (typeof HAS_ISSUES_VALUES)[number];\n\nconst TITLE_PREVIEW_WIDTH = 50;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: JobListItem) => row.id },\n { header: \"RUN#\", cell: (row: JobListItem) => String(row.run_number) },\n { header: \"STATUS\", cell: (row: JobListItem) => row.status },\n { header: \"AGENT\", cell: (row: JobListItem) => row.agent_name },\n {\n header: \"TITLE\",\n cell: (row: JobListItem) => row.title,\n maxWidth: TITLE_PREVIEW_WIDTH,\n },\n {\n header: \"CREATED\",\n cell: (row: JobListItem) => row.created_at.toISOString(),\n },\n] as const;\n\nfunction isSortOrder(value: string): value is SortOrder {\n return (SORT_ORDERS as readonly string[]).includes(value);\n}\n\nfunction isHasIssuesValue(value: string): value is HasIssuesValue {\n return (HAS_ISSUES_VALUES as readonly string[]).includes(value);\n}\n\nexport function registerRunsList(runs: Command): void {\n runs\n .command(\"list\")\n .description(\"List agent runs for your team\")\n .option(\"--limit <n>\", `page size (${MIN_LIMIT}-${MAX_LIMIT})`)\n .option(\"--offset <n>\", \"number of runs to skip\")\n .option(\"--sort-order <order>\", `sort direction (${SORT_ORDERS.join(\"|\")})`)\n .option(\n \"--status <status>\",\n \"filter by status (e.g. running, completed, failed, waiting, interrupted, stopped, needs_attention)\"\n )\n .option(\"--agent <id>\", \"filter by agent ID\")\n .option(\"--user <id>\", \"filter by user ID\")\n .option(\"--case-queue <id>\", \"filter by case queue ID\")\n .option(\"--source <source>\", \"filter by source\")\n .option(\"--search <query>\", \"free-text search across runs\")\n .option(\n \"--has-issues <true|false>\",\n `show only runs with (or without) issues (${HAS_ISSUES_VALUES.join(\"|\")})`\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const limit = parseLimit(options.limit, {\n defaultValue: DEFAULT_LIMIT,\n min: MIN_LIMIT,\n max: MAX_LIMIT,\n });\n const offset = parseOffset(options.offset);\n\n if (options.sortOrder !== undefined && !isSortOrder(options.sortOrder)) {\n throw new CliError(\n `--sort-order must be one of: ${SORT_ORDERS.join(\", \")}`\n );\n }\n\n if (\n options.hasIssues !== undefined &&\n !isHasIssuesValue(options.hasIssues)\n ) {\n throw new CliError(\n `--has-issues must be one of: ${HAS_ISSUES_VALUES.join(\", \")}`\n );\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", String(limit));\n searchParams.append(\"offset\", String(offset));\n\n if (options.sortOrder !== undefined) {\n searchParams.append(\"sort_order\", options.sortOrder);\n }\n\n if (options.status !== undefined) {\n searchParams.append(\"status\", options.status);\n }\n\n if (options.agent !== undefined) {\n searchParams.append(\"agent_id\", options.agent);\n }\n\n if (options.user !== undefined) {\n searchParams.append(\"user_id\", options.user);\n }\n\n if (options.caseQueue !== undefined) {\n searchParams.append(\"case_queue_id\", options.caseQueue);\n }\n\n if (options.source !== undefined) {\n searchParams.append(\"source\", options.source);\n }\n\n if (options.search !== undefined) {\n searchParams.append(\"search\", options.search);\n }\n\n if (options.hasIssues !== undefined) {\n searchParams.append(\"has_issues\", options.hasIssues);\n }\n\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/runs\",\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listRunsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const response = parsed.data;\n\n if (response.data.length === 0) {\n console.log(\"No runs found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, response.data));\n console.log(\n `Showing ${response.data.length} of ${response.total} \u00B7 offset ${offset}`\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport {\n listRunMessagesResponseSchema,\n type RunMessage,\n} from \"@/api/run-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { parseLimit, parseOffset } from \"../shared/pagination.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype MessagesOptions = {\n limit?: string;\n offset?: string;\n json?: boolean;\n};\n\nconst DEFAULT_LIMIT = 20;\nconst MIN_LIMIT = 1;\nconst MAX_LIMIT = 50;\n\nconst TEXT_PREVIEW_WIDTH = 60;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: RunMessage) => row.id },\n { header: \"ROLE\", cell: (row: RunMessage) => row.role },\n { header: \"TYPE\", cell: (row: RunMessage) => row.type },\n { header: \"TIMESTAMP\", cell: (row: RunMessage) => row.timestamp },\n {\n header: \"PREVIEW\",\n cell: previewCell,\n maxWidth: TEXT_PREVIEW_WIDTH,\n },\n] as const;\n\nfunction previewCell(row: RunMessage): string {\n if (row.text_content) {\n return row.text_content.replace(/\\s+/g, \" \").trim();\n }\n\n if (row.tool_call) {\n return `tool_call ${row.tool_call.name}`;\n }\n\n if (row.tool_result) {\n return `tool_result ${row.tool_result.tool_call_id}`;\n }\n\n return \"\";\n}\n\nexport function registerRunsMessages(runs: Command): void {\n runs\n .command(\"messages <id>\")\n .description(\"List messages for an agent run\")\n .option(\"--limit <n>\", `page size (${MIN_LIMIT}-${MAX_LIMIT})`)\n .option(\"--offset <n>\", \"number of messages to skip\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function messagesAction(\n this: Command,\n id: string,\n options: MessagesOptions\n ) {\n const limit = parseLimit(options.limit, {\n defaultValue: DEFAULT_LIMIT,\n min: MIN_LIMIT,\n max: MAX_LIMIT,\n });\n const offset = parseOffset(options.offset);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", String(limit));\n searchParams.append(\"offset\", String(offset));\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/runs/${encodeURIComponent(id)}/messages`,\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listRunMessagesResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const response = parsed.data;\n\n if (response.messages.length === 0) {\n console.log(\"No messages found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, response.messages));\n const resolvedOffset = response.offset ?? offset;\n const summary =\n response.total === null || response.total === undefined\n ? `Showing ${response.messages.length} \u00B7 offset ${resolvedOffset}`\n : `Showing ${response.messages.length} of ${response.total} \u00B7 offset ${resolvedOffset}`;\n console.log(summary);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport {\n getRunResponseSchema,\n respondHumanRequestResponseSchema,\n} from \"@/api/run-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype RespondOptions = {\n approve?: boolean;\n deny?: boolean;\n answer?: readonly string[];\n json?: boolean;\n};\n\ntype RequestBody = {\n approved?: boolean;\n answers?: Record<string, string>;\n};\n\nfunction collectAnswer(\n value: string,\n previous: readonly string[] = []\n): readonly string[] {\n return [...previous, value];\n}\n\nfunction parseAnswers(raw: readonly string[]): Record<string, string> {\n const answers: Record<string, string> = Object.create(null) as Record<\n string,\n string\n >;\n for (const entry of raw) {\n const eq = entry.indexOf(\"=\");\n if (eq === -1 || eq === 0) {\n throw new CliError(\n `Invalid --answer \"${entry}\". Expected \"question=answer\".`\n );\n }\n\n const question = entry.slice(0, eq);\n const answer = entry.slice(eq + 1);\n if (Object.prototype.hasOwnProperty.call(answers, question)) {\n throw new CliError(\n `Duplicate --answer for question \"${question}\". Each question may be answered once.`\n );\n }\n\n answers[question] = answer;\n }\n\n return answers;\n}\n\nfunction buildBody(options: RespondOptions): RequestBody {\n const approveSet = options.approve === true;\n const denySet = options.deny === true;\n const answers = options.answer ?? [];\n\n if (approveSet && denySet) {\n throw new CliError(\"Pass either --approve or --deny, not both.\");\n }\n\n if ((approveSet || denySet) && answers.length > 0) {\n throw new CliError(\n \"Pass either --approve/--deny (for approval-type requests) or --answer (for question-type requests), not both.\"\n );\n }\n\n if (approveSet) {\n return { approved: true };\n }\n\n if (denySet) {\n return { approved: false };\n }\n\n if (answers.length > 0) {\n return { answers: parseAnswers(answers) };\n }\n\n throw new CliError(\n \"Provide --approve, --deny, or at least one --answer question=answer.\"\n );\n}\n\nasync function resolvePendingRequestId(\n runId: string,\n apiKey: string,\n apiBaseUrl: string\n): Promise<string> {\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/runs/${encodeURIComponent(runId)}`,\n apiKey,\n apiBaseUrl,\n });\n const parsed = getRunResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const pending = parsed.data.pending_human_request;\n if (!pending) {\n throw new CliError(\n `Run ${runId} has no pending human request. Pass the request ID explicitly.`\n );\n }\n\n return pending.id;\n}\n\nexport function registerRunsRespond(runs: Command): void {\n runs\n .command(\"respond <run-id> [request-id]\")\n .description(\n \"Respond to a human-in-the-loop request on a run (defaults to the run's pending request)\"\n )\n .option(\"--approve\", \"approve an approval-type request\")\n .option(\"--deny\", \"deny an approval-type request\")\n .option(\n \"--answer <question=answer>\",\n \"answer a question-type request (repeatable)\",\n collectAnswer,\n [] as readonly string[]\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function respondAction(\n this: Command,\n runId: string,\n requestIdArg: string | undefined,\n options: RespondOptions\n ) {\n const body = buildBody(options);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const requestId =\n requestIdArg ??\n (await resolvePendingRequestId(runId, apiKey, apiBaseUrl));\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/runs/${encodeURIComponent(runId)}/human-requests/${encodeURIComponent(requestId)}/respond`,\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = respondHumanRequestResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { human_request: humanRequest } = parsed.data;\n\n console.log(green(\"Response sent!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: humanRequest.id },\n { label: \"Run\", value: humanRequest.run_id },\n { label: \"Title\", value: humanRequest.title },\n { label: \"Description\", value: humanRequest.description ?? \"\" },\n { label: \"Response\", value: humanRequest.response ?? \"\" },\n { label: \"Responded\", value: humanRequest.responded_at ?? \"\" },\n { label: \"Created\", value: humanRequest.created_at },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { postRunMessageResponseSchema } from \"@/api/run-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype SendMessageOptions = {\n message: string;\n json?: boolean;\n};\n\nexport function registerRunsSendMessage(runs: Command): void {\n runs\n .command(\"send-message <id>\")\n .description(\"Post a message to an agent run\")\n .requiredOption(\"--message <text>\", \"the message content to send\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function sendMessageAction(\n this: Command,\n id: string,\n options: SendMessageOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/runs/${encodeURIComponent(id)}/messages`,\n apiKey,\n apiBaseUrl,\n body: { message: options.message },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = postRunMessageResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { message } = parsed.data;\n\n console.log(green(\"Message sent!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: message.id },\n { label: \"Role\", value: message.role },\n { label: \"Type\", value: message.type },\n { label: \"Timestamp\", value: message.timestamp },\n { label: \"Content\", value: message.text_content },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { startRunResponseSchema } from \"@/api/run-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype StartOptions = {\n agent: string;\n message?: string;\n sandboxId?: string;\n webhookUrl?: string;\n json?: boolean;\n};\n\ntype RequestBody = {\n agent_id: string;\n message?: string;\n sandbox_id?: string;\n webhook_url?: string;\n};\n\nexport function registerRunsStart(runs: Command): void {\n runs\n .command(\"start\")\n .description(\"Start a new agent run\")\n .requiredOption(\"--agent <id>\", \"ID of the agent to run\")\n .option(\n \"--message <text>\",\n \"optional initial message to start the run with\"\n )\n .option(\"--sandbox-id <id>\", \"optional sandbox ID with pre-uploaded files\")\n .option(\"--webhook-url <url>\", \"optional webhook URL to POST run events to\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function startAction(this: Command, options: StartOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const body: RequestBody = {\n agent_id: options.agent,\n ...(options.message !== undefined ? { message: options.message } : {}),\n ...(options.sandboxId !== undefined\n ? { sandbox_id: options.sandboxId }\n : {}),\n ...(options.webhookUrl !== undefined\n ? { webhook_url: options.webhookUrl }\n : {}),\n };\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/runs\",\n apiKey,\n apiBaseUrl,\n body,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = startRunResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { run } = parsed.data;\n\n console.log(green(\"Run started!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: run.id },\n { label: \"Agent\", value: run.agent_id },\n { label: \"Build\", value: run.build_id },\n { label: \"Status\", value: run.status },\n { label: \"Created\", value: run.created_at },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { stopRunResponseSchema } from \"@/api/run-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype StopOptions = {\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerRunsStop(runs: Command): void {\n runs\n .command(\"stop <id>\")\n .description(\"Stop a running agent run\")\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function stopAction(\n this: Command,\n id: string,\n options: StopOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Stop run \"${id}\"?`,\n skip: options.yes ?? false,\n });\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/runs/${encodeURIComponent(id)}/stop`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = stopRunResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { success, message } = parsed.data;\n if (!success) {\n throw new CliError(message ?? `Failed to stop run \"${id}\".`);\n }\n\n const label = message ?? `Run \"${id}\" stopped.`;\n console.log(green(label));\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerRunsGet } from \"./get.js\";\nimport { registerRunsList } from \"./list.js\";\nimport { registerRunsMessages } from \"./messages.js\";\nimport { registerRunsRespond } from \"./respond.js\";\nimport { registerRunsSendMessage } from \"./send-message.js\";\nimport { registerRunsStart } from \"./start.js\";\nimport { registerRunsStop } from \"./stop.js\";\n\nexport function registerRuns(program: Command): void {\n const runs = program\n .command(\"runs\")\n .description(\"Manage agent runs in the Duvo public API\");\n\n registerRunsStart(runs);\n registerRunsList(runs);\n registerRunsGet(runs);\n registerRunsMessages(runs);\n registerRunsSendMessage(runs);\n registerRunsRespond(runs);\n registerRunsStop(runs);\n}\n", "import { z } from \"zod\";\n\nexport const createSandboxResponseSchema = z.object({\n sandbox_id: z.string(),\n expires_at: z.string(),\n});\n\nexport type CreateSandboxResponse = z.infer<typeof createSandboxResponseSchema>;\n\nexport const createSandboxUploadUrlResponseSchema = z.object({\n upload_url: z.string(),\n path: z.string(),\n expires_in_seconds: z.number(),\n});\n\nexport type CreateSandboxUploadUrlResponse = z.infer<\n typeof createSandboxUploadUrlResponseSchema\n>;\n\nconst sandboxFileSchema = z.object({\n name: z.string(),\n path: z.string(),\n type: z.enum([\"file\", \"dir\"]),\n size_bytes: z.number(),\n});\n\nexport type SandboxFile = z.infer<typeof sandboxFileSchema>;\n\nexport const listSandboxFilesResponseSchema = z.object({\n files: z.array(sandboxFileSchema),\n});\n\nexport type ListSandboxFilesResponse = z.infer<\n typeof listSandboxFilesResponseSchema\n>;\n\nexport const uploadSandboxFileResponseSchema = z.object({\n path: z.string(),\n size_bytes: z.number(),\n});\n\nexport type UploadSandboxFileResponse = z.infer<\n typeof uploadSandboxFileResponseSchema\n>;\n\nexport const DEFAULT_SANDBOX_FILES_PATH = \"/workspace\";\n", "import { type Command } from \"commander\";\n\nimport { createSandboxResponseSchema } from \"@/api/sandbox-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype CreateOptions = {\n json?: boolean;\n};\n\nexport function registerSandboxesCreate(sandboxes: Command): void {\n sandboxes\n .command(\"create\")\n .description(\"Create a new sandbox for staging files before a run\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function createAction(this: Command, options: CreateOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/sandboxes\",\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = createSandboxResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { sandbox_id: sandboxId, expires_at: expiresAt } = parsed.data;\n\n console.log(green(\"Sandbox created!\"));\n console.log(\n renderKeyValue([\n { label: \"ID\", value: sandboxId },\n { label: \"Expires\", value: expiresAt },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport {\n DEFAULT_SANDBOX_FILES_PATH,\n listSandboxFilesResponseSchema,\n type SandboxFile,\n} from \"@/api/sandbox-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype FilesOptions = {\n path?: string;\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"TYPE\", cell: (row: SandboxFile) => row.type },\n { header: \"NAME\", cell: (row: SandboxFile) => row.name },\n { header: \"PATH\", cell: (row: SandboxFile) => row.path },\n { header: \"SIZE\", cell: (row: SandboxFile) => String(row.size_bytes) },\n] as const;\n\nexport function registerSandboxesFiles(sandboxes: Command): void {\n sandboxes\n .command(\"files <sandbox_id>\")\n .description(\"List files in a sandbox directory\")\n .option(\n \"--path <path>\",\n `directory to list (defaults to ${DEFAULT_SANDBOX_FILES_PATH})`\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function filesAction(\n this: Command,\n sandboxId: string,\n options: FilesOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const searchParams = new URLSearchParams();\n if (options.path !== undefined) {\n searchParams.append(\"path\", options.path);\n }\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/sandboxes/${encodeURIComponent(sandboxId)}/files`,\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listSandboxFilesResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { files } = parsed.data;\n\n if (files.length === 0) {\n console.log(\"No files found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, files));\n console.log(`Showing ${files.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { createSandboxUploadUrlResponseSchema } from \"@/api/sandbox-schemas.js\";\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype PrepareUploadUrlOptions = {\n path: string;\n json?: boolean;\n};\n\nexport function registerSandboxesPrepareUploadUrl(sandboxes: Command): void {\n sandboxes\n .command(\"prepare-upload-url <sandbox_id>\")\n .description(\n \"Request a presigned URL for uploading a file larger than 10MB to a sandbox\"\n )\n .requiredOption(\n \"--path <path>\",\n \"destination path inside the sandbox (e.g. /workspace/data.csv)\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function prepareUploadUrlAction(\n this: Command,\n sandboxId: string,\n options: PrepareUploadUrlOptions\n ) {\n const trimmedPath = options.path.trim();\n if (trimmedPath.length === 0) {\n throw new CliError(\"--path must not be empty\");\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: `/v1/sandboxes/${encodeURIComponent(sandboxId)}/upload-urls`,\n apiKey,\n apiBaseUrl,\n body: { path: trimmedPath },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = createSandboxUploadUrlResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const {\n upload_url: uploadUrl,\n path: resolvedPath,\n expires_in_seconds: expiresInSeconds,\n } = parsed.data;\n\n console.log(\n renderKeyValue([\n { label: \"URL\", value: uploadUrl },\n { label: \"Path\", value: resolvedPath },\n { label: \"Expires in\", value: `${expiresInSeconds}s` },\n ])\n );\n });\n}\n", "import { readFile, stat } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\n\nimport { type Command } from \"commander\";\n\nimport { uploadSandboxFileResponseSchema } from \"@/api/sandbox-schemas.js\";\nimport { httpUpload } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderKeyValue } from \"@/output/text.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype UploadOptions = {\n path?: string;\n json?: boolean;\n};\n\nconst MAX_DIRECT_UPLOAD_BYTES = 10 * 1024 * 1024;\n\nexport function registerSandboxesUpload(sandboxes: Command): void {\n sandboxes\n .command(\"upload <sandbox_id> <file>\")\n .description(\n \"Upload a local file directly to a sandbox (max 10MB; use prepare-upload-url for larger files)\"\n )\n .option(\n \"--path <path>\",\n \"destination path inside the sandbox (defaults to /workspace/<filename>)\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function uploadAction(\n this: Command,\n sandboxId: string,\n file: string,\n options: UploadOptions\n ) {\n const trimmedPath = options.path?.trim();\n if (trimmedPath === \"\") {\n throw new CliError(\"--path must not be empty\");\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const stats = await stat(file).catch((error) => {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Could not read file \"${file}\": ${message}`);\n });\n if (!stats.isFile()) {\n throw new CliError(`Could not read file \"${file}\": not a regular file`);\n }\n\n if (stats.size > MAX_DIRECT_UPLOAD_BYTES) {\n throw new CliError(\n `File \"${file}\" is ${stats.size} bytes, larger than the ${MAX_DIRECT_UPLOAD_BYTES}-byte direct-upload limit. Use \\`duvo sandboxes prepare-upload-url\\` for larger files.`\n );\n }\n\n const content = await readFile(file).catch((error) => {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Could not read file \"${file}\": ${message}`);\n });\n const filename = basename(file);\n const formData = new FormData();\n formData.append(\"file\", new Blob([new Uint8Array(content)]), filename);\n if (trimmedPath !== undefined) {\n formData.append(\"path\", trimmedPath);\n }\n\n const raw = await httpUpload({\n path: `/v1/sandboxes/${encodeURIComponent(sandboxId)}/files`,\n apiKey,\n apiBaseUrl,\n formData,\n }).catch((error) => {\n if (error instanceof CliError && /\\b413\\b/.test(error.message)) {\n throw new CliError(\n \"Sandbox rejected the upload because the file is too large. Use `duvo sandboxes prepare-upload-url` for larger files.\"\n );\n }\n\n throw error;\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = uploadSandboxFileResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const { path: resolvedPath, size_bytes: sizeBytes } = parsed.data;\n\n console.log(green(\"File uploaded!\"));\n console.log(\n renderKeyValue([\n { label: \"Path\", value: resolvedPath },\n { label: \"Size\", value: `${sizeBytes} bytes` },\n ])\n );\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerSandboxesCreate } from \"./create.js\";\nimport { registerSandboxesFiles } from \"./files.js\";\nimport { registerSandboxesPrepareUploadUrl } from \"./prepare-upload-url.js\";\nimport { registerSandboxesUpload } from \"./upload.js\";\n\nexport function registerSandboxes(program: Command): void {\n const sandboxes = program\n .command(\"sandboxes\")\n .description(\"Manage sandboxes in the Duvo public API\");\n\n registerSandboxesCreate(sandboxes);\n registerSandboxesFiles(sandboxes);\n registerSandboxesUpload(sandboxes);\n registerSandboxesPrepareUploadUrl(sandboxes);\n}\n", "import { deleteSkillResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { confirmDestructive } from \"../shared/confirm.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype DeleteOptions = {\n yes?: boolean;\n json?: boolean;\n};\n\nexport function registerSkillsDelete(skills: Command): void {\n skills\n .command(\"delete <skill-id>\")\n .description(\"Delete a custom skill from the current team\")\n .option(\"-y, --yes\", \"skip confirmation prompt\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function deleteAction(\n this: Command,\n skillId: string,\n options: DeleteOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n await confirmDestructive({\n message: `Delete skill \"${skillId}\"?`,\n skip: Boolean(options.yes),\n });\n\n const raw = await httpRequest({\n method: \"DELETE\",\n path: `/v1/skills/${encodeURIComponent(skillId)}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = deleteSkillResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n throw new CliError(`Failed to delete skill: ${parsed.data.message}`);\n }\n\n console.log(green(\"Skill deleted!\"));\n if (parsed.data.message) {\n console.log(parsed.data.message);\n }\n });\n}\n", "import { writeFileSync } from \"node:fs\";\n\nimport { type Command } from \"commander\";\n\nimport { CliError, EXIT_CODE } from \"@/errors.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype DownloadOptions = {\n output?: string;\n};\n\nexport function registerSkillsDownload(skills: Command): void {\n skills\n .command(\"download <skill-id>\")\n .description(\"Download a custom skill as a ZIP archive\")\n .option(\n \"-o, --output <path>\",\n 'path to write the zip to (default \"<skill-id>.zip\"; use \"-\" for stdout)'\n )\n .action(async function downloadAction(\n this: Command,\n skillId: string,\n options: DownloadOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n // The download endpoint returns binary, so bypass the JSON helper and\n // call fetch directly.\n const url = new URL(\n `/v1/skills/${encodeURIComponent(skillId)}/download`,\n apiBaseUrl.endsWith(\"/\") ? apiBaseUrl : `${apiBaseUrl}/`\n );\n\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"application/zip\",\n },\n });\n\n if (response.status === 401) {\n throw new CliError(\n \"Unauthorized. Check that the API key is valid.\",\n EXIT_CODE.AUTH\n );\n }\n\n if (response.status === 404) {\n throw new CliError(\n `Not found: GET /v1/skills/${skillId}/download`,\n EXIT_CODE.NOT_FOUND\n );\n }\n\n if (!response.ok) {\n const detail = await response.text().catch(() => \"\");\n const suffix = detail.length > 0 ? `: ${detail}` : \"\";\n throw new CliError(\n `Request failed (${response.status} ${response.statusText})${suffix}`\n );\n }\n\n const buffer = Buffer.from(await response.arrayBuffer());\n const target = options.output ?? `${skillId}.zip`;\n\n if (target === \"-\") {\n process.stdout.write(buffer);\n return;\n }\n\n writeFileSync(target, buffer);\n console.log(`Wrote ${buffer.length} bytes to ${target}`);\n });\n}\n", "import { getSkillFileContentResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype FileGetOptions = {\n json?: boolean;\n};\n\nexport function registerSkillsFileGet(skills: Command): void {\n skills\n .command(\"file-get <skill-id> <path>\")\n .description(\n \"Get the content of a file in a skill (path is the relative file path inside the skill, e.g. SKILL.md)\"\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function fileGetAction(\n this: Command,\n skillId: string,\n filePath: string,\n options: FileGetOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n // Encode each path segment but leave slashes so the wildcard route\n // matches multi-segment paths like `references/foo.md`.\n const encodedPath = filePath\n .split(\"/\")\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/skills/${encodeURIComponent(skillId)}/files/${encodedPath}`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = getSkillFileContentResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n // Stream the file content straight to stdout so it's pipeable.\n process.stdout.write(parsed.data.content);\n });\n}\n", "import { readFileSync } from \"node:fs\";\n\nimport { updateSkillFileResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { green } from \"@/output/colors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype FileUpdateOptions = {\n content?: string;\n contentFile?: string;\n json?: boolean;\n};\n\nexport function registerSkillsFileUpdate(skills: Command): void {\n skills\n .command(\"file-update <skill-id> <path>\")\n .description(\n \"Update the content of a file in a skill (path is the relative file path inside the skill)\"\n )\n .option(\"--content <text>\", \"new file content as a string\")\n .option(\n \"--content-file <path>\",\n 'path to a file to read content from, or \"-\" for stdin'\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function fileUpdateAction(\n this: Command,\n skillId: string,\n filePath: string,\n options: FileUpdateOptions\n ) {\n if (options.content !== undefined && options.contentFile !== undefined) {\n throw new CliError(\n \"Pass either --content or --content-file, not both.\"\n );\n }\n\n const content = readContent(options);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const encodedPath = filePath\n .split(\"/\")\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n\n const raw = await httpRequest({\n method: \"PUT\",\n path: `/v1/skills/${encodeURIComponent(skillId)}/files/${encodedPath}`,\n apiKey,\n apiBaseUrl,\n body: { content },\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = updateSkillFileResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (!parsed.data.success) {\n throw new CliError(`Failed to update file: ${parsed.data.message}`);\n }\n\n console.log(green(\"File updated!\"));\n if (parsed.data.message) {\n console.log(parsed.data.message);\n }\n });\n}\n\nfunction readContent(options: FileUpdateOptions): string {\n if (options.content !== undefined) {\n return options.content;\n }\n\n if (options.contentFile === undefined) {\n throw new CliError(\"Pass either --content or --content-file\");\n }\n\n if (options.contentFile === \"-\") {\n return readFileSync(0, \"utf8\");\n }\n\n try {\n return readFileSync(options.contentFile, \"utf8\");\n } catch (error) {\n throw new CliError(\n `Cannot read --content-file ${options.contentFile}: ${(error as Error).message}`\n );\n }\n}\n", "import {\n listSkillFilesResponseSchema,\n type SkillFileItem,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype FilesOptions = {\n json?: boolean;\n};\n\nconst TABLE_COLUMNS = [\n { header: \"PATH\", cell: (row: SkillFileItem) => row.path },\n { header: \"NAME\", cell: (row: SkillFileItem) => row.name },\n {\n header: \"SIZE\",\n cell: (row: SkillFileItem) =>\n row.size === undefined ? \"\" : String(row.size),\n },\n {\n header: \"CONTENT TYPE\",\n cell: (row: SkillFileItem) => row.contentType ?? \"\",\n },\n {\n header: \"UPDATED\",\n cell: (row: SkillFileItem) => row.updatedAt ?? \"\",\n },\n] as const;\n\nexport function registerSkillsFiles(skills: Command): void {\n skills\n .command(\"files <skill-id>\")\n .description(\"List files in a skill\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function filesAction(\n this: Command,\n skillId: string,\n options: FilesOptions\n ) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/skills/${encodeURIComponent(skillId)}/files`,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listSkillFilesResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.files.length === 0) {\n console.log(\"No files found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, parsed.data.files));\n console.log(`Showing ${parsed.data.files.length}`);\n });\n}\n", "import { readFileSync } from \"node:fs\";\n\nimport { generateSkillResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype GenerateOptions = {\n prompt: string;\n existingContentFile?: string;\n json?: boolean;\n};\n\nexport function registerSkillsGenerate(skills: Command): void {\n skills\n .command(\"generate\")\n .description(\n \"Generate a SKILL.md file from a natural-language description (does not persist)\"\n )\n .requiredOption(\n \"--prompt <text>\",\n \"natural-language description of the skill (1-2000 chars)\"\n )\n .option(\n \"--existing-content-file <path>\",\n 'path to a file with existing SKILL.md content to refine, or \"-\" for stdin'\n )\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function generateAction(\n this: Command,\n options: GenerateOptions\n ) {\n const body: Record<string, unknown> = { prompt: options.prompt };\n\n if (options.existingContentFile !== undefined) {\n body.existingContent = readExistingContent(options.existingContentFile);\n }\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const raw = await httpRequest({\n method: \"POST\",\n path: \"/v1/skills/generate\",\n apiKey,\n apiBaseUrl,\n body,\n timeoutMs: 120_000,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = generateSkillResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n // Generated SKILL.md content goes straight to stdout so it's pipeable.\n process.stdout.write(parsed.data.content);\n });\n}\n\nfunction readExistingContent(source: string): string {\n const target = source === \"-\" ? 0 : source;\n const label = source === \"-\" ? \"stdin\" : `--existing-content-file ${source}`;\n try {\n return readFileSync(target, \"utf8\");\n } catch (error) {\n throw new CliError(`Cannot read ${label}: ${(error as Error).message}`);\n }\n}\n", "import {\n listSkillsResponseSchema,\n listSystemSkillsResponseSchema,\n type SkillApi,\n type SystemSkill,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype ListOptions = {\n system?: boolean;\n json?: boolean;\n};\n\nconst TEAM_COLUMNS = [\n { header: \"ID\", cell: (row: SkillApi) => row.id },\n { header: \"NAME\", cell: (row: SkillApi) => row.name },\n {\n header: \"DESCRIPTION\",\n cell: (row: SkillApi) => row.description,\n maxWidth: 60,\n },\n {\n header: \"SYSTEM\",\n cell: (row: SkillApi) => (row.team_id === null ? \"yes\" : \"no\"),\n },\n] as const;\n\nconst SYSTEM_COLUMNS = [\n { header: \"ID\", cell: (row: SystemSkill) => row.id },\n { header: \"NAME\", cell: (row: SystemSkill) => row.name },\n {\n header: \"DESCRIPTION\",\n cell: (row: SystemSkill) => row.description,\n maxWidth: 60,\n },\n] as const;\n\nexport function registerSkillsList(skills: Command): void {\n skills\n .command(\"list\", { isDefault: true })\n .description(\"List skills available to your team (or system skills only)\")\n .option(\"--system\", \"list system skills only\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function listAction(this: Command, options: ListOptions) {\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const path = options.system ? \"/v1/skills/system\" : \"/v1/skills\";\n const raw = await httpRequest({\n method: \"GET\",\n path,\n apiKey,\n apiBaseUrl,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n if (options.system) {\n const parsed = listSystemSkillsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.skills.length === 0) {\n console.log(\"No system skills found.\");\n return;\n }\n\n console.log(renderTable(SYSTEM_COLUMNS, parsed.data.skills));\n console.log(`Showing ${parsed.data.skills.length}`);\n return;\n }\n\n const parsed = listSkillsResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n if (parsed.data.skills.length === 0) {\n console.log(\"No skills found.\");\n return;\n }\n\n console.log(renderTable(TEAM_COLUMNS, parsed.data.skills));\n console.log(`Showing ${parsed.data.skills.length}`);\n });\n}\n", "import { type Command } from \"commander\";\n\nimport { registerSkillsDelete } from \"./delete.js\";\nimport { registerSkillsDownload } from \"./download.js\";\nimport { registerSkillsFileGet } from \"./file-get.js\";\nimport { registerSkillsFileUpdate } from \"./file-update.js\";\nimport { registerSkillsFiles } from \"./files.js\";\nimport { registerSkillsGenerate } from \"./generate.js\";\nimport { registerSkillsList } from \"./list.js\";\n\nexport function registerSkills(program: Command): void {\n const skills = program\n .command(\"skills\")\n .description(\"Manage skills (custom and system)\");\n\n registerSkillsList(skills);\n registerSkillsDelete(skills);\n registerSkillsFiles(skills);\n registerSkillsFileGet(skills);\n registerSkillsFileUpdate(skills);\n registerSkillsDownload(skills);\n registerSkillsGenerate(skills);\n}\n", "import {\n listTeamMembersResponseSchema,\n publicProfileResponseSchema,\n type TeamMemberApi,\n} from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { CliError } from \"@/errors.js\";\nimport { printJson } from \"@/output/json.js\";\nimport { renderTable } from \"@/output/table.js\";\n\nimport { parseLimit, parseOffset } from \"../shared/pagination.js\";\nimport { requireAuthenticatedConfig } from \"../shared/require-auth.js\";\n\ntype MembersOptions = {\n team?: string;\n limit?: string;\n offset?: string;\n json?: boolean;\n};\n\nconst DEFAULT_LIMIT = 50;\nconst MIN_LIMIT = 1;\nconst MAX_LIMIT = 100;\n\nconst TABLE_COLUMNS = [\n { header: \"ID\", cell: (row: TeamMemberApi) => row.id },\n { header: \"NAME\", cell: (row: TeamMemberApi) => row.name ?? \"\" },\n { header: \"EMAIL\", cell: (row: TeamMemberApi) => row.email },\n { header: \"ROLE\", cell: (row: TeamMemberApi) => row.role },\n {\n header: \"INHERITED\",\n cell: (row: TeamMemberApi) => (row.inheritedFromOrg ? \"yes\" : \"no\"),\n },\n] as const;\n\nexport function registerTeamMembers(team: Command): void {\n team\n .command(\"members\")\n .description(\"List members of a team\")\n .option(\n \"--team <id>\",\n \"team ID (defaults to the team scoped to your API key)\"\n )\n .option(\"--limit <n>\", `page size (${MIN_LIMIT}-${MAX_LIMIT})`)\n .option(\"--offset <n>\", \"number of members to skip\")\n .option(\"--json\", \"output raw JSON from the API\")\n .action(async function membersAction(\n this: Command,\n options: MembersOptions\n ) {\n const limit = parseLimit(options.limit, {\n defaultValue: DEFAULT_LIMIT,\n min: MIN_LIMIT,\n max: MAX_LIMIT,\n });\n const offset = parseOffset(options.offset);\n\n const { apiKey, apiBaseUrl } = await requireAuthenticatedConfig(this);\n\n const teamId =\n options.team ?? (await resolveTeamFromApiKey({ apiKey, apiBaseUrl }));\n\n const searchParams = new URLSearchParams();\n searchParams.append(\"limit\", String(limit));\n searchParams.append(\"offset\", String(offset));\n\n const raw = await httpRequest({\n method: \"GET\",\n path: `/v1/teams/${encodeURIComponent(teamId)}/members`,\n apiKey,\n apiBaseUrl,\n searchParams,\n });\n\n if (options.json) {\n printJson(raw);\n return;\n }\n\n const parsed = listTeamMembersResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API: ${parsed.error.message}`\n );\n }\n\n const response = parsed.data;\n if (response.members.length === 0) {\n console.log(\"No members found.\");\n return;\n }\n\n console.log(renderTable(TABLE_COLUMNS, response.members));\n console.log(\n `Showing ${response.members.length} of ${response.total} \u00B7 offset ${response.offset}`\n );\n });\n}\n\nasync function resolveTeamFromApiKey(options: {\n apiKey: string;\n apiBaseUrl: string;\n}): Promise<string> {\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/profile\",\n apiKey: options.apiKey,\n apiBaseUrl: options.apiBaseUrl,\n });\n const parsed = publicProfileResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new CliError(\n `Unexpected response from the API while resolving the team: ${parsed.error.message}`\n );\n }\n\n const teamId = parsed.data.profile.teamId;\n if (!teamId) {\n throw new CliError(\n \"Could not determine a team for this API key. Pass --team <id> explicitly.\"\n );\n }\n\n return teamId;\n}\n", "import { type Command } from \"commander\";\n\nimport { registerTeamMembers } from \"./members.js\";\n\nexport function registerTeam(program: Command): void {\n const team = program\n .command(\"team\")\n .description(\"Inspect team data exposed by the Duvo public API\");\n\n registerTeamMembers(team);\n}\n", "import { publicProfileResponseSchema } from \"@taskcrew/shared\";\nimport { type Command } from \"commander\";\n\nimport { httpRequest } from \"@/client/client.js\";\nimport { truncateApiKey } from \"@/output/format.js\";\n\nimport { requireAuthenticatedConfig } from \"./shared/require-auth.js\";\n\nexport function registerWhoami(program: Command): void {\n program\n .command(\"whoami\")\n .description(\n \"Print the active profile, the API key owner's name and email, the truncated API key, and the base URL\"\n )\n .action(async function whoamiAction(this: Command) {\n const resolved = await requireAuthenticatedConfig(this);\n\n const profileLabel =\n resolved.profileName ?? \"(env-only, no stored profile)\";\n console.log(`Profile ${profileLabel}`);\n\n const userLine = await fetchUserLine({\n apiKey: resolved.apiKey,\n apiBaseUrl: resolved.apiBaseUrl,\n });\n if (userLine !== null) {\n console.log(`User ${userLine}`);\n }\n\n const credentialLabel =\n resolved.authType === \"oauth\" ? \"Token \" : \"API key \";\n console.log(`${credentialLabel} ${truncateApiKey(resolved.apiKey)}`);\n console.log(`Base URL ${resolved.apiBaseUrl}`);\n });\n}\n\nasync function fetchUserLine(options: {\n apiKey: string;\n apiBaseUrl: string;\n}): Promise<string | null> {\n try {\n const raw = await httpRequest({\n method: \"GET\",\n path: \"/v1/profile\",\n apiKey: options.apiKey,\n apiBaseUrl: options.apiBaseUrl,\n });\n const parsed = publicProfileResponseSchema.safeParse(raw);\n if (!parsed.success) {\n return null;\n }\n\n const { name, email } = parsed.data.profile;\n return name ? `${name} <${email}>` : email;\n } catch {\n return null;\n }\n}\n", "#!/usr/bin/env node\nimport { createProgram } from \"@/bin/create-program.js\";\nimport { handleCliError } from \"@/errors.js\";\n\ncreateProgram()\n .parseAsync(process.argv)\n .catch((error: unknown) => {\n handleCliError(error);\n });\n"],
5
+ "mappings": ";;;;;AAAA,SAAS,gBAAAA,qBAAoB;AAC7B,SAAS,WAAAC,UAAS,QAAAC,aAAY;AAC9B,SAAS,qBAAqB;AAE9B,SAAS,eAAe;;;ACJxB,SAAS,SAAS;AAElB,IAAM,0BAA0B,EAAE,OAAO;AAAA,EACvC,IAAI,EAAE,OAAO;AAAA,EACb,MAAM,EAAE,OAAO;AAAA,EACf,SAAS,EAAE,OAAO,EAAE,QAAQ;AAAA,EAC5B,kBAAkB,EAAE,OAAO,EAAE,QAAQ;AAAA,EACrC,YAAY,EAAE,OAAO,EAAE,QAAQ;AAAA,EAC/B,YAAY,EAAE,OAAO,EAAE,QAAQ;AAAA,EAC/B,aAAa,EAAE,OAAO,EAAE,QAAQ;AAAA,EAChC,iBAAiB,EAAE,OAAO,EAAE,QAAQ;AACtC,CAAC;AAIM,IAAM,iCAAiC,EAAE,OAAO;AAAA,EACrD,SAAS,EAAE,MAAM,uBAAu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OAAO;IACP,gBAAgB;EAClB;EACA,2BAA2B;IACzB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,oBAAoB;IAClB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,8BAA8B;IAC5B,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,6BAA6B;IAC3B,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,6BAA6B;IAC3B,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,6BAA6B;IAC3B,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,gBAAgB;IACd,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,uBAAuB;IACrB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,uBAAuB;IACrB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,2BAA2B;IACzB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,sBAAsB;IACpB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,0BAA0B;IACxB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,cAAc;IACZ,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,oBAAoB;IAClB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,mBAAmB;IACjB,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;EAClB;EACA,cAAc;IACZ,OAAO;IACP,aACE;IACF,UAAU;IACV,OAAO;IACP,gBAAgB;E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CAAC,EACL;IACC;EACF;EACF,SAASA,IACN,OAAO,EACP,IAAI,CAAC,EACL;IACC;EACF;AACJ,CAAC;AAED,IAAM,iBAAiBA,IAAE,OAAO;EAC9B,QAAQA,IACL,OAAO,EACP,IAAI,CAAC,EACL;IACC;EACF;EACF,OAAOA,IACJ,OAAO,EACP,SAAS,EACT;IACC;EACF;EACF,WAAWA,IACR,QAAQ,EACR;IACC;EACF;AACJ,CAAC;AAEM,IAAM,wBAAwBA,IAAE,OAAO;EAC5C,IAAIA,IACD,OAAO,EACP,IAAI,CAAC,EACL;IACC;EACF;EAEF,UAAUA,IACP,KAAK,uBAAuB,EAC5B;IACC;EACF;EACF,aAAaA,IACV,KAAK;IACJ,GAAG;IACH,GAAG;IACH,GAAG;EACL,CAAC,EACA;IACC;EACF;EAEF,aAAaA,IACV,MAAM,cAAc,EACpB;IACC;EACF;EAEF,OAAOA,IACJ,OAAO,EACP,IAAI,CAAC,EACL;IACC;EACF;EACF,aAAaA,IACV,OAAO,EACP,IAAI,CAAC,EACL;IACC;EACF;EACF,QAAQA,IACL,OAAO,EACP,IAAI,CAAC,EACL,SAAS,EACT;IACC;EACF;EACF,WAAWA,IACR,OAAO,EACP,IAAI,CAAC,EACL;IACC;EACF;EACF,MAAMA,IACH,OAAO,EACP,IAAI,CAAC,EACL,SAAS,EACT;IACC;EACF;EACF,SAASA,IACN,MAAM,gBAAgB,EACtB,IAAI,CAAC,EACL;IACC;EACF;EAEF,QAAQA,IACL,OAAO,EACP,SAAS,EACT;IACC;EACF;EACF,OAAOA,IACJ,OAAO,EACP,SAAS,EACT;IACC;EACF;EACF,QAAQA,IACL,OAAO,EACP,SAAS,EACT;IACC;EACF;EACF,WAAWA,IACR,OAAO,EACP,SAAS,EACT;IACC;EACF;EACF,WAAWA,IACR,OAAO,EACP,SAAS,EACT;IACC;EACF;EACF,UAAUA,IACP,OAAO,EACP,SAAS,EACT;IACC;EACF;EACF,aAAaA,IACV,MAAMA,IAAE,OAAO,CAAC,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OAAO;AACvB,iBAAe,OAAO;AACtB,eAAa,OAAO;AAEpB,SAAO;AACT;AAlCgB;;;AiOpChB,cAAc,EACX,WAAW,QAAQ,IAAI,EACvB,MAAM,CAAC,UAAmB;AACzB,iBAAe,KAAK;AACtB,CAAC;",
6
+ "names": ["readFileSync", "dirname", "join", "text", "text", "z", "z", "version", "text", "text", "readFile", "confirm", "isCancel", "z", "JSONRepairError", "Error", "constructor", "message", "position", "codeSpace", "codeNewline", "codeTab", "codeReturn", "codeNonBreakingSpace", "codeEnQuad", "codeHairSpace", "codeNarrowNoBreakSpace", "codeMediumMathematicalSpace", "codeIdeographicSpace", "isHex", "char", "test", "isDigit", "isValidStringCharacter", "isDelimiter", "includes", "isFunctionNameCharStart", "isFunctionNameChar", "regexUrlStart", "regexUrlChar", "isUnquotedStringDelimiter", "isStartOfValue", "isQuote", "regexStartOfValue", "isControlCharacter", "isWhitespace", "text", "index", "code", "charCodeAt", "isWhitespaceExceptNewline", "isSpecialWhitespace", "isDoubleQuoteLike", "isSingleQuoteLike", "isDoubleQuote", "isSingleQuote", "stripLastOccurrence", "textToStrip", "stripRemainingText", "arguments", "length", "undefined", "lastIndexOf", "substring", "insertBeforeLastWhitespace", "textToInsert", "removeAtIndex", "start", "count", "endsWithCommaOrNewline", "controlCharacters", "escapeCharacters", "b", "f", "n", "r", "t", "jsonrepair", "text", "i", "output", "parseMarkdownCodeBlock", "processed", "parseValue", "throwUnexpectedEnd", "processedComma", "parseCharacter", "parseWhitespaceAndSkipComments", "isStartOfValue", "endsWithCommaOrNewline", "insertBeforeLastWhitespace", "parseNewlineDelimitedJSON", "stripLastOccurrence", "length", "throwUnexpectedCharacter", "parseObject", "parseArray", "parseString", "parseNumber", "parseKeywords", "parseUnquotedString", "parseRegex", "skipNewline", "arguments", "undefined", "start", "changed", "parseWhitespace", "parseComment", "_isWhiteSpace", "isWhitespace", "isWhitespaceExceptNewline", "whitespace", "isSpecialWhitespace", "atEndOfBlockComment", "blocks", "skipMarkdownCodeBlock", "isFunctionNameCharStart", "isFunctionNameChar", "block", "end", "slice", "char", "skipCharacter", "skipEscapeCharacter", "skipEllipsis", "initial", "processedKey", "throwObjectKeyExpected", "processedColon", "truncatedText", "throwColonExpected", "processedValue", "stopAtDelimiter", "stopAtIndex", "skipEscapeChars", "isQuote", "isEndQuote", "isDoubleQuote", "isSingleQuote", "isSingleQuoteLike", "isDoubleQuoteLike", "iBefore", "oBefore", "str", "iPrev", "prevNonWhitespaceIndex", "isDelimiter", "charAt", "substring", "iQuote", "oQuote", "isDigit", "parseConcatenatedString", "iPrevChar", "prevChar", "isUnquotedStringDelimiter", "regexUrlStart", "test", "regexUrlChar", "escapeChar", "j", "isHex", "throwInvalidUnicodeCharacter", "isControlCharacter", "isValidStringCharacter", "throwInvalidCharacter", "parsedStr", "removeAtIndex", "atEndOfNumber", "repairNumberEndingWithNumericSymbol", "num", "hasInvalidLeadingZero", "parseKeyword", "name", "value", "isKey", "symbol", "JSON", "stringify", "prev", "JSONRepairError", "chars", "z", "__name", "z", "z", "__name", "z", "__name", "__name", "__name", "__name", "__name", "z", "__name", "z", "__name", "z", "z", "z", "__name", "z", "z", "z", "z", "z", "z", "__name", "__name", "z", "z", "__name", "z", "z", "z", "__name", "__name", "z", "__name", "text", "z", "trimmed", "isCancel", "confirm", "readFile", "TABLE_COLUMNS", "z", "TABLE_COLUMNS", "buildBody", "readFileSync", "readFile", "readFileSync", "collect", "z", "integrationsListResponseSchema", "buildIntegrationConfigSchema", "listBuildIntegrationsResponseSchema", "TABLE_COLUMNS", "TABLE_COLUMNS", "listBuildIntegrationsResponseSchema", "z", "z", "publicBuildSchema", "z", "listBuildsResponseSchema", "DEFAULT_LIMIT", "MIN_LIMIT", "MAX_LIMIT", "TABLE_COLUMNS", "listBuildsResponseSchema", "buildConfirmMessage", "readFile", "TABLE_COLUMNS", "readStdin", "readFile", "TABLE_COLUMNS", "value", "DEFAULT_LIMIT", "MIN_LIMIT", "MAX_LIMIT", "TABLE_COLUMNS", "TABLE_COLUMNS", "TABLE_COLUMNS", "integrationsListResponseSchema", "readFileSync", "readFileSync", "TABLE_COLUMNS", "TABLE_COLUMNS", "integrationsListResponseSchema", "isCancel", "text", "text", "isCancel", "next", "TABLE_COLUMNS", "isCancel", "isCancel", "TABLE_COLUMNS", "registerList", "DEFAULT_LIMIT", "MIN_LIMIT", "MAX_LIMIT", "TABLE_COLUMNS", "z", "z", "DEFAULT_LIMIT", "MIN_LIMIT", "MAX_LIMIT", "SORT_ORDERS", "TABLE_COLUMNS", "DEFAULT_LIMIT", "MIN_LIMIT", "MAX_LIMIT", "TABLE_COLUMNS", "buildBody", "z", "TABLE_COLUMNS", "readFile", "readFile", "readFileSync", "readContent", "readFileSync", "TABLE_COLUMNS", "readFileSync", "readFileSync", "parsed", "DEFAULT_LIMIT", "MIN_LIMIT", "MAX_LIMIT", "TABLE_COLUMNS", "join", "dirname", "readFileSync"]
7
7
  }