olakai-cli 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-GXKHWBGO.js → chunk-B44Y3ZQP.js} +71 -4
- package/dist/{chunk-GXKHWBGO.js.map → chunk-B44Y3ZQP.js.map} +1 -1
- package/dist/{chunk-75YQWZ4Q.js → chunk-E33XD5CO.js} +1385 -19
- package/dist/chunk-E33XD5CO.js.map +1 -0
- package/dist/{doctor-27VDFNP7.js → doctor-TIVMQBE3.js} +3 -3
- package/dist/index.js +35 -3
- package/dist/index.js.map +1 -1
- package/dist/{repair-WSBWAW2B.js → repair-JYRH2ES4.js} +3 -3
- package/package.json +1 -1
- package/dist/chunk-75YQWZ4Q.js.map +0 -1
- /package/dist/{doctor-27VDFNP7.js.map → doctor-TIVMQBE3.js.map} +0 -0
- /package/dist/{repair-WSBWAW2B.js.map → repair-JYRH2ES4.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/whoami.ts","../src/commands/init.ts","../src/lib/handshake.ts","../src/monitor/detect-all.ts","../src/lib/branding.ts","../src/commands/agents.ts","../src/commands/workflows.ts","../src/commands/kpis.ts","../src/commands/custom-data.ts","../src/commands/activity.ts","../src/commands/monitor.ts","../src/commands/profiles.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { createRequire } from \"module\";\nimport { Command } from \"commander\";\nimport { loginCommand } from \"./commands/login.js\";\nimport { logoutCommand } from \"./commands/logout.js\";\nimport { whoamiCommand } from \"./commands/whoami.js\";\nimport { initCommand, type InitCommandOptions } from \"./commands/init.js\";\nimport { registerAgentsCommand } from \"./commands/agents.js\";\nimport { registerWorkflowsCommand } from \"./commands/workflows.js\";\nimport { registerKpisCommand } from \"./commands/kpis.js\";\nimport { registerCustomDataCommand } from \"./commands/custom-data.js\";\nimport { registerActivityCommand } from \"./commands/activity.js\";\nimport { registerMonitorCommand } from \"./commands/monitor.js\";\nimport { registerProfilesCommand } from \"./commands/profiles.js\";\nimport {\n setEnvironment,\n setHostOverride,\n isValidEnvironment,\n getValidEnvironments,\n type Environment,\n} from \"./lib/config.js\";\nimport { setProfileOverride } from \"./lib/profiles.js\";\n\nconst require = createRequire(import.meta.url);\nconst packageJson = require(\"../package.json\") as { version: string };\n\nconst program = new Command();\n\nprogram\n .name(\"olakai\")\n .description(\"Olakai CLI tool\")\n .version(packageJson.version)\n .option(\n \"-e, --env <environment>\",\n `Environment to use (${getValidEnvironments().join(\", \")})`,\n \"production\",\n )\n .option(\n \"--host <host>\",\n \"On-prem Olakai host (e.g. olakai.acme.com). Overrides --env and OLAKAI_HOST.\",\n )\n .option(\n \"--profile <name>\",\n \"Olakai profile to use (overrides OLAKAI_PROFILE, workspace config, and registry default).\",\n )\n .hook(\"preAction\", (thisCommand) => {\n const options = thisCommand.opts();\n if (options.env) {\n if (!isValidEnvironment(options.env)) {\n console.error(\n `Invalid environment: ${options.env}. Valid options: ${getValidEnvironments().join(\", \")}`,\n );\n process.exit(1);\n }\n setEnvironment(options.env as Environment);\n }\n if (typeof options.host === \"string\" && options.host.length > 0) {\n setHostOverride(options.host);\n }\n if (typeof options.profile === \"string\" && options.profile.length > 0) {\n setProfileOverride(options.profile);\n }\n });\n\nprogram\n .command(\"init\")\n .description(\n \"Interactive self-onboarding wizard: pick host, verify email, get a CLI token.\",\n )\n .option(\"--email <email>\", \"Pre-fill the email (skips the email prompt)\")\n .option(\n \"--non-interactive\",\n \"Fail fast on any missing required input (no prompts).\",\n )\n .option(\n \"--skip-monitor\",\n \"Skip the optional 'olakai monitor init' handoff at the end.\",\n )\n .action((options: InitCommandOptions) => initCommand(options));\n\nprogram\n .command(\"login\")\n .description(\"Log in to Olakai using browser authentication\")\n .action(loginCommand);\n\nprogram\n .command(\"logout\")\n .description(\"Log out from Olakai\")\n .action(logoutCommand);\n\nprogram\n .command(\"whoami\")\n .description(\"Show current logged-in user\")\n .action(whoamiCommand);\n\n// Register subcommands for config management\nregisterAgentsCommand(program);\nregisterWorkflowsCommand(program);\nregisterKpisCommand(program);\nregisterCustomDataCommand(program);\n\n// Register subcommands for activity inspection\nregisterActivityCommand(program);\n\n// Register subcommands for local agent monitoring\nregisterMonitorCommand(program);\n\n// Register subcommands for AWS-style profile management\nregisterProfilesCommand(program);\n\nprogram.parse();\n","import open from \"open\";\nimport { requestDeviceCode, pollForToken, getCurrentUser } from \"../lib/api.js\";\nimport { saveToken, isTokenValid } from \"../lib/auth.js\";\nimport { getBaseUrl, getEnvironment } from \"../lib/config.js\";\nimport { patchProfile, resolveProfileName } from \"../lib/profiles.js\";\n\nconst POLL_INTERVAL_MS = 5000; // 5 seconds\n\n/**\n * Login command handler\n */\nexport async function loginCommand(): Promise<void> {\n // Check if already logged in\n if (isTokenValid()) {\n try {\n const user = await getCurrentUser();\n console.log(`Already logged in as ${user.email}`);\n console.log(\"Run 'olakai logout' to log out first.\");\n return;\n } catch {\n // Token is invalid, continue with login\n }\n }\n\n const resolved = resolveProfileName();\n const profileName = resolved?.name ?? \"default\";\n console.log(\n `Logging in to Olakai (profile: ${profileName}, host: ${getBaseUrl()}, env: ${getEnvironment()})...\\n`,\n );\n\n try {\n // Request device code\n const deviceCode = await requestDeviceCode();\n\n // Display instructions\n console.log(\"To complete login, visit:\");\n console.log(`\\n ${deviceCode.verification_uri_complete}\\n`);\n console.log(`Or go to ${deviceCode.verification_uri} and enter code:`);\n console.log(`\\n ${deviceCode.user_code}\\n`);\n\n // Try to open browser\n console.log(\"Opening browser...\");\n try {\n await open(deviceCode.verification_uri_complete);\n } catch {\n console.log(\"(Could not open browser automatically)\");\n }\n\n console.log(\"\\nWaiting for authorization...\");\n\n // Poll for token\n const expiresAt = Date.now() + deviceCode.expires_in * 1000;\n\n while (Date.now() < expiresAt) {\n await sleep(POLL_INTERVAL_MS);\n\n try {\n const tokenResponse = await pollForToken(deviceCode.device_code);\n\n if (tokenResponse) {\n // Save token (lands in the active profile, or \"default\" if\n // no profile was explicitly selected).\n saveToken(tokenResponse.access_token, tokenResponse.expires_in);\n\n // Get user info and cache identifiers on the profile so\n // offline `whoami` still has something to show.\n const user = await getCurrentUser();\n try {\n patchProfile(profileName, {\n email: user.email,\n userId: user.id,\n accountId: user.accountId,\n });\n } catch {\n // best-effort\n }\n\n console.log(`\\nLogged in as ${user.email}`);\n console.log(`Profile: ${profileName}`);\n console.log(`Account: ${user.accountId}`);\n console.log(`Role: ${user.role}`);\n return;\n }\n\n // Still pending, show spinner\n process.stdout.write(\".\");\n } catch (error) {\n if (error instanceof Error) {\n console.error(`\\nLogin failed: ${error.message}`);\n } else {\n console.error(\"\\nLogin failed: Unknown error\");\n }\n process.exit(1);\n }\n }\n\n console.error(\"\\nLogin timed out. Please try again.\");\n process.exit(1);\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Login failed: ${error.message}`);\n } else {\n console.error(\"Login failed: Unknown error\");\n }\n process.exit(1);\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import { clearToken, isTokenValid } from \"../lib/auth.js\";\n\n/**\n * Logout command handler\n */\nexport function logoutCommand(): void {\n if (!isTokenValid()) {\n console.log(\"Not currently logged in.\");\n return;\n }\n\n clearToken();\n console.log(\"Logged out successfully.\");\n}\n","import { getCurrentUser } from \"../lib/api.js\";\nimport { isTokenValid, loadToken } from \"../lib/auth.js\";\nimport { getBaseUrl, getEnvironment } from \"../lib/config.js\";\nimport { patchProfile, resolveActiveProfile } from \"../lib/profiles.js\";\n\nfunction formatExpiry(expiresAt: number | undefined): string {\n if (typeof expiresAt !== \"number\") return \"no token\";\n const now = Math.floor(Date.now() / 1000);\n if (expiresAt <= now) return \"expired\";\n const seconds = expiresAt - now;\n const days = Math.floor(seconds / 86400);\n const hours = Math.floor((seconds % 86400) / 3600);\n if (days > 0) return `${days}d ${hours}h`;\n const minutes = Math.floor((seconds % 3600) / 60);\n if (hours > 0) return `${hours}h ${minutes}m`;\n return `${minutes}m`;\n}\n\n/**\n * Whoami command handler.\n *\n * Prints the active profile, host, user identity (email + name +\n * account), and token expiry. Falls back gracefully when individual\n * fields aren't available (e.g. unauthenticated, or the backend is\n * unreachable but a profile is configured locally).\n */\nexport async function whoamiCommand(): Promise<void> {\n let active;\n try {\n active = resolveActiveProfile();\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n\n // Always print the resolved local view first — works even when\n // unauthenticated.\n if (active) {\n const effectiveHost = getBaseUrl();\n console.log(`Profile: ${active.name} (from ${active.source})`);\n if (effectiveHost !== active.host) {\n console.log(`Host: ${effectiveHost} (overrides profile host)`);\n console.log(`Profile host: ${active.host}`);\n } else if (active.hostFromWorkspaceConfig) {\n console.log(`Host: ${active.host} (from workspace config)`);\n } else {\n console.log(`Host: ${active.host}`);\n }\n } else {\n // \"Not logged in\" is an error state — write to stderr so scripts\n // that pipe `whoami` to grep / jq don't catch this in their stdout.\n console.error(`Profile: (none)`);\n console.error(`Host: ${getBaseUrl()}`);\n console.error(`Environment: ${getEnvironment()}`);\n console.error(\"Not logged in. Run 'olakai login' to authenticate.\");\n process.exit(1);\n }\n\n if (!isTokenValid()) {\n const creds = loadToken();\n console.log(`Token: ${creds ? \"expired\" : \"missing\"}`);\n console.log(\"Not logged in. Run 'olakai login' to authenticate.\");\n process.exit(1);\n }\n\n try {\n const user = await getCurrentUser();\n\n // Backfill cached identifiers so subsequent `profiles list` /\n // `whoami` (and future offline commands) can display them without\n // a network round-trip. Best-effort: any failure is swallowed.\n try {\n patchProfile(active.name, {\n email: user.email,\n userId: user.id,\n accountId: user.accountId,\n });\n } catch {\n // ignore\n }\n\n console.log(`Email: ${user.email}`);\n console.log(`Name: ${user.firstName} ${user.lastName}`);\n console.log(`Role: ${user.role}`);\n console.log(`Account ID: ${user.accountId}`);\n console.log(\n `Token: valid (expires in ${formatExpiry(active.profile.expiresAt)})`,\n );\n } catch (error) {\n // Fall back to cached identifiers when the backend is unreachable\n // but we still have a valid local token.\n if (active.profile.email) {\n console.log(`Email: ${active.profile.email} (cached)`);\n }\n if (active.profile.accountId) {\n console.log(`Account ID: ${active.profile.accountId} (cached)`);\n }\n console.log(\n `Token: valid (expires in ${formatExpiry(active.profile.expiresAt)})`,\n );\n if (error instanceof Error) {\n console.error(`Warning: could not contact Olakai backend: ${error.message}`);\n } else {\n console.error(\"Warning: could not contact Olakai backend\");\n }\n }\n}\n","/**\n * `olakai init` — the self-onboarding wizard (OLA-212).\n *\n * Flow at a glance:\n *\n * 1. Resolve the target profile name. If it already holds a valid\n * token, offer an early exit (\"already authenticated\").\n * 2. Pick a host: `--host`/env > existing profile host > interactive\n * menu (production / staging / on-prem custom).\n * 3. Collect the user's email.\n * 4. POST /api/cli/handshake. Branch on the response:\n * - device-flow → hand off to the existing `loginCommand`\n * (same device-flow used by `olakai login`; we DO NOT\n * duplicate that flow here).\n * - OTP → enter the OTP loop (verify → exchange).\n * - signup → open browser + ask user to re-run.\n * - blocked → fail with a clear admin-action message.\n * 5. On OTP success: exchange the consent token for the 30-day\n * bearer, persist it to the active profile via `saveToken`.\n * 6. Offer monitor setup. Actually chaining into `olakai monitor`\n * is owned by S5 (OLA-214); for now we just print the one-liner.\n *\n * Non-interactive mode (`--non-interactive`) fails fast on any prompt\n * the user could have answered via flag/env. That makes the wizard\n * safe to call from automation (e.g. CI bootstrapping a profile from\n * a service account email).\n */\n\nimport open from \"open\";\nimport {\n postHandshake,\n postHandshakeExchange,\n postHandshakeVerify,\n} from \"../lib/handshake.js\";\nimport { loginCommand } from \"./login.js\";\nimport { saveToken, isTokenValid } from \"../lib/auth.js\";\nimport { getBaseUrl, setHostOverride } from \"../lib/config.js\";\nimport {\n HOSTS,\n patchProfile,\n readProfilesFile,\n resolveProfileName,\n} from \"../lib/profiles.js\";\nimport { promptUser, isInteractive } from \"../monitor/prompt.js\";\nimport { detectInstalledTools } from \"../monitor/detect-all.js\";\nimport { runMonitorInstall } from \"../monitor/install.js\";\nimport {\n formatExistingUserBrowserGreeting,\n printLogoHeader,\n} from \"../lib/branding.js\";\n\nexport interface InitCommandOptions {\n email?: string;\n host?: string;\n /** Identical to the global `--profile` flag; commander passes it through. */\n profile?: string;\n nonInteractive?: boolean;\n skipMonitor?: boolean;\n}\n\n/**\n * The most permissive RFC-5322-ish email check the CLI is comfortable\n * shipping. Backend does the real validation; this is just enough to\n * stop obviously-broken input from costing the user a network round\n * trip.\n */\nconst EMAIL_REGEX = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst OTP_REGEX = /^\\d{6}$/;\nconst PRESET_HOSTS: ReadonlyArray<{ label: string; url: string }> = [\n { label: \"production (app.olakai.ai)\", url: HOSTS.production },\n { label: \"staging (staging.app.olakai.ai)\", url: HOSTS.staging },\n];\n\nexport async function initCommand(options: InitCommandOptions): Promise<void> {\n const interactive = !options.nonInteractive && isInteractive();\n\n // Logo + tagline at the very top of the interactive flow. Suppressed\n // by `printLogoHeader` itself when stdout isn't a TTY so CI runs and\n // piped output stay clean.\n if (interactive) {\n printLogoHeader();\n }\n\n try {\n // 1. Resolve the profile we'll be writing to. `resolveProfileName`\n // is the lenient resolver — it never throws, and may return null\n // if no registry exists yet (fresh install).\n const resolved = resolveProfileName();\n const profileName = resolved?.name ?? \"default\";\n\n // 2. Early-exit / re-auth check FIRST (before host resolution).\n //\n // We must run this before `resolveHost` so the user's choice\n // (\"Re-authenticate? [y/N]\") can influence host resolution. The\n // previous order resolved the host first, which silently locked in\n // the stored host whenever the token was still valid — leaving no\n // path to switch workspaces (e.g. staging → production) without\n // first running `olakai logout`.\n //\n // The prompt references the *stored* host (the workspace the\n // current token authenticates against), not a freshly-picked one.\n let optedReAuth = false;\n if (isTokenValid()) {\n const file = readProfilesFile();\n const existing = file.profiles[profileName];\n const who = existing?.email ?? \"unknown\";\n const where = existing?.host ?? \"(unknown host)\";\n if (options.nonInteractive) {\n // Non-interactive: idempotent no-op. Don't surprise scripts.\n console.log(\n `Already authenticated as ${who} on ${where} (profile: ${profileName}).`,\n );\n return;\n }\n const answer = await promptUser(\n `Already authenticated as ${who} on ${where} (profile: ${profileName}). Re-authenticate? [y/N]: `,\n );\n if (answer.trim().toLowerCase() !== \"y\") {\n console.log(\n \"Keeping existing credentials. Run 'olakai logout' to sign out.\",\n );\n return;\n }\n optedReAuth = true;\n }\n\n // 3. Resolve the host. CLI flag (already handled by the global\n // preAction hook) wins via getBaseUrl(). Otherwise prefer the\n // profile's stored host — but offer a switch prompt when the\n // user is actively re-authenticating (post-logout OR via the\n // \"Re-authenticate? [y]\" path above).\n const host = await resolveHost(\n profileName,\n options,\n interactive,\n optedReAuth,\n );\n // Apply the host so all subsequent `getBaseUrl()` calls (incl. the\n // handshake client) point at the right backend.\n setHostOverride(host);\n\n // 4. Email.\n const email = await resolveEmail(options, interactive);\n\n console.log(`\\nContacting ${host} for ${email}...`);\n\n // 5. Handshake. One retry on transient network failures (per\n // spec) — only `network_error`, never 4xx/5xx, which carry\n // semantic meaning the wizard must surface unchanged.\n let handshake = await postHandshake({ email, host });\n if (handshake.kind === \"error\" && handshake.code === \"network_error\") {\n console.log(\"(Network error contacting Olakai — retrying once...)\");\n handshake = await postHandshake({ email, host });\n }\n if (handshake.kind === \"error\") {\n handleHandshakeError(handshake);\n return;\n }\n\n const response = handshake.data;\n\n switch (response.status) {\n case \"user_exists\":\n if (\"deviceFlowOk\" in response && response.deviceFlowOk === true) {\n // Existing non-EMPLOYEE user → existing device-flow login.\n // Reuse `loginCommand` verbatim so there's exactly one\n // device-flow code path in the CLI.\n //\n // Pre-browser greeting (OLA-226): the prior one-liner read as\n // unexplained friction to admins evaluating Olakai (Xavier\n // session, 2026-05-14). Surface that we identified the user,\n // explain the role-tier reason for the browser step, and\n // make the contrast with the Employee-role OTP path explicit\n // so admins don't generalize the friction to their team.\n console.log(\"\");\n console.log(formatExistingUserBrowserGreeting(email));\n if (interactive) {\n // Press-Enter gate. The user has read the message; opening\n // the browser without acknowledgement felt abrupt during\n // Xavier's evaluation. Ctrl-C still bails as expected.\n await promptUser(\n \"\\n > Press Enter to open your browser, or Ctrl-C to cancel: \",\n );\n }\n console.log(\"\");\n await loginCommand();\n await offerMonitorSetup(options, interactive);\n return;\n }\n // EMPLOYEE refresh path: OTP. Narrow via the OTP-branch shape.\n if (\"otpSent\" in response && response.otpSent === true) {\n await runOtpFlow(email, profileName, {\n emailObfuscated: response.emailObfuscated,\n expiresIn: response.expiresIn,\n });\n await offerMonitorSetup(options, interactive);\n return;\n }\n // Defensive fallback — the backend returned `user_exists`\n // without the expected discriminator. Surface clearly instead\n // of silently hanging.\n console.error(\n \"Unexpected handshake response: 'user_exists' without device-flow or OTP signal.\",\n );\n process.exit(1);\n return;\n\n case \"domain_claimed\":\n await runOtpFlow(email, profileName, {\n emailObfuscated: response.emailObfuscated,\n expiresIn: response.expiresIn,\n });\n await offerMonitorSetup(options, interactive);\n return;\n\n case \"saas_can_self_signup\": {\n console.log(\n \"\\nWe don't have you yet. Opening your browser to create an account...\",\n );\n // BLOCKING from pre-PR review: validate the URL scheme before\n // handing it to the platform opener. A compromised or\n // misconfigured backend could otherwise return `file://`,\n // `javascript:`, `vscode://`, `ssh://`, etc. — anything the\n // OS opener accepts. Defense-in-depth: only http/https.\n if (isSafeOpenUrl(response.signupUrl)) {\n try {\n await open(response.signupUrl);\n } catch {\n console.log(\n `(Could not open browser automatically. Visit ${response.signupUrl})`,\n );\n }\n } else {\n console.log(\n `(Server returned an unexpected signup URL scheme. Visit ${response.signupUrl} manually in your browser.)`,\n );\n }\n console.log(\n \"When done, re-run 'olakai init' to finish authenticating this CLI.\",\n );\n return;\n }\n\n case \"blocked\": {\n const domain = email.split(\"@\")[1] ?? email;\n console.error(\n `\\nYour domain \"${domain}\" isn't connected to an Olakai workspace.`,\n );\n if (response.message) {\n console.error(response.message);\n }\n console.error(\"Ask your admin to claim it, then re-run 'olakai init'.\");\n process.exit(1);\n }\n }\n } catch (err) {\n if (err instanceof InitAbortedError) {\n if (err.message) console.error(err.message);\n process.exit(err.exitCode);\n }\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\n/**\n * Allow only `http:` / `https:` schemes for any URL we hand to the\n * platform opener (`open`). The OS opener accepts `file:`, `mailto:`,\n * `vscode://`, `ssh://`, custom URL handlers, etc. — none of which a\n * trustworthy handshake response should ever return. Falling through to\n * a manual copy/paste message is the safe degradation.\n */\nfunction isSafeOpenUrl(raw: string): boolean {\n try {\n const url = new URL(raw);\n return url.protocol === \"http:\" || url.protocol === \"https:\";\n } catch {\n return false;\n }\n}\n\n// ---- host selection --------------------------------------------------------\n\nasync function resolveHost(\n profileName: string,\n options: InitCommandOptions,\n interactive: boolean,\n forceHostPrompt = false,\n): Promise<string> {\n // `getBaseUrl()` already applies `--host`/OLAKAI_HOST overrides set\n // by the global preAction hook. If either is in effect, that's the\n // host we use. If neither is in effect, the lenient resolver in\n // `getBaseUrl()` may still return the profile's stored host — that's\n // also fine.\n //\n // Precedence per CLAUDE.md: `--host` flag wins over `OLAKAI_HOST`\n // env (the flag is the more explicit signal). Practically a no-op\n // today because `preAction` already pushed both into `getBaseUrl()`,\n // but checking the flag first keeps this in lockstep with the\n // documented resolution order so a future refactor can't drift.\n const fromFlag = options.host?.trim() || process.env.OLAKAI_HOST?.trim();\n if (fromFlag) {\n return getBaseUrl();\n }\n\n // If the profile already has a host, prefer it — but offer an\n // override path for interactive users with no valid token (OLA-229).\n //\n // The stored host survives `olakai logout` (which only clears\n // `token` + `expiresAt`, see `profiles.ts`), so a user who logged\n // out specifically to switch workspaces would otherwise be quietly\n // routed back to the same one. Silent prefer is right for:\n // - non-interactive runs (CI / scripts)\n // - re-runs with a still-valid token (the user opted into\n // re-auth via the early-exit prompt; they're keeping the\n // current workspace)\n // Re-prompt is right when interactive AND there's no valid token —\n // the user is actively re-authenticating from a logged-out state\n // and might be switching contexts.\n const file = readProfilesFile();\n const existing = file.profiles[profileName];\n if (existing?.host) {\n // Offer a workspace-switch prompt when either:\n // - the user is post-logout (no valid token; OLA-229), OR\n // - the user explicitly opted to re-authenticate via the\n // valid-token early-exit prompt in `initCommand`\n // (`forceHostPrompt`).\n // Otherwise the stored host is silently reused (idempotent\n // re-runs, non-interactive scripts).\n const shouldOfferSwitch =\n interactive && (forceHostPrompt || !isTokenValid());\n if (!shouldOfferSwitch) {\n return existing.host;\n }\n const keep = await promptUser(\n `\\nConnect to ${existing.host}? [Y/n] (or pick a different domain such as on-prem): `,\n );\n if (keep.trim().toLowerCase() !== \"n\") {\n return existing.host;\n }\n // Fall through to the picker below.\n console.log(\"\");\n }\n\n if (!interactive) {\n throw new InitAbortedError(\n \"No host configured. Pass --host or set OLAKAI_HOST in non-interactive mode.\",\n );\n }\n\n // Interactive picker.\n console.log(\"\\nWhich Olakai workspace are you connecting to?\");\n for (let i = 0; i < PRESET_HOSTS.length; i += 1) {\n const entry = PRESET_HOSTS[i]!;\n console.log(` ${i + 1}) ${entry.label}`);\n }\n console.log(` ${PRESET_HOSTS.length + 1}) Custom (on-prem)`);\n\n const choice = await promptUser(`Choose [1-${PRESET_HOSTS.length + 1}]: `);\n const idx = Number.parseInt(choice.trim(), 10);\n if (idx >= 1 && idx <= PRESET_HOSTS.length) {\n return PRESET_HOSTS[idx - 1]!.url;\n }\n if (idx === PRESET_HOSTS.length + 1) {\n return promptForCustomHost();\n }\n console.error(\n \"Invalid choice. Re-run 'olakai init' and pick a valid option.\",\n );\n throw new InitAbortedError(\"\", 1);\n}\n\nasync function promptForCustomHost(): Promise<string> {\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const raw = await promptUser(\n \"On-prem URL or hostname (e.g. olakai.acme.com): \",\n );\n const normalized = normalizeHost(raw.trim());\n if (normalized) {\n return normalized;\n }\n console.log(\"That doesn't look like a valid host. Try again.\");\n }\n throw new InitAbortedError(\"Too many invalid host entries.\", 1);\n}\n\nfunction normalizeHost(value: string): string | null {\n if (!value) return null;\n // Allow bare hostnames; require at least one dot OR `localhost`.\n // Anything else is almost certainly a typo.\n const withScheme = /^https?:\\/\\//i.test(value) ? value : `https://${value}`;\n let url: URL;\n try {\n url = new URL(withScheme);\n } catch {\n return null;\n }\n if (!url.hostname) return null;\n if (!url.hostname.includes(\".\") && url.hostname !== \"localhost\") {\n return null;\n }\n return `${url.protocol}//${url.host}`.replace(/\\/+$/, \"\");\n}\n\n// ---- email collection ------------------------------------------------------\n\nasync function resolveEmail(\n options: InitCommandOptions,\n interactive: boolean,\n): Promise<string> {\n if (options.email) {\n const trimmed = options.email.trim();\n if (!EMAIL_REGEX.test(trimmed)) {\n throw new InitAbortedError(\n `Invalid email: \"${options.email}\". Re-run with a well-formed --email.`,\n );\n }\n return trimmed;\n }\n if (!interactive) {\n throw new InitAbortedError(\n \"Missing --email in non-interactive mode. Pass --email <you@company.com>.\",\n );\n }\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const raw = await promptUser(\"Enter your primary work email address: \");\n const trimmed = raw.trim();\n if (EMAIL_REGEX.test(trimmed)) {\n return trimmed;\n }\n console.log(\"That doesn't look like a valid email. Try again.\");\n }\n throw new InitAbortedError(\"Too many invalid email entries.\", 1);\n}\n\n// ---- OTP loop --------------------------------------------------------------\n\ninterface OtpContext {\n emailObfuscated: string;\n expiresIn: number;\n}\n\nasync function runOtpFlow(\n email: string,\n profileName: string,\n ctx: OtpContext,\n): Promise<void> {\n const expiryMin = Math.max(1, Math.round(ctx.expiresIn / 60));\n console.log(\n `\\nWe sent a 6-digit code to your email ${ctx.emailObfuscated} (expires in ${expiryMin} min).`,\n );\n\n // The OTP loop terminates on:\n // - verify success → break and exchange\n // - locked / no_code → exit 1\n // - expired → restart handshake (caller's responsibility — we\n // surface a clear message and exit 1, instructing the user to\n // re-run init; that's strictly simpler than re-driving the\n // handshake mid-loop, and matches the wording in the spec)\n for (;;) {\n const code = await promptUser(\n \"Please enter the 6-digit code you received: \",\n );\n const trimmed = code.trim();\n if (!OTP_REGEX.test(trimmed)) {\n console.log(\"Codes are 6 digits. Try again.\");\n continue;\n }\n // One-shot retry on transient network failure. Same shape as the\n // existing handshake retry — `verify` is idempotent on the wire\n // (no state change unless the request reaches the server and\n // decodes), so retrying a connection-level failure is safe. The\n // rare race where the server consumed an OTP attempt but the\n // response was lost trades one attempt-counter slot for not\n // aborting the whole flow on a TLS hiccup — favorable trade given\n // the 5-attempt lockout budget.\n let result = await postHandshakeVerify({ email, code: trimmed });\n if (result.kind === \"error\" && result.code === \"network_error\") {\n console.log(\"(Network error verifying code — retrying once...)\");\n result = await postHandshakeVerify({ email, code: trimmed });\n }\n if (result.kind === \"ok\") {\n const consentToken = result.data.consentToken;\n await runExchange(consentToken, profileName, email);\n return;\n }\n\n switch (result.code) {\n case \"invalid_code\": {\n const remaining = result.detail?.attemptsRemaining;\n const tail =\n typeof remaining === \"number\"\n ? ` ${remaining} attempt${remaining === 1 ? \"\" : \"s\"} remaining.`\n : \"\";\n console.log(`Wrong code.${tail}`);\n continue;\n }\n case \"locked\":\n console.error(\n \"Too many attempts. Request a fresh code by re-running 'olakai init'.\",\n );\n throw new InitAbortedError(\"\", 1);\n case \"expired\":\n console.error(\n \"Code expired. Re-run 'olakai init' to request a new one.\",\n );\n throw new InitAbortedError(\"\", 1);\n case \"no_code\":\n console.error(\n \"No live code for this email. Run 'olakai init' again to request one.\",\n );\n throw new InitAbortedError(\"\", 1);\n case \"rate_limited\": {\n const wait = result.retryAfter\n ? ` Retry in ${result.retryAfter}s.`\n : \"\";\n console.error(`Rate limit hit while verifying.${wait}`);\n throw new InitAbortedError(\"\", 1);\n }\n case \"service_unavailable\":\n console.error(\n \"Olakai is temporarily unavailable. Try again in a minute.\",\n );\n throw new InitAbortedError(\"\", 1);\n case \"network_error\":\n console.error(\n `Network error${result.causeCode ? ` (${result.causeCode})` : \"\"}: ${result.message}`,\n );\n throw new InitAbortedError(\"\", 1);\n default:\n console.error(\n `Verification failed (${result.code}): ${result.message}`,\n );\n throw new InitAbortedError(\"\", 1);\n }\n }\n}\n\nasync function runExchange(\n consentToken: string,\n profileName: string,\n email: string,\n): Promise<void> {\n // One-shot retry on transient network failure. The undici socket\n // drops we saw in production (Xavier session, 2026-05-14) were one\n // failure followed by an immediate success on the same call. Without\n // this retry, that flake aborts the wizard after the user has\n // already typed the OTP.\n //\n // Edge case: if the server actually processed the exchange and the\n // response socket died, the consent JWT is already burned and the\n // retry returns `invalid_consent`. User sees the standard\n // \"Consent token was rejected. Re-run 'olakai init' to start over.\"\n // — same outcome as today's no-retry path on that rare race, so\n // strictly net-positive on every other transient failure mode.\n let result = await postHandshakeExchange({ consentToken });\n if (result.kind === \"error\" && result.code === \"network_error\") {\n console.log(\"(Network error exchanging consent — retrying once...)\");\n result = await postHandshakeExchange({ consentToken });\n }\n if (result.kind === \"error\") {\n switch (result.code) {\n case \"invalid_consent\":\n console.error(\n \"Consent token was rejected. Re-run 'olakai init' to start over.\",\n );\n break;\n case \"user_unavailable\":\n console.error(\n \"Your user record is unavailable on the backend. Contact your admin.\",\n );\n break;\n case \"rate_limited\": {\n const wait = result.retryAfter\n ? ` Retry in ${result.retryAfter}s.`\n : \"\";\n console.error(`Rate limit hit while exchanging consent.${wait}`);\n break;\n }\n case \"service_unavailable\":\n console.error(\n \"Olakai is temporarily unavailable. Try again in a minute.\",\n );\n break;\n case \"network_error\":\n console.error(\n `Network error exchanging consent${result.causeCode ? ` (${result.causeCode})` : \"\"}: ${result.message}`,\n );\n break;\n default:\n console.error(`Exchange failed (${result.code}): ${result.message}`);\n }\n throw new InitAbortedError(\"\", 1);\n }\n\n // Persist into the active profile. `saveToken` writes to the\n // resolved profile (creating it if needed) and respects the active\n // host via `getBaseUrl()`.\n saveToken(result.data.access_token, result.data.expires_in);\n // Cache the email on the profile so subsequent `whoami` calls don't\n // need to round-trip when offline. We don't have user/account IDs\n // until the user hits an authenticated endpoint, but the email\n // alone is enough for friendly re-auth prompts.\n try {\n patchProfile(profileName, { email });\n } catch {\n // Best-effort — failure here doesn't invalidate the login.\n }\n\n console.log(`\\nLogged in as ${email} on ${getBaseUrl()}.`);\n console.log(`Profile: ${profileName}`);\n}\n\n// ---- handshake-level error surfacing --------------------------------------\n\nfunction handleHandshakeError(\n err: Extract<Awaited<ReturnType<typeof postHandshake>>, { kind: \"error\" }>,\n): never {\n switch (err.code) {\n case \"validation_error\":\n console.error(`That email didn't pass validation: ${err.message}`);\n break;\n case \"blocked\":\n console.error(err.message);\n console.error(\n \"Ask your admin to claim your domain, then re-run 'olakai init'.\",\n );\n break;\n case \"rate_limited\": {\n const wait = err.retryAfter ? ` Retry in ${err.retryAfter}s.` : \"\";\n console.error(`Too many attempts.${wait}`);\n break;\n }\n case \"service_unavailable\":\n console.error(\n \"Olakai is temporarily unavailable. Try again in a minute.\",\n );\n break;\n case \"network_error\":\n console.error(\n `Network error contacting Olakai${err.causeCode ? ` (${err.causeCode})` : \"\"}: ${err.message}`,\n );\n break;\n default:\n console.error(`Handshake failed (${err.code}): ${err.message}`);\n }\n process.exit(1);\n}\n\n// ---- monitor handoff (OLA-214) --------------------------------------------\n\n/**\n * Auto-detect installed local coding agents, prompt per-tool, and chain\n * into the existing `monitor init` plugin install for each tool the\n * user opts into.\n *\n * Design notes:\n *\n * - `--skip-monitor` short-circuits before detection runs. We treat it\n * as an explicit \"don't touch hooks here\", not \"I'll do it later\"\n * — so no docs-pointer line either. The wizard already said\n * everything it needed to say at that point.\n *\n * - Non-interactive mode auto-accepts each detected tool. Rationale:\n * if you went out of your way to run `olakai init --non-interactive`\n * you've opted into the chained setup; failing fast here would\n * defeat the CI use case. Inside each `runMonitorInstall` the\n * plugin still gates on required inputs and fast-fails on missing\n * ones (e.g. unable to mint an API key without a prompt) rather\n * than hanging.\n *\n * - Per-tool failures are isolated. A flake on the agents-API for one\n * tool must not strand the user without monitoring on the others.\n * We catch, surface a retry hint, and continue.\n *\n * - The plugin's own `install()` already handles the \"config already\n * exists in this workspace, replace? [y/N]\" prompt — we don't\n * re-implement it here.\n */\nasync function offerMonitorSetup(\n options: InitCommandOptions,\n interactive: boolean,\n): Promise<void> {\n if (options.skipMonitor) return;\n\n const detected = await detectInstalledTools(process.cwd());\n if (detected.length === 0) {\n console.log(\"\\nNo coding agents detected in this workspace.\");\n console.log(\n \"Install Claude Code, Codex, or Cursor and run 'olakai monitor init' to start tracking.\",\n );\n return;\n }\n\n console.log(\n `\\nDetected ${detected.length} coding agent${detected.length === 1 ? \"\" : \"s\"} in this workspace.`,\n );\n\n for (const { tool, reason } of detected) {\n let proceed = true;\n if (interactive) {\n const answer = await promptUser(\n `\\nSet up monitoring for ${tool}? (${reason}) [Y/n]: `,\n );\n const normalized = answer.trim().toLowerCase();\n // Default-yes: empty / 'y' / 'yes' all proceed. Anything else\n // counts as a decline (matches the convention used by the\n // re-auth prompt earlier in the wizard).\n proceed = normalized === \"\" || normalized === \"y\" || normalized === \"yes\";\n }\n\n if (!proceed) {\n console.log(\n `Skipped ${tool}. Run 'olakai monitor init --tool ${tool}' later if you change your mind.`,\n );\n continue;\n }\n\n try {\n await runMonitorInstall(tool, { interactive });\n console.log(`${tool} monitoring configured.`);\n } catch (err) {\n // Isolate the failure — don't poison the remaining tools or\n // abort the wizard with a non-zero exit. Re-running just the\n // failed tool is a single command, so we surface it.\n const message = err instanceof Error ? err.message : String(err);\n console.error(`${tool} setup failed: ${message}`);\n console.error(`Run 'olakai monitor init --tool ${tool}' to retry.`);\n }\n }\n}\n\n// ---- exit signaling --------------------------------------------------------\n\n/**\n * Internal marker for \"we've already printed a clear user-facing\n * message; just exit with the given code\". Lets nested helpers bail\n * out without each one calling `process.exit()` directly (which would\n * be untestable).\n */\nclass InitAbortedError extends Error {\n exitCode: number;\n constructor(message: string, exitCode = 1) {\n super(message);\n this.name = \"InitAbortedError\";\n this.exitCode = exitCode;\n }\n}\n","/**\n * Typed client for the CLI handshake API (OLA-210).\n *\n * Three unauthenticated endpoints back the `olakai init` wizard:\n *\n * POST /api/cli/handshake → branch the wizard (device-flow,\n * OTP, signup, or blocked)\n * POST /api/cli/handshake/verify → exchange a 6-digit OTP for a\n * short-lived consent token\n * POST /api/cli/handshake/exchange → exchange the consent token for\n * the long-lived CLI bearer\n *\n * The HTTP layer is intentionally thin: no retries, no progress\n * reporting. The wizard owns retry/UX decisions because the right\n * behavior depends heavily on the user-facing branch (e.g. `expired`\n * vs `invalid_code` need very different prompts).\n *\n * Every function returns a discriminated-union result keyed by `kind`:\n *\n * `kind === \"ok\"` — happy path, payload in `data`\n * `kind === \"error\"` — typed failure with backend `code`\n *\n * Backend error contract (mirrors S1 spec):\n *\n * 400 validation_error\n * 400 invalid_code (verify, with `attemptsRemaining`)\n * 401 invalid_consent / user_unavailable (exchange)\n * 403 blocked (handshake)\n * 404 no_code (verify)\n * 410 expired (verify)\n * 429 locked (verify, lockout) / rate_limited\n * 503 service_unavailable\n *\n * Rate-limit responses surface `Retry-After` (seconds) so the wizard\n * can print an informed wait message.\n */\n\nimport { getBaseUrl } from \"./config.js\";\n\n/** Discriminated success/error envelope used by every handshake call. */\nexport type HandshakeResult<TOk, TError = HandshakeErrorCode> =\n | { kind: \"ok\"; data: TOk }\n | {\n kind: \"error\";\n code: TError;\n message: string;\n status: number;\n retryAfter?: number;\n /**\n * For `network_error`s: the underlying undici / Node error code\n * (e.g. `UND_ERR_CONNECT`, `ECONNRESET`). `Error.cause` carries\n * this on `fetch()` failures; we surface it here so the UI can\n * print something more actionable than the bare `\"fetch failed\"`\n * string. Unset for non-network errors and for network errors\n * with no exposed cause code.\n */\n causeCode?: string;\n };\n\nexport type HandshakeErrorCode =\n | \"validation_error\"\n | \"invalid_code\"\n | \"invalid_consent\"\n | \"user_unavailable\"\n | \"blocked\"\n | \"no_code\"\n | \"expired\"\n | \"locked\"\n | \"rate_limited\"\n | \"service_unavailable\"\n | \"network_error\"\n | \"unknown_error\";\n\n// ---- POST /api/cli/handshake -----------------------------------------------\n\n/**\n * The branch the backend tells us to follow. Each variant is a tagged\n * object so callers can `switch (resp.data.status)`.\n */\nexport type HandshakeResponse =\n | { status: \"user_exists\"; deviceFlowOk: true }\n | {\n status: \"user_exists\";\n otpSent: true;\n emailObfuscated: string;\n codeExpiresAt: string;\n expiresIn: number;\n }\n | {\n status: \"domain_claimed\";\n accountId: string;\n userId: string;\n matchType: \"exact\" | \"suffix\";\n emailObfuscated: string;\n codeExpiresAt: string;\n expiresIn: number;\n }\n | { status: \"saas_can_self_signup\"; signupUrl: string }\n | { status: \"blocked\"; message: string };\n\nexport interface HandshakeRequest {\n email: string;\n /** Optional explicit host hint (the backend may key per-host policy off this). */\n host?: string;\n}\n\n/**\n * POST /api/cli/handshake. Returns one of the five branches above, or a\n * typed error envelope. Network/parse failures map to `network_error`.\n */\nexport async function postHandshake(\n body: HandshakeRequest,\n): Promise<HandshakeResult<HandshakeResponse, HandshakeErrorCode>> {\n return postHandshakeJson<HandshakeResponse>(\n `${getBaseUrl()}/api/cli/handshake`,\n body,\n );\n}\n\n// ---- POST /api/cli/handshake/verify ---------------------------------------\n\nexport interface VerifyRequest {\n email: string;\n code: string;\n}\n\nexport interface VerifySuccess {\n consentToken: string;\n expiresIn: number;\n}\n\n/**\n * Extra context for the `invalid_code` branch. Backend includes\n * `attemptsRemaining` so we can print \"N attempts remaining\" before\n * the next prompt.\n */\nexport interface VerifyErrorDetail {\n attemptsRemaining?: number;\n}\n\nexport type VerifyResult = HandshakeResult<VerifySuccess, HandshakeErrorCode> & {\n detail?: VerifyErrorDetail;\n};\n\nexport async function postHandshakeVerify(\n body: VerifyRequest,\n): Promise<VerifyResult> {\n const url = `${getBaseUrl()}/api/cli/handshake/verify`;\n const result = await postHandshakeJson<VerifySuccess>(url, body, {\n captureDetail: true,\n });\n return result as VerifyResult;\n}\n\n// ---- POST /api/cli/handshake/exchange -------------------------------------\n\nexport interface ExchangeRequest {\n consentToken: string;\n}\n\n/** Same shape as device-flow's `/api/auth/device/token` response. */\nexport interface ExchangeSuccess {\n access_token: string;\n token_type: \"Bearer\";\n expires_in: number;\n}\n\nexport async function postHandshakeExchange(\n body: ExchangeRequest,\n): Promise<HandshakeResult<ExchangeSuccess, HandshakeErrorCode>> {\n return postHandshakeJson<ExchangeSuccess>(\n `${getBaseUrl()}/api/cli/handshake/exchange`,\n body,\n );\n}\n\n// ---- shared transport ------------------------------------------------------\n\ninterface PostOptions {\n /**\n * When true, attempts to surface response-body fields (esp.\n * `attemptsRemaining` on `invalid_code`) on the returned envelope's\n * `detail` field. Other endpoints don't need it.\n */\n captureDetail?: boolean;\n}\n\ninterface ErrorBody {\n error?: string;\n code?: string;\n message?: string;\n attemptsRemaining?: number;\n}\n\n/**\n * Shared transport for the three handshake endpoints. Centralized so\n * Retry-After parsing, JSON-error decoding, and the network-error\n * fallback live in one place.\n */\nasync function postHandshakeJson<TOk>(\n url: string,\n body: unknown,\n options: PostOptions = {},\n): Promise<HandshakeResult<TOk, HandshakeErrorCode> & { detail?: VerifyErrorDetail }> {\n let response: Response;\n try {\n response = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n } catch (err) {\n return buildNetworkError(err);\n }\n\n if (response.ok) {\n let data: TOk;\n try {\n data = (await response.json()) as TOk;\n } catch (err) {\n return {\n kind: \"error\",\n code: \"unknown_error\",\n message: err instanceof Error ? err.message : \"Failed to parse response\",\n status: response.status,\n };\n }\n return { kind: \"ok\", data };\n }\n\n // Best-effort error body decode — backend may return a JSON envelope\n // or (rarely) a plain string. Anything unparseable degrades to a\n // generic unknown_error with the HTTP status preserved.\n let errBody: ErrorBody = {};\n try {\n errBody = (await response.json()) as ErrorBody;\n } catch {\n // ignore\n }\n\n const code = mapErrorCode(response.status, errBody);\n // Fallback message includes the request pathname so an unannotated\n // 5xx tells the user *what* failed, not just the status code.\n // Hostname is intentionally omitted — it varies by environment and\n // contributes nothing to the user's understanding of the error.\n let fallbackPath = \"\";\n try {\n fallbackPath = new URL(url).pathname;\n } catch {\n // Malformed URL — use the raw url string as a last resort.\n fallbackPath = url;\n }\n const message =\n errBody.message ||\n errBody.error ||\n `Request to ${fallbackPath} failed with status ${response.status}`;\n const retryAfter = parseRetryAfter(response.headers.get(\"retry-after\"));\n\n const envelope: HandshakeResult<TOk, HandshakeErrorCode> & {\n detail?: VerifyErrorDetail;\n } = {\n kind: \"error\",\n code,\n message,\n status: response.status,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n };\n\n if (options.captureDetail && typeof errBody.attemptsRemaining === \"number\") {\n envelope.detail = { attemptsRemaining: errBody.attemptsRemaining };\n }\n\n return envelope;\n}\n\n/**\n * Map an HTTP status + parsed error body to a canonical\n * `HandshakeErrorCode`. The backend's `code` field wins when present;\n * otherwise we fall back to the status code semantics from the S1\n * spec.\n */\nfunction mapErrorCode(status: number, body: ErrorBody): HandshakeErrorCode {\n const known: HandshakeErrorCode[] = [\n \"validation_error\",\n \"invalid_code\",\n \"invalid_consent\",\n \"user_unavailable\",\n \"blocked\",\n \"no_code\",\n \"expired\",\n \"locked\",\n \"rate_limited\",\n \"service_unavailable\",\n ];\n // Defensive: only trust the backend's `code` / `error` fields when\n // they're actually strings. A malformed server returning numeric or\n // object payloads must not slip past the `includes()` guard.\n if (typeof body.code === \"string\" && (known as string[]).includes(body.code)) {\n return body.code as HandshakeErrorCode;\n }\n if (typeof body.error === \"string\" && (known as string[]).includes(body.error)) {\n return body.error as HandshakeErrorCode;\n }\n switch (status) {\n case 400:\n return \"validation_error\";\n case 401:\n return \"invalid_consent\";\n case 403:\n return \"blocked\";\n case 404:\n return \"no_code\";\n case 410:\n return \"expired\";\n case 429:\n return \"rate_limited\";\n case 503:\n return \"service_unavailable\";\n default:\n return \"unknown_error\";\n }\n}\n\n/**\n * Build a `network_error` envelope from a `fetch()` rejection, surfacing\n * the undici `err.cause.code` (e.g. `UND_ERR_CONNECT`, `ECONNRESET`)\n * when present. The bare `err.message` from undici is the unhelpful\n * `\"fetch failed\"`; the cause carries the actionable signal. We pull\n * `cause.code` onto the envelope's `causeCode` and append `cause.message`\n * onto the human message so both the structured field and the rendered\n * string carry the diagnostic.\n *\n * `Error.cause` is `unknown` per TS lib types; we treat it defensively\n * as a possibly-object value with optional string `code` / `message`.\n */\nfunction buildNetworkError(\n err: unknown,\n): { kind: \"error\"; code: \"network_error\"; message: string; status: 0; causeCode?: string } {\n const base =\n err instanceof Error ? err.message : \"Network request failed\";\n let causeCode: string | undefined;\n let causeMessage: string | undefined;\n if (err instanceof Error && err.cause && typeof err.cause === \"object\") {\n const c = err.cause as { code?: unknown; message?: unknown };\n if (typeof c.code === \"string\" && c.code.length > 0) {\n causeCode = c.code;\n }\n if (typeof c.message === \"string\" && c.message.length > 0) {\n causeMessage = c.message;\n }\n }\n // Compose the message: keep \"fetch failed\" prefix (some downstream\n // tooling matches against it), append cause-message when different.\n const message =\n causeMessage && causeMessage !== base ? `${base}: ${causeMessage}` : base;\n return {\n kind: \"error\",\n code: \"network_error\",\n message,\n status: 0,\n ...(causeCode ? { causeCode } : {}),\n };\n}\n\nfunction parseRetryAfter(header: string | null): number | undefined {\n if (!header) return undefined;\n const asNumber = Number(header);\n if (Number.isFinite(asNumber) && asNumber > 0) {\n return Math.floor(asNumber);\n }\n // Retry-After can also be an HTTP date — convert to seconds-from-now.\n const asDate = Date.parse(header);\n if (Number.isFinite(asDate)) {\n const seconds = Math.floor((asDate - Date.now()) / 1000);\n return seconds > 0 ? seconds : undefined;\n }\n return undefined;\n}\n","/**\n * Multi-tool detection for chained `olakai init` → `olakai monitor init`\n * (OLA-214).\n *\n * Walks the registered monitor plugins (see `plugins/index.ts`) and\n * reports which of them appear installed in the current workspace.\n * Each entry carries a short human-readable `reason` we surface in the\n * per-tool consent prompt — the wizard's UX promise was\n *\n * \"Detected Claude Code in this workspace. Set up monitoring? [Y/n]\"\n *\n * The reason string is what makes that line specific (e.g.\n * \"found `.claude/settings.json`\") rather than a generic \"detected\".\n *\n * Implementation note: we don't reimplement each plugin's `detectInstalled`\n * here — that would diverge over time. Instead we call the plugin's\n * boolean probe and then, when it returns true, do a cheap follow-up\n * stat on a small set of well-known signal paths to pick the most\n * informative reason. If none match, we fall back to a generic phrase\n * so the prompt is always at least readable.\n */\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport {\n getLegacyClaudeMonitorConfigPath,\n getMonitorConfigPath,\n} from \"./paths.js\";\nimport {\n getCodexConfigPath as getCodexHomeConfigPath,\n getCodexHomeDir,\n} from \"./plugins/codex/paths.js\";\n// Side-effect import: ensures plugins are registered when the init\n// wizard pulls this module in without going through monitor.ts.\nimport \"./plugins/index.js\";\nimport {\n listPlugins,\n type ToolId,\n type ToolMonitorPlugin,\n} from \"./plugin.js\";\n\nexport interface DetectedTool {\n tool: ToolId;\n /**\n * Short human-readable phrase identifying what signal triggered the\n * match. Designed to be inlined into a prompt: e.g.\n * `\"detected (found .claude/settings.json)\"`.\n */\n reason: string;\n}\n\n/**\n * Returns the detected tools, in the order plugins were registered. We\n * preserve order so the consent prompts are deterministic across runs\n * (and across `process.cwd()` shifts in tests).\n */\nexport async function detectInstalledTools(\n projectRoot: string = process.cwd(),\n): Promise<DetectedTool[]> {\n const detected: DetectedTool[] = [];\n for (const plugin of listPlugins()) {\n let installed = false;\n try {\n installed = await plugin.detectInstalled({ projectRoot });\n } catch {\n // detectInstalled is best-effort. A throwing probe should never\n // poison the wizard — treat it as \"not detected\".\n installed = false;\n }\n if (!installed) continue;\n detected.push({\n tool: plugin.id,\n reason: describeDetection(plugin, projectRoot),\n });\n }\n return detected;\n}\n\nfunction describeDetection(\n plugin: ToolMonitorPlugin,\n projectRoot: string,\n): string {\n // Prefer the most specific signal: an existing workspace-local\n // monitor config means the user already ran `olakai monitor init`\n // for this tool in this workspace at some point. Mention that so\n // they understand a re-run will trigger the plugin's own\n // \"replace?\" prompt rather than a fresh install.\n try {\n if (fs.existsSync(getMonitorConfigPath(projectRoot, plugin.id))) {\n return `existing config at .olakai/monitor-${plugin.id}.json`;\n }\n } catch {\n // fall through\n }\n\n switch (plugin.id) {\n case \"claude-code\": {\n try {\n if (fs.existsSync(getLegacyClaudeMonitorConfigPath(projectRoot))) {\n return \"legacy config at .claude/olakai-monitor.json\";\n }\n } catch {\n // fall through\n }\n try {\n const settings = path.join(projectRoot, \".claude\", \"settings.json\");\n if (fs.existsSync(settings)) {\n return \"found .claude/settings.json\";\n }\n } catch {\n // fall through\n }\n return \"Claude Code detected\";\n }\n case \"codex\": {\n try {\n if (fs.existsSync(getCodexHomeConfigPath())) {\n return \"found ~/.codex/config.toml\";\n }\n if (fs.existsSync(getCodexHomeDir())) {\n return \"found ~/.codex/\";\n }\n } catch {\n // fall through\n }\n return \"Codex CLI on PATH\";\n }\n case \"cursor\": {\n return \"Cursor installed for this user\";\n }\n default: {\n // Compile-time exhaustiveness check: when a 4th tool gets added\n // to `ToolId` (see CLAUDE.md \"Adding a New Local Coding Agent\n // Tool\" guide), this assertion fires at type-check time so the\n // missing case is impossible to miss. Until then, we keep a\n // graceful runtime fallback so a future tool doesn't ship with\n // `Set up monitoring for newtool? (undefined)` in the prompt.\n const _exhaustive: never = plugin.id;\n void _exhaustive;\n return `${plugin.displayName} detected`;\n }\n }\n}\n","/**\n * Terminal branding for the `olakai init` wizard (OLA-226).\n *\n * `olakai init` is the first thing an admin evaluating Olakai sees from\n * the CLI — Xavier's product-feedback session flagged the current\n * messaging as too curt for that role. This module owns the visual\n * shell (logo header, colors) and the role-aware copy for the admin /\n * analyst handoff to the browser device-flow.\n *\n * Color strategy: raw ANSI escapes, no new dependency. Cyan-tinted\n * `◉` mark matches the Olakai logo's teal/cyan palette. We respect\n * `NO_COLOR` (https://no-color.org/) and only emit color sequences\n * when stdout is a TTY — pipelines and CI logs stay clean.\n */\n\nconst RESET = \"\\x1b[0m\";\nconst CYAN = \"\\x1b[36m\";\nconst DIM = \"\\x1b[2m\";\n\nfunction colorize(text: string, color: string): string {\n if (process.env.NO_COLOR) return text;\n if (!process.stdout.isTTY) return text;\n return `${color}${text}${RESET}`;\n}\n\n/**\n * Prints the wizard's logo header. Call once at the very top of the\n * interactive `olakai init` flow — it sets the visual tone for the\n * entire session.\n *\n * Skipped automatically when stdout is not a TTY (CI, piped output)\n * so logs / `--non-interactive` runs stay machine-parseable.\n */\nexport function printLogoHeader(): void {\n if (!process.stdout.isTTY) return;\n const mark = colorize(\"◉\", CYAN);\n const tagline = colorize(\"Enterprise AI Adoption, ROI and Governance\", DIM);\n console.log(\"\");\n console.log(` ${mark} olakai`);\n console.log(` ${tagline}`);\n console.log(` ──────────────────────────────`);\n console.log(\"\");\n}\n\n/**\n * Multi-line greeting shown to existing-account users (ADMIN /\n * ANALYST / USER) on the `user_exists + deviceFlowOk` branch BEFORE\n * the browser opens for device-flow auth.\n *\n * Two goals:\n * 1. Acknowledge that we identified the user by name/email — Xavier\n * flagged the current \"Welcome back! Opening browser...\" as\n * feeling impersonal for someone evaluating the product.\n * 2. Explain WHY the browser step applies here AND clarify it does\n * NOT apply to Employee-role developers (who get the OTP flow).\n * The distinction is the heart of the feedback: admins shouldn't\n * conclude \"this is friction for my whole team\" from their own\n * elevated-privileges flow.\n *\n * Personalization is email-only by design. The handshake `user_exists\n * + deviceFlowOk` response is deliberately bounded to a tiny\n * email-enumeration oracle (status + boolean) — adding name/role/\n * accountName here would enlarge the oracle on an unauthenticated\n * endpoint. The richer per-user display (name, role, account) comes\n * AFTER browser auth, where `loginCommand` already prints them.\n */\nexport function formatExistingUserBrowserGreeting(email: string): string {\n return [\n ` ✓ Found your Olakai account — ${email}`,\n ``,\n ` Since you have login access to an Olakai workspace, we'll route`,\n ` you through your account's standard sign-in. Admin and analyst`,\n ` users authenticate the CLI through the browser, matching how`,\n ` they sign in to the web app.`,\n ``,\n ` Employee-role developers skip this step and self-onboard with`,\n ` a one-time email code — no browser, no SSO prompt.`,\n ].join(\"\\n\");\n}\n","import { Command } from \"commander\";\nimport {\n listAgents,\n getAgent,\n createAgent,\n updateAgent,\n deleteAgent,\n listMyAgents,\n type Agent,\n type MineAgent,\n} from \"../lib/api.js\";\nimport { getToolSource } from \"../monitor/registry.js\";\nimport { TOOL_IDS, isToolId } from \"../monitor/plugin.js\";\n\nfunction formatAgentTable(agents: Agent[]): void {\n if (agents.length === 0) {\n console.log(\"No agents found.\");\n return;\n }\n\n // Calculate column widths\n const headers = [\"ID\", \"NAME\", \"ROLE\", \"WORKFLOW\", \"API KEY\"];\n const rows = agents.map((agent) => [\n agent.id.slice(0, 12) + \"...\",\n agent.name.slice(0, 30),\n agent.role,\n agent.workflowId ? agent.workflowId.slice(0, 12) + \"...\" : \"-\",\n agent.apiKey ? (agent.apiKey.isActive ? \"Active\" : \"Inactive\") : \"None\",\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n // Print header\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n // Print rows\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n}\n\nfunction formatAgentDetail(agent: Agent): void {\n console.log(`ID: ${agent.id}`);\n console.log(`Name: ${agent.name}`);\n console.log(`Description: ${agent.description || \"-\"}`);\n console.log(`Role: ${agent.role}`);\n console.log(`Source: ${agent.source}`);\n console.log(`Category: ${agent.category || \"-\"}`);\n console.log(`Workflow ID: ${agent.workflowId || \"-\"}`);\n\n if (agent.workflow) {\n console.log(`Workflow: ${agent.workflow.name}`);\n }\n\n console.log(\"\");\n console.log(\"API Key:\");\n if (agent.apiKey) {\n console.log(` ID: ${agent.apiKey.id}`);\n if (agent.apiKey.key) {\n console.log(` Key: ${agent.apiKey.key}`);\n } else {\n console.log(` Key: ${agent.apiKey.keyMasked}`);\n }\n console.log(` Status: ${agent.apiKey.isActive ? \"Active\" : \"Inactive\"}`);\n } else {\n console.log(\" None\");\n }\n\n if (agent.kpiDefinitions && agent.kpiDefinitions.length > 0) {\n console.log(\"\");\n console.log(\"KPI Definitions:\");\n for (const kpi of agent.kpiDefinitions) {\n console.log(` - ${kpi.name} (${kpi.type})`);\n }\n }\n}\n\n/**\n * Render the account lens (`agents mine`) as a table:\n * name · source · agentId · created · apiKey active?\n */\nfunction formatMineTable(agents: MineAgent[]): void {\n if (agents.length === 0) {\n console.log(\"You haven't created any agents.\");\n return;\n }\n\n const headers = [\"NAME\", \"SOURCE\", \"AGENT ID\", \"CREATED\", \"API KEY\"];\n const rows = agents.map((agent) => [\n agent.name.slice(0, 30),\n agent.source,\n agent.id.slice(0, 12) + \"...\",\n agent.createdAt ? agent.createdAt.slice(0, 10) : \"-\",\n agent.apiKey ? (agent.apiKey.isActive ? \"Active\" : \"Inactive\") : \"None\",\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n}\n\nasync function listCommand(options: {\n json?: boolean;\n includeKpis?: boolean;\n}): Promise<void> {\n try {\n const agents = await listAgents({ includeKpis: options.includeKpis });\n\n if (options.json) {\n console.log(JSON.stringify(agents, null, 2));\n } else {\n formatAgentTable(agents);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function getCommand(id: string, options: { json?: boolean }): Promise<void> {\n try {\n const agent = await getAgent(id);\n\n if (options.json) {\n console.log(JSON.stringify(agent, null, 2));\n } else {\n formatAgentDetail(agent);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function createCommand(options: {\n name: string;\n description?: string;\n role?: string;\n workflow?: string;\n withApiKey?: boolean;\n category?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n if (!options.name) {\n console.error(\"Error: --name is required\");\n process.exit(1);\n }\n\n const agent = await createAgent({\n name: options.name,\n description: options.description || \"\",\n role: (options.role as \"WORKER\" | \"COORDINATOR\") || \"WORKER\",\n workflowId: options.workflow,\n createApiKey: options.withApiKey || false,\n category: options.category,\n });\n\n if (options.json) {\n console.log(JSON.stringify(agent, null, 2));\n } else {\n console.log(\"Agent created successfully!\");\n console.log(\"\");\n formatAgentDetail(agent);\n\n if (agent.apiKey?.key) {\n console.log(\"\");\n console.log(\n \"IMPORTANT: Save your API key now. It will not be shown again.\"\n );\n }\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function updateCommand(\n id: string,\n options: {\n name?: string;\n description?: string;\n role?: string;\n workflow?: string;\n category?: string;\n json?: boolean;\n }\n): Promise<void> {\n try {\n const payload: {\n name?: string;\n description?: string;\n role?: \"WORKER\" | \"COORDINATOR\";\n workflowId?: string | null;\n category?: string | null;\n } = {};\n\n if (options.name !== undefined) payload.name = options.name;\n if (options.description !== undefined)\n payload.description = options.description;\n if (options.role !== undefined)\n payload.role = options.role as \"WORKER\" | \"COORDINATOR\";\n if (options.workflow !== undefined) payload.workflowId = options.workflow;\n if (options.category !== undefined) payload.category = options.category;\n\n if (Object.keys(payload).length === 0) {\n console.error(\"Error: At least one field to update is required\");\n process.exit(1);\n }\n\n const agent = await updateAgent(id, payload);\n\n if (options.json) {\n console.log(JSON.stringify(agent, null, 2));\n } else {\n console.log(\"Agent updated successfully!\");\n console.log(\"\");\n formatAgentDetail(agent);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function deleteCommand(\n id: string,\n options: { force?: boolean }\n): Promise<void> {\n try {\n if (!options.force) {\n // In a real CLI, we'd use readline for confirmation\n // For now, require --force flag\n console.log(\"Are you sure you want to delete this agent?\");\n console.log(\"Use --force to confirm deletion.\");\n process.exit(1);\n }\n\n await deleteAgent(id);\n console.log(\"Agent deleted successfully.\");\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\n/**\n * `olakai agents mine [--source X] [--json]` — the ACCOUNT lens.\n *\n * Lists the agents the current user created, across the whole account\n * (cross-machine), via `GET /api/config/agents/mine`. This is distinct\n * from `olakai monitor list`, which is the MACHINE lens (only what's\n * installed on this box, read from the local registry).\n *\n * `--source` narrows to a single coding-agent source. It accepts the\n * lowercase tool identifier (claude-code|codex|cursor) and maps it to\n * the backend AgentSource enum (CLAUDE_CODE|CODEX|CURSOR).\n */\nasync function mineCommand(options: {\n source?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n let source: string | undefined;\n if (options.source !== undefined) {\n if (!isToolId(options.source)) {\n console.error(\n `Unknown --source \"${options.source}\". Supported coding-agent sources: ${TOOL_IDS.join(\", \")}`,\n );\n process.exit(1);\n }\n source = getToolSource(options.source);\n }\n\n const agents = await listMyAgents(source ? { source } : undefined);\n\n if (options.json) {\n console.log(JSON.stringify(agents, null, 2));\n } else {\n formatMineTable(agents);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\n/**\n * `olakai agents archive <id> [--unarchive]` — soft archive / restore an\n * agent account-wide. PUT /api/config/agents/:id { archived }.\n */\nasync function archiveCommand(\n id: string,\n options: { unarchive?: boolean; json?: boolean }\n): Promise<void> {\n try {\n const archived = !options.unarchive;\n const agent = await updateAgent(id, { archived });\n\n if (options.json) {\n console.log(JSON.stringify(agent, null, 2));\n } else {\n console.log(\n archived\n ? `Agent ${id} archived.`\n : `Agent ${id} unarchived.`\n );\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\n/**\n * `olakai agents rename <id> <name>` — rename an agent account-wide.\n * PUT /api/config/agents/:id { name }.\n */\nasync function renameCommand(\n id: string,\n name: string,\n options: { json?: boolean }\n): Promise<void> {\n try {\n if (!name || !name.trim()) {\n console.error(\"Error: a non-empty <name> is required\");\n process.exit(1);\n }\n\n const agent = await updateAgent(id, { name: name.trim() });\n\n if (options.json) {\n console.log(JSON.stringify(agent, null, 2));\n } else {\n console.log(`Agent ${id} renamed to \"${agent.name}\".`);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nexport function registerAgentsCommand(program: Command): void {\n const agents = program\n .command(\"agents\")\n .description(\"Manage agents\");\n\n agents\n .command(\"list\")\n .description(\"List all agents\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--include-kpis\", \"Include KPI definitions\")\n .action(listCommand);\n\n agents\n .command(\"get <id>\")\n .description(\"Get agent details\")\n .option(\"--json\", \"Output as JSON\")\n .action(getCommand);\n\n agents\n .command(\"create\")\n .description(\"Create a new agent\")\n .requiredOption(\"--name <name>\", \"Agent name\")\n .option(\"--description <description>\", \"Agent description\")\n .option(\"--role <role>\", \"Agent role (WORKER or COORDINATOR)\", \"WORKER\")\n .option(\"--workflow <id>\", \"Workflow ID to assign\")\n .option(\"--with-api-key\", \"Create an API key for this agent\")\n .option(\"--category <category>\", \"Agent category\")\n .option(\"--json\", \"Output as JSON\")\n .action(createCommand);\n\n agents\n .command(\"update <id>\")\n .description(\"Update an agent\")\n .option(\"--name <name>\", \"Agent name\")\n .option(\"--description <description>\", \"Agent description\")\n .option(\"--role <role>\", \"Agent role (WORKER or COORDINATOR)\")\n .option(\"--workflow <id>\", \"Workflow ID to assign\")\n .option(\"--category <category>\", \"Agent category\")\n .option(\"--json\", \"Output as JSON\")\n .action(updateCommand);\n\n agents\n .command(\"delete <id>\")\n .description(\n \"Delete an agent (account-wide). Owner or ADMIN only — non-owners get a permission error.\",\n )\n .option(\"--force\", \"Skip confirmation\")\n .action(deleteCommand);\n\n agents\n .command(\"mine\")\n .description(\n \"List agents you created across your whole account (the account lens, cross-machine). For what's installed on THIS machine, use 'olakai monitor list'.\",\n )\n .option(\n \"--source <source>\",\n `Filter to a coding-agent source (${TOOL_IDS.join(\"|\")})`,\n )\n .option(\"--json\", \"Output as JSON\")\n .action(mineCommand);\n\n agents\n .command(\"archive <id>\")\n .description(\"Archive an agent account-wide (soft delete). Owner or ADMIN only.\")\n .option(\"--unarchive\", \"Restore an archived agent instead\")\n .option(\"--json\", \"Output as JSON\")\n .action(archiveCommand);\n\n agents\n .command(\"rename <id> <name>\")\n .description(\"Rename an agent account-wide. Owner or ADMIN only.\")\n .option(\"--json\", \"Output as JSON\")\n .action(renameCommand);\n}\n","import { Command } from \"commander\";\nimport {\n listWorkflows,\n getWorkflow,\n createWorkflow,\n updateWorkflow,\n deleteWorkflow,\n type Workflow,\n} from \"../lib/api.js\";\n\nfunction formatWorkflowTable(workflows: Workflow[]): void {\n if (workflows.length === 0) {\n console.log(\"No workflows found.\");\n return;\n }\n\n // Calculate column widths\n const headers = [\"ID\", \"NAME\", \"AGENTS\", \"STATUS\"];\n const rows = workflows.map((wf) => [\n wf.id.slice(0, 12) + \"...\",\n wf.name.slice(0, 30),\n wf.agentCount.toString(),\n wf.isActive ? \"Active\" : \"Inactive\",\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n // Print header\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n // Print rows\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n}\n\nfunction formatWorkflowDetail(workflow: Workflow): void {\n console.log(`ID: ${workflow.id}`);\n console.log(`Name: ${workflow.name}`);\n console.log(`Description: ${workflow.description || \"-\"}`);\n console.log(`Status: ${workflow.isActive ? \"Active\" : \"Inactive\"}`);\n console.log(`Agents: ${workflow.agentCount}`);\n if (workflow.createdAt) {\n console.log(`Created: ${new Date(workflow.createdAt).toISOString()}`);\n }\n if (workflow.updatedAt) {\n console.log(`Updated: ${new Date(workflow.updatedAt).toISOString()}`);\n }\n\n if (workflow.agents && workflow.agents.length > 0) {\n console.log(\"\");\n console.log(\"Agents:\");\n for (const agent of workflow.agents) {\n const apiKeyStatus = agent.apiKey\n ? agent.apiKey.isActive\n ? \"API Key: Active\"\n : \"API Key: Inactive\"\n : \"No API Key\";\n console.log(` - ${agent.name} (${agent.role}) - ${apiKeyStatus}`);\n }\n }\n}\n\nasync function listCommand(options: {\n json?: boolean;\n includeAgents?: boolean;\n includeInactive?: boolean;\n}): Promise<void> {\n try {\n const workflows = await listWorkflows({\n includeAgents: options.includeAgents,\n includeInactive: options.includeInactive,\n });\n\n if (options.json) {\n console.log(JSON.stringify(workflows, null, 2));\n } else {\n formatWorkflowTable(workflows);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function getCommand(id: string, options: { json?: boolean }): Promise<void> {\n try {\n const workflow = await getWorkflow(id);\n\n if (options.json) {\n console.log(JSON.stringify(workflow, null, 2));\n } else {\n formatWorkflowDetail(workflow);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function createCommand(options: {\n name: string;\n description?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n if (!options.name) {\n console.error(\"Error: --name is required\");\n process.exit(1);\n }\n\n const workflow = await createWorkflow({\n name: options.name,\n description: options.description,\n });\n\n if (options.json) {\n console.log(JSON.stringify(workflow, null, 2));\n } else {\n console.log(\"Workflow created successfully!\");\n console.log(\"\");\n formatWorkflowDetail(workflow);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function updateCommand(\n id: string,\n options: {\n name?: string;\n description?: string;\n active?: boolean;\n inactive?: boolean;\n json?: boolean;\n }\n): Promise<void> {\n try {\n const payload: {\n name?: string;\n description?: string | null;\n isActive?: boolean;\n } = {};\n\n if (options.name !== undefined) payload.name = options.name;\n if (options.description !== undefined)\n payload.description = options.description;\n if (options.active) payload.isActive = true;\n if (options.inactive) payload.isActive = false;\n\n if (Object.keys(payload).length === 0) {\n console.error(\"Error: At least one field to update is required\");\n process.exit(1);\n }\n\n const workflow = await updateWorkflow(id, payload);\n\n if (options.json) {\n console.log(JSON.stringify(workflow, null, 2));\n } else {\n console.log(\"Workflow updated successfully!\");\n console.log(\"\");\n formatWorkflowDetail(workflow);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function deleteCommand(\n id: string,\n options: { force?: boolean }\n): Promise<void> {\n try {\n if (!options.force) {\n // In a real CLI, we'd use readline for confirmation\n // For now, require --force flag\n console.log(\"Are you sure you want to delete this workflow?\");\n console.log(\"Use --force to confirm deletion.\");\n process.exit(1);\n }\n\n await deleteWorkflow(id);\n console.log(\"Workflow deleted successfully.\");\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nexport function registerWorkflowsCommand(program: Command): void {\n const workflows = program\n .command(\"workflows\")\n .description(\"Manage workflows\");\n\n workflows\n .command(\"list\")\n .description(\"List all workflows\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--include-agents\", \"Include agent details\")\n .option(\"--include-inactive\", \"Include inactive workflows\")\n .action(listCommand);\n\n workflows\n .command(\"get <id>\")\n .description(\"Get workflow details\")\n .option(\"--json\", \"Output as JSON\")\n .action(getCommand);\n\n workflows\n .command(\"create\")\n .description(\"Create a new workflow\")\n .requiredOption(\"--name <name>\", \"Workflow name\")\n .option(\"--description <description>\", \"Workflow description\")\n .option(\"--json\", \"Output as JSON\")\n .action(createCommand);\n\n workflows\n .command(\"update <id>\")\n .description(\"Update a workflow\")\n .option(\"--name <name>\", \"Workflow name\")\n .option(\"--description <description>\", \"Workflow description\")\n .option(\"--active\", \"Set workflow as active\")\n .option(\"--inactive\", \"Set workflow as inactive\")\n .option(\"--json\", \"Output as JSON\")\n .action(updateCommand);\n\n workflows\n .command(\"delete <id>\")\n .description(\"Delete a workflow\")\n .option(\"--force\", \"Skip confirmation\")\n .action(deleteCommand);\n}\n","import { Command } from \"commander\";\nimport {\n listKpis,\n getKpi,\n createKpi,\n updateKpi,\n deleteKpi,\n getKpiContextVariables,\n validateKpiFormula,\n type KpiDefinition,\n type KpiScope,\n type ContextVariable,\n type CreateKpiPayload,\n type DefaultAggregationMethod,\n} from \"../lib/api.js\";\n\nconst AGGREGATION_METHODS: DefaultAggregationMethod[] = [\n \"SUM\",\n \"AVERAGE\",\n \"COUNT\",\n \"MIN\",\n \"MAX\",\n \"LATEST\",\n];\n\nconst CALCULATOR_IDS = [\"formula\", \"classifier\", \"llm-data\"];\n\nconst KPI_SCOPES: KpiScope[] = [\"PROMPT_REQUEST\", \"CHAT\", \"DOCUMENT\"];\n\n// Classifier template definitions — mirrors CLASSIFIER_TEMPLATES from\n// localnode-app/packages/config/classifier-templates.ts\ntype OutputClassOption = { label: string; value: number };\n\ntype ClassifierTemplate = {\n id: string;\n name: string;\n description: string;\n promptTemplate: string;\n defaultUnit: string;\n defaultOutputClasses: OutputClassOption[];\n};\n\nconst CLASSIFIER_TEMPLATES: ClassifierTemplate[] = [\n {\n id: \"sentiment_scorer\",\n name: \"Sentiment Scorer\",\n description:\n \"Scores the overall emotional tone and user satisfaction of a conversation\",\n defaultUnit: \"score\",\n promptTemplate: `Analyze the overall sentiment of the following AI assistant conversation. Consider the user's tone, satisfaction level, and emotional state throughout the interaction.\n\nConversation:\n{{Complete exchange}}\n\nRate the sentiment using exactly one of these numeric scores:\n{{outputClassDescriptions}}\n\nRespond with only the numeric score.`,\n defaultOutputClasses: [\n { label: \"Very Negative\", value: 1 },\n { label: \"Negative\", value: 2 },\n { label: \"Neutral\", value: 3 },\n { label: \"Positive\", value: 4 },\n { label: \"Very Positive\", value: 5 },\n ],\n },\n {\n id: \"time_saved_estimator\",\n name: \"Time Saved Estimator\",\n description:\n \"Estimates how much time the AI interaction saved compared to manual effort\",\n defaultUnit: \"minutes\",\n promptTemplate: `Estimate how much time this AI assistant interaction saved the user compared to completing the task manually without AI assistance. Consider the complexity of the request, the completeness of the response, and typical human effort for similar tasks.\n\nConversation:\n{{Complete exchange}}\n\nClassify the estimated time saved using exactly one of these values (in minutes):\n{{outputClassDescriptions}}\n\nRespond with only the numeric value.`,\n defaultOutputClasses: [\n { label: \"No time saved\", value: 0 },\n { label: \"A few minutes\", value: 3 },\n { label: \"Moderate time\", value: 10 },\n { label: \"Significant time\", value: 30 },\n { label: \"Major time savings\", value: 60 },\n ],\n },\n];\n\nfunction resolveOutputClassDescriptions(classes: OutputClassOption[]): string {\n return classes.map((c) => `${c.value} = ${c.label}`).join(\"\\n\");\n}\n\nfunction resolveTemplatePrompt(\n template: ClassifierTemplate,\n classes: OutputClassOption[],\n): string {\n return template.promptTemplate.replace(\n \"{{outputClassDescriptions}}\",\n resolveOutputClassDescriptions(classes),\n );\n}\n\nfunction formatKpiTable(kpis: KpiDefinition[]): void {\n if (kpis.length === 0) {\n console.log(\"No KPI definitions found.\");\n return;\n }\n\n // Calculate column widths\n const headers = [\"ID\", \"NAME\", \"SCOPE\", \"CALCULATOR\", \"AGGREGATION\", \"STATUS\"];\n const rows = kpis.map((kpi) => [\n kpi.id.slice(0, 12) + \"...\",\n kpi.name.slice(0, 25),\n kpi.scope || \"PROMPT_REQUEST\",\n kpi.calculatorId,\n kpi.defaultAggregationMethod,\n kpi.isActive ? \"Active\" : \"Inactive\",\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n // Print header\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n // Print rows\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n}\n\nfunction formatKpiDetail(kpi: KpiDefinition): void {\n console.log(`ID: ${kpi.id}`);\n console.log(`Name: ${kpi.name}`);\n console.log(`Description: ${kpi.description || \"-\"}`);\n console.log(`Type: ${kpi.type}`);\n console.log(`Category: ${kpi.category || \"-\"}`);\n console.log(`Agent ID: ${kpi.agentId || \"-\"}`);\n console.log(`Scope: ${kpi.scope || \"PROMPT_REQUEST\"}`);\n console.log(`Calculator: ${kpi.calculatorId}`);\n console.log(`Aggregation: ${kpi.defaultAggregationMethod}`);\n console.log(`Unit: ${kpi.unit || \"-\"}`);\n console.log(`Status: ${kpi.isActive ? \"Active\" : \"Inactive\"}`);\n\n if (kpi.calculatorParams) {\n console.log(\"\");\n console.log(\"Calculator Parameters:\");\n console.log(JSON.stringify(kpi.calculatorParams, null, 2));\n }\n\n if (kpi.createdAt) {\n console.log(\"\");\n console.log(`Created: ${new Date(kpi.createdAt).toISOString()}`);\n }\n if (kpi.updatedAt) {\n console.log(`Updated: ${new Date(kpi.updatedAt).toISOString()}`);\n }\n}\n\nfunction formatContextVariablesTable(variables: ContextVariable[]): void {\n if (variables.length === 0) {\n console.log(\"No context variables found.\");\n return;\n }\n\n // Calculate column widths\n const headers = [\"NAME\", \"TYPE\", \"SOURCE\", \"DESCRIPTION\"];\n const rows = variables.map((v) => [\n v.name,\n v.type,\n v.source,\n v.description.slice(0, 50),\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n // Print header\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n // Print rows\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n}\n\nasync function listCommand(options: {\n json?: boolean;\n agentId?: string;\n includeInactive?: boolean;\n}): Promise<void> {\n try {\n const kpis = await listKpis({\n agentId: options.agentId,\n includeInactive: options.includeInactive,\n });\n\n if (options.json) {\n console.log(JSON.stringify(kpis, null, 2));\n } else {\n formatKpiTable(kpis);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function getCommand(\n id: string,\n options: { json?: boolean }\n): Promise<void> {\n try {\n const kpi = await getKpi(id);\n\n if (options.json) {\n console.log(JSON.stringify(kpi, null, 2));\n } else {\n formatKpiDetail(kpi);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function createCommand(options: {\n name: string;\n calculatorId: string;\n scope: string;\n description?: string;\n type?: string;\n category?: string;\n agentId?: string;\n formula?: string;\n templateId?: string;\n outputClasses?: string;\n outputLabels?: string;\n samplingFactor?: string;\n unit?: string;\n aggregation?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n if (!options.name) {\n console.error(\"Error: --name is required\");\n process.exit(1);\n }\n\n if (!options.calculatorId) {\n console.error(\"Error: --calculator-id is required\");\n console.error(`Valid values: ${CALCULATOR_IDS.join(\", \")}`);\n process.exit(1);\n }\n\n if (!CALCULATOR_IDS.includes(options.calculatorId)) {\n console.error(`Error: Invalid calculator ID \"${options.calculatorId}\"`);\n console.error(`Valid values: ${CALCULATOR_IDS.join(\", \")}`);\n process.exit(1);\n }\n\n // Validate scope\n const upperScope = options.scope.toUpperCase() as KpiScope;\n if (!KPI_SCOPES.includes(upperScope)) {\n console.error(`Error: Invalid scope \"${options.scope}\"`);\n console.error(`Valid values: ${KPI_SCOPES.join(\", \")}`);\n process.exit(1);\n }\n\n // Build calculator params\n let calculatorParams: Record<string, unknown> | undefined;\n let resolvedUnit = options.unit;\n\n if (options.calculatorId === \"formula\") {\n if (!options.formula) {\n console.error(\n \"Error: --formula is required when calculator-id is 'formula'\"\n );\n process.exit(1);\n }\n // Validate and parse the formula using the API\n const validation = await validateKpiFormula(options.formula, options.agentId, upperScope);\n if (!validation.valid) {\n console.error(`Error: Invalid formula: ${validation.error}`);\n process.exit(1);\n }\n // Use the parsed formula AST, not the raw string\n calculatorParams = { formula: validation.parsedFormula };\n } else if (options.calculatorId === \"classifier\") {\n if (!options.templateId) {\n console.error(\n \"Error: Classifier KPIs require --template-id. Run `olakai kpis templates` to see available templates.\"\n );\n process.exit(1);\n }\n\n const templateIds = CLASSIFIER_TEMPLATES.map((t) => t.id);\n const template = CLASSIFIER_TEMPLATES.find(\n (t) => t.id === options.templateId,\n );\n if (!template) {\n console.error(\n `Error: Unknown template \"${options.templateId}\". Valid templates: ${templateIds.join(\", \")}`\n );\n process.exit(1);\n }\n\n // Resolve output classes — use overrides if provided, else template defaults\n let outputClasses = template.defaultOutputClasses;\n if (options.outputClasses || options.outputLabels) {\n const rawValues = options.outputClasses\n ? options.outputClasses.split(\",\").map((v) => v.trim())\n : template.defaultOutputClasses.map((c) => String(c.value));\n const rawLabels = options.outputLabels\n ? options.outputLabels.split(\",\").map((l) => l.trim())\n : template.defaultOutputClasses.map((c) => c.label);\n\n if (rawValues.length !== rawLabels.length) {\n console.error(\n `Error: --output-classes (${rawValues.length} values) and --output-labels (${rawLabels.length} labels) must have the same count.`\n );\n process.exit(1);\n }\n\n outputClasses = rawValues.map((v, i) => ({\n label: rawLabels[i],\n value: Number(v),\n }));\n }\n\n // Resolve prompt with output class descriptions\n const promptTemplate = resolveTemplatePrompt(template, outputClasses);\n\n calculatorParams = {\n promptTemplate,\n outputClasses: outputClasses.map((c) => c.value),\n outputClassLabels: outputClasses.map((c) => c.label),\n classifierTemplateId: template.id,\n };\n\n // Parse sampling factor if provided\n if (options.samplingFactor !== undefined) {\n const factor = Number(options.samplingFactor);\n if (isNaN(factor) || factor < 0 || factor > 1) {\n console.error(\"Error: --sampling-factor must be a number between 0 and 1.\");\n process.exit(1);\n }\n calculatorParams.samplingFactor = factor;\n }\n\n // Use template default unit unless explicitly overridden\n if (!resolvedUnit) {\n resolvedUnit = template.defaultUnit;\n }\n }\n\n // Validate aggregation method\n let aggregation: DefaultAggregationMethod | undefined;\n if (options.aggregation) {\n const upperAggregation =\n options.aggregation.toUpperCase() as DefaultAggregationMethod;\n if (!AGGREGATION_METHODS.includes(upperAggregation)) {\n console.error(`Error: Invalid aggregation method \"${options.aggregation}\"`);\n console.error(`Valid values: ${AGGREGATION_METHODS.join(\", \")}`);\n process.exit(1);\n }\n aggregation = upperAggregation;\n }\n\n const payload: CreateKpiPayload = {\n name: options.name,\n calculatorId: options.calculatorId,\n scope: upperScope,\n description: options.description,\n type:\n options.type === \"PREDEFINED\" ? \"PREDEFINED\" : \"USER_DEFINED\",\n category: options.category,\n agentId: options.agentId,\n calculatorParams,\n unit: resolvedUnit,\n defaultAggregationMethod: aggregation,\n };\n\n const kpi = await createKpi(payload);\n\n if (options.json) {\n console.log(JSON.stringify(kpi, null, 2));\n } else {\n console.log(\"KPI definition created successfully!\");\n console.log(\"\");\n formatKpiDetail(kpi);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function updateCommand(\n id: string,\n options: {\n name?: string;\n description?: string;\n category?: string;\n agentId?: string;\n scope?: string;\n calculatorId?: string;\n formula?: string;\n unit?: string;\n aggregation?: string;\n active?: boolean;\n inactive?: boolean;\n json?: boolean;\n }\n): Promise<void> {\n try {\n const payload: Record<string, unknown> = {};\n\n if (options.name !== undefined) payload.name = options.name;\n if (options.description !== undefined)\n payload.description = options.description;\n if (options.category !== undefined) payload.category = options.category;\n if (options.agentId !== undefined) payload.agentId = options.agentId;\n if (options.calculatorId !== undefined)\n payload.calculatorId = options.calculatorId;\n if (options.unit !== undefined) payload.unit = options.unit;\n if (options.active) payload.isActive = true;\n if (options.inactive) payload.isActive = false;\n\n // Validate and set scope\n let validatedScope: KpiScope | undefined;\n if (options.scope !== undefined) {\n const upperScope = options.scope.toUpperCase() as KpiScope;\n if (!KPI_SCOPES.includes(upperScope)) {\n console.error(`Error: Invalid scope \"${options.scope}\"`);\n console.error(`Valid values: ${KPI_SCOPES.join(\", \")}`);\n process.exit(1);\n }\n payload.scope = upperScope;\n validatedScope = upperScope;\n }\n\n // Handle formula update - validate and parse before storing\n if (options.formula !== undefined) {\n const validation = await validateKpiFormula(options.formula, options.agentId, validatedScope);\n if (!validation.valid) {\n console.error(`Error: Invalid formula: ${validation.error}`);\n process.exit(1);\n }\n // Use the parsed formula AST, not the raw string\n payload.calculatorParams = { formula: validation.parsedFormula };\n }\n\n // Validate and set aggregation method\n if (options.aggregation) {\n const upperAggregation =\n options.aggregation.toUpperCase() as DefaultAggregationMethod;\n if (!AGGREGATION_METHODS.includes(upperAggregation)) {\n console.error(`Error: Invalid aggregation method \"${options.aggregation}\"`);\n console.error(`Valid values: ${AGGREGATION_METHODS.join(\", \")}`);\n process.exit(1);\n }\n payload.defaultAggregationMethod = upperAggregation;\n }\n\n if (Object.keys(payload).length === 0) {\n console.error(\"Error: At least one field to update is required\");\n process.exit(1);\n }\n\n const kpi = await updateKpi(id, payload);\n\n if (options.json) {\n console.log(JSON.stringify(kpi, null, 2));\n } else {\n console.log(\"KPI definition updated successfully!\");\n console.log(\"\");\n formatKpiDetail(kpi);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function deleteCommand(\n id: string,\n options: { force?: boolean }\n): Promise<void> {\n try {\n if (!options.force) {\n console.log(\"Are you sure you want to delete this KPI definition?\");\n console.log(\"Use --force to confirm deletion.\");\n process.exit(1);\n }\n\n await deleteKpi(id);\n console.log(\"KPI definition deleted successfully.\");\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function contextVariablesCommand(options: {\n json?: boolean;\n agentId?: string;\n scope?: string;\n}): Promise<void> {\n try {\n // Validate scope if provided\n let validatedScope: KpiScope | undefined;\n if (options.scope) {\n const upperScope = options.scope.toUpperCase() as KpiScope;\n if (!KPI_SCOPES.includes(upperScope)) {\n console.error(`Error: Invalid scope \"${options.scope}\"`);\n console.error(`Valid values: ${KPI_SCOPES.join(\", \")}`);\n process.exit(1);\n }\n validatedScope = upperScope;\n }\n\n const variables = await getKpiContextVariables(options.agentId, validatedScope);\n\n if (options.json) {\n console.log(JSON.stringify(variables, null, 2));\n } else {\n console.log(\"Available context variables for KPI formulas:\");\n console.log(\"\");\n formatContextVariablesTable(variables);\n console.log(\"\");\n console.log(\n \"Use these variable names in your formula expressions, e.g.:\"\n );\n console.log(' IF(PII detected, 1, 0)');\n console.log(' Documents count * 10');\n console.log(' IF(CODE detected AND SECRET detected, \"high-risk\", \"normal\")');\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function validateCommand(options: {\n formula: string;\n agentId?: string;\n scope?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n if (!options.formula) {\n console.error(\"Error: --formula is required\");\n process.exit(1);\n }\n\n // Validate scope if provided\n let validatedScope: KpiScope | undefined;\n if (options.scope) {\n const upperScope = options.scope.toUpperCase() as KpiScope;\n if (!KPI_SCOPES.includes(upperScope)) {\n console.error(`Error: Invalid scope \"${options.scope}\"`);\n console.error(`Valid values: ${KPI_SCOPES.join(\", \")}`);\n process.exit(1);\n }\n validatedScope = upperScope;\n }\n\n const result = await validateKpiFormula(options.formula, options.agentId, validatedScope);\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n if (result.valid) {\n console.log(\"Formula is valid!\");\n console.log(`Result type: ${result.type || \"unknown\"}`);\n } else {\n console.error(\"Formula is invalid:\");\n console.error(` ${result.error}`);\n if (result.charIndex !== undefined) {\n console.error(` Position: character ${result.charIndex}`);\n }\n process.exit(1);\n }\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nfunction templatesCommand(options: { json?: boolean }): void {\n if (options.json) {\n console.log(\n JSON.stringify(\n CLASSIFIER_TEMPLATES.map((t) => ({\n id: t.id,\n name: t.name,\n description: t.description,\n defaultUnit: t.defaultUnit,\n outputClasses: t.defaultOutputClasses,\n })),\n null,\n 2,\n ),\n );\n } else {\n console.log(\"Available Classifier Templates:\");\n console.log(\"\");\n for (const t of CLASSIFIER_TEMPLATES) {\n console.log(` ${t.id.padEnd(24)} ${t.description}`);\n const classRange = t.defaultOutputClasses;\n console.log(\n `${\"\".padEnd(26)}Classes: ${classRange.map((c) => `${c.value} (${c.label})`).join(\", \")}`,\n );\n console.log(\n `${\"\".padEnd(26)}Default unit: ${t.defaultUnit}`,\n );\n console.log(\"\");\n }\n console.log(\"Usage:\");\n console.log(\n ' olakai kpis create --name \"User Satisfaction\" --calculator-id classifier --template-id sentiment_scorer --scope CHAT',\n );\n }\n}\n\nexport function registerKpisCommand(program: Command): void {\n const kpis = program\n .command(\"kpis\")\n .description(\"Manage KPI definitions\");\n\n kpis\n .command(\"list\")\n .description(\"List all KPI definitions\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--agent-id <id>\", \"Filter by agent ID\")\n .option(\"--include-inactive\", \"Include inactive KPI definitions\")\n .action(listCommand);\n\n kpis\n .command(\"get <id>\")\n .description(\"Get KPI definition details\")\n .option(\"--json\", \"Output as JSON\")\n .action(getCommand);\n\n kpis\n .command(\"create\")\n .description(\"Create a new KPI definition\")\n .requiredOption(\"--name <name>\", \"KPI name\")\n .requiredOption(\n \"--calculator-id <id>\",\n \"Calculator type: formula, classifier, or llm-data\"\n )\n .requiredOption(\n \"--scope <scope>\",\n \"KPI scope: PROMPT_REQUEST, CHAT, or DOCUMENT\"\n )\n .option(\"--description <description>\", \"KPI description\")\n .option(\"--type <type>\", \"KPI type: PREDEFINED or USER_DEFINED (default)\")\n .option(\"--category <category>\", \"KPI category for grouping\")\n .option(\"--agent-id <id>\", \"Associate KPI with a specific agent\")\n .option(\"--formula <formula>\", \"Formula expression (required for formula calculator)\")\n .option(\"--template-id <id>\", \"Classifier template: sentiment_scorer, time_saved_estimator\")\n .option(\"--output-classes <values>\", \"Override output class values (comma-separated numbers)\")\n .option(\"--output-labels <labels>\", \"Override output class labels (comma-separated)\")\n .option(\"--sampling-factor <factor>\", \"Fraction of events to classify, 0-1 (cost control)\")\n .option(\"--unit <unit>\", 'Display unit (e.g., \"ms\", \"%\", \"count\")')\n .option(\n \"--aggregation <method>\",\n \"Default aggregation: SUM, AVERAGE, COUNT, MIN, MAX, LATEST (default)\"\n )\n .option(\"--json\", \"Output as JSON\")\n .action(createCommand);\n\n kpis\n .command(\"templates\")\n .description(\"List available classifier templates\")\n .option(\"--json\", \"Output as JSON\")\n .action(templatesCommand);\n\n kpis\n .command(\"update <id>\")\n .description(\"Update a KPI definition\")\n .option(\"--name <name>\", \"KPI name\")\n .option(\"--description <description>\", \"KPI description\")\n .option(\"--category <category>\", \"KPI category\")\n .option(\"--agent-id <id>\", \"Associate with agent\")\n .option(\"--scope <scope>\", \"KPI scope: PROMPT_REQUEST, CHAT, or DOCUMENT\")\n .option(\"--calculator-id <id>\", \"Calculator type\")\n .option(\"--formula <formula>\", \"Formula expression\")\n .option(\"--unit <unit>\", \"Display unit\")\n .option(\"--aggregation <method>\", \"Default aggregation method\")\n .option(\"--active\", \"Set KPI as active\")\n .option(\"--inactive\", \"Set KPI as inactive\")\n .option(\"--json\", \"Output as JSON\")\n .action(updateCommand);\n\n kpis\n .command(\"delete <id>\")\n .description(\"Delete a KPI definition\")\n .option(\"--force\", \"Skip confirmation\")\n .action(deleteCommand);\n\n kpis\n .command(\"context-variables\")\n .description(\"List available context variables for formulas\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--agent-id <id>\", \"Include agent-specific variables\")\n .option(\"--scope <scope>\", \"Filter variables by scope: PROMPT_REQUEST, CHAT, or DOCUMENT\")\n .action(contextVariablesCommand);\n\n kpis\n .command(\"validate\")\n .description(\"Validate a KPI formula expression\")\n .requiredOption(\"--formula <formula>\", \"Formula expression to validate\")\n .option(\"--agent-id <id>\", \"Include agent-specific context\")\n .option(\"--scope <scope>\", \"Validate against scope: PROMPT_REQUEST, CHAT, or DOCUMENT\")\n .option(\"--json\", \"Output as JSON\")\n .action(validateCommand);\n}\n","import { Command } from \"commander\";\nimport {\n listCustomDataConfigs,\n getCustomDataConfig,\n createCustomDataConfig,\n updateCustomDataConfig,\n deleteCustomDataConfig,\n type CustomDataConfig,\n type CustomDataType,\n} from \"../lib/api.js\";\n\nconst DATA_TYPES: CustomDataType[] = [\"STRING\", \"NUMBER\", \"BOOLEAN\"];\n\nfunction formatTable(configs: CustomDataConfig[]): void {\n if (configs.length === 0) {\n console.log(\"No custom data configurations found.\");\n return;\n }\n\n // Calculate column widths\n const headers = [\"ID\", \"NAME\", \"TYPE\", \"AGENT ID\", \"DESCRIPTION\"];\n const rows = configs.map((config) => [\n config.id.slice(0, 12) + \"...\",\n config.name.slice(0, 25),\n config.type,\n config.agentId ? config.agentId.slice(0, 12) + \"...\" : \"(account-level)\",\n (config.description || \"-\").slice(0, 30),\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n // Print header\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n // Print rows\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n}\n\nfunction formatDetail(config: CustomDataConfig): void {\n console.log(`ID: ${config.id}`);\n console.log(`Name: ${config.name}`);\n console.log(`Type: ${config.type}`);\n console.log(`Agent ID: ${config.agentId || \"(account-level / legacy)\"}`);\n console.log(`Description: ${config.description || \"-\"}`);\n if (config.createdAt) {\n console.log(`Created: ${new Date(config.createdAt).toISOString()}`);\n }\n if (config.updatedAt) {\n console.log(`Updated: ${new Date(config.updatedAt).toISOString()}`);\n }\n}\n\nasync function listCommand(options: { agentId?: string; json?: boolean }): Promise<void> {\n try {\n const configs = await listCustomDataConfigs(options.agentId);\n\n if (options.json) {\n console.log(JSON.stringify(configs, null, 2));\n } else {\n formatTable(configs);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function getCommand(\n id: string,\n options: { json?: boolean }\n): Promise<void> {\n try {\n const config = await getCustomDataConfig(id);\n\n if (options.json) {\n console.log(JSON.stringify(config, null, 2));\n } else {\n formatDetail(config);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function createCommand(options: {\n agentId: string;\n name: string;\n type: string;\n description?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n if (!options.agentId) {\n console.error(\"Error: --agent-id is required\");\n console.error(\"Custom data configurations must be associated with an agent.\");\n process.exit(1);\n }\n\n if (!options.name) {\n console.error(\"Error: --name is required\");\n process.exit(1);\n }\n\n if (!options.type) {\n console.error(\"Error: --type is required\");\n console.error(`Valid values: ${DATA_TYPES.join(\", \")}`);\n process.exit(1);\n }\n\n const upperType = options.type.toUpperCase() as CustomDataType;\n if (!DATA_TYPES.includes(upperType)) {\n console.error(`Error: Invalid type \"${options.type}\"`);\n console.error(`Valid values: ${DATA_TYPES.join(\", \")}`);\n process.exit(1);\n }\n\n const config = await createCustomDataConfig({\n agentId: options.agentId,\n name: options.name,\n type: upperType,\n description: options.description ?? null,\n });\n\n if (options.json) {\n console.log(JSON.stringify(config, null, 2));\n } else {\n console.log(\"Custom data configuration created successfully!\");\n console.log(\"\");\n formatDetail(config);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function updateCommand(\n id: string,\n options: {\n name?: string;\n type?: string;\n description?: string;\n json?: boolean;\n }\n): Promise<void> {\n try {\n const payload: {\n name?: string;\n type?: CustomDataType;\n description?: string | null;\n } = {};\n\n if (options.name !== undefined) payload.name = options.name;\n if (options.description !== undefined)\n payload.description = options.description || null;\n\n if (options.type !== undefined) {\n const upperType = options.type.toUpperCase() as CustomDataType;\n if (!DATA_TYPES.includes(upperType)) {\n console.error(`Error: Invalid type \"${options.type}\"`);\n console.error(`Valid values: ${DATA_TYPES.join(\", \")}`);\n process.exit(1);\n }\n payload.type = upperType;\n }\n\n if (Object.keys(payload).length === 0) {\n console.error(\"Error: At least one field to update is required\");\n process.exit(1);\n }\n\n const config = await updateCustomDataConfig(id, payload);\n\n if (options.json) {\n console.log(JSON.stringify(config, null, 2));\n } else {\n console.log(\"Custom data configuration updated successfully!\");\n console.log(\"\");\n formatDetail(config);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function deleteCommand(\n id: string,\n options: { force?: boolean }\n): Promise<void> {\n try {\n if (!options.force) {\n console.log(\n \"Are you sure you want to delete this custom data configuration?\"\n );\n console.log(\"Use --force to confirm deletion.\");\n process.exit(1);\n }\n\n await deleteCustomDataConfig(id);\n console.log(\"Custom data configuration deleted successfully.\");\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nexport function registerCustomDataCommand(program: Command): void {\n const customData = program\n .command(\"custom-data\")\n .description(\"Manage custom data configurations for KPI formulas\");\n\n customData\n .command(\"list\")\n .description(\"List custom data configurations\")\n .option(\"--agent-id <agentId>\", \"Filter by agent ID (omit to list all account configs)\")\n .option(\"--json\", \"Output as JSON\")\n .action(listCommand);\n\n customData\n .command(\"get <id>\")\n .description(\"Get custom data configuration details\")\n .option(\"--json\", \"Output as JSON\")\n .action(getCommand);\n\n customData\n .command(\"create\")\n .description(\"Create a new custom data configuration for an agent\")\n .requiredOption(\"--agent-id <agentId>\", \"Agent ID (required)\")\n .requiredOption(\"--name <name>\", \"Configuration name (used in KPI formulas)\")\n .requiredOption(\n \"--type <type>\",\n \"Data type: STRING, NUMBER, or BOOLEAN\"\n )\n .option(\"--description <description>\", \"Configuration description\")\n .option(\"--json\", \"Output as JSON\")\n .action(createCommand);\n\n customData\n .command(\"update <id>\")\n .description(\"Update a custom data configuration\")\n .option(\"--name <name>\", \"Configuration name\")\n .option(\"--type <type>\", \"Data type: STRING, NUMBER, or BOOLEAN\")\n .option(\"--description <description>\", \"Configuration description\")\n .option(\"--json\", \"Output as JSON\")\n .action(updateCommand);\n\n customData\n .command(\"delete <id>\")\n .description(\"Delete a custom data configuration\")\n .option(\"--force\", \"Skip confirmation\")\n .action(deleteCommand);\n}\n","import { Command } from \"commander\";\nimport {\n listActivity,\n getActivity,\n getActivityKpis,\n listSessions,\n type ActivityPrompt,\n type ActivityListResponse,\n type ActivityKpisResponse,\n type CoreKpiValue,\n type SessionsListResponse,\n} from \"../lib/api.js\";\n\nfunction formatActivityTable(data: ActivityListResponse): void {\n if (data.prompts.length === 0) {\n console.log(\"No activity found.\");\n return;\n }\n\n // Calculate column widths\n const headers = [\"ID\", \"AGENT\", \"APP\", \"MODEL\", \"TOKENS\", \"TIME(ms)\", \"RISK\", \"STATUS\"];\n const rows = data.prompts.map((prompt) => [\n prompt.id.slice(0, 12) + \"...\",\n prompt.agentName || (prompt.agentId ? prompt.agentId.slice(0, 12) + \"...\" : \"-\"),\n prompt.app.slice(0, 12),\n prompt.modelId?.slice(0, 15) || \"-\",\n String(prompt.tokens),\n String(prompt.requestTime),\n prompt.isHighRisk ? \"Yes\" : \"No\",\n prompt.decorationStatus.slice(0, 10),\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n // Print header\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n // Print rows\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n\n // Print pagination info\n console.log(\"\");\n console.log(`Showing ${data.prompts.length} of ${data.total} results (offset: ${data.offset})`);\n if (data.hasMore) {\n console.log(`Use --offset ${data.offset + data.limit} to see more results`);\n }\n}\n\nfunction formatActivityDetail(prompt: ActivityPrompt): void {\n console.log(`ID: ${prompt.id}`);\n console.log(`Created: ${prompt.createdAt}`);\n console.log(`Agent: ${prompt.agentName || \"-\"} (${prompt.agentId || \"-\"})`);\n console.log(`Workflow: ${prompt.workflowName || \"-\"} (${prompt.workflowId || \"-\"})`);\n if (prompt.taskExecutionId) {\n console.log(`Task Exec ID: ${prompt.taskExecutionId}`);\n }\n console.log(`App: ${prompt.app}`);\n console.log(`Model: ${prompt.modelId || \"-\"} (${prompt.modelType || \"-\"})`);\n console.log(`Tokens: ${prompt.tokens}`);\n console.log(`Request Time: ${prompt.requestTime}ms`);\n console.log(`High Risk: ${prompt.isHighRisk ? \"Yes\" : \"No\"}`);\n console.log(`Blocked: ${prompt.blocked ? \"Yes\" : \"No\"}`);\n console.log(`Status: ${prompt.decorationStatus}`);\n\n if (prompt.sensitivity && prompt.sensitivity.length > 0) {\n console.log(`Sensitivity: ${prompt.sensitivity.join(\", \")}`);\n }\n\n if (prompt.analytics) {\n console.log(\"\");\n console.log(\"Analytics:\");\n console.log(` Task: ${prompt.analytics.task || \"-\"}`);\n console.log(` Subtask: ${prompt.analytics.subtask || \"-\"}`);\n console.log(` Time Saved: ${prompt.analytics.timesaved_minutes ?? \"-\"} minutes`);\n console.log(` Risk Score: ${prompt.analytics.riskassessment_dangerousity ?? \"-\"}`);\n }\n\n if (prompt.kpiData && Object.keys(prompt.kpiData).length > 0) {\n console.log(\"\");\n console.log(\"KPIs:\");\n for (const [key, value] of Object.entries(prompt.kpiData)) {\n console.log(` ${key}: ${value}`);\n }\n }\n\n if (prompt.prompt !== undefined) {\n console.log(\"\");\n console.log(\"Prompt:\");\n console.log(\"---\");\n console.log(prompt.prompt.slice(0, 1000) + (prompt.prompt.length > 1000 ? \"...\" : \"\"));\n console.log(\"---\");\n }\n\n if (prompt.response !== undefined) {\n console.log(\"\");\n console.log(\"Response:\");\n console.log(\"---\");\n console.log(prompt.response.slice(0, 1000) + (prompt.response.length > 1000 ? \"...\" : \"\"));\n console.log(\"---\");\n }\n}\n\nfunction formatCoreKpi(kpi: CoreKpiValue): string {\n const prefix = kpi.unitPrefix || \"\";\n const suffix = kpi.unitSuffix || \"\";\n return `${prefix}${kpi.value}${suffix}`;\n}\n\nfunction formatKpisResponse(data: ActivityKpisResponse): void {\n // Core KPIs\n console.log(\"Core KPIs:\");\n for (const kpi of data.coreKpis) {\n console.log(` ${kpi.name.padEnd(25)} ${formatCoreKpi(kpi)}`);\n }\n\n // Custom KPIs\n if (data.kpis.length > 0) {\n console.log(\"\");\n console.log(\"Custom KPIs:\");\n const headers = [\"NAME\", \"VALUE\", \"UNIT\", \"AGGREGATION\", \"DATA POINTS\"];\n const rows = data.kpis.map((kpi) => [\n kpi.name.slice(0, 25),\n kpi.value !== null ? String(kpi.value) : \"-\",\n kpi.unit || \"-\",\n kpi.aggregationMethod,\n String(kpi.dataPointCount),\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n console.log(\" \" + headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(\" \" + widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n for (const row of rows) {\n console.log(\" \" + row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n }\n\n // Period data\n if (data.periodData && data.periodData.length > 0) {\n console.log(\"\");\n console.log(\"Period Breakdown:\");\n for (const period of data.periodData) {\n console.log(` ${period.periodStart} - ${period.periodEnd}`);\n for (const kpi of period.coreKpis) {\n console.log(` ${kpi.name}: ${formatCoreKpi(kpi)}`);\n }\n }\n }\n\n // Atoms summary\n if (data.atoms && data.atoms.length > 0) {\n console.log(\"\");\n console.log(`Per-Prompt KPI Atoms: ${data.atoms.length} records`);\n console.log(\" (Use --json for full atom data)\");\n }\n}\n\nasync function listCommand(options: {\n agentId?: string;\n workflowId?: string;\n since?: string;\n until?: string;\n limit?: string;\n offset?: string;\n includeContent?: boolean;\n includeAnalytics?: boolean;\n json?: boolean;\n}): Promise<void> {\n try {\n const data = await listActivity({\n agentId: options.agentId,\n workflowId: options.workflowId,\n since: options.since,\n until: options.until,\n limit: options.limit ? parseInt(options.limit, 10) : undefined,\n offset: options.offset ? parseInt(options.offset, 10) : undefined,\n includeContent: options.includeContent,\n includeAnalytics: options.includeAnalytics,\n });\n\n if (options.json) {\n console.log(JSON.stringify(data, null, 2));\n } else {\n formatActivityTable(data);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function getCommand(\n id: string,\n options: { includeContent?: boolean; json?: boolean }\n): Promise<void> {\n try {\n const prompt = await getActivity(id, options.includeContent);\n\n if (options.json) {\n console.log(JSON.stringify(prompt, null, 2));\n } else {\n formatActivityDetail(prompt);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function kpisCommand(options: {\n agentId?: string;\n workflowId?: string;\n since?: string;\n until?: string;\n period?: string;\n includeAtoms?: boolean;\n json?: boolean;\n}): Promise<void> {\n try {\n if (!options.agentId && !options.workflowId) {\n console.error(\"Error: Either --agent-id or --workflow-id is required\");\n process.exit(1);\n }\n\n const data = await getActivityKpis({\n agentId: options.agentId,\n workflowId: options.workflowId,\n since: options.since,\n until: options.until,\n period: options.period as \"hourly\" | \"daily\" | \"weekly\" | undefined,\n includeAtoms: options.includeAtoms,\n });\n\n if (options.json) {\n console.log(JSON.stringify(data, null, 2));\n } else {\n formatKpisResponse(data);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nfunction formatSessionsTable(data: SessionsListResponse): void {\n // Summary\n console.log(\"Session Decoration Status\");\n console.log(\"\");\n console.log(\"Summary:\");\n console.log(` Total Sessions: ${data.summary.sessionCount}`);\n\n const statuses = [\"DECORATED\", \"NEW\", \"DECORATION_FAILED\", \"DECORATION_OUTDATED\", \"SKIPPED\"];\n for (const status of statuses) {\n const count = data.summary.byStatus[status] || 0;\n const pct = data.summary.sessionCount > 0 ? ((count / data.summary.sessionCount) * 100).toFixed(1) : \"0.0\";\n const label = status.charAt(0) + status.slice(1).toLowerCase().replace(/_/g, \" \");\n console.log(` ${label.padEnd(17)} ${String(count).padStart(4)} (${pct}%)`);\n }\n\n if (data.sessions.length === 0) {\n console.log(\"\");\n console.log(\"No sessions found.\");\n return;\n }\n\n console.log(\"\");\n\n // Table\n const headers = [\"ID\", \"STATUS\", \"DATE\", \"CANDIDATE\", \"ERRORS\", \"KPI DATA\", \"VERSION\"];\n const rows = data.sessions.map((s) => [\n s.id.slice(0, 15) + \"...\",\n s.decorationStatus,\n s.decorationDate || \"-\",\n s.decorationCandidate ? \"Yes\" : \"No\",\n String(s.decorationErrorStreak),\n s.hasKpiData ? \"Yes\" : \"No\",\n s.decoratorVersion || \"-\",\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n\n console.log(\"\");\n console.log(`Showing ${data.sessions.length} of ${data.total} results (offset: ${data.offset})`);\n if (data.hasMore) {\n console.log(`Use --offset ${data.offset + data.limit} to see more results`);\n }\n}\n\nasync function sessionsCommand(options: {\n agentId: string;\n since?: string;\n until?: string;\n limit?: string;\n offset?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n const data = await listSessions({\n agentId: options.agentId,\n since: options.since,\n until: options.until,\n limit: options.limit ? parseInt(options.limit, 10) : undefined,\n offset: options.offset ? parseInt(options.offset, 10) : undefined,\n });\n\n if (options.json) {\n console.log(JSON.stringify(data, null, 2));\n } else {\n formatSessionsTable(data);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nexport function registerActivityCommand(program: Command): void {\n const activity = program\n .command(\"activity\")\n .description(\"Inspect AI activity and prompts\");\n\n activity\n .command(\"list\")\n .description(\"List prompt requests with filters\")\n .option(\"--agent-id <id>\", \"Filter by agent ID\")\n .option(\"--workflow-id <id>\", \"Filter by workflow ID\")\n .option(\"--since <date>\", \"Start date (ISO format)\")\n .option(\"--until <date>\", \"End date (ISO format)\")\n .option(\"--limit <n>\", \"Results per page\", \"20\")\n .option(\"--offset <n>\", \"Skip first N results\", \"0\")\n .option(\"--include-content\", \"Include prompt/response content\")\n .option(\"--include-analytics\", \"Include advanced analytics\")\n .option(\"--json\", \"Output as JSON\")\n .action(listCommand);\n\n activity\n .command(\"get <id>\")\n .description(\"Get prompt request details\")\n .option(\"--include-content\", \"Include prompt/response content\")\n .option(\"--json\", \"Output as JSON\")\n .action(getCommand);\n\n activity\n .command(\"kpis\")\n .description(\"Get aggregated KPI values\")\n .option(\"--agent-id <id>\", \"Agent ID\")\n .option(\"--workflow-id <id>\", \"Workflow ID\")\n .option(\"--since <date>\", \"Period start (ISO format)\")\n .option(\"--until <date>\", \"Period end (ISO format)\")\n .option(\"--period <type>\", \"Aggregation period (hourly, daily, weekly)\")\n .option(\"--include-atoms\", \"Include per-prompt KPI data\")\n .option(\"--json\", \"Output as JSON\")\n .action(kpisCommand);\n\n activity\n .command(\"sessions\")\n .description(\"Inspect chat/session decoration status for troubleshooting\")\n .requiredOption(\"--agent-id <id>\", \"Agent ID (required)\")\n .option(\"--since <date>\", \"Start date (ISO format)\")\n .option(\"--until <date>\", \"End date (ISO format)\")\n .option(\"--limit <n>\", \"Results per page\", \"20\")\n .option(\"--offset <n>\", \"Skip first N results\", \"0\")\n .option(\"--json\", \"Output as JSON\")\n .action(sessionsCommand);\n}\n","import * as fs from \"node:fs\";\nimport { Command } from \"commander\";\nimport \"../monitor/plugins/index.js\";\nimport {\n TOOL_IDS,\n getPlugin,\n isToolId,\n listPlugins,\n type HookResult,\n type ToolId,\n type ToolMonitorPlugin,\n} from \"../monitor/plugin.js\";\nimport { isInteractive, promptUser } from \"../monitor/prompt.js\";\nimport { runMonitorInstall } from \"../monitor/install.js\";\nimport {\n formatRegistryTable,\n readRegistry,\n reconcileCurrentWorkspace,\n removeEntry,\n} from \"../monitor/registry.js\";\nimport { findConfiguredWorkspace } from \"../monitor/paths.js\";\n\n// Pre-Stage-2 `monitor.ts` exposed these symbols directly; downstream\n// tests and possibly external scripts import them from this module.\n// Re-export so the public surface is unchanged after the plugin split.\nexport {\n mergeHooksSettings,\n type HookMatcherEntry,\n type HookCommand,\n} from \"../monitor/plugins/claude-code/settings.js\";\nexport {\n buildClaudeCodePayload as buildPayload,\n type ClaudeHookEvent,\n} from \"../monitor/plugins/claude-code/hook.js\";\nexport { resolveProjectRootFromPayload } from \"../monitor/plugins/claude-code/index.js\";\nexport { type MonitorConfig } from \"../monitor/plugins/claude-code/config.js\";\n\nfunction readStdin(timeoutMs: number = 3000): Promise<string> {\n return new Promise((resolve) => {\n if (process.stdin.isTTY) {\n resolve(\"\");\n return;\n }\n\n let data = \"\";\n const timer = setTimeout(() => {\n process.stdin.removeAllListeners();\n process.stdin.destroy();\n resolve(data);\n }, timeoutMs);\n\n process.stdin.setEncoding(\"utf-8\");\n process.stdin.on(\"data\", (chunk: string) => {\n data += chunk;\n });\n process.stdin.on(\"end\", () => {\n clearTimeout(timer);\n resolve(data);\n });\n process.stdin.on(\"error\", () => {\n clearTimeout(timer);\n resolve(data);\n });\n });\n}\n\n// D-002 surface: in non-interactive contexts (CI, scripts) `--tool` is\n// optional and defaults to claude-code with a deprecation notice — this\n// keeps pre-Stage-2 automation working while signalling that the flag\n// is the way forward. Interactive contexts always prompt when the flag\n// is absent.\nconst DEFAULT_NON_INTERACTIVE_TOOL: ToolId = \"claude-code\";\n\nasync function resolveToolFromOptions(\n flag: string | undefined,\n context: \"init\" | \"status\" | \"disable\",\n): Promise<ToolId> {\n if (typeof flag === \"string\" && flag.length > 0) {\n if (!isToolId(flag)) {\n console.error(\n `Unknown --tool \"${flag}\". Supported: ${TOOL_IDS.join(\", \")}`,\n );\n process.exit(1);\n }\n return flag;\n }\n\n if (!isInteractive()) {\n console.error(\n `[olakai] --tool not provided; defaulting to \"${DEFAULT_NON_INTERACTIVE_TOOL}\". This default will be removed in a future version — please pass --tool <tool> explicitly.`,\n );\n return DEFAULT_NON_INTERACTIVE_TOOL;\n }\n\n return promptForTool(context);\n}\n\nasync function promptForTool(\n context: \"init\" | \"status\" | \"disable\",\n): Promise<ToolId> {\n const plugins = listPlugins();\n const detected: ToolId[] = [];\n for (const p of plugins) {\n try {\n if (await p.detectInstalled()) detected.push(p.id);\n } catch {\n // detectInstalled is best-effort\n }\n }\n\n console.log(\"Which coding tool do you want to monitor?\");\n for (let i = 0; i < plugins.length; i++) {\n const p = plugins[i];\n const flag = detected.includes(p.id) ? \" (detected)\" : \"\";\n console.log(` ${i + 1}. ${p.displayName} [${p.id}]${flag}`);\n }\n\n const defaultIdx = plugins.findIndex((p) => detected.includes(p.id));\n const defaultLabel = defaultIdx >= 0 ? `${defaultIdx + 1}` : \"1\";\n const answer = await promptUser(\n `Select a tool to ${context} (1-${plugins.length}) [${defaultLabel}]: `,\n );\n\n const choice = answer.trim() === \"\" ? defaultLabel : answer.trim();\n const idx = parseInt(choice, 10) - 1;\n if (isNaN(idx) || idx < 0 || idx >= plugins.length) {\n console.error(\"Invalid selection.\");\n process.exit(1);\n }\n return plugins[idx].id;\n}\n\ninterface ToolFlag {\n tool?: string;\n}\n\nasync function initCommand(options: ToolFlag): Promise<void> {\n const toolId = await resolveToolFromOptions(options.tool, \"init\");\n const plugin = getPlugin(toolId);\n // Delegate to `runMonitorInstall` so this command and the chained\n // `olakai init` path go through exactly one install code path. Any\n // future cross-cutting addition (telemetry, validation, logging)\n // only needs to touch `src/monitor/install.ts`.\n await runPluginAction(plugin, () => runMonitorInstall(toolId, { interactive: true }));\n}\n\nasync function statusCommand(\n options: ToolFlag & { json?: boolean },\n): Promise<void> {\n const toolId = await resolveToolFromOptions(options.tool, \"status\");\n const plugin = getPlugin(toolId);\n\n if (options.json) {\n const report = await plugin.status({ projectRoot: process.cwd() });\n console.log(JSON.stringify(report, null, 2));\n return;\n }\n\n // For non-JSON Claude Code we keep the rich human formatter from\n // pre-Stage-2 (recent activity table). Other plugins ship their own\n // pretty printer in S3/S4; until then, surface their `notes` array\n // as one line per note so a user running `olakai monitor status\n // --tool codex` today sees the \"coming soon\" message rather than\n // raw JSON.\n if (plugin.id === \"claude-code\") {\n const { printClaudeCodeStatus } = await import(\n \"../monitor/plugins/claude-code/status.js\"\n );\n await printClaudeCodeStatus({ projectRoot: process.cwd() });\n return;\n }\n\n const report = await plugin.status({ projectRoot: process.cwd() });\n if (report.notes && report.notes.length > 0) {\n for (const note of report.notes) {\n console.log(note);\n }\n return;\n }\n // No notes to surface — fall through to JSON so the user sees\n // something rather than nothing.\n console.log(JSON.stringify(report, null, 2));\n}\n\nasync function disableCommand(\n options: ToolFlag & { keepConfig?: boolean; deleteAgent?: boolean },\n): Promise<void> {\n const toolId = await resolveToolFromOptions(options.tool, \"disable\");\n const plugin = getPlugin(toolId);\n\n // Capture the agent id BEFORE uninstall when the user asks to delete\n // the remote agent — uninstall removes the local monitor config, so\n // status() afterwards would have nothing to report. Errors here are\n // non-fatal: if status fails we still proceed with the local\n // uninstall and skip the remote delete.\n let agentIdToDelete: string | undefined;\n if (options.deleteAgent) {\n try {\n const report = await plugin.status({ projectRoot: process.cwd() });\n if (report.configured && report.agentId) {\n agentIdToDelete = report.agentId;\n } else {\n console.log(\n \"No monitor config found in this workspace — nothing to delete remotely.\",\n );\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.warn(\n `Couldn't read local monitor config to identify the agent (${msg}). Proceeding with local-only uninstall.`,\n );\n }\n }\n\n // Resolve the configured workspace root BEFORE uninstall so we can key\n // the registry removal even when `--keep-config` is absent (uninstall\n // deletes the config, after which the root is no longer discoverable).\n const registryRoot = findConfiguredWorkspace(process.cwd(), TOOL_IDS);\n\n await runPluginAction(plugin, () =>\n plugin.uninstall({\n projectRoot: process.cwd(),\n keepConfig: options.keepConfig,\n }),\n );\n\n // Drop the machine-registry entry (best-effort — the registry is an\n // index, not the source of truth). Only when the config is actually\n // gone; `--keep-config` leaves the workspace monitored.\n if (registryRoot && !options.keepConfig) {\n try {\n removeEntry(registryRoot, toolId);\n } catch {\n // Never let a registry write failure surface from disable.\n }\n }\n\n if (agentIdToDelete) {\n const { deleteAgent } = await import(\"../lib/api.js\");\n try {\n await deleteAgent(agentIdToDelete);\n console.log(`✓ Remote agent ${agentIdToDelete} deleted.`);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(\n `Local uninstall succeeded, but remote agent delete failed: ${msg}`,\n );\n console.error(\n `You can retry by visiting the Olakai dashboard, or rerun 'olakai monitor disable --tool ${toolId} --delete-agent' (the local config is gone, so the agent id won't be re-discovered — use the dashboard).`,\n );\n process.exit(1);\n }\n }\n}\n\n/**\n * `olakai monitor list [--json]` — the machine lens (D-001). Shows every\n * monitored (workspace, tool) recorded in `~/.olakai/registry.json`\n * across this whole machine, not just `process.cwd()` (which is all\n * `monitor status` sees).\n *\n * Adoption: we first reconcile the current workspace so installs that\n * predate the registry (config on disk, no registry entry) get backfilled\n * before we render — otherwise a user who upgraded the CLI would see an\n * empty list despite having monitoring configured here.\n */\nasync function listCommand(options: { json?: boolean }): Promise<void> {\n // Backfill the current workspace from disk if it's configured but\n // unregistered. Best-effort — never block the list on it.\n try {\n reconcileCurrentWorkspace(process.cwd());\n } catch {\n // reconcile is best-effort; fall through and render whatever the\n // registry already holds.\n }\n\n const registry = readRegistry();\n\n if (options.json) {\n console.log(JSON.stringify(registry.workspaces, null, 2));\n return;\n }\n\n console.log(formatRegistryTable(registry));\n}\n\n/**\n * `olakai monitor doctor [--tool X] [--all] [--fix] [--json]` (OLA-244,\n * S2). The end-to-end health check. Runs an ordered check chain per\n * (workspace, tool); `--fix` runs the registered repair for each fixable\n * failure. `--all` fans out across every registry entry on the machine.\n *\n * Tool resolution: `--all` ignores `--tool` (it iterates the registry).\n * Otherwise we resolve `--tool` the same way init/status/disable do —\n * prompting in interactive mode when omitted.\n */\nasync function doctorCommand(\n options: ToolFlag & {\n all?: boolean;\n fix?: boolean;\n json?: boolean;\n recreateMissing?: boolean;\n },\n): Promise<void> {\n const { runDoctor, printDoctorResult, exitCodeForStatus } = await import(\n \"../monitor/doctor.js\"\n );\n\n let tool: ToolId | undefined;\n if (!options.all) {\n tool = await resolveToolFromOptions(options.tool, \"status\");\n }\n\n const result = await runDoctor({\n tool,\n all: options.all,\n fix: options.fix,\n json: options.json,\n recreateMissing: options.recreateMissing,\n interactive: isInteractive(),\n });\n\n printDoctorResult(result, Boolean(options.json));\n process.exitCode = exitCodeForStatus(result.report.overall);\n}\n\n/**\n * `olakai monitor repair [--tool X] [--json]` (OLA-245, S3). The\n * forceful one-shot re-init for this workspace's monitoring. Unlike\n * `monitor doctor --fix` (which only repairs detected failures and gates\n * agent recreation behind `--recreate-missing`), `repair`:\n * - always forces an idempotent hook re-merge,\n * - WILL recreate a 404'd agent (preserving linkage otherwise),\n * - migrates a legacy config path if applicable,\n * then prints a before/after summary of what it changed.\n */\nasync function repairCommand(\n options: ToolFlag & { json?: boolean },\n): Promise<void> {\n const tool = await resolveToolFromOptions(options.tool, \"init\");\n\n const { runRepair, formatRepairResult, exitCodeForRepair } = await import(\n \"../monitor/repair.js\"\n );\n\n const result = await runRepair({\n tool,\n interactive: isInteractive(),\n });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(formatRepairResult(result));\n }\n process.exitCode = exitCodeForRepair(result);\n}\n\nasync function runPluginAction<T>(\n plugin: ToolMonitorPlugin,\n fn: () => Promise<T>,\n): Promise<T | void> {\n try {\n return await fn();\n } catch (err) {\n const e = err as Error;\n if (e.name === \"NotImplementedError\") {\n console.error(`${plugin.displayName}: ${e.message}`);\n process.exit(1);\n }\n throw err;\n }\n}\n\n/**\n * Fire-and-forget hook handler invoked by the tool's hook system. MUST\n * NOT produce stderr or exit non-zero — hook failures must never break\n * the host tool. `--tool` defaults to claude-code only when the flag\n * is *absent entirely* (back-compat with pre-Stage-2 hook commands\n * installed in existing workspaces' `.claude/settings.json`). When the\n * flag is present-but-invalid (typo like `--tool clade-code`), we\n * silent-exit rather than route to claude-code, to avoid silently\n * misrouting hooks for the wrong tool.\n */\nasync function hookCommand(\n event: string,\n options: ToolFlag,\n command: Command,\n): Promise<void> {\n try {\n // Distinguish \"flag absent\" from \"flag present but invalid\" via\n // Commander's `getOptionValueSource`. Source `undefined` means the\n // user didn't pass `--tool`; any other source means they did.\n const flagPresent =\n command.getOptionValueSource(\"tool\") !== undefined;\n\n let toolId: ToolId;\n if (flagPresent) {\n if (!options.tool || !isToolId(options.tool)) {\n // Invalid value supplied — silent-exit so hook failures don't\n // break the host tool. Debug-log so it's not totally invisible.\n debugInvalidToolFlag(options.tool, event);\n return;\n }\n toolId = options.tool;\n } else {\n toolId = \"claude-code\";\n }\n const plugin = getPlugin(toolId);\n\n const stdinData = await readStdin(3000);\n let payloadJson: unknown = {};\n if (stdinData) {\n try {\n payloadJson = JSON.parse(stdinData);\n } catch {\n // Plugins decide what to do with a bare event (the Claude Code\n // plugin silent-exits when transcript_path is missing).\n }\n }\n\n const result = await plugin.handleHook(event, payloadJson);\n if (!result) return;\n\n // The plugin already resolved workspace + transport inside\n // handleHook (where dedup/state writes happen). Use those values\n // directly — re-resolving here would race against `monitor disable`\n // and could disagree on CWD between the plugin and dispatcher.\n await postMonitoringPayload(result);\n } catch {\n // Silently swallow ALL errors. Hook failures must not break the\n // host tool.\n }\n}\n\nfunction debugInvalidToolFlag(\n value: string | undefined,\n event: string,\n): void {\n if (process.env.OLAKAI_MONITOR_DEBUG !== \"1\") return;\n try {\n // Mirror the claude-code plugin's debug-log location so users have\n // a single place to look for hook-path diagnostics.\n const logPath = `/tmp/olakai-monitor-debug-${process.pid}.log`;\n const line = `[${new Date().toISOString()}] hook-invalid-tool-flag: ${JSON.stringify(\n { event, tool: value ?? null },\n )}\\n`;\n fs.appendFileSync(logPath, line, \"utf-8\");\n } catch {\n // Ignore debug-log failures — never break the hook path.\n }\n}\n\nasync function postMonitoringPayload(result: HookResult): Promise<void> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 5000);\n const debug = process.env.OLAKAI_MONITOR_DEBUG === \"1\";\n const logPath = `/tmp/olakai-monitor-debug-${process.pid}.log`;\n const log = (event: string, data: unknown) => {\n if (!debug) return;\n try {\n fs.appendFileSync(\n logPath,\n `[${new Date().toISOString()}] dispatcher/${event}: ${JSON.stringify(data)}\\n`,\n \"utf-8\",\n );\n } catch {\n // Never let a debug-log failure break the hook path.\n }\n };\n try {\n log(\"posting\", {\n endpoint: result.transport.endpoint,\n apiKeyPresent: Boolean(result.transport.apiKey),\n apiKeyPrefix: result.transport.apiKey\n ? result.transport.apiKey.slice(0, 8) + \"...\"\n : null,\n bodyBytes: JSON.stringify([result.payload]).length,\n });\n const response = await fetch(result.transport.endpoint, {\n method: \"POST\",\n headers: {\n \"x-api-key\": result.transport.apiKey,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify([result.payload]),\n signal: controller.signal,\n });\n let bodyPreview: string | null = null;\n try {\n bodyPreview = (await response.text()).slice(0, 500);\n } catch {\n // Body read failures are not actionable here.\n }\n log(\"posted\", { status: response.status, bodyPreview });\n } catch (err) {\n log(\"post-error\", {\n name: err instanceof Error ? err.name : \"unknown\",\n message: err instanceof Error ? err.message : String(err),\n });\n throw err;\n } finally {\n clearTimeout(timeoutId);\n }\n}\n\nexport function registerMonitorCommand(program: Command): void {\n const monitor = program\n .command(\"monitor\")\n .description(\n \"Monitor local coding agents (Claude Code, Codex, Cursor) with Olakai\",\n );\n\n monitor\n .command(\"init\")\n .description(\"Set up Olakai monitoring for this workspace\")\n .option(\n \"--tool <tool>\",\n `Tool to configure (${TOOL_IDS.join(\"|\")}). Prompts when omitted in interactive mode.`,\n )\n .action(initCommand);\n\n monitor\n .command(\"hook <event>\")\n .description(\"Hook handler invoked by the tool's hook system (internal)\")\n .option(\n \"--tool <tool>\",\n `Tool whose hook is firing (defaults to claude-code for back-compat)`,\n )\n .action(hookCommand);\n\n monitor\n .command(\"status\")\n .description(\"Show monitoring status for this workspace\")\n .option(\n \"--tool <tool>\",\n `Tool to inspect (${TOOL_IDS.join(\"|\")}). Prompts when omitted in interactive mode.`,\n )\n .option(\"--json\", \"Output as JSON\")\n .action(statusCommand);\n\n monitor\n .command(\"list\")\n .description(\n \"List every workspace monitored on this machine (the machine lens)\",\n )\n .option(\"--json\", \"Output the raw registry entries as JSON\")\n .action(listCommand);\n\n monitor\n .command(\"doctor\")\n .description(\n \"Diagnose (and optionally repair) monitoring health for this workspace or the whole machine\",\n )\n .option(\n \"--tool <tool>\",\n `Tool to diagnose (${TOOL_IDS.join(\"|\")}). Prompts when omitted in interactive mode. Ignored with --all.`,\n )\n .option(\n \"--all\",\n \"Diagnose every workspace monitored on this machine (the machine lens), not just the current one\",\n )\n .option(\"--fix\", \"Attempt to repair fixable failures (idempotent, best-effort)\")\n .option(\n \"--recreate-missing\",\n \"With --fix, also recreate a self-monitor agent that no longer exists on the backend (provisions a NEW agent). Off by default; 'olakai monitor repair' is the heavier alternative.\",\n )\n .option(\"--json\", \"Output the structured diagnostic results as JSON\")\n .action(doctorCommand);\n\n monitor\n .command(\"repair\")\n .description(\n \"Forcefully re-initialize monitoring for this workspace (re-merge hooks, re-link/recreate the agent if needed) while preserving agent linkage\",\n )\n .option(\n \"--tool <tool>\",\n `Tool to repair (${TOOL_IDS.join(\"|\")}). Prompts when omitted in interactive mode.`,\n )\n .option(\"--json\", \"Output the structured repair result as JSON\")\n .action(repairCommand);\n\n monitor\n .command(\"disable\")\n .description(\"Remove Olakai monitoring from this workspace\")\n .option(\n \"--tool <tool>\",\n `Tool to disable (${TOOL_IDS.join(\"|\")}). Prompts when omitted in interactive mode.`,\n )\n .option(\n \"--keep-config\",\n \"Keep the monitor config file (only remove hooks)\",\n )\n .option(\n \"--delete-agent\",\n \"Also delete the remote agent on the Olakai backend. Useful when retiring a workspace permanently. Self-monitor owner or ADMIN only.\",\n )\n .action(disableCommand);\n\n // Allow plugins to register tool-specific subcommands (e.g. future\n // `olakai monitor claude-code transcript <path>`). Optional — most\n // plugins won't need this hook.\n for (const plugin of listPlugins()) {\n plugin.registerCommands?.(monitor);\n }\n}\n","/**\n * `olakai profiles ...` — AWS-style profile management.\n *\n * Subcommands:\n * - list Print all profiles, mark the active one\n * - use Set the registry default\n * - remove Delete a profile (refuses to remove the active default)\n * - current Show the resolved active profile\n */\n\nimport { Command } from \"commander\";\nimport { getBaseUrl } from \"../lib/config.js\";\nimport {\n readProfilesFile,\n removeProfile,\n resolveActiveProfile,\n resolveProfileName,\n setDefaultProfile,\n} from \"../lib/profiles.js\";\n\nfunction formatExpiry(expiresAt: number | undefined): string {\n if (typeof expiresAt !== \"number\") return \"no token\";\n const now = Math.floor(Date.now() / 1000);\n if (expiresAt <= now) return \"expired\";\n const seconds = expiresAt - now;\n const days = Math.floor(seconds / 86400);\n const hours = Math.floor((seconds % 86400) / 3600);\n if (days > 0) return `${days}d ${hours}h`;\n const minutes = Math.floor((seconds % 3600) / 60);\n if (hours > 0) return `${hours}h ${minutes}m`;\n return `${minutes}m`;\n}\n\nfunction maskToken(token: string | undefined): string {\n if (!token) return \"—\";\n if (token.length <= 8) return \"***\";\n return `${token.slice(0, 4)}…${token.slice(-4)}`;\n}\n\nfunction listAction(options: { json?: boolean }): void {\n const file = readProfilesFile();\n let resolved: { name: string } | null = null;\n try {\n resolved = resolveProfileName();\n } catch {\n resolved = null;\n }\n const activeName = resolved?.name ?? file.default;\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n default: file.default ?? null,\n active: activeName ?? null,\n profiles: Object.entries(file.profiles).map(([name, p]) => ({\n name,\n host: p.host,\n isDefault: file.default === name,\n isActive: activeName === name,\n email: p.email ?? null,\n accountId: p.accountId ?? null,\n expiresIn: p.expiresAt\n ? Math.max(0, p.expiresAt - Math.floor(Date.now() / 1000))\n : null,\n hasToken: Boolean(p.token),\n })),\n },\n null,\n 2,\n ),\n );\n return;\n }\n\n const names = Object.keys(file.profiles);\n if (names.length === 0) {\n console.log(\"No profiles configured. Run 'olakai login' to create one.\");\n return;\n }\n\n for (const name of names) {\n const p = file.profiles[name];\n if (!p) continue;\n const markers: string[] = [];\n if (file.default === name) markers.push(\"default\");\n if (activeName === name) markers.push(\"active\");\n const label = markers.length > 0 ? ` (${markers.join(\", \")})` : \"\";\n const expiry = formatExpiry(p.expiresAt);\n const email = p.email ? ` — ${p.email}` : \"\";\n console.log(`* ${name}${label}`);\n console.log(` host: ${p.host}`);\n console.log(` token: ${maskToken(p.token)} (${expiry})${email}`);\n }\n}\n\nfunction useAction(name: string): void {\n try {\n setDefaultProfile(name);\n console.log(`Default profile is now: ${name}`);\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\nfunction removeAction(name: string): void {\n try {\n removeProfile(name);\n console.log(`Removed profile: ${name}`);\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\nfunction currentAction(options: { json?: boolean }): void {\n let active;\n try {\n active = resolveActiveProfile();\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n if (!active) {\n if (options.json) {\n console.log(JSON.stringify({ active: null }, null, 2));\n } else {\n console.log(\"No profile configured. Run 'olakai login' to create one.\");\n }\n return;\n }\n\n // The \"effective\" host is what `getBaseUrl()` actually returns\n // (factoring in --host / OLAKAI_HOST overrides). The profile's\n // stored host is shown separately so the user can see when an\n // override is in effect.\n const effectiveHost = getBaseUrl();\n const overridden = effectiveHost !== active.host;\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n name: active.name,\n host: effectiveHost,\n profileHost: active.host,\n source: active.source,\n hostFromWorkspaceConfig: active.hostFromWorkspaceConfig,\n hostOverridden: overridden,\n email: active.profile.email ?? null,\n accountId: active.profile.accountId ?? null,\n hasToken: Boolean(active.profile.token),\n expiresAt: active.profile.expiresAt ?? null,\n expiresIn: active.profile.expiresAt\n ? Math.max(\n 0,\n active.profile.expiresAt - Math.floor(Date.now() / 1000),\n )\n : null,\n },\n null,\n 2,\n ),\n );\n return;\n }\n\n console.log(`Profile: ${active.name} (from ${active.source})`);\n if (overridden) {\n console.log(`Host: ${effectiveHost} (overrides profile host)`);\n console.log(`Profile host: ${active.host}`);\n } else if (active.hostFromWorkspaceConfig) {\n console.log(`Host: ${active.host} (from workspace config)`);\n } else {\n console.log(`Host: ${active.host}`);\n }\n if (active.profile.email) {\n console.log(`Email: ${active.profile.email}`);\n }\n if (active.profile.accountId) {\n console.log(`Account ID: ${active.profile.accountId}`);\n }\n console.log(`Token: ${maskToken(active.profile.token)}`);\n console.log(`Expires in: ${formatExpiry(active.profile.expiresAt)}`);\n}\n\nexport function registerProfilesCommand(program: Command): void {\n const profiles = program\n .command(\"profiles\")\n .description(\"Manage Olakai authentication profiles (AWS-style)\");\n\n profiles\n .command(\"list\")\n .description(\"List all configured profiles\")\n .option(\"--json\", \"Output as JSON\")\n .action((options: { json?: boolean }) => {\n listAction(options);\n });\n\n profiles\n .command(\"use <name>\")\n .description(\"Set <name> as the default profile\")\n .action((name: string) => {\n useAction(name);\n });\n\n profiles\n .command(\"remove <name>\")\n .description(\"Remove a profile (refuses to remove the active default)\")\n .action((name: string) => {\n removeAction(name);\n });\n\n profiles\n .command(\"current\")\n .description(\"Print the active profile (resolved from flag/env/workspace/default)\")\n .option(\"--json\", \"Output as JSON\")\n .action((options: { json?: boolean }) => {\n currentAction(options);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,qBA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C3D,OAAO,YAAY;AAEtB,QACG,QAAQ,QAAQ,EAChB,YAAY,qBAAqB,EACjC,OAAO,aAAa;AAEvB,QACG,QAAQ,QAAQ,EAChB,YAAY,6BAA6B,EACzC,OAAO,aAAa;AAGvB,sBAAsB,OAAO;AAC7B,yBAAyB,OAAO;AAChC,oBAAoB,OAAO;AAC3B,0BAA0B,OAAO;AAGjC,wBAAwB,OAAO;AAG/B,uBAAuB,OAAO;AAG9B,wBAAwB,OAAO;AAE/B,QAAQ,MAAM;","names":["open","open","program","listCommand","getCommand","createCommand","updateCommand","deleteCommand","program","listCommand","getCommand","createCommand","updateCommand","deleteCommand","program","listCommand","getCommand","createCommand","updateCommand","deleteCommand","program","listCommand","getCommand","program","fs","initCommand","report","deleteAgent","listCommand","program","formatExpiry","program","require"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/whoami.ts","../src/commands/init.ts","../src/lib/handshake.ts","../src/monitor/detect-all.ts","../src/lib/branding.ts","../src/commands/agents.ts","../src/commands/workflows.ts","../src/commands/kpis.ts","../src/commands/custom-data.ts","../src/commands/activity.ts","../src/commands/monitor.ts","../src/commands/profiles.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { createRequire } from \"module\";\nimport { Command } from \"commander\";\nimport { loginCommand } from \"./commands/login.js\";\nimport { logoutCommand } from \"./commands/logout.js\";\nimport { whoamiCommand } from \"./commands/whoami.js\";\nimport { initCommand, type InitCommandOptions } from \"./commands/init.js\";\nimport { registerAgentsCommand } from \"./commands/agents.js\";\nimport { registerWorkflowsCommand } from \"./commands/workflows.js\";\nimport { registerKpisCommand } from \"./commands/kpis.js\";\nimport { registerCustomDataCommand } from \"./commands/custom-data.js\";\nimport { registerActivityCommand } from \"./commands/activity.js\";\nimport { registerMonitorCommand } from \"./commands/monitor.js\";\nimport { registerProfilesCommand } from \"./commands/profiles.js\";\nimport {\n setEnvironment,\n setHostOverride,\n isValidEnvironment,\n getValidEnvironments,\n type Environment,\n} from \"./lib/config.js\";\nimport { setProfileOverride } from \"./lib/profiles.js\";\n\nconst require = createRequire(import.meta.url);\nconst packageJson = require(\"../package.json\") as { version: string };\n\nconst program = new Command();\n\nprogram\n .name(\"olakai\")\n .description(\"Olakai CLI tool\")\n .version(packageJson.version)\n .option(\n \"-e, --env <environment>\",\n `Environment to use (${getValidEnvironments().join(\", \")})`,\n \"production\",\n )\n .option(\n \"--host <host>\",\n \"On-prem Olakai host (e.g. olakai.acme.com). Overrides --env and OLAKAI_HOST.\",\n )\n .option(\n \"--profile <name>\",\n \"Olakai profile to use (overrides OLAKAI_PROFILE, workspace config, and registry default).\",\n )\n .hook(\"preAction\", (thisCommand) => {\n const options = thisCommand.opts();\n if (options.env) {\n if (!isValidEnvironment(options.env)) {\n console.error(\n `Invalid environment: ${options.env}. Valid options: ${getValidEnvironments().join(\", \")}`,\n );\n process.exit(1);\n }\n setEnvironment(options.env as Environment);\n }\n if (typeof options.host === \"string\" && options.host.length > 0) {\n setHostOverride(options.host);\n }\n if (typeof options.profile === \"string\" && options.profile.length > 0) {\n setProfileOverride(options.profile);\n }\n });\n\nprogram\n .command(\"init\")\n .description(\n \"Interactive self-onboarding wizard: pick host, verify email, get a CLI token.\",\n )\n .option(\"--email <email>\", \"Pre-fill the email (skips the email prompt)\")\n .option(\n \"--non-interactive\",\n \"Fail fast on any missing required input (no prompts).\",\n )\n .option(\n \"--skip-monitor\",\n \"Skip the optional 'olakai monitor init' handoff at the end.\",\n )\n .action((options: InitCommandOptions) => initCommand(options));\n\nprogram\n .command(\"login\")\n .description(\"Log in to Olakai using browser authentication\")\n .action(loginCommand);\n\nprogram\n .command(\"logout\")\n .description(\"Log out from Olakai\")\n .action(logoutCommand);\n\nprogram\n .command(\"whoami\")\n .description(\"Show current logged-in user\")\n .action(whoamiCommand);\n\n// Register subcommands for config management\nregisterAgentsCommand(program);\nregisterWorkflowsCommand(program);\nregisterKpisCommand(program);\nregisterCustomDataCommand(program);\n\n// Register subcommands for activity inspection\nregisterActivityCommand(program);\n\n// Register subcommands for local agent monitoring\nregisterMonitorCommand(program);\n\n// Register subcommands for AWS-style profile management\nregisterProfilesCommand(program);\n\nprogram.parse();\n","import open from \"open\";\nimport { requestDeviceCode, pollForToken, getCurrentUser } from \"../lib/api.js\";\nimport { saveToken, isTokenValid } from \"../lib/auth.js\";\nimport { getBaseUrl, getEnvironment } from \"../lib/config.js\";\nimport { patchProfile, resolveProfileName } from \"../lib/profiles.js\";\n\nconst POLL_INTERVAL_MS = 5000; // 5 seconds\n\n/**\n * Login command handler\n */\nexport async function loginCommand(): Promise<void> {\n // Check if already logged in\n if (isTokenValid()) {\n try {\n const user = await getCurrentUser();\n console.log(`Already logged in as ${user.email}`);\n console.log(\"Run 'olakai logout' to log out first.\");\n return;\n } catch {\n // Token is invalid, continue with login\n }\n }\n\n const resolved = resolveProfileName();\n const profileName = resolved?.name ?? \"default\";\n console.log(\n `Logging in to Olakai (profile: ${profileName}, host: ${getBaseUrl()}, env: ${getEnvironment()})...\\n`,\n );\n\n try {\n // Request device code\n const deviceCode = await requestDeviceCode();\n\n // Display instructions\n console.log(\"To complete login, visit:\");\n console.log(`\\n ${deviceCode.verification_uri_complete}\\n`);\n console.log(`Or go to ${deviceCode.verification_uri} and enter code:`);\n console.log(`\\n ${deviceCode.user_code}\\n`);\n\n // Try to open browser\n console.log(\"Opening browser...\");\n try {\n await open(deviceCode.verification_uri_complete);\n } catch {\n console.log(\"(Could not open browser automatically)\");\n }\n\n console.log(\"\\nWaiting for authorization...\");\n\n // Poll for token\n const expiresAt = Date.now() + deviceCode.expires_in * 1000;\n\n while (Date.now() < expiresAt) {\n await sleep(POLL_INTERVAL_MS);\n\n try {\n const tokenResponse = await pollForToken(deviceCode.device_code);\n\n if (tokenResponse) {\n // Save token (lands in the active profile, or \"default\" if\n // no profile was explicitly selected).\n saveToken(tokenResponse.access_token, tokenResponse.expires_in);\n\n // Get user info and cache identifiers on the profile so\n // offline `whoami` still has something to show.\n const user = await getCurrentUser();\n try {\n patchProfile(profileName, {\n email: user.email,\n userId: user.id,\n accountId: user.accountId,\n });\n } catch {\n // best-effort\n }\n\n console.log(`\\nLogged in as ${user.email}`);\n console.log(`Profile: ${profileName}`);\n console.log(`Account: ${user.accountId}`);\n console.log(`Role: ${user.role}`);\n return;\n }\n\n // Still pending, show spinner\n process.stdout.write(\".\");\n } catch (error) {\n if (error instanceof Error) {\n console.error(`\\nLogin failed: ${error.message}`);\n } else {\n console.error(\"\\nLogin failed: Unknown error\");\n }\n process.exit(1);\n }\n }\n\n console.error(\"\\nLogin timed out. Please try again.\");\n process.exit(1);\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Login failed: ${error.message}`);\n } else {\n console.error(\"Login failed: Unknown error\");\n }\n process.exit(1);\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import { clearToken, isTokenValid } from \"../lib/auth.js\";\n\n/**\n * Logout command handler\n */\nexport function logoutCommand(): void {\n if (!isTokenValid()) {\n console.log(\"Not currently logged in.\");\n return;\n }\n\n clearToken();\n console.log(\"Logged out successfully.\");\n}\n","import { getCurrentUser } from \"../lib/api.js\";\nimport { isTokenValid, loadToken } from \"../lib/auth.js\";\nimport { getBaseUrl, getEnvironment } from \"../lib/config.js\";\nimport { patchProfile, resolveActiveProfile } from \"../lib/profiles.js\";\n\nfunction formatExpiry(expiresAt: number | undefined): string {\n if (typeof expiresAt !== \"number\") return \"no token\";\n const now = Math.floor(Date.now() / 1000);\n if (expiresAt <= now) return \"expired\";\n const seconds = expiresAt - now;\n const days = Math.floor(seconds / 86400);\n const hours = Math.floor((seconds % 86400) / 3600);\n if (days > 0) return `${days}d ${hours}h`;\n const minutes = Math.floor((seconds % 3600) / 60);\n if (hours > 0) return `${hours}h ${minutes}m`;\n return `${minutes}m`;\n}\n\n/**\n * Whoami command handler.\n *\n * Prints the active profile, host, user identity (email + name +\n * account), and token expiry. Falls back gracefully when individual\n * fields aren't available (e.g. unauthenticated, or the backend is\n * unreachable but a profile is configured locally).\n */\nexport async function whoamiCommand(): Promise<void> {\n let active;\n try {\n active = resolveActiveProfile();\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n\n // Always print the resolved local view first — works even when\n // unauthenticated.\n if (active) {\n const effectiveHost = getBaseUrl();\n console.log(`Profile: ${active.name} (from ${active.source})`);\n if (effectiveHost !== active.host) {\n console.log(`Host: ${effectiveHost} (overrides profile host)`);\n console.log(`Profile host: ${active.host}`);\n } else if (active.hostFromWorkspaceConfig) {\n console.log(`Host: ${active.host} (from workspace config)`);\n } else {\n console.log(`Host: ${active.host}`);\n }\n } else {\n // \"Not logged in\" is an error state — write to stderr so scripts\n // that pipe `whoami` to grep / jq don't catch this in their stdout.\n console.error(`Profile: (none)`);\n console.error(`Host: ${getBaseUrl()}`);\n console.error(`Environment: ${getEnvironment()}`);\n console.error(\"Not logged in. Run 'olakai login' to authenticate.\");\n process.exit(1);\n }\n\n if (!isTokenValid()) {\n const creds = loadToken();\n console.log(`Token: ${creds ? \"expired\" : \"missing\"}`);\n console.log(\"Not logged in. Run 'olakai login' to authenticate.\");\n process.exit(1);\n }\n\n try {\n const user = await getCurrentUser();\n\n // Backfill cached identifiers so subsequent `profiles list` /\n // `whoami` (and future offline commands) can display them without\n // a network round-trip. Best-effort: any failure is swallowed.\n try {\n patchProfile(active.name, {\n email: user.email,\n userId: user.id,\n accountId: user.accountId,\n });\n } catch {\n // ignore\n }\n\n console.log(`Email: ${user.email}`);\n console.log(`Name: ${user.firstName} ${user.lastName}`);\n console.log(`Role: ${user.role}`);\n console.log(`Account ID: ${user.accountId}`);\n console.log(\n `Token: valid (expires in ${formatExpiry(active.profile.expiresAt)})`,\n );\n } catch (error) {\n // Fall back to cached identifiers when the backend is unreachable\n // but we still have a valid local token.\n if (active.profile.email) {\n console.log(`Email: ${active.profile.email} (cached)`);\n }\n if (active.profile.accountId) {\n console.log(`Account ID: ${active.profile.accountId} (cached)`);\n }\n console.log(\n `Token: valid (expires in ${formatExpiry(active.profile.expiresAt)})`,\n );\n if (error instanceof Error) {\n console.error(`Warning: could not contact Olakai backend: ${error.message}`);\n } else {\n console.error(\"Warning: could not contact Olakai backend\");\n }\n }\n}\n","/**\n * `olakai init` — the self-onboarding wizard (OLA-212).\n *\n * Flow at a glance:\n *\n * 1. Resolve the target profile name. If it already holds a valid\n * token, offer an early exit (\"already authenticated\").\n * 2. Pick a host: `--host`/env > existing profile host > interactive\n * menu (production / staging / on-prem custom).\n * 3. Collect the user's email.\n * 4. POST /api/cli/handshake. Branch on the response:\n * - device-flow → hand off to the existing `loginCommand`\n * (same device-flow used by `olakai login`; we DO NOT\n * duplicate that flow here).\n * - OTP → enter the OTP loop (verify → exchange).\n * - signup → open browser + ask user to re-run.\n * - blocked → fail with a clear admin-action message.\n * 5. On OTP success: exchange the consent token for the 30-day\n * bearer, persist it to the active profile via `saveToken`.\n * 6. Offer monitor setup. Actually chaining into `olakai monitor`\n * is owned by S5 (OLA-214); for now we just print the one-liner.\n *\n * Non-interactive mode (`--non-interactive`) fails fast on any prompt\n * the user could have answered via flag/env. That makes the wizard\n * safe to call from automation (e.g. CI bootstrapping a profile from\n * a service account email).\n */\n\nimport open from \"open\";\nimport {\n postHandshake,\n postHandshakeExchange,\n postHandshakeVerify,\n} from \"../lib/handshake.js\";\nimport { loginCommand } from \"./login.js\";\nimport { saveToken, isTokenValid } from \"../lib/auth.js\";\nimport { getBaseUrl, setHostOverride } from \"../lib/config.js\";\nimport {\n HOSTS,\n patchProfile,\n readProfilesFile,\n resolveProfileName,\n} from \"../lib/profiles.js\";\nimport { promptUser, isInteractive } from \"../monitor/prompt.js\";\nimport { detectInstalledTools } from \"../monitor/detect-all.js\";\nimport { runMonitorInstall } from \"../monitor/install.js\";\nimport {\n formatExistingUserBrowserGreeting,\n printLogoHeader,\n} from \"../lib/branding.js\";\n\nexport interface InitCommandOptions {\n email?: string;\n host?: string;\n /** Identical to the global `--profile` flag; commander passes it through. */\n profile?: string;\n nonInteractive?: boolean;\n skipMonitor?: boolean;\n}\n\n/**\n * The most permissive RFC-5322-ish email check the CLI is comfortable\n * shipping. Backend does the real validation; this is just enough to\n * stop obviously-broken input from costing the user a network round\n * trip.\n */\nconst EMAIL_REGEX = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst OTP_REGEX = /^\\d{6}$/;\nconst PRESET_HOSTS: ReadonlyArray<{ label: string; url: string }> = [\n { label: \"production (app.olakai.ai)\", url: HOSTS.production },\n { label: \"staging (staging.app.olakai.ai)\", url: HOSTS.staging },\n];\n\nexport async function initCommand(options: InitCommandOptions): Promise<void> {\n const interactive = !options.nonInteractive && isInteractive();\n\n // Logo + tagline at the very top of the interactive flow. Suppressed\n // by `printLogoHeader` itself when stdout isn't a TTY so CI runs and\n // piped output stay clean.\n if (interactive) {\n printLogoHeader();\n }\n\n try {\n // 1. Resolve the profile we'll be writing to. `resolveProfileName`\n // is the lenient resolver — it never throws, and may return null\n // if no registry exists yet (fresh install).\n const resolved = resolveProfileName();\n const profileName = resolved?.name ?? \"default\";\n\n // 2. Early-exit / re-auth check FIRST (before host resolution).\n //\n // We must run this before `resolveHost` so the user's choice\n // (\"Re-authenticate? [y/N]\") can influence host resolution. The\n // previous order resolved the host first, which silently locked in\n // the stored host whenever the token was still valid — leaving no\n // path to switch workspaces (e.g. staging → production) without\n // first running `olakai logout`.\n //\n // The prompt references the *stored* host (the workspace the\n // current token authenticates against), not a freshly-picked one.\n let optedReAuth = false;\n if (isTokenValid()) {\n const file = readProfilesFile();\n const existing = file.profiles[profileName];\n const who = existing?.email ?? \"unknown\";\n const where = existing?.host ?? \"(unknown host)\";\n if (options.nonInteractive) {\n // Non-interactive: idempotent no-op. Don't surprise scripts.\n console.log(\n `Already authenticated as ${who} on ${where} (profile: ${profileName}).`,\n );\n return;\n }\n const answer = await promptUser(\n `Already authenticated as ${who} on ${where} (profile: ${profileName}). Re-authenticate? [y/N]: `,\n );\n if (answer.trim().toLowerCase() !== \"y\") {\n console.log(\n \"Keeping existing credentials. Run 'olakai logout' to sign out.\",\n );\n return;\n }\n optedReAuth = true;\n }\n\n // 3. Resolve the host. CLI flag (already handled by the global\n // preAction hook) wins via getBaseUrl(). Otherwise prefer the\n // profile's stored host — but offer a switch prompt when the\n // user is actively re-authenticating (post-logout OR via the\n // \"Re-authenticate? [y]\" path above).\n const host = await resolveHost(\n profileName,\n options,\n interactive,\n optedReAuth,\n );\n // Apply the host so all subsequent `getBaseUrl()` calls (incl. the\n // handshake client) point at the right backend.\n setHostOverride(host);\n\n // 4. Email.\n const email = await resolveEmail(options, interactive);\n\n console.log(`\\nContacting ${host} for ${email}...`);\n\n // 5. Handshake. One retry on transient network failures (per\n // spec) — only `network_error`, never 4xx/5xx, which carry\n // semantic meaning the wizard must surface unchanged.\n let handshake = await postHandshake({ email, host });\n if (handshake.kind === \"error\" && handshake.code === \"network_error\") {\n console.log(\"(Network error contacting Olakai — retrying once...)\");\n handshake = await postHandshake({ email, host });\n }\n if (handshake.kind === \"error\") {\n handleHandshakeError(handshake);\n return;\n }\n\n const response = handshake.data;\n\n switch (response.status) {\n case \"user_exists\":\n if (\"deviceFlowOk\" in response && response.deviceFlowOk === true) {\n // Existing non-EMPLOYEE user → existing device-flow login.\n // Reuse `loginCommand` verbatim so there's exactly one\n // device-flow code path in the CLI.\n //\n // Pre-browser greeting (OLA-226): the prior one-liner read as\n // unexplained friction to admins evaluating Olakai (Xavier\n // session, 2026-05-14). Surface that we identified the user,\n // explain the role-tier reason for the browser step, and\n // make the contrast with the Employee-role OTP path explicit\n // so admins don't generalize the friction to their team.\n console.log(\"\");\n console.log(formatExistingUserBrowserGreeting(email));\n if (interactive) {\n // Press-Enter gate. The user has read the message; opening\n // the browser without acknowledgement felt abrupt during\n // Xavier's evaluation. Ctrl-C still bails as expected.\n await promptUser(\n \"\\n > Press Enter to open your browser, or Ctrl-C to cancel: \",\n );\n }\n console.log(\"\");\n await loginCommand();\n await offerMonitorSetup(options, interactive);\n return;\n }\n // EMPLOYEE refresh path: OTP. Narrow via the OTP-branch shape.\n if (\"otpSent\" in response && response.otpSent === true) {\n await runOtpFlow(email, profileName, {\n emailObfuscated: response.emailObfuscated,\n expiresIn: response.expiresIn,\n });\n await offerMonitorSetup(options, interactive);\n return;\n }\n // Defensive fallback — the backend returned `user_exists`\n // without the expected discriminator. Surface clearly instead\n // of silently hanging.\n console.error(\n \"Unexpected handshake response: 'user_exists' without device-flow or OTP signal.\",\n );\n process.exit(1);\n return;\n\n case \"domain_claimed\":\n await runOtpFlow(email, profileName, {\n emailObfuscated: response.emailObfuscated,\n expiresIn: response.expiresIn,\n });\n await offerMonitorSetup(options, interactive);\n return;\n\n case \"saas_can_self_signup\": {\n console.log(\n \"\\nWe don't have you yet. Opening your browser to create an account...\",\n );\n // BLOCKING from pre-PR review: validate the URL scheme before\n // handing it to the platform opener. A compromised or\n // misconfigured backend could otherwise return `file://`,\n // `javascript:`, `vscode://`, `ssh://`, etc. — anything the\n // OS opener accepts. Defense-in-depth: only http/https.\n if (isSafeOpenUrl(response.signupUrl)) {\n try {\n await open(response.signupUrl);\n } catch {\n console.log(\n `(Could not open browser automatically. Visit ${response.signupUrl})`,\n );\n }\n } else {\n console.log(\n `(Server returned an unexpected signup URL scheme. Visit ${response.signupUrl} manually in your browser.)`,\n );\n }\n console.log(\n \"When done, re-run 'olakai init' to finish authenticating this CLI.\",\n );\n return;\n }\n\n case \"blocked\": {\n const domain = email.split(\"@\")[1] ?? email;\n console.error(\n `\\nYour domain \"${domain}\" isn't connected to an Olakai workspace.`,\n );\n if (response.message) {\n console.error(response.message);\n }\n console.error(\"Ask your admin to claim it, then re-run 'olakai init'.\");\n process.exit(1);\n }\n }\n } catch (err) {\n if (err instanceof InitAbortedError) {\n if (err.message) console.error(err.message);\n process.exit(err.exitCode);\n }\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\n/**\n * Allow only `http:` / `https:` schemes for any URL we hand to the\n * platform opener (`open`). The OS opener accepts `file:`, `mailto:`,\n * `vscode://`, `ssh://`, custom URL handlers, etc. — none of which a\n * trustworthy handshake response should ever return. Falling through to\n * a manual copy/paste message is the safe degradation.\n */\nfunction isSafeOpenUrl(raw: string): boolean {\n try {\n const url = new URL(raw);\n return url.protocol === \"http:\" || url.protocol === \"https:\";\n } catch {\n return false;\n }\n}\n\n// ---- host selection --------------------------------------------------------\n\nasync function resolveHost(\n profileName: string,\n options: InitCommandOptions,\n interactive: boolean,\n forceHostPrompt = false,\n): Promise<string> {\n // `getBaseUrl()` already applies `--host`/OLAKAI_HOST overrides set\n // by the global preAction hook. If either is in effect, that's the\n // host we use. If neither is in effect, the lenient resolver in\n // `getBaseUrl()` may still return the profile's stored host — that's\n // also fine.\n //\n // Precedence per CLAUDE.md: `--host` flag wins over `OLAKAI_HOST`\n // env (the flag is the more explicit signal). Practically a no-op\n // today because `preAction` already pushed both into `getBaseUrl()`,\n // but checking the flag first keeps this in lockstep with the\n // documented resolution order so a future refactor can't drift.\n const fromFlag = options.host?.trim() || process.env.OLAKAI_HOST?.trim();\n if (fromFlag) {\n return getBaseUrl();\n }\n\n // If the profile already has a host, prefer it — but offer an\n // override path for interactive users with no valid token (OLA-229).\n //\n // The stored host survives `olakai logout` (which only clears\n // `token` + `expiresAt`, see `profiles.ts`), so a user who logged\n // out specifically to switch workspaces would otherwise be quietly\n // routed back to the same one. Silent prefer is right for:\n // - non-interactive runs (CI / scripts)\n // - re-runs with a still-valid token (the user opted into\n // re-auth via the early-exit prompt; they're keeping the\n // current workspace)\n // Re-prompt is right when interactive AND there's no valid token —\n // the user is actively re-authenticating from a logged-out state\n // and might be switching contexts.\n const file = readProfilesFile();\n const existing = file.profiles[profileName];\n if (existing?.host) {\n // Offer a workspace-switch prompt when either:\n // - the user is post-logout (no valid token; OLA-229), OR\n // - the user explicitly opted to re-authenticate via the\n // valid-token early-exit prompt in `initCommand`\n // (`forceHostPrompt`).\n // Otherwise the stored host is silently reused (idempotent\n // re-runs, non-interactive scripts).\n const shouldOfferSwitch =\n interactive && (forceHostPrompt || !isTokenValid());\n if (!shouldOfferSwitch) {\n return existing.host;\n }\n const keep = await promptUser(\n `\\nConnect to ${existing.host}? [Y/n] (or pick a different domain such as on-prem): `,\n );\n if (keep.trim().toLowerCase() !== \"n\") {\n return existing.host;\n }\n // Fall through to the picker below.\n console.log(\"\");\n }\n\n if (!interactive) {\n throw new InitAbortedError(\n \"No host configured. Pass --host or set OLAKAI_HOST in non-interactive mode.\",\n );\n }\n\n // Interactive picker.\n console.log(\"\\nWhich Olakai workspace are you connecting to?\");\n for (let i = 0; i < PRESET_HOSTS.length; i += 1) {\n const entry = PRESET_HOSTS[i]!;\n console.log(` ${i + 1}) ${entry.label}`);\n }\n console.log(` ${PRESET_HOSTS.length + 1}) Custom (on-prem)`);\n\n const choice = await promptUser(`Choose [1-${PRESET_HOSTS.length + 1}]: `);\n const idx = Number.parseInt(choice.trim(), 10);\n if (idx >= 1 && idx <= PRESET_HOSTS.length) {\n return PRESET_HOSTS[idx - 1]!.url;\n }\n if (idx === PRESET_HOSTS.length + 1) {\n return promptForCustomHost();\n }\n console.error(\n \"Invalid choice. Re-run 'olakai init' and pick a valid option.\",\n );\n throw new InitAbortedError(\"\", 1);\n}\n\nasync function promptForCustomHost(): Promise<string> {\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const raw = await promptUser(\n \"On-prem URL or hostname (e.g. olakai.acme.com): \",\n );\n const normalized = normalizeHost(raw.trim());\n if (normalized) {\n return normalized;\n }\n console.log(\"That doesn't look like a valid host. Try again.\");\n }\n throw new InitAbortedError(\"Too many invalid host entries.\", 1);\n}\n\nfunction normalizeHost(value: string): string | null {\n if (!value) return null;\n // Allow bare hostnames; require at least one dot OR `localhost`.\n // Anything else is almost certainly a typo.\n const withScheme = /^https?:\\/\\//i.test(value) ? value : `https://${value}`;\n let url: URL;\n try {\n url = new URL(withScheme);\n } catch {\n return null;\n }\n if (!url.hostname) return null;\n if (!url.hostname.includes(\".\") && url.hostname !== \"localhost\") {\n return null;\n }\n return `${url.protocol}//${url.host}`.replace(/\\/+$/, \"\");\n}\n\n// ---- email collection ------------------------------------------------------\n\nasync function resolveEmail(\n options: InitCommandOptions,\n interactive: boolean,\n): Promise<string> {\n if (options.email) {\n const trimmed = options.email.trim();\n if (!EMAIL_REGEX.test(trimmed)) {\n throw new InitAbortedError(\n `Invalid email: \"${options.email}\". Re-run with a well-formed --email.`,\n );\n }\n return trimmed;\n }\n if (!interactive) {\n throw new InitAbortedError(\n \"Missing --email in non-interactive mode. Pass --email <you@company.com>.\",\n );\n }\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const raw = await promptUser(\"Enter your primary work email address: \");\n const trimmed = raw.trim();\n if (EMAIL_REGEX.test(trimmed)) {\n return trimmed;\n }\n console.log(\"That doesn't look like a valid email. Try again.\");\n }\n throw new InitAbortedError(\"Too many invalid email entries.\", 1);\n}\n\n// ---- OTP loop --------------------------------------------------------------\n\ninterface OtpContext {\n emailObfuscated: string;\n expiresIn: number;\n}\n\nasync function runOtpFlow(\n email: string,\n profileName: string,\n ctx: OtpContext,\n): Promise<void> {\n const expiryMin = Math.max(1, Math.round(ctx.expiresIn / 60));\n console.log(\n `\\nWe sent a 6-digit code to your email ${ctx.emailObfuscated} (expires in ${expiryMin} min).`,\n );\n\n // The OTP loop terminates on:\n // - verify success → break and exchange\n // - locked / no_code → exit 1\n // - expired → restart handshake (caller's responsibility — we\n // surface a clear message and exit 1, instructing the user to\n // re-run init; that's strictly simpler than re-driving the\n // handshake mid-loop, and matches the wording in the spec)\n for (;;) {\n const code = await promptUser(\n \"Please enter the 6-digit code you received: \",\n );\n const trimmed = code.trim();\n if (!OTP_REGEX.test(trimmed)) {\n console.log(\"Codes are 6 digits. Try again.\");\n continue;\n }\n // One-shot retry on transient network failure. Same shape as the\n // existing handshake retry — `verify` is idempotent on the wire\n // (no state change unless the request reaches the server and\n // decodes), so retrying a connection-level failure is safe. The\n // rare race where the server consumed an OTP attempt but the\n // response was lost trades one attempt-counter slot for not\n // aborting the whole flow on a TLS hiccup — favorable trade given\n // the 5-attempt lockout budget.\n let result = await postHandshakeVerify({ email, code: trimmed });\n if (result.kind === \"error\" && result.code === \"network_error\") {\n console.log(\"(Network error verifying code — retrying once...)\");\n result = await postHandshakeVerify({ email, code: trimmed });\n }\n if (result.kind === \"ok\") {\n const consentToken = result.data.consentToken;\n await runExchange(consentToken, profileName, email);\n return;\n }\n\n switch (result.code) {\n case \"invalid_code\": {\n const remaining = result.detail?.attemptsRemaining;\n const tail =\n typeof remaining === \"number\"\n ? ` ${remaining} attempt${remaining === 1 ? \"\" : \"s\"} remaining.`\n : \"\";\n console.log(`Wrong code.${tail}`);\n continue;\n }\n case \"locked\":\n console.error(\n \"Too many attempts. Request a fresh code by re-running 'olakai init'.\",\n );\n throw new InitAbortedError(\"\", 1);\n case \"expired\":\n console.error(\n \"Code expired. Re-run 'olakai init' to request a new one.\",\n );\n throw new InitAbortedError(\"\", 1);\n case \"no_code\":\n console.error(\n \"No live code for this email. Run 'olakai init' again to request one.\",\n );\n throw new InitAbortedError(\"\", 1);\n case \"rate_limited\": {\n const wait = result.retryAfter\n ? ` Retry in ${result.retryAfter}s.`\n : \"\";\n console.error(`Rate limit hit while verifying.${wait}`);\n throw new InitAbortedError(\"\", 1);\n }\n case \"service_unavailable\":\n console.error(\n \"Olakai is temporarily unavailable. Try again in a minute.\",\n );\n throw new InitAbortedError(\"\", 1);\n case \"network_error\":\n console.error(\n `Network error${result.causeCode ? ` (${result.causeCode})` : \"\"}: ${result.message}`,\n );\n throw new InitAbortedError(\"\", 1);\n default:\n console.error(\n `Verification failed (${result.code}): ${result.message}`,\n );\n throw new InitAbortedError(\"\", 1);\n }\n }\n}\n\nasync function runExchange(\n consentToken: string,\n profileName: string,\n email: string,\n): Promise<void> {\n // One-shot retry on transient network failure. The undici socket\n // drops we saw in production (Xavier session, 2026-05-14) were one\n // failure followed by an immediate success on the same call. Without\n // this retry, that flake aborts the wizard after the user has\n // already typed the OTP.\n //\n // Edge case: if the server actually processed the exchange and the\n // response socket died, the consent JWT is already burned and the\n // retry returns `invalid_consent`. User sees the standard\n // \"Consent token was rejected. Re-run 'olakai init' to start over.\"\n // — same outcome as today's no-retry path on that rare race, so\n // strictly net-positive on every other transient failure mode.\n let result = await postHandshakeExchange({ consentToken });\n if (result.kind === \"error\" && result.code === \"network_error\") {\n console.log(\"(Network error exchanging consent — retrying once...)\");\n result = await postHandshakeExchange({ consentToken });\n }\n if (result.kind === \"error\") {\n switch (result.code) {\n case \"invalid_consent\":\n console.error(\n \"Consent token was rejected. Re-run 'olakai init' to start over.\",\n );\n break;\n case \"user_unavailable\":\n console.error(\n \"Your user record is unavailable on the backend. Contact your admin.\",\n );\n break;\n case \"rate_limited\": {\n const wait = result.retryAfter\n ? ` Retry in ${result.retryAfter}s.`\n : \"\";\n console.error(`Rate limit hit while exchanging consent.${wait}`);\n break;\n }\n case \"service_unavailable\":\n console.error(\n \"Olakai is temporarily unavailable. Try again in a minute.\",\n );\n break;\n case \"network_error\":\n console.error(\n `Network error exchanging consent${result.causeCode ? ` (${result.causeCode})` : \"\"}: ${result.message}`,\n );\n break;\n default:\n console.error(`Exchange failed (${result.code}): ${result.message}`);\n }\n throw new InitAbortedError(\"\", 1);\n }\n\n // Persist into the active profile. `saveToken` writes to the\n // resolved profile (creating it if needed) and respects the active\n // host via `getBaseUrl()`.\n saveToken(result.data.access_token, result.data.expires_in);\n // Cache the email on the profile so subsequent `whoami` calls don't\n // need to round-trip when offline. We don't have user/account IDs\n // until the user hits an authenticated endpoint, but the email\n // alone is enough for friendly re-auth prompts.\n try {\n patchProfile(profileName, { email });\n } catch {\n // Best-effort — failure here doesn't invalidate the login.\n }\n\n console.log(`\\nLogged in as ${email} on ${getBaseUrl()}.`);\n console.log(`Profile: ${profileName}`);\n}\n\n// ---- handshake-level error surfacing --------------------------------------\n\nfunction handleHandshakeError(\n err: Extract<Awaited<ReturnType<typeof postHandshake>>, { kind: \"error\" }>,\n): never {\n switch (err.code) {\n case \"validation_error\":\n console.error(`That email didn't pass validation: ${err.message}`);\n break;\n case \"blocked\":\n console.error(err.message);\n console.error(\n \"Ask your admin to claim your domain, then re-run 'olakai init'.\",\n );\n break;\n case \"rate_limited\": {\n const wait = err.retryAfter ? ` Retry in ${err.retryAfter}s.` : \"\";\n console.error(`Too many attempts.${wait}`);\n break;\n }\n case \"service_unavailable\":\n console.error(\n \"Olakai is temporarily unavailable. Try again in a minute.\",\n );\n break;\n case \"network_error\":\n console.error(\n `Network error contacting Olakai${err.causeCode ? ` (${err.causeCode})` : \"\"}: ${err.message}`,\n );\n break;\n default:\n console.error(`Handshake failed (${err.code}): ${err.message}`);\n }\n process.exit(1);\n}\n\n// ---- monitor handoff (OLA-214) --------------------------------------------\n\n/**\n * Auto-detect installed local coding agents, prompt per-tool, and chain\n * into the existing `monitor init` plugin install for each tool the\n * user opts into.\n *\n * Design notes:\n *\n * - `--skip-monitor` short-circuits before detection runs. We treat it\n * as an explicit \"don't touch hooks here\", not \"I'll do it later\"\n * — so no docs-pointer line either. The wizard already said\n * everything it needed to say at that point.\n *\n * - Non-interactive mode auto-accepts each detected tool. Rationale:\n * if you went out of your way to run `olakai init --non-interactive`\n * you've opted into the chained setup; failing fast here would\n * defeat the CI use case. Inside each `runMonitorInstall` the\n * plugin still gates on required inputs and fast-fails on missing\n * ones (e.g. unable to mint an API key without a prompt) rather\n * than hanging.\n *\n * - Per-tool failures are isolated. A flake on the agents-API for one\n * tool must not strand the user without monitoring on the others.\n * We catch, surface a retry hint, and continue.\n *\n * - The plugin's own `install()` already handles the \"config already\n * exists in this workspace, replace? [y/N]\" prompt — we don't\n * re-implement it here.\n */\nasync function offerMonitorSetup(\n options: InitCommandOptions,\n interactive: boolean,\n): Promise<void> {\n if (options.skipMonitor) return;\n\n const detected = await detectInstalledTools(process.cwd());\n if (detected.length === 0) {\n console.log(\"\\nNo coding agents detected in this workspace.\");\n console.log(\n \"Install Claude Code, Codex, or Cursor and run 'olakai monitor init' to start tracking.\",\n );\n return;\n }\n\n console.log(\n `\\nDetected ${detected.length} coding agent${detected.length === 1 ? \"\" : \"s\"} in this workspace.`,\n );\n\n for (const { tool, reason } of detected) {\n let proceed = true;\n if (interactive) {\n const answer = await promptUser(\n `\\nSet up monitoring for ${tool}? (${reason}) [Y/n]: `,\n );\n const normalized = answer.trim().toLowerCase();\n // Default-yes: empty / 'y' / 'yes' all proceed. Anything else\n // counts as a decline (matches the convention used by the\n // re-auth prompt earlier in the wizard).\n proceed = normalized === \"\" || normalized === \"y\" || normalized === \"yes\";\n }\n\n if (!proceed) {\n console.log(\n `Skipped ${tool}. Run 'olakai monitor init --tool ${tool}' later if you change your mind.`,\n );\n continue;\n }\n\n try {\n await runMonitorInstall(tool, { interactive });\n console.log(`${tool} monitoring configured.`);\n } catch (err) {\n // Isolate the failure — don't poison the remaining tools or\n // abort the wizard with a non-zero exit. Re-running just the\n // failed tool is a single command, so we surface it.\n const message = err instanceof Error ? err.message : String(err);\n console.error(`${tool} setup failed: ${message}`);\n console.error(`Run 'olakai monitor init --tool ${tool}' to retry.`);\n }\n }\n}\n\n// ---- exit signaling --------------------------------------------------------\n\n/**\n * Internal marker for \"we've already printed a clear user-facing\n * message; just exit with the given code\". Lets nested helpers bail\n * out without each one calling `process.exit()` directly (which would\n * be untestable).\n */\nclass InitAbortedError extends Error {\n exitCode: number;\n constructor(message: string, exitCode = 1) {\n super(message);\n this.name = \"InitAbortedError\";\n this.exitCode = exitCode;\n }\n}\n","/**\n * Typed client for the CLI handshake API (OLA-210).\n *\n * Three unauthenticated endpoints back the `olakai init` wizard:\n *\n * POST /api/cli/handshake → branch the wizard (device-flow,\n * OTP, signup, or blocked)\n * POST /api/cli/handshake/verify → exchange a 6-digit OTP for a\n * short-lived consent token\n * POST /api/cli/handshake/exchange → exchange the consent token for\n * the long-lived CLI bearer\n *\n * The HTTP layer is intentionally thin: no retries, no progress\n * reporting. The wizard owns retry/UX decisions because the right\n * behavior depends heavily on the user-facing branch (e.g. `expired`\n * vs `invalid_code` need very different prompts).\n *\n * Every function returns a discriminated-union result keyed by `kind`:\n *\n * `kind === \"ok\"` — happy path, payload in `data`\n * `kind === \"error\"` — typed failure with backend `code`\n *\n * Backend error contract (mirrors S1 spec):\n *\n * 400 validation_error\n * 400 invalid_code (verify, with `attemptsRemaining`)\n * 401 invalid_consent / user_unavailable (exchange)\n * 403 blocked (handshake)\n * 404 no_code (verify)\n * 410 expired (verify)\n * 429 locked (verify, lockout) / rate_limited\n * 503 service_unavailable\n *\n * Rate-limit responses surface `Retry-After` (seconds) so the wizard\n * can print an informed wait message.\n */\n\nimport { getBaseUrl } from \"./config.js\";\n\n/** Discriminated success/error envelope used by every handshake call. */\nexport type HandshakeResult<TOk, TError = HandshakeErrorCode> =\n | { kind: \"ok\"; data: TOk }\n | {\n kind: \"error\";\n code: TError;\n message: string;\n status: number;\n retryAfter?: number;\n /**\n * For `network_error`s: the underlying undici / Node error code\n * (e.g. `UND_ERR_CONNECT`, `ECONNRESET`). `Error.cause` carries\n * this on `fetch()` failures; we surface it here so the UI can\n * print something more actionable than the bare `\"fetch failed\"`\n * string. Unset for non-network errors and for network errors\n * with no exposed cause code.\n */\n causeCode?: string;\n };\n\nexport type HandshakeErrorCode =\n | \"validation_error\"\n | \"invalid_code\"\n | \"invalid_consent\"\n | \"user_unavailable\"\n | \"blocked\"\n | \"no_code\"\n | \"expired\"\n | \"locked\"\n | \"rate_limited\"\n | \"service_unavailable\"\n | \"network_error\"\n | \"unknown_error\";\n\n// ---- POST /api/cli/handshake -----------------------------------------------\n\n/**\n * The branch the backend tells us to follow. Each variant is a tagged\n * object so callers can `switch (resp.data.status)`.\n */\nexport type HandshakeResponse =\n | { status: \"user_exists\"; deviceFlowOk: true }\n | {\n status: \"user_exists\";\n otpSent: true;\n emailObfuscated: string;\n codeExpiresAt: string;\n expiresIn: number;\n }\n | {\n status: \"domain_claimed\";\n accountId: string;\n userId: string;\n matchType: \"exact\" | \"suffix\";\n emailObfuscated: string;\n codeExpiresAt: string;\n expiresIn: number;\n }\n | { status: \"saas_can_self_signup\"; signupUrl: string }\n | { status: \"blocked\"; message: string };\n\nexport interface HandshakeRequest {\n email: string;\n /** Optional explicit host hint (the backend may key per-host policy off this). */\n host?: string;\n}\n\n/**\n * POST /api/cli/handshake. Returns one of the five branches above, or a\n * typed error envelope. Network/parse failures map to `network_error`.\n */\nexport async function postHandshake(\n body: HandshakeRequest,\n): Promise<HandshakeResult<HandshakeResponse, HandshakeErrorCode>> {\n return postHandshakeJson<HandshakeResponse>(\n `${getBaseUrl()}/api/cli/handshake`,\n body,\n );\n}\n\n// ---- POST /api/cli/handshake/verify ---------------------------------------\n\nexport interface VerifyRequest {\n email: string;\n code: string;\n}\n\nexport interface VerifySuccess {\n consentToken: string;\n expiresIn: number;\n}\n\n/**\n * Extra context for the `invalid_code` branch. Backend includes\n * `attemptsRemaining` so we can print \"N attempts remaining\" before\n * the next prompt.\n */\nexport interface VerifyErrorDetail {\n attemptsRemaining?: number;\n}\n\nexport type VerifyResult = HandshakeResult<VerifySuccess, HandshakeErrorCode> & {\n detail?: VerifyErrorDetail;\n};\n\nexport async function postHandshakeVerify(\n body: VerifyRequest,\n): Promise<VerifyResult> {\n const url = `${getBaseUrl()}/api/cli/handshake/verify`;\n const result = await postHandshakeJson<VerifySuccess>(url, body, {\n captureDetail: true,\n });\n return result as VerifyResult;\n}\n\n// ---- POST /api/cli/handshake/exchange -------------------------------------\n\nexport interface ExchangeRequest {\n consentToken: string;\n}\n\n/** Same shape as device-flow's `/api/auth/device/token` response. */\nexport interface ExchangeSuccess {\n access_token: string;\n token_type: \"Bearer\";\n expires_in: number;\n}\n\nexport async function postHandshakeExchange(\n body: ExchangeRequest,\n): Promise<HandshakeResult<ExchangeSuccess, HandshakeErrorCode>> {\n return postHandshakeJson<ExchangeSuccess>(\n `${getBaseUrl()}/api/cli/handshake/exchange`,\n body,\n );\n}\n\n// ---- shared transport ------------------------------------------------------\n\ninterface PostOptions {\n /**\n * When true, attempts to surface response-body fields (esp.\n * `attemptsRemaining` on `invalid_code`) on the returned envelope's\n * `detail` field. Other endpoints don't need it.\n */\n captureDetail?: boolean;\n}\n\ninterface ErrorBody {\n error?: string;\n code?: string;\n message?: string;\n attemptsRemaining?: number;\n}\n\n/**\n * Shared transport for the three handshake endpoints. Centralized so\n * Retry-After parsing, JSON-error decoding, and the network-error\n * fallback live in one place.\n */\nasync function postHandshakeJson<TOk>(\n url: string,\n body: unknown,\n options: PostOptions = {},\n): Promise<HandshakeResult<TOk, HandshakeErrorCode> & { detail?: VerifyErrorDetail }> {\n let response: Response;\n try {\n response = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n } catch (err) {\n return buildNetworkError(err);\n }\n\n if (response.ok) {\n let data: TOk;\n try {\n data = (await response.json()) as TOk;\n } catch (err) {\n return {\n kind: \"error\",\n code: \"unknown_error\",\n message: err instanceof Error ? err.message : \"Failed to parse response\",\n status: response.status,\n };\n }\n return { kind: \"ok\", data };\n }\n\n // Best-effort error body decode — backend may return a JSON envelope\n // or (rarely) a plain string. Anything unparseable degrades to a\n // generic unknown_error with the HTTP status preserved.\n let errBody: ErrorBody = {};\n try {\n errBody = (await response.json()) as ErrorBody;\n } catch {\n // ignore\n }\n\n const code = mapErrorCode(response.status, errBody);\n // Fallback message includes the request pathname so an unannotated\n // 5xx tells the user *what* failed, not just the status code.\n // Hostname is intentionally omitted — it varies by environment and\n // contributes nothing to the user's understanding of the error.\n let fallbackPath = \"\";\n try {\n fallbackPath = new URL(url).pathname;\n } catch {\n // Malformed URL — use the raw url string as a last resort.\n fallbackPath = url;\n }\n const message =\n errBody.message ||\n errBody.error ||\n `Request to ${fallbackPath} failed with status ${response.status}`;\n const retryAfter = parseRetryAfter(response.headers.get(\"retry-after\"));\n\n const envelope: HandshakeResult<TOk, HandshakeErrorCode> & {\n detail?: VerifyErrorDetail;\n } = {\n kind: \"error\",\n code,\n message,\n status: response.status,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n };\n\n if (options.captureDetail && typeof errBody.attemptsRemaining === \"number\") {\n envelope.detail = { attemptsRemaining: errBody.attemptsRemaining };\n }\n\n return envelope;\n}\n\n/**\n * Map an HTTP status + parsed error body to a canonical\n * `HandshakeErrorCode`. The backend's `code` field wins when present;\n * otherwise we fall back to the status code semantics from the S1\n * spec.\n */\nfunction mapErrorCode(status: number, body: ErrorBody): HandshakeErrorCode {\n const known: HandshakeErrorCode[] = [\n \"validation_error\",\n \"invalid_code\",\n \"invalid_consent\",\n \"user_unavailable\",\n \"blocked\",\n \"no_code\",\n \"expired\",\n \"locked\",\n \"rate_limited\",\n \"service_unavailable\",\n ];\n // Defensive: only trust the backend's `code` / `error` fields when\n // they're actually strings. A malformed server returning numeric or\n // object payloads must not slip past the `includes()` guard.\n if (typeof body.code === \"string\" && (known as string[]).includes(body.code)) {\n return body.code as HandshakeErrorCode;\n }\n if (typeof body.error === \"string\" && (known as string[]).includes(body.error)) {\n return body.error as HandshakeErrorCode;\n }\n switch (status) {\n case 400:\n return \"validation_error\";\n case 401:\n return \"invalid_consent\";\n case 403:\n return \"blocked\";\n case 404:\n return \"no_code\";\n case 410:\n return \"expired\";\n case 429:\n return \"rate_limited\";\n case 503:\n return \"service_unavailable\";\n default:\n return \"unknown_error\";\n }\n}\n\n/**\n * Build a `network_error` envelope from a `fetch()` rejection, surfacing\n * the undici `err.cause.code` (e.g. `UND_ERR_CONNECT`, `ECONNRESET`)\n * when present. The bare `err.message` from undici is the unhelpful\n * `\"fetch failed\"`; the cause carries the actionable signal. We pull\n * `cause.code` onto the envelope's `causeCode` and append `cause.message`\n * onto the human message so both the structured field and the rendered\n * string carry the diagnostic.\n *\n * `Error.cause` is `unknown` per TS lib types; we treat it defensively\n * as a possibly-object value with optional string `code` / `message`.\n */\nfunction buildNetworkError(\n err: unknown,\n): { kind: \"error\"; code: \"network_error\"; message: string; status: 0; causeCode?: string } {\n const base =\n err instanceof Error ? err.message : \"Network request failed\";\n let causeCode: string | undefined;\n let causeMessage: string | undefined;\n if (err instanceof Error && err.cause && typeof err.cause === \"object\") {\n const c = err.cause as { code?: unknown; message?: unknown };\n if (typeof c.code === \"string\" && c.code.length > 0) {\n causeCode = c.code;\n }\n if (typeof c.message === \"string\" && c.message.length > 0) {\n causeMessage = c.message;\n }\n }\n // Compose the message: keep \"fetch failed\" prefix (some downstream\n // tooling matches against it), append cause-message when different.\n const message =\n causeMessage && causeMessage !== base ? `${base}: ${causeMessage}` : base;\n return {\n kind: \"error\",\n code: \"network_error\",\n message,\n status: 0,\n ...(causeCode ? { causeCode } : {}),\n };\n}\n\nfunction parseRetryAfter(header: string | null): number | undefined {\n if (!header) return undefined;\n const asNumber = Number(header);\n if (Number.isFinite(asNumber) && asNumber > 0) {\n return Math.floor(asNumber);\n }\n // Retry-After can also be an HTTP date — convert to seconds-from-now.\n const asDate = Date.parse(header);\n if (Number.isFinite(asDate)) {\n const seconds = Math.floor((asDate - Date.now()) / 1000);\n return seconds > 0 ? seconds : undefined;\n }\n return undefined;\n}\n","/**\n * Multi-tool detection for chained `olakai init` → `olakai monitor init`\n * (OLA-214).\n *\n * Walks the registered monitor plugins (see `plugins/index.ts`) and\n * reports which of them appear installed in the current workspace.\n * Each entry carries a short human-readable `reason` we surface in the\n * per-tool consent prompt — the wizard's UX promise was\n *\n * \"Detected Claude Code in this workspace. Set up monitoring? [Y/n]\"\n *\n * The reason string is what makes that line specific (e.g.\n * \"found `.claude/settings.json`\") rather than a generic \"detected\".\n *\n * Implementation note: we don't reimplement each plugin's `detectInstalled`\n * here — that would diverge over time. Instead we call the plugin's\n * boolean probe and then, when it returns true, do a cheap follow-up\n * stat on a small set of well-known signal paths to pick the most\n * informative reason. If none match, we fall back to a generic phrase\n * so the prompt is always at least readable.\n */\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport {\n getLegacyClaudeMonitorConfigPath,\n getMonitorConfigPath,\n} from \"./paths.js\";\nimport {\n getCodexConfigPath as getCodexHomeConfigPath,\n getCodexHomeDir,\n} from \"./plugins/codex/paths.js\";\n// Side-effect import: ensures plugins are registered when the init\n// wizard pulls this module in without going through monitor.ts.\nimport \"./plugins/index.js\";\nimport {\n listPlugins,\n type ToolId,\n type ToolMonitorPlugin,\n} from \"./plugin.js\";\n\nexport interface DetectedTool {\n tool: ToolId;\n /**\n * Short human-readable phrase identifying what signal triggered the\n * match. Designed to be inlined into a prompt: e.g.\n * `\"detected (found .claude/settings.json)\"`.\n */\n reason: string;\n}\n\n/**\n * Returns the detected tools, in the order plugins were registered. We\n * preserve order so the consent prompts are deterministic across runs\n * (and across `process.cwd()` shifts in tests).\n */\nexport async function detectInstalledTools(\n projectRoot: string = process.cwd(),\n): Promise<DetectedTool[]> {\n const detected: DetectedTool[] = [];\n for (const plugin of listPlugins()) {\n let installed = false;\n try {\n installed = await plugin.detectInstalled({ projectRoot });\n } catch {\n // detectInstalled is best-effort. A throwing probe should never\n // poison the wizard — treat it as \"not detected\".\n installed = false;\n }\n if (!installed) continue;\n detected.push({\n tool: plugin.id,\n reason: describeDetection(plugin, projectRoot),\n });\n }\n return detected;\n}\n\nfunction describeDetection(\n plugin: ToolMonitorPlugin,\n projectRoot: string,\n): string {\n // Prefer the most specific signal: an existing workspace-local\n // monitor config means the user already ran `olakai monitor init`\n // for this tool in this workspace at some point. Mention that so\n // they understand a re-run will trigger the plugin's own\n // \"replace?\" prompt rather than a fresh install.\n try {\n if (fs.existsSync(getMonitorConfigPath(projectRoot, plugin.id))) {\n return `existing config at .olakai/monitor-${plugin.id}.json`;\n }\n } catch {\n // fall through\n }\n\n switch (plugin.id) {\n case \"claude-code\": {\n try {\n if (fs.existsSync(getLegacyClaudeMonitorConfigPath(projectRoot))) {\n return \"legacy config at .claude/olakai-monitor.json\";\n }\n } catch {\n // fall through\n }\n try {\n const settings = path.join(projectRoot, \".claude\", \"settings.json\");\n if (fs.existsSync(settings)) {\n return \"found .claude/settings.json\";\n }\n } catch {\n // fall through\n }\n return \"Claude Code detected\";\n }\n case \"codex\": {\n try {\n if (fs.existsSync(getCodexHomeConfigPath())) {\n return \"found ~/.codex/config.toml\";\n }\n if (fs.existsSync(getCodexHomeDir())) {\n return \"found ~/.codex/\";\n }\n } catch {\n // fall through\n }\n return \"Codex CLI on PATH\";\n }\n case \"cursor\": {\n return \"Cursor installed for this user\";\n }\n case \"gemini-cli\": {\n try {\n const homeSettings = path.join(\n process.env.HOME ?? \"\",\n \".gemini\",\n \"settings.json\",\n );\n if (process.env.HOME && fs.existsSync(homeSettings)) {\n return \"found ~/.gemini/settings.json\";\n }\n const homeDir = path.join(process.env.HOME ?? \"\", \".gemini\");\n if (process.env.HOME && fs.existsSync(homeDir)) {\n return \"found ~/.gemini/\";\n }\n } catch {\n // fall through\n }\n return \"Gemini CLI on PATH\";\n }\n case \"antigravity\": {\n try {\n const cliDir = path.join(\n process.env.HOME ?? \"\",\n \".gemini\",\n \"antigravity-cli\",\n );\n if (process.env.HOME && fs.existsSync(cliDir)) {\n return \"found ~/.gemini/antigravity-cli/\";\n }\n } catch {\n // fall through\n }\n return \"Antigravity (agy) on PATH\";\n }\n default: {\n // Compile-time exhaustiveness check: when a 4th tool gets added\n // to `ToolId` (see CLAUDE.md \"Adding a New Local Coding Agent\n // Tool\" guide), this assertion fires at type-check time so the\n // missing case is impossible to miss. Until then, we keep a\n // graceful runtime fallback so a future tool doesn't ship with\n // `Set up monitoring for newtool? (undefined)` in the prompt.\n const _exhaustive: never = plugin.id;\n void _exhaustive;\n return `${plugin.displayName} detected`;\n }\n }\n}\n","/**\n * Terminal branding for the `olakai init` wizard (OLA-226).\n *\n * `olakai init` is the first thing an admin evaluating Olakai sees from\n * the CLI — Xavier's product-feedback session flagged the current\n * messaging as too curt for that role. This module owns the visual\n * shell (logo header, colors) and the role-aware copy for the admin /\n * analyst handoff to the browser device-flow.\n *\n * Color strategy: raw ANSI escapes, no new dependency. Cyan-tinted\n * `◉` mark matches the Olakai logo's teal/cyan palette. We respect\n * `NO_COLOR` (https://no-color.org/) and only emit color sequences\n * when stdout is a TTY — pipelines and CI logs stay clean.\n */\n\nconst RESET = \"\\x1b[0m\";\nconst CYAN = \"\\x1b[36m\";\nconst DIM = \"\\x1b[2m\";\n\nfunction colorize(text: string, color: string): string {\n if (process.env.NO_COLOR) return text;\n if (!process.stdout.isTTY) return text;\n return `${color}${text}${RESET}`;\n}\n\n/**\n * Prints the wizard's logo header. Call once at the very top of the\n * interactive `olakai init` flow — it sets the visual tone for the\n * entire session.\n *\n * Skipped automatically when stdout is not a TTY (CI, piped output)\n * so logs / `--non-interactive` runs stay machine-parseable.\n */\nexport function printLogoHeader(): void {\n if (!process.stdout.isTTY) return;\n const mark = colorize(\"◉\", CYAN);\n const tagline = colorize(\"Enterprise AI Adoption, ROI and Governance\", DIM);\n console.log(\"\");\n console.log(` ${mark} olakai`);\n console.log(` ${tagline}`);\n console.log(` ──────────────────────────────`);\n console.log(\"\");\n}\n\n/**\n * Multi-line greeting shown to existing-account users (ADMIN /\n * ANALYST / USER) on the `user_exists + deviceFlowOk` branch BEFORE\n * the browser opens for device-flow auth.\n *\n * Two goals:\n * 1. Acknowledge that we identified the user by name/email — Xavier\n * flagged the current \"Welcome back! Opening browser...\" as\n * feeling impersonal for someone evaluating the product.\n * 2. Explain WHY the browser step applies here AND clarify it does\n * NOT apply to Employee-role developers (who get the OTP flow).\n * The distinction is the heart of the feedback: admins shouldn't\n * conclude \"this is friction for my whole team\" from their own\n * elevated-privileges flow.\n *\n * Personalization is email-only by design. The handshake `user_exists\n * + deviceFlowOk` response is deliberately bounded to a tiny\n * email-enumeration oracle (status + boolean) — adding name/role/\n * accountName here would enlarge the oracle on an unauthenticated\n * endpoint. The richer per-user display (name, role, account) comes\n * AFTER browser auth, where `loginCommand` already prints them.\n */\nexport function formatExistingUserBrowserGreeting(email: string): string {\n return [\n ` ✓ Found your Olakai account — ${email}`,\n ``,\n ` Since you have login access to an Olakai workspace, we'll route`,\n ` you through your account's standard sign-in. Admin and analyst`,\n ` users authenticate the CLI through the browser, matching how`,\n ` they sign in to the web app.`,\n ``,\n ` Employee-role developers skip this step and self-onboard with`,\n ` a one-time email code — no browser, no SSO prompt.`,\n ].join(\"\\n\");\n}\n","import { Command } from \"commander\";\nimport {\n listAgents,\n getAgent,\n createAgent,\n updateAgent,\n deleteAgent,\n listMyAgents,\n type Agent,\n type MineAgent,\n} from \"../lib/api.js\";\nimport { getToolSource } from \"../monitor/registry.js\";\nimport { TOOL_IDS, isToolId } from \"../monitor/plugin.js\";\n\nfunction formatAgentTable(agents: Agent[]): void {\n if (agents.length === 0) {\n console.log(\"No agents found.\");\n return;\n }\n\n // Calculate column widths\n const headers = [\"ID\", \"NAME\", \"ROLE\", \"WORKFLOW\", \"API KEY\"];\n const rows = agents.map((agent) => [\n agent.id.slice(0, 12) + \"...\",\n agent.name.slice(0, 30),\n agent.role,\n agent.workflowId ? agent.workflowId.slice(0, 12) + \"...\" : \"-\",\n agent.apiKey ? (agent.apiKey.isActive ? \"Active\" : \"Inactive\") : \"None\",\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n // Print header\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n // Print rows\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n}\n\nfunction formatAgentDetail(agent: Agent): void {\n console.log(`ID: ${agent.id}`);\n console.log(`Name: ${agent.name}`);\n console.log(`Description: ${agent.description || \"-\"}`);\n console.log(`Role: ${agent.role}`);\n console.log(`Source: ${agent.source}`);\n console.log(`Category: ${agent.category || \"-\"}`);\n console.log(`Workflow ID: ${agent.workflowId || \"-\"}`);\n\n if (agent.workflow) {\n console.log(`Workflow: ${agent.workflow.name}`);\n }\n\n console.log(\"\");\n console.log(\"API Key:\");\n if (agent.apiKey) {\n console.log(` ID: ${agent.apiKey.id}`);\n if (agent.apiKey.key) {\n console.log(` Key: ${agent.apiKey.key}`);\n } else {\n console.log(` Key: ${agent.apiKey.keyMasked}`);\n }\n console.log(` Status: ${agent.apiKey.isActive ? \"Active\" : \"Inactive\"}`);\n } else {\n console.log(\" None\");\n }\n\n if (agent.kpiDefinitions && agent.kpiDefinitions.length > 0) {\n console.log(\"\");\n console.log(\"KPI Definitions:\");\n for (const kpi of agent.kpiDefinitions) {\n console.log(` - ${kpi.name} (${kpi.type})`);\n }\n }\n}\n\n/**\n * Render the account lens (`agents mine`) as a table:\n * name · source · agentId · created · apiKey active?\n */\nfunction formatMineTable(agents: MineAgent[]): void {\n if (agents.length === 0) {\n console.log(\"You haven't created any agents.\");\n return;\n }\n\n const headers = [\"NAME\", \"SOURCE\", \"AGENT ID\", \"CREATED\", \"API KEY\"];\n const rows = agents.map((agent) => [\n agent.name.slice(0, 30),\n agent.source,\n agent.id.slice(0, 12) + \"...\",\n agent.createdAt ? agent.createdAt.slice(0, 10) : \"-\",\n agent.apiKey ? (agent.apiKey.isActive ? \"Active\" : \"Inactive\") : \"None\",\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n}\n\nasync function listCommand(options: {\n json?: boolean;\n includeKpis?: boolean;\n}): Promise<void> {\n try {\n const agents = await listAgents({ includeKpis: options.includeKpis });\n\n if (options.json) {\n console.log(JSON.stringify(agents, null, 2));\n } else {\n formatAgentTable(agents);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function getCommand(id: string, options: { json?: boolean }): Promise<void> {\n try {\n const agent = await getAgent(id);\n\n if (options.json) {\n console.log(JSON.stringify(agent, null, 2));\n } else {\n formatAgentDetail(agent);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function createCommand(options: {\n name: string;\n description?: string;\n role?: string;\n workflow?: string;\n withApiKey?: boolean;\n category?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n if (!options.name) {\n console.error(\"Error: --name is required\");\n process.exit(1);\n }\n\n const agent = await createAgent({\n name: options.name,\n description: options.description || \"\",\n role: (options.role as \"WORKER\" | \"COORDINATOR\") || \"WORKER\",\n workflowId: options.workflow,\n createApiKey: options.withApiKey || false,\n category: options.category,\n });\n\n if (options.json) {\n console.log(JSON.stringify(agent, null, 2));\n } else {\n console.log(\"Agent created successfully!\");\n console.log(\"\");\n formatAgentDetail(agent);\n\n if (agent.apiKey?.key) {\n console.log(\"\");\n console.log(\n \"IMPORTANT: Save your API key now. It will not be shown again.\"\n );\n }\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function updateCommand(\n id: string,\n options: {\n name?: string;\n description?: string;\n role?: string;\n workflow?: string;\n category?: string;\n json?: boolean;\n }\n): Promise<void> {\n try {\n const payload: {\n name?: string;\n description?: string;\n role?: \"WORKER\" | \"COORDINATOR\";\n workflowId?: string | null;\n category?: string | null;\n } = {};\n\n if (options.name !== undefined) payload.name = options.name;\n if (options.description !== undefined)\n payload.description = options.description;\n if (options.role !== undefined)\n payload.role = options.role as \"WORKER\" | \"COORDINATOR\";\n if (options.workflow !== undefined) payload.workflowId = options.workflow;\n if (options.category !== undefined) payload.category = options.category;\n\n if (Object.keys(payload).length === 0) {\n console.error(\"Error: At least one field to update is required\");\n process.exit(1);\n }\n\n const agent = await updateAgent(id, payload);\n\n if (options.json) {\n console.log(JSON.stringify(agent, null, 2));\n } else {\n console.log(\"Agent updated successfully!\");\n console.log(\"\");\n formatAgentDetail(agent);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function deleteCommand(\n id: string,\n options: { force?: boolean }\n): Promise<void> {\n try {\n if (!options.force) {\n // In a real CLI, we'd use readline for confirmation\n // For now, require --force flag\n console.log(\"Are you sure you want to delete this agent?\");\n console.log(\"Use --force to confirm deletion.\");\n process.exit(1);\n }\n\n await deleteAgent(id);\n console.log(\"Agent deleted successfully.\");\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\n/**\n * `olakai agents mine [--source X] [--json]` — the ACCOUNT lens.\n *\n * Lists the agents the current user created, across the whole account\n * (cross-machine), via `GET /api/config/agents/mine`. This is distinct\n * from `olakai monitor list`, which is the MACHINE lens (only what's\n * installed on this box, read from the local registry).\n *\n * `--source` narrows to a single coding-agent source. It accepts the\n * lowercase tool identifier (claude-code|codex|cursor) and maps it to\n * the backend AgentSource enum (CLAUDE_CODE|CODEX|CURSOR).\n */\nasync function mineCommand(options: {\n source?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n let source: string | undefined;\n if (options.source !== undefined) {\n if (!isToolId(options.source)) {\n console.error(\n `Unknown --source \"${options.source}\". Supported coding-agent sources: ${TOOL_IDS.join(\", \")}`,\n );\n process.exit(1);\n }\n source = getToolSource(options.source);\n }\n\n const agents = await listMyAgents(source ? { source } : undefined);\n\n if (options.json) {\n console.log(JSON.stringify(agents, null, 2));\n } else {\n formatMineTable(agents);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\n/**\n * `olakai agents archive <id> [--unarchive]` — soft archive / restore an\n * agent account-wide. PUT /api/config/agents/:id { archived }.\n */\nasync function archiveCommand(\n id: string,\n options: { unarchive?: boolean; json?: boolean }\n): Promise<void> {\n try {\n const archived = !options.unarchive;\n const agent = await updateAgent(id, { archived });\n\n if (options.json) {\n console.log(JSON.stringify(agent, null, 2));\n } else {\n console.log(\n archived\n ? `Agent ${id} archived.`\n : `Agent ${id} unarchived.`\n );\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\n/**\n * `olakai agents rename <id> <name>` — rename an agent account-wide.\n * PUT /api/config/agents/:id { name }.\n */\nasync function renameCommand(\n id: string,\n name: string,\n options: { json?: boolean }\n): Promise<void> {\n try {\n if (!name || !name.trim()) {\n console.error(\"Error: a non-empty <name> is required\");\n process.exit(1);\n }\n\n const agent = await updateAgent(id, { name: name.trim() });\n\n if (options.json) {\n console.log(JSON.stringify(agent, null, 2));\n } else {\n console.log(`Agent ${id} renamed to \"${agent.name}\".`);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nexport function registerAgentsCommand(program: Command): void {\n const agents = program\n .command(\"agents\")\n .description(\"Manage agents\");\n\n agents\n .command(\"list\")\n .description(\"List all agents\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--include-kpis\", \"Include KPI definitions\")\n .action(listCommand);\n\n agents\n .command(\"get <id>\")\n .description(\"Get agent details\")\n .option(\"--json\", \"Output as JSON\")\n .action(getCommand);\n\n agents\n .command(\"create\")\n .description(\"Create a new agent\")\n .requiredOption(\"--name <name>\", \"Agent name\")\n .option(\"--description <description>\", \"Agent description\")\n .option(\"--role <role>\", \"Agent role (WORKER or COORDINATOR)\", \"WORKER\")\n .option(\"--workflow <id>\", \"Workflow ID to assign\")\n .option(\"--with-api-key\", \"Create an API key for this agent\")\n .option(\"--category <category>\", \"Agent category\")\n .option(\"--json\", \"Output as JSON\")\n .action(createCommand);\n\n agents\n .command(\"update <id>\")\n .description(\"Update an agent\")\n .option(\"--name <name>\", \"Agent name\")\n .option(\"--description <description>\", \"Agent description\")\n .option(\"--role <role>\", \"Agent role (WORKER or COORDINATOR)\")\n .option(\"--workflow <id>\", \"Workflow ID to assign\")\n .option(\"--category <category>\", \"Agent category\")\n .option(\"--json\", \"Output as JSON\")\n .action(updateCommand);\n\n agents\n .command(\"delete <id>\")\n .description(\n \"Delete an agent (account-wide). Owner or ADMIN only — non-owners get a permission error.\",\n )\n .option(\"--force\", \"Skip confirmation\")\n .action(deleteCommand);\n\n agents\n .command(\"mine\")\n .description(\n \"List agents you created across your whole account (the account lens, cross-machine). For what's installed on THIS machine, use 'olakai monitor list'.\",\n )\n .option(\n \"--source <source>\",\n `Filter to a coding-agent source (${TOOL_IDS.join(\"|\")})`,\n )\n .option(\"--json\", \"Output as JSON\")\n .action(mineCommand);\n\n agents\n .command(\"archive <id>\")\n .description(\"Archive an agent account-wide (soft delete). Owner or ADMIN only.\")\n .option(\"--unarchive\", \"Restore an archived agent instead\")\n .option(\"--json\", \"Output as JSON\")\n .action(archiveCommand);\n\n agents\n .command(\"rename <id> <name>\")\n .description(\"Rename an agent account-wide. Owner or ADMIN only.\")\n .option(\"--json\", \"Output as JSON\")\n .action(renameCommand);\n}\n","import { Command } from \"commander\";\nimport {\n listWorkflows,\n getWorkflow,\n createWorkflow,\n updateWorkflow,\n deleteWorkflow,\n type Workflow,\n} from \"../lib/api.js\";\n\nfunction formatWorkflowTable(workflows: Workflow[]): void {\n if (workflows.length === 0) {\n console.log(\"No workflows found.\");\n return;\n }\n\n // Calculate column widths\n const headers = [\"ID\", \"NAME\", \"AGENTS\", \"STATUS\"];\n const rows = workflows.map((wf) => [\n wf.id.slice(0, 12) + \"...\",\n wf.name.slice(0, 30),\n wf.agentCount.toString(),\n wf.isActive ? \"Active\" : \"Inactive\",\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n // Print header\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n // Print rows\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n}\n\nfunction formatWorkflowDetail(workflow: Workflow): void {\n console.log(`ID: ${workflow.id}`);\n console.log(`Name: ${workflow.name}`);\n console.log(`Description: ${workflow.description || \"-\"}`);\n console.log(`Status: ${workflow.isActive ? \"Active\" : \"Inactive\"}`);\n console.log(`Agents: ${workflow.agentCount}`);\n if (workflow.createdAt) {\n console.log(`Created: ${new Date(workflow.createdAt).toISOString()}`);\n }\n if (workflow.updatedAt) {\n console.log(`Updated: ${new Date(workflow.updatedAt).toISOString()}`);\n }\n\n if (workflow.agents && workflow.agents.length > 0) {\n console.log(\"\");\n console.log(\"Agents:\");\n for (const agent of workflow.agents) {\n const apiKeyStatus = agent.apiKey\n ? agent.apiKey.isActive\n ? \"API Key: Active\"\n : \"API Key: Inactive\"\n : \"No API Key\";\n console.log(` - ${agent.name} (${agent.role}) - ${apiKeyStatus}`);\n }\n }\n}\n\nasync function listCommand(options: {\n json?: boolean;\n includeAgents?: boolean;\n includeInactive?: boolean;\n}): Promise<void> {\n try {\n const workflows = await listWorkflows({\n includeAgents: options.includeAgents,\n includeInactive: options.includeInactive,\n });\n\n if (options.json) {\n console.log(JSON.stringify(workflows, null, 2));\n } else {\n formatWorkflowTable(workflows);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function getCommand(id: string, options: { json?: boolean }): Promise<void> {\n try {\n const workflow = await getWorkflow(id);\n\n if (options.json) {\n console.log(JSON.stringify(workflow, null, 2));\n } else {\n formatWorkflowDetail(workflow);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function createCommand(options: {\n name: string;\n description?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n if (!options.name) {\n console.error(\"Error: --name is required\");\n process.exit(1);\n }\n\n const workflow = await createWorkflow({\n name: options.name,\n description: options.description,\n });\n\n if (options.json) {\n console.log(JSON.stringify(workflow, null, 2));\n } else {\n console.log(\"Workflow created successfully!\");\n console.log(\"\");\n formatWorkflowDetail(workflow);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function updateCommand(\n id: string,\n options: {\n name?: string;\n description?: string;\n active?: boolean;\n inactive?: boolean;\n json?: boolean;\n }\n): Promise<void> {\n try {\n const payload: {\n name?: string;\n description?: string | null;\n isActive?: boolean;\n } = {};\n\n if (options.name !== undefined) payload.name = options.name;\n if (options.description !== undefined)\n payload.description = options.description;\n if (options.active) payload.isActive = true;\n if (options.inactive) payload.isActive = false;\n\n if (Object.keys(payload).length === 0) {\n console.error(\"Error: At least one field to update is required\");\n process.exit(1);\n }\n\n const workflow = await updateWorkflow(id, payload);\n\n if (options.json) {\n console.log(JSON.stringify(workflow, null, 2));\n } else {\n console.log(\"Workflow updated successfully!\");\n console.log(\"\");\n formatWorkflowDetail(workflow);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function deleteCommand(\n id: string,\n options: { force?: boolean }\n): Promise<void> {\n try {\n if (!options.force) {\n // In a real CLI, we'd use readline for confirmation\n // For now, require --force flag\n console.log(\"Are you sure you want to delete this workflow?\");\n console.log(\"Use --force to confirm deletion.\");\n process.exit(1);\n }\n\n await deleteWorkflow(id);\n console.log(\"Workflow deleted successfully.\");\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nexport function registerWorkflowsCommand(program: Command): void {\n const workflows = program\n .command(\"workflows\")\n .description(\"Manage workflows\");\n\n workflows\n .command(\"list\")\n .description(\"List all workflows\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--include-agents\", \"Include agent details\")\n .option(\"--include-inactive\", \"Include inactive workflows\")\n .action(listCommand);\n\n workflows\n .command(\"get <id>\")\n .description(\"Get workflow details\")\n .option(\"--json\", \"Output as JSON\")\n .action(getCommand);\n\n workflows\n .command(\"create\")\n .description(\"Create a new workflow\")\n .requiredOption(\"--name <name>\", \"Workflow name\")\n .option(\"--description <description>\", \"Workflow description\")\n .option(\"--json\", \"Output as JSON\")\n .action(createCommand);\n\n workflows\n .command(\"update <id>\")\n .description(\"Update a workflow\")\n .option(\"--name <name>\", \"Workflow name\")\n .option(\"--description <description>\", \"Workflow description\")\n .option(\"--active\", \"Set workflow as active\")\n .option(\"--inactive\", \"Set workflow as inactive\")\n .option(\"--json\", \"Output as JSON\")\n .action(updateCommand);\n\n workflows\n .command(\"delete <id>\")\n .description(\"Delete a workflow\")\n .option(\"--force\", \"Skip confirmation\")\n .action(deleteCommand);\n}\n","import { Command } from \"commander\";\nimport {\n listKpis,\n getKpi,\n createKpi,\n updateKpi,\n deleteKpi,\n getKpiContextVariables,\n validateKpiFormula,\n type KpiDefinition,\n type KpiScope,\n type ContextVariable,\n type CreateKpiPayload,\n type DefaultAggregationMethod,\n} from \"../lib/api.js\";\n\nconst AGGREGATION_METHODS: DefaultAggregationMethod[] = [\n \"SUM\",\n \"AVERAGE\",\n \"COUNT\",\n \"MIN\",\n \"MAX\",\n \"LATEST\",\n];\n\nconst CALCULATOR_IDS = [\"formula\", \"classifier\", \"llm-data\"];\n\nconst KPI_SCOPES: KpiScope[] = [\"PROMPT_REQUEST\", \"CHAT\", \"DOCUMENT\"];\n\n// Classifier template definitions — mirrors CLASSIFIER_TEMPLATES from\n// localnode-app/packages/config/classifier-templates.ts\ntype OutputClassOption = { label: string; value: number };\n\ntype ClassifierTemplate = {\n id: string;\n name: string;\n description: string;\n promptTemplate: string;\n defaultUnit: string;\n defaultOutputClasses: OutputClassOption[];\n};\n\nconst CLASSIFIER_TEMPLATES: ClassifierTemplate[] = [\n {\n id: \"sentiment_scorer\",\n name: \"Sentiment Scorer\",\n description:\n \"Scores the overall emotional tone and user satisfaction of a conversation\",\n defaultUnit: \"score\",\n promptTemplate: `Analyze the overall sentiment of the following AI assistant conversation. Consider the user's tone, satisfaction level, and emotional state throughout the interaction.\n\nConversation:\n{{Complete exchange}}\n\nRate the sentiment using exactly one of these numeric scores:\n{{outputClassDescriptions}}\n\nRespond with only the numeric score.`,\n defaultOutputClasses: [\n { label: \"Very Negative\", value: 1 },\n { label: \"Negative\", value: 2 },\n { label: \"Neutral\", value: 3 },\n { label: \"Positive\", value: 4 },\n { label: \"Very Positive\", value: 5 },\n ],\n },\n {\n id: \"time_saved_estimator\",\n name: \"Time Saved Estimator\",\n description:\n \"Estimates how much time the AI interaction saved compared to manual effort\",\n defaultUnit: \"minutes\",\n promptTemplate: `Estimate how much time this AI assistant interaction saved the user compared to completing the task manually without AI assistance. Consider the complexity of the request, the completeness of the response, and typical human effort for similar tasks.\n\nConversation:\n{{Complete exchange}}\n\nClassify the estimated time saved using exactly one of these values (in minutes):\n{{outputClassDescriptions}}\n\nRespond with only the numeric value.`,\n defaultOutputClasses: [\n { label: \"No time saved\", value: 0 },\n { label: \"A few minutes\", value: 3 },\n { label: \"Moderate time\", value: 10 },\n { label: \"Significant time\", value: 30 },\n { label: \"Major time savings\", value: 60 },\n ],\n },\n];\n\nfunction resolveOutputClassDescriptions(classes: OutputClassOption[]): string {\n return classes.map((c) => `${c.value} = ${c.label}`).join(\"\\n\");\n}\n\nfunction resolveTemplatePrompt(\n template: ClassifierTemplate,\n classes: OutputClassOption[],\n): string {\n return template.promptTemplate.replace(\n \"{{outputClassDescriptions}}\",\n resolveOutputClassDescriptions(classes),\n );\n}\n\nfunction formatKpiTable(kpis: KpiDefinition[]): void {\n if (kpis.length === 0) {\n console.log(\"No KPI definitions found.\");\n return;\n }\n\n // Calculate column widths\n const headers = [\"ID\", \"NAME\", \"SCOPE\", \"CALCULATOR\", \"AGGREGATION\", \"STATUS\"];\n const rows = kpis.map((kpi) => [\n kpi.id.slice(0, 12) + \"...\",\n kpi.name.slice(0, 25),\n kpi.scope || \"PROMPT_REQUEST\",\n kpi.calculatorId,\n kpi.defaultAggregationMethod,\n kpi.isActive ? \"Active\" : \"Inactive\",\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n // Print header\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n // Print rows\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n}\n\nfunction formatKpiDetail(kpi: KpiDefinition): void {\n console.log(`ID: ${kpi.id}`);\n console.log(`Name: ${kpi.name}`);\n console.log(`Description: ${kpi.description || \"-\"}`);\n console.log(`Type: ${kpi.type}`);\n console.log(`Category: ${kpi.category || \"-\"}`);\n console.log(`Agent ID: ${kpi.agentId || \"-\"}`);\n console.log(`Scope: ${kpi.scope || \"PROMPT_REQUEST\"}`);\n console.log(`Calculator: ${kpi.calculatorId}`);\n console.log(`Aggregation: ${kpi.defaultAggregationMethod}`);\n console.log(`Unit: ${kpi.unit || \"-\"}`);\n console.log(`Status: ${kpi.isActive ? \"Active\" : \"Inactive\"}`);\n\n if (kpi.calculatorParams) {\n console.log(\"\");\n console.log(\"Calculator Parameters:\");\n console.log(JSON.stringify(kpi.calculatorParams, null, 2));\n }\n\n if (kpi.createdAt) {\n console.log(\"\");\n console.log(`Created: ${new Date(kpi.createdAt).toISOString()}`);\n }\n if (kpi.updatedAt) {\n console.log(`Updated: ${new Date(kpi.updatedAt).toISOString()}`);\n }\n}\n\nfunction formatContextVariablesTable(variables: ContextVariable[]): void {\n if (variables.length === 0) {\n console.log(\"No context variables found.\");\n return;\n }\n\n // Calculate column widths\n const headers = [\"NAME\", \"TYPE\", \"SOURCE\", \"DESCRIPTION\"];\n const rows = variables.map((v) => [\n v.name,\n v.type,\n v.source,\n v.description.slice(0, 50),\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n // Print header\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n // Print rows\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n}\n\nasync function listCommand(options: {\n json?: boolean;\n agentId?: string;\n includeInactive?: boolean;\n}): Promise<void> {\n try {\n const kpis = await listKpis({\n agentId: options.agentId,\n includeInactive: options.includeInactive,\n });\n\n if (options.json) {\n console.log(JSON.stringify(kpis, null, 2));\n } else {\n formatKpiTable(kpis);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function getCommand(\n id: string,\n options: { json?: boolean }\n): Promise<void> {\n try {\n const kpi = await getKpi(id);\n\n if (options.json) {\n console.log(JSON.stringify(kpi, null, 2));\n } else {\n formatKpiDetail(kpi);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function createCommand(options: {\n name: string;\n calculatorId: string;\n scope: string;\n description?: string;\n type?: string;\n category?: string;\n agentId?: string;\n formula?: string;\n templateId?: string;\n outputClasses?: string;\n outputLabels?: string;\n samplingFactor?: string;\n unit?: string;\n aggregation?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n if (!options.name) {\n console.error(\"Error: --name is required\");\n process.exit(1);\n }\n\n if (!options.calculatorId) {\n console.error(\"Error: --calculator-id is required\");\n console.error(`Valid values: ${CALCULATOR_IDS.join(\", \")}`);\n process.exit(1);\n }\n\n if (!CALCULATOR_IDS.includes(options.calculatorId)) {\n console.error(`Error: Invalid calculator ID \"${options.calculatorId}\"`);\n console.error(`Valid values: ${CALCULATOR_IDS.join(\", \")}`);\n process.exit(1);\n }\n\n // Validate scope\n const upperScope = options.scope.toUpperCase() as KpiScope;\n if (!KPI_SCOPES.includes(upperScope)) {\n console.error(`Error: Invalid scope \"${options.scope}\"`);\n console.error(`Valid values: ${KPI_SCOPES.join(\", \")}`);\n process.exit(1);\n }\n\n // Build calculator params\n let calculatorParams: Record<string, unknown> | undefined;\n let resolvedUnit = options.unit;\n\n if (options.calculatorId === \"formula\") {\n if (!options.formula) {\n console.error(\n \"Error: --formula is required when calculator-id is 'formula'\"\n );\n process.exit(1);\n }\n // Validate and parse the formula using the API\n const validation = await validateKpiFormula(options.formula, options.agentId, upperScope);\n if (!validation.valid) {\n console.error(`Error: Invalid formula: ${validation.error}`);\n process.exit(1);\n }\n // Use the parsed formula AST, not the raw string\n calculatorParams = { formula: validation.parsedFormula };\n } else if (options.calculatorId === \"classifier\") {\n if (!options.templateId) {\n console.error(\n \"Error: Classifier KPIs require --template-id. Run `olakai kpis templates` to see available templates.\"\n );\n process.exit(1);\n }\n\n const templateIds = CLASSIFIER_TEMPLATES.map((t) => t.id);\n const template = CLASSIFIER_TEMPLATES.find(\n (t) => t.id === options.templateId,\n );\n if (!template) {\n console.error(\n `Error: Unknown template \"${options.templateId}\". Valid templates: ${templateIds.join(\", \")}`\n );\n process.exit(1);\n }\n\n // Resolve output classes — use overrides if provided, else template defaults\n let outputClasses = template.defaultOutputClasses;\n if (options.outputClasses || options.outputLabels) {\n const rawValues = options.outputClasses\n ? options.outputClasses.split(\",\").map((v) => v.trim())\n : template.defaultOutputClasses.map((c) => String(c.value));\n const rawLabels = options.outputLabels\n ? options.outputLabels.split(\",\").map((l) => l.trim())\n : template.defaultOutputClasses.map((c) => c.label);\n\n if (rawValues.length !== rawLabels.length) {\n console.error(\n `Error: --output-classes (${rawValues.length} values) and --output-labels (${rawLabels.length} labels) must have the same count.`\n );\n process.exit(1);\n }\n\n outputClasses = rawValues.map((v, i) => ({\n label: rawLabels[i],\n value: Number(v),\n }));\n }\n\n // Resolve prompt with output class descriptions\n const promptTemplate = resolveTemplatePrompt(template, outputClasses);\n\n calculatorParams = {\n promptTemplate,\n outputClasses: outputClasses.map((c) => c.value),\n outputClassLabels: outputClasses.map((c) => c.label),\n classifierTemplateId: template.id,\n };\n\n // Parse sampling factor if provided\n if (options.samplingFactor !== undefined) {\n const factor = Number(options.samplingFactor);\n if (isNaN(factor) || factor < 0 || factor > 1) {\n console.error(\"Error: --sampling-factor must be a number between 0 and 1.\");\n process.exit(1);\n }\n calculatorParams.samplingFactor = factor;\n }\n\n // Use template default unit unless explicitly overridden\n if (!resolvedUnit) {\n resolvedUnit = template.defaultUnit;\n }\n }\n\n // Validate aggregation method\n let aggregation: DefaultAggregationMethod | undefined;\n if (options.aggregation) {\n const upperAggregation =\n options.aggregation.toUpperCase() as DefaultAggregationMethod;\n if (!AGGREGATION_METHODS.includes(upperAggregation)) {\n console.error(`Error: Invalid aggregation method \"${options.aggregation}\"`);\n console.error(`Valid values: ${AGGREGATION_METHODS.join(\", \")}`);\n process.exit(1);\n }\n aggregation = upperAggregation;\n }\n\n const payload: CreateKpiPayload = {\n name: options.name,\n calculatorId: options.calculatorId,\n scope: upperScope,\n description: options.description,\n type:\n options.type === \"PREDEFINED\" ? \"PREDEFINED\" : \"USER_DEFINED\",\n category: options.category,\n agentId: options.agentId,\n calculatorParams,\n unit: resolvedUnit,\n defaultAggregationMethod: aggregation,\n };\n\n const kpi = await createKpi(payload);\n\n if (options.json) {\n console.log(JSON.stringify(kpi, null, 2));\n } else {\n console.log(\"KPI definition created successfully!\");\n console.log(\"\");\n formatKpiDetail(kpi);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function updateCommand(\n id: string,\n options: {\n name?: string;\n description?: string;\n category?: string;\n agentId?: string;\n scope?: string;\n calculatorId?: string;\n formula?: string;\n unit?: string;\n aggregation?: string;\n active?: boolean;\n inactive?: boolean;\n json?: boolean;\n }\n): Promise<void> {\n try {\n const payload: Record<string, unknown> = {};\n\n if (options.name !== undefined) payload.name = options.name;\n if (options.description !== undefined)\n payload.description = options.description;\n if (options.category !== undefined) payload.category = options.category;\n if (options.agentId !== undefined) payload.agentId = options.agentId;\n if (options.calculatorId !== undefined)\n payload.calculatorId = options.calculatorId;\n if (options.unit !== undefined) payload.unit = options.unit;\n if (options.active) payload.isActive = true;\n if (options.inactive) payload.isActive = false;\n\n // Validate and set scope\n let validatedScope: KpiScope | undefined;\n if (options.scope !== undefined) {\n const upperScope = options.scope.toUpperCase() as KpiScope;\n if (!KPI_SCOPES.includes(upperScope)) {\n console.error(`Error: Invalid scope \"${options.scope}\"`);\n console.error(`Valid values: ${KPI_SCOPES.join(\", \")}`);\n process.exit(1);\n }\n payload.scope = upperScope;\n validatedScope = upperScope;\n }\n\n // Handle formula update - validate and parse before storing\n if (options.formula !== undefined) {\n const validation = await validateKpiFormula(options.formula, options.agentId, validatedScope);\n if (!validation.valid) {\n console.error(`Error: Invalid formula: ${validation.error}`);\n process.exit(1);\n }\n // Use the parsed formula AST, not the raw string\n payload.calculatorParams = { formula: validation.parsedFormula };\n }\n\n // Validate and set aggregation method\n if (options.aggregation) {\n const upperAggregation =\n options.aggregation.toUpperCase() as DefaultAggregationMethod;\n if (!AGGREGATION_METHODS.includes(upperAggregation)) {\n console.error(`Error: Invalid aggregation method \"${options.aggregation}\"`);\n console.error(`Valid values: ${AGGREGATION_METHODS.join(\", \")}`);\n process.exit(1);\n }\n payload.defaultAggregationMethod = upperAggregation;\n }\n\n if (Object.keys(payload).length === 0) {\n console.error(\"Error: At least one field to update is required\");\n process.exit(1);\n }\n\n const kpi = await updateKpi(id, payload);\n\n if (options.json) {\n console.log(JSON.stringify(kpi, null, 2));\n } else {\n console.log(\"KPI definition updated successfully!\");\n console.log(\"\");\n formatKpiDetail(kpi);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function deleteCommand(\n id: string,\n options: { force?: boolean }\n): Promise<void> {\n try {\n if (!options.force) {\n console.log(\"Are you sure you want to delete this KPI definition?\");\n console.log(\"Use --force to confirm deletion.\");\n process.exit(1);\n }\n\n await deleteKpi(id);\n console.log(\"KPI definition deleted successfully.\");\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function contextVariablesCommand(options: {\n json?: boolean;\n agentId?: string;\n scope?: string;\n}): Promise<void> {\n try {\n // Validate scope if provided\n let validatedScope: KpiScope | undefined;\n if (options.scope) {\n const upperScope = options.scope.toUpperCase() as KpiScope;\n if (!KPI_SCOPES.includes(upperScope)) {\n console.error(`Error: Invalid scope \"${options.scope}\"`);\n console.error(`Valid values: ${KPI_SCOPES.join(\", \")}`);\n process.exit(1);\n }\n validatedScope = upperScope;\n }\n\n const variables = await getKpiContextVariables(options.agentId, validatedScope);\n\n if (options.json) {\n console.log(JSON.stringify(variables, null, 2));\n } else {\n console.log(\"Available context variables for KPI formulas:\");\n console.log(\"\");\n formatContextVariablesTable(variables);\n console.log(\"\");\n console.log(\n \"Use these variable names in your formula expressions, e.g.:\"\n );\n console.log(' IF(PII detected, 1, 0)');\n console.log(' Documents count * 10');\n console.log(' IF(CODE detected AND SECRET detected, \"high-risk\", \"normal\")');\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function validateCommand(options: {\n formula: string;\n agentId?: string;\n scope?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n if (!options.formula) {\n console.error(\"Error: --formula is required\");\n process.exit(1);\n }\n\n // Validate scope if provided\n let validatedScope: KpiScope | undefined;\n if (options.scope) {\n const upperScope = options.scope.toUpperCase() as KpiScope;\n if (!KPI_SCOPES.includes(upperScope)) {\n console.error(`Error: Invalid scope \"${options.scope}\"`);\n console.error(`Valid values: ${KPI_SCOPES.join(\", \")}`);\n process.exit(1);\n }\n validatedScope = upperScope;\n }\n\n const result = await validateKpiFormula(options.formula, options.agentId, validatedScope);\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n if (result.valid) {\n console.log(\"Formula is valid!\");\n console.log(`Result type: ${result.type || \"unknown\"}`);\n } else {\n console.error(\"Formula is invalid:\");\n console.error(` ${result.error}`);\n if (result.charIndex !== undefined) {\n console.error(` Position: character ${result.charIndex}`);\n }\n process.exit(1);\n }\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nfunction templatesCommand(options: { json?: boolean }): void {\n if (options.json) {\n console.log(\n JSON.stringify(\n CLASSIFIER_TEMPLATES.map((t) => ({\n id: t.id,\n name: t.name,\n description: t.description,\n defaultUnit: t.defaultUnit,\n outputClasses: t.defaultOutputClasses,\n })),\n null,\n 2,\n ),\n );\n } else {\n console.log(\"Available Classifier Templates:\");\n console.log(\"\");\n for (const t of CLASSIFIER_TEMPLATES) {\n console.log(` ${t.id.padEnd(24)} ${t.description}`);\n const classRange = t.defaultOutputClasses;\n console.log(\n `${\"\".padEnd(26)}Classes: ${classRange.map((c) => `${c.value} (${c.label})`).join(\", \")}`,\n );\n console.log(\n `${\"\".padEnd(26)}Default unit: ${t.defaultUnit}`,\n );\n console.log(\"\");\n }\n console.log(\"Usage:\");\n console.log(\n ' olakai kpis create --name \"User Satisfaction\" --calculator-id classifier --template-id sentiment_scorer --scope CHAT',\n );\n }\n}\n\nexport function registerKpisCommand(program: Command): void {\n const kpis = program\n .command(\"kpis\")\n .description(\"Manage KPI definitions\");\n\n kpis\n .command(\"list\")\n .description(\"List all KPI definitions\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--agent-id <id>\", \"Filter by agent ID\")\n .option(\"--include-inactive\", \"Include inactive KPI definitions\")\n .action(listCommand);\n\n kpis\n .command(\"get <id>\")\n .description(\"Get KPI definition details\")\n .option(\"--json\", \"Output as JSON\")\n .action(getCommand);\n\n kpis\n .command(\"create\")\n .description(\"Create a new KPI definition\")\n .requiredOption(\"--name <name>\", \"KPI name\")\n .requiredOption(\n \"--calculator-id <id>\",\n \"Calculator type: formula, classifier, or llm-data\"\n )\n .requiredOption(\n \"--scope <scope>\",\n \"KPI scope: PROMPT_REQUEST, CHAT, or DOCUMENT\"\n )\n .option(\"--description <description>\", \"KPI description\")\n .option(\"--type <type>\", \"KPI type: PREDEFINED or USER_DEFINED (default)\")\n .option(\"--category <category>\", \"KPI category for grouping\")\n .option(\"--agent-id <id>\", \"Associate KPI with a specific agent\")\n .option(\"--formula <formula>\", \"Formula expression (required for formula calculator)\")\n .option(\"--template-id <id>\", \"Classifier template: sentiment_scorer, time_saved_estimator\")\n .option(\"--output-classes <values>\", \"Override output class values (comma-separated numbers)\")\n .option(\"--output-labels <labels>\", \"Override output class labels (comma-separated)\")\n .option(\"--sampling-factor <factor>\", \"Fraction of events to classify, 0-1 (cost control)\")\n .option(\"--unit <unit>\", 'Display unit (e.g., \"ms\", \"%\", \"count\")')\n .option(\n \"--aggregation <method>\",\n \"Default aggregation: SUM, AVERAGE, COUNT, MIN, MAX, LATEST (default)\"\n )\n .option(\"--json\", \"Output as JSON\")\n .action(createCommand);\n\n kpis\n .command(\"templates\")\n .description(\"List available classifier templates\")\n .option(\"--json\", \"Output as JSON\")\n .action(templatesCommand);\n\n kpis\n .command(\"update <id>\")\n .description(\"Update a KPI definition\")\n .option(\"--name <name>\", \"KPI name\")\n .option(\"--description <description>\", \"KPI description\")\n .option(\"--category <category>\", \"KPI category\")\n .option(\"--agent-id <id>\", \"Associate with agent\")\n .option(\"--scope <scope>\", \"KPI scope: PROMPT_REQUEST, CHAT, or DOCUMENT\")\n .option(\"--calculator-id <id>\", \"Calculator type\")\n .option(\"--formula <formula>\", \"Formula expression\")\n .option(\"--unit <unit>\", \"Display unit\")\n .option(\"--aggregation <method>\", \"Default aggregation method\")\n .option(\"--active\", \"Set KPI as active\")\n .option(\"--inactive\", \"Set KPI as inactive\")\n .option(\"--json\", \"Output as JSON\")\n .action(updateCommand);\n\n kpis\n .command(\"delete <id>\")\n .description(\"Delete a KPI definition\")\n .option(\"--force\", \"Skip confirmation\")\n .action(deleteCommand);\n\n kpis\n .command(\"context-variables\")\n .description(\"List available context variables for formulas\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--agent-id <id>\", \"Include agent-specific variables\")\n .option(\"--scope <scope>\", \"Filter variables by scope: PROMPT_REQUEST, CHAT, or DOCUMENT\")\n .action(contextVariablesCommand);\n\n kpis\n .command(\"validate\")\n .description(\"Validate a KPI formula expression\")\n .requiredOption(\"--formula <formula>\", \"Formula expression to validate\")\n .option(\"--agent-id <id>\", \"Include agent-specific context\")\n .option(\"--scope <scope>\", \"Validate against scope: PROMPT_REQUEST, CHAT, or DOCUMENT\")\n .option(\"--json\", \"Output as JSON\")\n .action(validateCommand);\n}\n","import { Command } from \"commander\";\nimport {\n listCustomDataConfigs,\n getCustomDataConfig,\n createCustomDataConfig,\n updateCustomDataConfig,\n deleteCustomDataConfig,\n type CustomDataConfig,\n type CustomDataType,\n} from \"../lib/api.js\";\n\nconst DATA_TYPES: CustomDataType[] = [\"STRING\", \"NUMBER\", \"BOOLEAN\"];\n\nfunction formatTable(configs: CustomDataConfig[]): void {\n if (configs.length === 0) {\n console.log(\"No custom data configurations found.\");\n return;\n }\n\n // Calculate column widths\n const headers = [\"ID\", \"NAME\", \"TYPE\", \"AGENT ID\", \"DESCRIPTION\"];\n const rows = configs.map((config) => [\n config.id.slice(0, 12) + \"...\",\n config.name.slice(0, 25),\n config.type,\n config.agentId ? config.agentId.slice(0, 12) + \"...\" : \"(account-level)\",\n (config.description || \"-\").slice(0, 30),\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n // Print header\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n // Print rows\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n}\n\nfunction formatDetail(config: CustomDataConfig): void {\n console.log(`ID: ${config.id}`);\n console.log(`Name: ${config.name}`);\n console.log(`Type: ${config.type}`);\n console.log(`Agent ID: ${config.agentId || \"(account-level / legacy)\"}`);\n console.log(`Description: ${config.description || \"-\"}`);\n if (config.createdAt) {\n console.log(`Created: ${new Date(config.createdAt).toISOString()}`);\n }\n if (config.updatedAt) {\n console.log(`Updated: ${new Date(config.updatedAt).toISOString()}`);\n }\n}\n\nasync function listCommand(options: { agentId?: string; json?: boolean }): Promise<void> {\n try {\n const configs = await listCustomDataConfigs(options.agentId);\n\n if (options.json) {\n console.log(JSON.stringify(configs, null, 2));\n } else {\n formatTable(configs);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function getCommand(\n id: string,\n options: { json?: boolean }\n): Promise<void> {\n try {\n const config = await getCustomDataConfig(id);\n\n if (options.json) {\n console.log(JSON.stringify(config, null, 2));\n } else {\n formatDetail(config);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function createCommand(options: {\n agentId: string;\n name: string;\n type: string;\n description?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n if (!options.agentId) {\n console.error(\"Error: --agent-id is required\");\n console.error(\"Custom data configurations must be associated with an agent.\");\n process.exit(1);\n }\n\n if (!options.name) {\n console.error(\"Error: --name is required\");\n process.exit(1);\n }\n\n if (!options.type) {\n console.error(\"Error: --type is required\");\n console.error(`Valid values: ${DATA_TYPES.join(\", \")}`);\n process.exit(1);\n }\n\n const upperType = options.type.toUpperCase() as CustomDataType;\n if (!DATA_TYPES.includes(upperType)) {\n console.error(`Error: Invalid type \"${options.type}\"`);\n console.error(`Valid values: ${DATA_TYPES.join(\", \")}`);\n process.exit(1);\n }\n\n const config = await createCustomDataConfig({\n agentId: options.agentId,\n name: options.name,\n type: upperType,\n description: options.description ?? null,\n });\n\n if (options.json) {\n console.log(JSON.stringify(config, null, 2));\n } else {\n console.log(\"Custom data configuration created successfully!\");\n console.log(\"\");\n formatDetail(config);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function updateCommand(\n id: string,\n options: {\n name?: string;\n type?: string;\n description?: string;\n json?: boolean;\n }\n): Promise<void> {\n try {\n const payload: {\n name?: string;\n type?: CustomDataType;\n description?: string | null;\n } = {};\n\n if (options.name !== undefined) payload.name = options.name;\n if (options.description !== undefined)\n payload.description = options.description || null;\n\n if (options.type !== undefined) {\n const upperType = options.type.toUpperCase() as CustomDataType;\n if (!DATA_TYPES.includes(upperType)) {\n console.error(`Error: Invalid type \"${options.type}\"`);\n console.error(`Valid values: ${DATA_TYPES.join(\", \")}`);\n process.exit(1);\n }\n payload.type = upperType;\n }\n\n if (Object.keys(payload).length === 0) {\n console.error(\"Error: At least one field to update is required\");\n process.exit(1);\n }\n\n const config = await updateCustomDataConfig(id, payload);\n\n if (options.json) {\n console.log(JSON.stringify(config, null, 2));\n } else {\n console.log(\"Custom data configuration updated successfully!\");\n console.log(\"\");\n formatDetail(config);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function deleteCommand(\n id: string,\n options: { force?: boolean }\n): Promise<void> {\n try {\n if (!options.force) {\n console.log(\n \"Are you sure you want to delete this custom data configuration?\"\n );\n console.log(\"Use --force to confirm deletion.\");\n process.exit(1);\n }\n\n await deleteCustomDataConfig(id);\n console.log(\"Custom data configuration deleted successfully.\");\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nexport function registerCustomDataCommand(program: Command): void {\n const customData = program\n .command(\"custom-data\")\n .description(\"Manage custom data configurations for KPI formulas\");\n\n customData\n .command(\"list\")\n .description(\"List custom data configurations\")\n .option(\"--agent-id <agentId>\", \"Filter by agent ID (omit to list all account configs)\")\n .option(\"--json\", \"Output as JSON\")\n .action(listCommand);\n\n customData\n .command(\"get <id>\")\n .description(\"Get custom data configuration details\")\n .option(\"--json\", \"Output as JSON\")\n .action(getCommand);\n\n customData\n .command(\"create\")\n .description(\"Create a new custom data configuration for an agent\")\n .requiredOption(\"--agent-id <agentId>\", \"Agent ID (required)\")\n .requiredOption(\"--name <name>\", \"Configuration name (used in KPI formulas)\")\n .requiredOption(\n \"--type <type>\",\n \"Data type: STRING, NUMBER, or BOOLEAN\"\n )\n .option(\"--description <description>\", \"Configuration description\")\n .option(\"--json\", \"Output as JSON\")\n .action(createCommand);\n\n customData\n .command(\"update <id>\")\n .description(\"Update a custom data configuration\")\n .option(\"--name <name>\", \"Configuration name\")\n .option(\"--type <type>\", \"Data type: STRING, NUMBER, or BOOLEAN\")\n .option(\"--description <description>\", \"Configuration description\")\n .option(\"--json\", \"Output as JSON\")\n .action(updateCommand);\n\n customData\n .command(\"delete <id>\")\n .description(\"Delete a custom data configuration\")\n .option(\"--force\", \"Skip confirmation\")\n .action(deleteCommand);\n}\n","import { Command } from \"commander\";\nimport {\n listActivity,\n getActivity,\n getActivityKpis,\n listSessions,\n type ActivityPrompt,\n type ActivityListResponse,\n type ActivityKpisResponse,\n type CoreKpiValue,\n type SessionsListResponse,\n} from \"../lib/api.js\";\n\nfunction formatActivityTable(data: ActivityListResponse): void {\n if (data.prompts.length === 0) {\n console.log(\"No activity found.\");\n return;\n }\n\n // Calculate column widths\n const headers = [\"ID\", \"AGENT\", \"APP\", \"MODEL\", \"TOKENS\", \"TIME(ms)\", \"RISK\", \"STATUS\"];\n const rows = data.prompts.map((prompt) => [\n prompt.id.slice(0, 12) + \"...\",\n prompt.agentName || (prompt.agentId ? prompt.agentId.slice(0, 12) + \"...\" : \"-\"),\n prompt.app.slice(0, 12),\n prompt.modelId?.slice(0, 15) || \"-\",\n String(prompt.tokens),\n String(prompt.requestTime),\n prompt.isHighRisk ? \"Yes\" : \"No\",\n prompt.decorationStatus.slice(0, 10),\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n // Print header\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n // Print rows\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n\n // Print pagination info\n console.log(\"\");\n console.log(`Showing ${data.prompts.length} of ${data.total} results (offset: ${data.offset})`);\n if (data.hasMore) {\n console.log(`Use --offset ${data.offset + data.limit} to see more results`);\n }\n}\n\nfunction formatActivityDetail(prompt: ActivityPrompt): void {\n console.log(`ID: ${prompt.id}`);\n console.log(`Created: ${prompt.createdAt}`);\n console.log(`Agent: ${prompt.agentName || \"-\"} (${prompt.agentId || \"-\"})`);\n console.log(`Workflow: ${prompt.workflowName || \"-\"} (${prompt.workflowId || \"-\"})`);\n if (prompt.taskExecutionId) {\n console.log(`Task Exec ID: ${prompt.taskExecutionId}`);\n }\n console.log(`App: ${prompt.app}`);\n console.log(`Model: ${prompt.modelId || \"-\"} (${prompt.modelType || \"-\"})`);\n console.log(`Tokens: ${prompt.tokens}`);\n console.log(`Request Time: ${prompt.requestTime}ms`);\n console.log(`High Risk: ${prompt.isHighRisk ? \"Yes\" : \"No\"}`);\n console.log(`Blocked: ${prompt.blocked ? \"Yes\" : \"No\"}`);\n console.log(`Status: ${prompt.decorationStatus}`);\n\n if (prompt.sensitivity && prompt.sensitivity.length > 0) {\n console.log(`Sensitivity: ${prompt.sensitivity.join(\", \")}`);\n }\n\n if (prompt.analytics) {\n console.log(\"\");\n console.log(\"Analytics:\");\n console.log(` Task: ${prompt.analytics.task || \"-\"}`);\n console.log(` Subtask: ${prompt.analytics.subtask || \"-\"}`);\n console.log(` Time Saved: ${prompt.analytics.timesaved_minutes ?? \"-\"} minutes`);\n console.log(` Risk Score: ${prompt.analytics.riskassessment_dangerousity ?? \"-\"}`);\n }\n\n if (prompt.kpiData && Object.keys(prompt.kpiData).length > 0) {\n console.log(\"\");\n console.log(\"KPIs:\");\n for (const [key, value] of Object.entries(prompt.kpiData)) {\n console.log(` ${key}: ${value}`);\n }\n }\n\n if (prompt.prompt !== undefined) {\n console.log(\"\");\n console.log(\"Prompt:\");\n console.log(\"---\");\n console.log(prompt.prompt.slice(0, 1000) + (prompt.prompt.length > 1000 ? \"...\" : \"\"));\n console.log(\"---\");\n }\n\n if (prompt.response !== undefined) {\n console.log(\"\");\n console.log(\"Response:\");\n console.log(\"---\");\n console.log(prompt.response.slice(0, 1000) + (prompt.response.length > 1000 ? \"...\" : \"\"));\n console.log(\"---\");\n }\n}\n\nfunction formatCoreKpi(kpi: CoreKpiValue): string {\n const prefix = kpi.unitPrefix || \"\";\n const suffix = kpi.unitSuffix || \"\";\n return `${prefix}${kpi.value}${suffix}`;\n}\n\nfunction formatKpisResponse(data: ActivityKpisResponse): void {\n // Core KPIs\n console.log(\"Core KPIs:\");\n for (const kpi of data.coreKpis) {\n console.log(` ${kpi.name.padEnd(25)} ${formatCoreKpi(kpi)}`);\n }\n\n // Custom KPIs\n if (data.kpis.length > 0) {\n console.log(\"\");\n console.log(\"Custom KPIs:\");\n const headers = [\"NAME\", \"VALUE\", \"UNIT\", \"AGGREGATION\", \"DATA POINTS\"];\n const rows = data.kpis.map((kpi) => [\n kpi.name.slice(0, 25),\n kpi.value !== null ? String(kpi.value) : \"-\",\n kpi.unit || \"-\",\n kpi.aggregationMethod,\n String(kpi.dataPointCount),\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n console.log(\" \" + headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(\" \" + widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n for (const row of rows) {\n console.log(\" \" + row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n }\n\n // Period data\n if (data.periodData && data.periodData.length > 0) {\n console.log(\"\");\n console.log(\"Period Breakdown:\");\n for (const period of data.periodData) {\n console.log(` ${period.periodStart} - ${period.periodEnd}`);\n for (const kpi of period.coreKpis) {\n console.log(` ${kpi.name}: ${formatCoreKpi(kpi)}`);\n }\n }\n }\n\n // Atoms summary\n if (data.atoms && data.atoms.length > 0) {\n console.log(\"\");\n console.log(`Per-Prompt KPI Atoms: ${data.atoms.length} records`);\n console.log(\" (Use --json for full atom data)\");\n }\n}\n\nasync function listCommand(options: {\n agentId?: string;\n workflowId?: string;\n since?: string;\n until?: string;\n limit?: string;\n offset?: string;\n includeContent?: boolean;\n includeAnalytics?: boolean;\n json?: boolean;\n}): Promise<void> {\n try {\n const data = await listActivity({\n agentId: options.agentId,\n workflowId: options.workflowId,\n since: options.since,\n until: options.until,\n limit: options.limit ? parseInt(options.limit, 10) : undefined,\n offset: options.offset ? parseInt(options.offset, 10) : undefined,\n includeContent: options.includeContent,\n includeAnalytics: options.includeAnalytics,\n });\n\n if (options.json) {\n console.log(JSON.stringify(data, null, 2));\n } else {\n formatActivityTable(data);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function getCommand(\n id: string,\n options: { includeContent?: boolean; json?: boolean }\n): Promise<void> {\n try {\n const prompt = await getActivity(id, options.includeContent);\n\n if (options.json) {\n console.log(JSON.stringify(prompt, null, 2));\n } else {\n formatActivityDetail(prompt);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nasync function kpisCommand(options: {\n agentId?: string;\n workflowId?: string;\n since?: string;\n until?: string;\n period?: string;\n includeAtoms?: boolean;\n json?: boolean;\n}): Promise<void> {\n try {\n if (!options.agentId && !options.workflowId) {\n console.error(\"Error: Either --agent-id or --workflow-id is required\");\n process.exit(1);\n }\n\n const data = await getActivityKpis({\n agentId: options.agentId,\n workflowId: options.workflowId,\n since: options.since,\n until: options.until,\n period: options.period as \"hourly\" | \"daily\" | \"weekly\" | undefined,\n includeAtoms: options.includeAtoms,\n });\n\n if (options.json) {\n console.log(JSON.stringify(data, null, 2));\n } else {\n formatKpisResponse(data);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nfunction formatSessionsTable(data: SessionsListResponse): void {\n // Summary\n console.log(\"Session Decoration Status\");\n console.log(\"\");\n console.log(\"Summary:\");\n console.log(` Total Sessions: ${data.summary.sessionCount}`);\n\n const statuses = [\"DECORATED\", \"NEW\", \"DECORATION_FAILED\", \"DECORATION_OUTDATED\", \"SKIPPED\"];\n for (const status of statuses) {\n const count = data.summary.byStatus[status] || 0;\n const pct = data.summary.sessionCount > 0 ? ((count / data.summary.sessionCount) * 100).toFixed(1) : \"0.0\";\n const label = status.charAt(0) + status.slice(1).toLowerCase().replace(/_/g, \" \");\n console.log(` ${label.padEnd(17)} ${String(count).padStart(4)} (${pct}%)`);\n }\n\n if (data.sessions.length === 0) {\n console.log(\"\");\n console.log(\"No sessions found.\");\n return;\n }\n\n console.log(\"\");\n\n // Table\n const headers = [\"ID\", \"STATUS\", \"DATE\", \"CANDIDATE\", \"ERRORS\", \"KPI DATA\", \"VERSION\"];\n const rows = data.sessions.map((s) => [\n s.id.slice(0, 15) + \"...\",\n s.decorationStatus,\n s.decorationDate || \"-\",\n s.decorationCandidate ? \"Yes\" : \"No\",\n String(s.decorationErrorStreak),\n s.hasKpiData ? \"Yes\" : \"No\",\n s.decoratorVersion || \"-\",\n ]);\n\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => r[i].length))\n );\n\n console.log(headers.map((h, i) => h.padEnd(widths[i])).join(\" \"));\n console.log(widths.map((w) => \"-\".repeat(w)).join(\" \"));\n\n for (const row of rows) {\n console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(\" \"));\n }\n\n console.log(\"\");\n console.log(`Showing ${data.sessions.length} of ${data.total} results (offset: ${data.offset})`);\n if (data.hasMore) {\n console.log(`Use --offset ${data.offset + data.limit} to see more results`);\n }\n}\n\nasync function sessionsCommand(options: {\n agentId: string;\n since?: string;\n until?: string;\n limit?: string;\n offset?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n const data = await listSessions({\n agentId: options.agentId,\n since: options.since,\n until: options.until,\n limit: options.limit ? parseInt(options.limit, 10) : undefined,\n offset: options.offset ? parseInt(options.offset, 10) : undefined,\n });\n\n if (options.json) {\n console.log(JSON.stringify(data, null, 2));\n } else {\n formatSessionsTable(data);\n }\n } catch (error) {\n console.error(\n `Error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n process.exit(1);\n }\n}\n\nexport function registerActivityCommand(program: Command): void {\n const activity = program\n .command(\"activity\")\n .description(\"Inspect AI activity and prompts\");\n\n activity\n .command(\"list\")\n .description(\"List prompt requests with filters\")\n .option(\"--agent-id <id>\", \"Filter by agent ID\")\n .option(\"--workflow-id <id>\", \"Filter by workflow ID\")\n .option(\"--since <date>\", \"Start date (ISO format)\")\n .option(\"--until <date>\", \"End date (ISO format)\")\n .option(\"--limit <n>\", \"Results per page\", \"20\")\n .option(\"--offset <n>\", \"Skip first N results\", \"0\")\n .option(\"--include-content\", \"Include prompt/response content\")\n .option(\"--include-analytics\", \"Include advanced analytics\")\n .option(\"--json\", \"Output as JSON\")\n .action(listCommand);\n\n activity\n .command(\"get <id>\")\n .description(\"Get prompt request details\")\n .option(\"--include-content\", \"Include prompt/response content\")\n .option(\"--json\", \"Output as JSON\")\n .action(getCommand);\n\n activity\n .command(\"kpis\")\n .description(\"Get aggregated KPI values\")\n .option(\"--agent-id <id>\", \"Agent ID\")\n .option(\"--workflow-id <id>\", \"Workflow ID\")\n .option(\"--since <date>\", \"Period start (ISO format)\")\n .option(\"--until <date>\", \"Period end (ISO format)\")\n .option(\"--period <type>\", \"Aggregation period (hourly, daily, weekly)\")\n .option(\"--include-atoms\", \"Include per-prompt KPI data\")\n .option(\"--json\", \"Output as JSON\")\n .action(kpisCommand);\n\n activity\n .command(\"sessions\")\n .description(\"Inspect chat/session decoration status for troubleshooting\")\n .requiredOption(\"--agent-id <id>\", \"Agent ID (required)\")\n .option(\"--since <date>\", \"Start date (ISO format)\")\n .option(\"--until <date>\", \"End date (ISO format)\")\n .option(\"--limit <n>\", \"Results per page\", \"20\")\n .option(\"--offset <n>\", \"Skip first N results\", \"0\")\n .option(\"--json\", \"Output as JSON\")\n .action(sessionsCommand);\n}\n","import * as fs from \"node:fs\";\nimport { Command } from \"commander\";\nimport \"../monitor/plugins/index.js\";\nimport {\n TOOL_IDS,\n getPlugin,\n isToolId,\n listPlugins,\n type HookResult,\n type ToolId,\n type ToolMonitorPlugin,\n} from \"../monitor/plugin.js\";\nimport { isInteractive, promptUser } from \"../monitor/prompt.js\";\nimport { runMonitorInstall } from \"../monitor/install.js\";\nimport {\n formatRegistryTable,\n readRegistry,\n reconcileCurrentWorkspace,\n removeEntry,\n} from \"../monitor/registry.js\";\nimport { findConfiguredWorkspace } from \"../monitor/paths.js\";\n\n// Pre-Stage-2 `monitor.ts` exposed these symbols directly; downstream\n// tests and possibly external scripts import them from this module.\n// Re-export so the public surface is unchanged after the plugin split.\nexport {\n mergeHooksSettings,\n type HookMatcherEntry,\n type HookCommand,\n} from \"../monitor/plugins/claude-code/settings.js\";\nexport {\n buildClaudeCodePayload as buildPayload,\n type ClaudeHookEvent,\n} from \"../monitor/plugins/claude-code/hook.js\";\nexport { resolveProjectRootFromPayload } from \"../monitor/plugins/claude-code/index.js\";\nexport { type MonitorConfig } from \"../monitor/plugins/claude-code/config.js\";\n\nfunction readStdin(timeoutMs: number = 3000): Promise<string> {\n return new Promise((resolve) => {\n if (process.stdin.isTTY) {\n resolve(\"\");\n return;\n }\n\n let data = \"\";\n const timer = setTimeout(() => {\n process.stdin.removeAllListeners();\n process.stdin.destroy();\n resolve(data);\n }, timeoutMs);\n\n process.stdin.setEncoding(\"utf-8\");\n process.stdin.on(\"data\", (chunk: string) => {\n data += chunk;\n });\n process.stdin.on(\"end\", () => {\n clearTimeout(timer);\n resolve(data);\n });\n process.stdin.on(\"error\", () => {\n clearTimeout(timer);\n resolve(data);\n });\n });\n}\n\n// D-002 surface: in non-interactive contexts (CI, scripts) `--tool` is\n// optional and defaults to claude-code with a deprecation notice — this\n// keeps pre-Stage-2 automation working while signalling that the flag\n// is the way forward. Interactive contexts always prompt when the flag\n// is absent.\nconst DEFAULT_NON_INTERACTIVE_TOOL: ToolId = \"claude-code\";\n\nasync function resolveToolFromOptions(\n flag: string | undefined,\n context: \"init\" | \"status\" | \"disable\",\n): Promise<ToolId> {\n if (typeof flag === \"string\" && flag.length > 0) {\n if (!isToolId(flag)) {\n console.error(\n `Unknown --tool \"${flag}\". Supported: ${TOOL_IDS.join(\", \")}`,\n );\n process.exit(1);\n }\n return flag;\n }\n\n if (!isInteractive()) {\n console.error(\n `[olakai] --tool not provided; defaulting to \"${DEFAULT_NON_INTERACTIVE_TOOL}\". This default will be removed in a future version — please pass --tool <tool> explicitly.`,\n );\n return DEFAULT_NON_INTERACTIVE_TOOL;\n }\n\n return promptForTool(context);\n}\n\nasync function promptForTool(\n context: \"init\" | \"status\" | \"disable\",\n): Promise<ToolId> {\n const plugins = listPlugins();\n const detected: ToolId[] = [];\n for (const p of plugins) {\n try {\n if (await p.detectInstalled()) detected.push(p.id);\n } catch {\n // detectInstalled is best-effort\n }\n }\n\n console.log(\"Which coding tool do you want to monitor?\");\n for (let i = 0; i < plugins.length; i++) {\n const p = plugins[i];\n const flag = detected.includes(p.id) ? \" (detected)\" : \"\";\n console.log(` ${i + 1}. ${p.displayName} [${p.id}]${flag}`);\n }\n\n const defaultIdx = plugins.findIndex((p) => detected.includes(p.id));\n const defaultLabel = defaultIdx >= 0 ? `${defaultIdx + 1}` : \"1\";\n const answer = await promptUser(\n `Select a tool to ${context} (1-${plugins.length}) [${defaultLabel}]: `,\n );\n\n const choice = answer.trim() === \"\" ? defaultLabel : answer.trim();\n const idx = parseInt(choice, 10) - 1;\n if (isNaN(idx) || idx < 0 || idx >= plugins.length) {\n console.error(\"Invalid selection.\");\n process.exit(1);\n }\n return plugins[idx].id;\n}\n\ninterface ToolFlag {\n tool?: string;\n}\n\nasync function initCommand(options: ToolFlag): Promise<void> {\n const toolId = await resolveToolFromOptions(options.tool, \"init\");\n const plugin = getPlugin(toolId);\n // Delegate to `runMonitorInstall` so this command and the chained\n // `olakai init` path go through exactly one install code path. Any\n // future cross-cutting addition (telemetry, validation, logging)\n // only needs to touch `src/monitor/install.ts`.\n await runPluginAction(plugin, () => runMonitorInstall(toolId, { interactive: true }));\n}\n\nasync function statusCommand(\n options: ToolFlag & { json?: boolean },\n): Promise<void> {\n const toolId = await resolveToolFromOptions(options.tool, \"status\");\n const plugin = getPlugin(toolId);\n\n if (options.json) {\n const report = await plugin.status({ projectRoot: process.cwd() });\n console.log(JSON.stringify(report, null, 2));\n return;\n }\n\n // For non-JSON Claude Code we keep the rich human formatter from\n // pre-Stage-2 (recent activity table). Other plugins ship their own\n // pretty printer in S3/S4; until then, surface their `notes` array\n // as one line per note so a user running `olakai monitor status\n // --tool codex` today sees the \"coming soon\" message rather than\n // raw JSON.\n if (plugin.id === \"claude-code\") {\n const { printClaudeCodeStatus } = await import(\n \"../monitor/plugins/claude-code/status.js\"\n );\n await printClaudeCodeStatus({ projectRoot: process.cwd() });\n return;\n }\n\n const report = await plugin.status({ projectRoot: process.cwd() });\n if (report.notes && report.notes.length > 0) {\n for (const note of report.notes) {\n console.log(note);\n }\n return;\n }\n // No notes to surface — fall through to JSON so the user sees\n // something rather than nothing.\n console.log(JSON.stringify(report, null, 2));\n}\n\nasync function disableCommand(\n options: ToolFlag & { keepConfig?: boolean; deleteAgent?: boolean },\n): Promise<void> {\n const toolId = await resolveToolFromOptions(options.tool, \"disable\");\n const plugin = getPlugin(toolId);\n\n // Capture the agent id BEFORE uninstall when the user asks to delete\n // the remote agent — uninstall removes the local monitor config, so\n // status() afterwards would have nothing to report. Errors here are\n // non-fatal: if status fails we still proceed with the local\n // uninstall and skip the remote delete.\n let agentIdToDelete: string | undefined;\n if (options.deleteAgent) {\n try {\n const report = await plugin.status({ projectRoot: process.cwd() });\n if (report.configured && report.agentId) {\n agentIdToDelete = report.agentId;\n } else {\n console.log(\n \"No monitor config found in this workspace — nothing to delete remotely.\",\n );\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.warn(\n `Couldn't read local monitor config to identify the agent (${msg}). Proceeding with local-only uninstall.`,\n );\n }\n }\n\n // Resolve the configured workspace root BEFORE uninstall so we can key\n // the registry removal even when `--keep-config` is absent (uninstall\n // deletes the config, after which the root is no longer discoverable).\n const registryRoot = findConfiguredWorkspace(process.cwd(), TOOL_IDS);\n\n await runPluginAction(plugin, () =>\n plugin.uninstall({\n projectRoot: process.cwd(),\n keepConfig: options.keepConfig,\n }),\n );\n\n // Drop the machine-registry entry (best-effort — the registry is an\n // index, not the source of truth). Only when the config is actually\n // gone; `--keep-config` leaves the workspace monitored.\n if (registryRoot && !options.keepConfig) {\n try {\n removeEntry(registryRoot, toolId);\n } catch {\n // Never let a registry write failure surface from disable.\n }\n }\n\n if (agentIdToDelete) {\n const { deleteAgent } = await import(\"../lib/api.js\");\n try {\n await deleteAgent(agentIdToDelete);\n console.log(`✓ Remote agent ${agentIdToDelete} deleted.`);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(\n `Local uninstall succeeded, but remote agent delete failed: ${msg}`,\n );\n console.error(\n `You can retry by visiting the Olakai dashboard, or rerun 'olakai monitor disable --tool ${toolId} --delete-agent' (the local config is gone, so the agent id won't be re-discovered — use the dashboard).`,\n );\n process.exit(1);\n }\n }\n}\n\n/**\n * `olakai monitor list [--json]` — the machine lens (D-001). Shows every\n * monitored (workspace, tool) recorded in `~/.olakai/registry.json`\n * across this whole machine, not just `process.cwd()` (which is all\n * `monitor status` sees).\n *\n * Adoption: we first reconcile the current workspace so installs that\n * predate the registry (config on disk, no registry entry) get backfilled\n * before we render — otherwise a user who upgraded the CLI would see an\n * empty list despite having monitoring configured here.\n */\nasync function listCommand(options: { json?: boolean }): Promise<void> {\n // Backfill the current workspace from disk if it's configured but\n // unregistered. Best-effort — never block the list on it.\n try {\n reconcileCurrentWorkspace(process.cwd());\n } catch {\n // reconcile is best-effort; fall through and render whatever the\n // registry already holds.\n }\n\n const registry = readRegistry();\n\n if (options.json) {\n console.log(JSON.stringify(registry.workspaces, null, 2));\n return;\n }\n\n console.log(formatRegistryTable(registry));\n}\n\n/**\n * `olakai monitor doctor [--tool X] [--all] [--fix] [--json]` (OLA-244,\n * S2). The end-to-end health check. Runs an ordered check chain per\n * (workspace, tool); `--fix` runs the registered repair for each fixable\n * failure. `--all` fans out across every registry entry on the machine.\n *\n * Tool resolution: `--all` ignores `--tool` (it iterates the registry).\n * Otherwise we resolve `--tool` the same way init/status/disable do —\n * prompting in interactive mode when omitted.\n */\nasync function doctorCommand(\n options: ToolFlag & {\n all?: boolean;\n fix?: boolean;\n json?: boolean;\n recreateMissing?: boolean;\n },\n): Promise<void> {\n const { runDoctor, printDoctorResult, exitCodeForStatus } = await import(\n \"../monitor/doctor.js\"\n );\n\n let tool: ToolId | undefined;\n if (!options.all) {\n tool = await resolveToolFromOptions(options.tool, \"status\");\n }\n\n const result = await runDoctor({\n tool,\n all: options.all,\n fix: options.fix,\n json: options.json,\n recreateMissing: options.recreateMissing,\n interactive: isInteractive(),\n });\n\n printDoctorResult(result, Boolean(options.json));\n process.exitCode = exitCodeForStatus(result.report.overall);\n}\n\n/**\n * `olakai monitor repair [--tool X] [--json]` (OLA-245, S3). The\n * forceful one-shot re-init for this workspace's monitoring. Unlike\n * `monitor doctor --fix` (which only repairs detected failures and gates\n * agent recreation behind `--recreate-missing`), `repair`:\n * - always forces an idempotent hook re-merge,\n * - WILL recreate a 404'd agent (preserving linkage otherwise),\n * - migrates a legacy config path if applicable,\n * then prints a before/after summary of what it changed.\n */\nasync function repairCommand(\n options: ToolFlag & { json?: boolean },\n): Promise<void> {\n const tool = await resolveToolFromOptions(options.tool, \"init\");\n\n const { runRepair, formatRepairResult, exitCodeForRepair } = await import(\n \"../monitor/repair.js\"\n );\n\n const result = await runRepair({\n tool,\n interactive: isInteractive(),\n });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(formatRepairResult(result));\n }\n process.exitCode = exitCodeForRepair(result);\n}\n\nasync function runPluginAction<T>(\n plugin: ToolMonitorPlugin,\n fn: () => Promise<T>,\n): Promise<T | void> {\n try {\n return await fn();\n } catch (err) {\n const e = err as Error;\n if (e.name === \"NotImplementedError\") {\n console.error(`${plugin.displayName}: ${e.message}`);\n process.exit(1);\n }\n throw err;\n }\n}\n\n/**\n * Fire-and-forget hook handler invoked by the tool's hook system. MUST\n * NOT produce stderr or exit non-zero — hook failures must never break\n * the host tool. `--tool` defaults to claude-code only when the flag\n * is *absent entirely* (back-compat with pre-Stage-2 hook commands\n * installed in existing workspaces' `.claude/settings.json`). When the\n * flag is present-but-invalid (typo like `--tool clade-code`), we\n * silent-exit rather than route to claude-code, to avoid silently\n * misrouting hooks for the wrong tool.\n */\nasync function hookCommand(\n event: string,\n options: ToolFlag,\n command: Command,\n): Promise<void> {\n try {\n // Distinguish \"flag absent\" from \"flag present but invalid\" via\n // Commander's `getOptionValueSource`. Source `undefined` means the\n // user didn't pass `--tool`; any other source means they did.\n const flagPresent =\n command.getOptionValueSource(\"tool\") !== undefined;\n\n let toolId: ToolId;\n if (flagPresent) {\n if (!options.tool || !isToolId(options.tool)) {\n // Invalid value supplied — silent-exit so hook failures don't\n // break the host tool. Debug-log so it's not totally invisible.\n debugInvalidToolFlag(options.tool, event);\n return;\n }\n toolId = options.tool;\n } else {\n toolId = \"claude-code\";\n }\n const plugin = getPlugin(toolId);\n\n const stdinData = await readStdin(3000);\n let payloadJson: unknown = {};\n if (stdinData) {\n try {\n payloadJson = JSON.parse(stdinData);\n } catch {\n // Plugins decide what to do with a bare event (the Claude Code\n // plugin silent-exits when transcript_path is missing).\n }\n }\n\n const result = await plugin.handleHook(event, payloadJson);\n if (!result) return;\n\n // The plugin already resolved workspace + transport inside\n // handleHook (where dedup/state writes happen). Use those values\n // directly — re-resolving here would race against `monitor disable`\n // and could disagree on CWD between the plugin and dispatcher.\n await postMonitoringPayload(result);\n } catch {\n // Silently swallow ALL errors. Hook failures must not break the\n // host tool.\n }\n}\n\nfunction debugInvalidToolFlag(\n value: string | undefined,\n event: string,\n): void {\n if (process.env.OLAKAI_MONITOR_DEBUG !== \"1\") return;\n try {\n // Mirror the claude-code plugin's debug-log location so users have\n // a single place to look for hook-path diagnostics.\n const logPath = `/tmp/olakai-monitor-debug-${process.pid}.log`;\n const line = `[${new Date().toISOString()}] hook-invalid-tool-flag: ${JSON.stringify(\n { event, tool: value ?? null },\n )}\\n`;\n fs.appendFileSync(logPath, line, \"utf-8\");\n } catch {\n // Ignore debug-log failures — never break the hook path.\n }\n}\n\nasync function postMonitoringPayload(result: HookResult): Promise<void> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 5000);\n const debug = process.env.OLAKAI_MONITOR_DEBUG === \"1\";\n const logPath = `/tmp/olakai-monitor-debug-${process.pid}.log`;\n const log = (event: string, data: unknown) => {\n if (!debug) return;\n try {\n fs.appendFileSync(\n logPath,\n `[${new Date().toISOString()}] dispatcher/${event}: ${JSON.stringify(data)}\\n`,\n \"utf-8\",\n );\n } catch {\n // Never let a debug-log failure break the hook path.\n }\n };\n try {\n log(\"posting\", {\n endpoint: result.transport.endpoint,\n apiKeyPresent: Boolean(result.transport.apiKey),\n apiKeyPrefix: result.transport.apiKey\n ? result.transport.apiKey.slice(0, 8) + \"...\"\n : null,\n bodyBytes: JSON.stringify([result.payload]).length,\n });\n const response = await fetch(result.transport.endpoint, {\n method: \"POST\",\n headers: {\n \"x-api-key\": result.transport.apiKey,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify([result.payload]),\n signal: controller.signal,\n });\n let bodyPreview: string | null = null;\n try {\n bodyPreview = (await response.text()).slice(0, 500);\n } catch {\n // Body read failures are not actionable here.\n }\n log(\"posted\", { status: response.status, bodyPreview });\n } catch (err) {\n log(\"post-error\", {\n name: err instanceof Error ? err.name : \"unknown\",\n message: err instanceof Error ? err.message : String(err),\n });\n throw err;\n } finally {\n clearTimeout(timeoutId);\n }\n}\n\nexport function registerMonitorCommand(program: Command): void {\n const monitor = program\n .command(\"monitor\")\n .description(\n \"Monitor local coding agents (Claude Code, Codex, Cursor) with Olakai\",\n );\n\n monitor\n .command(\"init\")\n .description(\"Set up Olakai monitoring for this workspace\")\n .option(\n \"--tool <tool>\",\n `Tool to configure (${TOOL_IDS.join(\"|\")}). Prompts when omitted in interactive mode.`,\n )\n .action(initCommand);\n\n monitor\n .command(\"hook <event>\")\n .description(\"Hook handler invoked by the tool's hook system (internal)\")\n .option(\n \"--tool <tool>\",\n `Tool whose hook is firing (defaults to claude-code for back-compat)`,\n )\n .action(hookCommand);\n\n monitor\n .command(\"status\")\n .description(\"Show monitoring status for this workspace\")\n .option(\n \"--tool <tool>\",\n `Tool to inspect (${TOOL_IDS.join(\"|\")}). Prompts when omitted in interactive mode.`,\n )\n .option(\"--json\", \"Output as JSON\")\n .action(statusCommand);\n\n monitor\n .command(\"list\")\n .description(\n \"List every workspace monitored on this machine (the machine lens)\",\n )\n .option(\"--json\", \"Output the raw registry entries as JSON\")\n .action(listCommand);\n\n monitor\n .command(\"doctor\")\n .description(\n \"Diagnose (and optionally repair) monitoring health for this workspace or the whole machine\",\n )\n .option(\n \"--tool <tool>\",\n `Tool to diagnose (${TOOL_IDS.join(\"|\")}). Prompts when omitted in interactive mode. Ignored with --all.`,\n )\n .option(\n \"--all\",\n \"Diagnose every workspace monitored on this machine (the machine lens), not just the current one\",\n )\n .option(\"--fix\", \"Attempt to repair fixable failures (idempotent, best-effort)\")\n .option(\n \"--recreate-missing\",\n \"With --fix, also recreate a self-monitor agent that no longer exists on the backend (provisions a NEW agent). Off by default; 'olakai monitor repair' is the heavier alternative.\",\n )\n .option(\"--json\", \"Output the structured diagnostic results as JSON\")\n .action(doctorCommand);\n\n monitor\n .command(\"repair\")\n .description(\n \"Forcefully re-initialize monitoring for this workspace (re-merge hooks, re-link/recreate the agent if needed) while preserving agent linkage\",\n )\n .option(\n \"--tool <tool>\",\n `Tool to repair (${TOOL_IDS.join(\"|\")}). Prompts when omitted in interactive mode.`,\n )\n .option(\"--json\", \"Output the structured repair result as JSON\")\n .action(repairCommand);\n\n monitor\n .command(\"disable\")\n .description(\"Remove Olakai monitoring from this workspace\")\n .option(\n \"--tool <tool>\",\n `Tool to disable (${TOOL_IDS.join(\"|\")}). Prompts when omitted in interactive mode.`,\n )\n .option(\n \"--keep-config\",\n \"Keep the monitor config file (only remove hooks)\",\n )\n .option(\n \"--delete-agent\",\n \"Also delete the remote agent on the Olakai backend. Useful when retiring a workspace permanently. Self-monitor owner or ADMIN only.\",\n )\n .action(disableCommand);\n\n // Allow plugins to register tool-specific subcommands (e.g. future\n // `olakai monitor claude-code transcript <path>`). Optional — most\n // plugins won't need this hook.\n for (const plugin of listPlugins()) {\n plugin.registerCommands?.(monitor);\n }\n}\n","/**\n * `olakai profiles ...` — AWS-style profile management.\n *\n * Subcommands:\n * - list Print all profiles, mark the active one\n * - use Set the registry default\n * - remove Delete a profile (refuses to remove the active default)\n * - current Show the resolved active profile\n */\n\nimport { Command } from \"commander\";\nimport { getBaseUrl } from \"../lib/config.js\";\nimport {\n readProfilesFile,\n removeProfile,\n resolveActiveProfile,\n resolveProfileName,\n setDefaultProfile,\n} from \"../lib/profiles.js\";\n\nfunction formatExpiry(expiresAt: number | undefined): string {\n if (typeof expiresAt !== \"number\") return \"no token\";\n const now = Math.floor(Date.now() / 1000);\n if (expiresAt <= now) return \"expired\";\n const seconds = expiresAt - now;\n const days = Math.floor(seconds / 86400);\n const hours = Math.floor((seconds % 86400) / 3600);\n if (days > 0) return `${days}d ${hours}h`;\n const minutes = Math.floor((seconds % 3600) / 60);\n if (hours > 0) return `${hours}h ${minutes}m`;\n return `${minutes}m`;\n}\n\nfunction maskToken(token: string | undefined): string {\n if (!token) return \"—\";\n if (token.length <= 8) return \"***\";\n return `${token.slice(0, 4)}…${token.slice(-4)}`;\n}\n\nfunction listAction(options: { json?: boolean }): void {\n const file = readProfilesFile();\n let resolved: { name: string } | null = null;\n try {\n resolved = resolveProfileName();\n } catch {\n resolved = null;\n }\n const activeName = resolved?.name ?? file.default;\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n default: file.default ?? null,\n active: activeName ?? null,\n profiles: Object.entries(file.profiles).map(([name, p]) => ({\n name,\n host: p.host,\n isDefault: file.default === name,\n isActive: activeName === name,\n email: p.email ?? null,\n accountId: p.accountId ?? null,\n expiresIn: p.expiresAt\n ? Math.max(0, p.expiresAt - Math.floor(Date.now() / 1000))\n : null,\n hasToken: Boolean(p.token),\n })),\n },\n null,\n 2,\n ),\n );\n return;\n }\n\n const names = Object.keys(file.profiles);\n if (names.length === 0) {\n console.log(\"No profiles configured. Run 'olakai login' to create one.\");\n return;\n }\n\n for (const name of names) {\n const p = file.profiles[name];\n if (!p) continue;\n const markers: string[] = [];\n if (file.default === name) markers.push(\"default\");\n if (activeName === name) markers.push(\"active\");\n const label = markers.length > 0 ? ` (${markers.join(\", \")})` : \"\";\n const expiry = formatExpiry(p.expiresAt);\n const email = p.email ? ` — ${p.email}` : \"\";\n console.log(`* ${name}${label}`);\n console.log(` host: ${p.host}`);\n console.log(` token: ${maskToken(p.token)} (${expiry})${email}`);\n }\n}\n\nfunction useAction(name: string): void {\n try {\n setDefaultProfile(name);\n console.log(`Default profile is now: ${name}`);\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\nfunction removeAction(name: string): void {\n try {\n removeProfile(name);\n console.log(`Removed profile: ${name}`);\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\nfunction currentAction(options: { json?: boolean }): void {\n let active;\n try {\n active = resolveActiveProfile();\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n if (!active) {\n if (options.json) {\n console.log(JSON.stringify({ active: null }, null, 2));\n } else {\n console.log(\"No profile configured. Run 'olakai login' to create one.\");\n }\n return;\n }\n\n // The \"effective\" host is what `getBaseUrl()` actually returns\n // (factoring in --host / OLAKAI_HOST overrides). The profile's\n // stored host is shown separately so the user can see when an\n // override is in effect.\n const effectiveHost = getBaseUrl();\n const overridden = effectiveHost !== active.host;\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n name: active.name,\n host: effectiveHost,\n profileHost: active.host,\n source: active.source,\n hostFromWorkspaceConfig: active.hostFromWorkspaceConfig,\n hostOverridden: overridden,\n email: active.profile.email ?? null,\n accountId: active.profile.accountId ?? null,\n hasToken: Boolean(active.profile.token),\n expiresAt: active.profile.expiresAt ?? null,\n expiresIn: active.profile.expiresAt\n ? Math.max(\n 0,\n active.profile.expiresAt - Math.floor(Date.now() / 1000),\n )\n : null,\n },\n null,\n 2,\n ),\n );\n return;\n }\n\n console.log(`Profile: ${active.name} (from ${active.source})`);\n if (overridden) {\n console.log(`Host: ${effectiveHost} (overrides profile host)`);\n console.log(`Profile host: ${active.host}`);\n } else if (active.hostFromWorkspaceConfig) {\n console.log(`Host: ${active.host} (from workspace config)`);\n } else {\n console.log(`Host: ${active.host}`);\n }\n if (active.profile.email) {\n console.log(`Email: ${active.profile.email}`);\n }\n if (active.profile.accountId) {\n console.log(`Account ID: ${active.profile.accountId}`);\n }\n console.log(`Token: ${maskToken(active.profile.token)}`);\n console.log(`Expires in: ${formatExpiry(active.profile.expiresAt)}`);\n}\n\nexport function registerProfilesCommand(program: Command): void {\n const profiles = program\n .command(\"profiles\")\n .description(\"Manage Olakai authentication profiles (AWS-style)\");\n\n profiles\n .command(\"list\")\n .description(\"List all configured profiles\")\n .option(\"--json\", \"Output as JSON\")\n .action((options: { json?: boolean }) => {\n listAction(options);\n });\n\n profiles\n .command(\"use <name>\")\n .description(\"Set <name> as the default profile\")\n .action((name: string) => {\n useAction(name);\n });\n\n profiles\n .command(\"remove <name>\")\n .description(\"Remove a profile (refuses to remove the active default)\")\n .action((name: string) => {\n removeAction(name);\n });\n\n profiles\n .command(\"current\")\n .description(\"Print the active profile (resolved from flag/env/workspace/default)\")\n .option(\"--json\", \"Output as JSON\")\n .action((options: { json?: boolean }) => {\n currentAction(options);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,qBAAqB;AAC9B,SAAS,eAAe;;;ACHxB,OAAO,UAAU;AAMjB,IAAM,mBAAmB;AAKzB,eAAsB,eAA8B;AAElD,MAAI,aAAa,GAAG;AAClB,QAAI;AACF,YAAM,OAAO,MAAM,eAAe;AAClC,cAAQ,IAAI,wBAAwB,KAAK,KAAK,EAAE;AAChD,cAAQ,IAAI,uCAAuC;AACnD;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,QAAM,WAAW,mBAAmB;AACpC,QAAM,cAAc,UAAU,QAAQ;AACtC,UAAQ;AAAA,IACN,kCAAkC,WAAW,WAAW,WAAW,CAAC,UAAU,eAAe,CAAC;AAAA;AAAA,EAChG;AAEA,MAAI;AAEF,UAAM,aAAa,MAAM,kBAAkB;AAG3C,YAAQ,IAAI,2BAA2B;AACvC,YAAQ,IAAI;AAAA,IAAO,WAAW,yBAAyB;AAAA,CAAI;AAC3D,YAAQ,IAAI,YAAY,WAAW,gBAAgB,kBAAkB;AACrE,YAAQ,IAAI;AAAA,IAAO,WAAW,SAAS;AAAA,CAAI;AAG3C,YAAQ,IAAI,oBAAoB;AAChC,QAAI;AACF,YAAM,KAAK,WAAW,yBAAyB;AAAA,IACjD,QAAQ;AACN,cAAQ,IAAI,wCAAwC;AAAA,IACtD;AAEA,YAAQ,IAAI,gCAAgC;AAG5C,UAAM,YAAY,KAAK,IAAI,IAAI,WAAW,aAAa;AAEvD,WAAO,KAAK,IAAI,IAAI,WAA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wB,OAAO;AAE/B,QAAQ,MAAM;","names":["open","open","program","listCommand","getCommand","createCommand","updateCommand","deleteCommand","program","listCommand","getCommand","createCommand","updateCommand","deleteCommand","program","listCommand","getCommand","createCommand","updateCommand","deleteCommand","program","listCommand","getCommand","program","fs","initCommand","report","deleteAgent","listCommand","program","formatExpiry","program","require"]}
|