kagura-memory 0.3.0 → 0.6.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/LICENSE +21 -21
- package/README.md +392 -164
- package/dist/cli.js +1294 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +429 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +604 -3
- package/dist/index.d.ts +604 -3
- package/dist/index.js +402 -12
- package/dist/index.js.map +1 -1
- package/package.json +66 -63
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/errors.ts","../src/version.ts","../src/http.ts","../src/auth/credentials.ts","../src/auth/deviceFlow.ts","../src/auth/filelock.ts","../src/config.ts","../src/auth/resolve.ts","../src/auth/login.ts","../src/auth/refresh.ts","../src/cli/openBrowser.ts","../src/cli/parseArgs.ts","../src/cli/run.ts"],"sourcesContent":["/**\r\n * `kagura-memory` bin — the thin shim around {@link runCli}.\r\n *\r\n * Everything testable lives in `cli/run.ts` behind injected dependencies;\r\n * this file holds only what needs a real terminal, a real browser, and a\r\n * real process exit.\r\n */\r\n\r\nimport * as readline from \"node:readline/promises\";\r\n\r\nimport { login } from \"./auth/login.js\";\r\nimport { refresh } from \"./auth/refresh.js\";\r\nimport { openBrowser } from \"./cli/openBrowser.js\";\r\nimport { runCli } from \"./cli/run.js\";\r\n\r\nasync function confirm(question: string): Promise<boolean> {\r\n // A non-interactive stdin (CI, a pipe) must not hang waiting for input\r\n // that will never arrive; treat it as a decline and let --yes be the\r\n // explicit opt-in.\r\n if (!process.stdin.isTTY) {\r\n process.stderr.write(\"Refusing to prompt on a non-interactive stdin. Re-run with --yes.\\n\");\r\n return false;\r\n }\r\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\r\n try {\r\n const answer = await rl.question(`${question} [y/N] `);\r\n return /^y(es)?$/i.test(answer.trim());\r\n } finally {\r\n rl.close();\r\n }\r\n}\r\n\r\nconst code = await runCli(process.argv.slice(2), {\r\n write: (line) => process.stdout.write(`${line}\\n`),\r\n writeError: (line) => process.stderr.write(`${line}\\n`),\r\n confirm,\r\n openBrowser,\r\n login,\r\n refresh,\r\n});\r\n\r\nprocess.exitCode = code;\r\n","/** Custom errors for the Kagura Memory SDK (port of exceptions.py). */\n\n/**\n * Subset of the standard DOM/Node `ErrorOptions`. Declared locally so the\n * published `.d.ts` does not force consumers onto an ES2022 `lib` just to\n * reference our error constructors.\n */\nexport interface KaguraErrorOptions {\n cause?: unknown;\n}\n\n/**\n * Return `String(e)` when non-empty, otherwise the constructor name.\n *\n * Defensive fallback so an unmessaged error still produces a non-empty\n * diagnostic when interpolated into a user-facing error string.\n */\nexport function excMessage(e: unknown): string {\n if (e instanceof Error) {\n return e.message || e.constructor.name;\n }\n const s = String(e);\n return s || (typeof e === \"object\" && e !== null ? e.constructor.name : \"unknown error\");\n}\n\n/** Base error for the Kagura SDK. */\nexport class KaguraError extends Error {\n constructor(message: string, options?: KaguraErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\n/** Authentication failed. */\nexport class KaguraAuthError extends KaguraError {}\n\n/**\n * OAuth refresh token expired or invalid.\n *\n * Raised when an attempted refresh returns `invalid_grant` (or the server\n * otherwise indicates that the stored refresh token can no longer be used).\n * The caller must re-authenticate via `kagura auth login`.\n */\nexport class KaguraAuthExpiredError extends KaguraAuthError {\n readonly expiresAt: Date | null;\n\n constructor(message: string, expiresAt: Date | null = null, options?: KaguraErrorOptions) {\n super(message, options);\n this.expiresAt = expiresAt;\n }\n}\n\n/** User denied authorization at the device-flow consent screen. */\nexport class KaguraAuthDeniedError extends KaguraAuthError {}\n\n/** Connection to Kagura server failed. */\nexport class KaguraConnectionError extends KaguraError {}\n\n/** Requested resource not found (HTTP 404). */\nexport class KaguraNotFoundError extends KaguraError {}\n\n/** Rate limit exceeded. */\nexport class KaguraRateLimitError extends KaguraError {\n readonly retryAfter: number | null;\n\n constructor(message: string, retryAfter: number | null = null, options?: KaguraErrorOptions) {\n super(message, options);\n this.retryAfter = retryAfter;\n }\n}\n\n/** LLM call failed. */\nexport class KaguraLLMError extends KaguraError {}\n\n/** Context not found or invalid. */\nexport class KaguraContextError extends KaguraError {}\n\n/** Resource token quota exceeded (events per hour). */\nexport class KaguraQuotaError extends KaguraError {\n readonly retryAfter: number | null;\n\n constructor(message: string, retryAfter: number | null = null, options?: KaguraErrorOptions) {\n super(message, options);\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * Object store rejected an upload with HTTP 400.\n *\n * Raised for any HTTP 400 response from the object store on a presigned\n * PUT — most commonly R2 `BadDigest` (the body's sha256 did not match the\n * value bound into the presigned PUT URL), but also covers other 400\n * causes such as a malformed presigned URL or a Content-Length mismatch.\n */\nexport class KaguraIntegrityError extends KaguraError {}\n\n/**\n * URL or file fetch failed (SSRF guard, byte cap, redirect loop, etc.).\n *\n * The original URL/path is exposed via the `url` property so callers can\n * present it without re-parsing the message.\n */\nexport class KaguraFetchError extends KaguraError {\n readonly url: string | null;\n\n constructor(message: string, url: string | null = null, options?: KaguraErrorOptions) {\n super(message, options);\n this.url = url;\n }\n}\n\n/** File ingestion orchestration failed for a non-fetch reason. */\nexport class KaguraIngestError extends KaguraError {}\n","/**\r\n * Package version string, shared across client modules (User-Agent, MCP\r\n * clientInfo). Kept in sync with package.json by the release process.\r\n */\r\nexport const SDK_VERSION = \"0.6.0\";\r\n","/** Shared HTTP utilities for Kagura Memory SDK clients (port of _http.py). */\r\n\r\nimport {\r\n KaguraAuthError,\r\n KaguraConnectionError,\r\n KaguraRateLimitError,\r\n} from \"./errors.js\";\r\n\r\nexport { SDK_VERSION } from \"./version.js\";\r\n\r\n/**\r\n * Derive the REST API base URL from an MCP URL.\r\n *\r\n * Strips `/mcp` and everything after it (e.g. `/mcp/w/{workspace}`).\r\n */\r\nexport function baseUrlFromMcp(mcpUrl: string): string {\r\n const m = /\\/mcp(?=\\/|$)/.exec(mcpUrl);\r\n return m ? mcpUrl.slice(0, m.index) : mcpUrl;\r\n}\r\n\r\nfunction formatValidationErrors(errors: unknown[]): string {\r\n // Silent-skip malformed entries so a single bad entry doesn't blank the line.\r\n const parts: string[] = [];\r\n for (const entry of errors) {\r\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\r\n continue;\r\n }\r\n const rec = entry as Record<string, unknown>;\r\n const msg = rec.msg;\r\n if (typeof msg !== \"string\" || !msg) {\r\n continue;\r\n }\r\n const loc = rec.loc;\r\n if (Array.isArray(loc) && loc.length > 0) {\r\n parts.push(`${loc.map(String).join(\".\")}: ${msg}`);\r\n } else {\r\n parts.push(msg);\r\n }\r\n }\r\n return parts.join(\"; \");\r\n}\r\n\r\n/**\r\n * Return a useful server-supplied error string from a response body.\r\n *\r\n * Handles four response shapes:\r\n * - `{\"detail\": \"string\"}` — returned as-is (FastAPI HTTPException default).\r\n * - `{\"detail\": [{\"loc\": [...], \"msg\": \"...\", ...}, ...]}` — FastAPI's\r\n * validation-error format; each entry becomes `\"<loc.path>: <msg>\"`.\r\n * - `{\"error\": \"<CODE>\", \"message\": \"string\", \"details\": {...}}` — the\r\n * memory-cloud canonical envelope; returns `message`, appending\r\n * `details.errors` validation entries when present.\r\n * - Anything else — returns an empty string so callers can fall back.\r\n */\r\nexport function extractDetail(bodyText: string): string {\r\n let body: unknown;\r\n try {\r\n body = JSON.parse(bodyText);\r\n } catch {\r\n return \"\";\r\n }\r\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\r\n return \"\";\r\n }\r\n const rec = body as Record<string, unknown>;\r\n const detail = rec.detail;\r\n if (typeof detail === \"string\") {\r\n return detail;\r\n }\r\n if (Array.isArray(detail)) {\r\n return formatValidationErrors(detail);\r\n }\r\n const message = rec.message;\r\n if (typeof message === \"string\" && message) {\r\n const details = rec.details;\r\n if (typeof details === \"object\" && details !== null && !Array.isArray(details)) {\r\n const errors = (details as Record<string, unknown>).errors;\r\n if (Array.isArray(errors)) {\r\n const formatted = formatValidationErrors(errors);\r\n if (formatted) {\r\n return `${message}: ${formatted}`;\r\n }\r\n }\r\n }\r\n return message;\r\n }\r\n return \"\";\r\n}\r\n\r\n/**\r\n * Drop server-provided detail strings that contain credential markers.\r\n *\r\n * A future server bug echoing back the Bearer header or api_key must not\r\n * be passed straight to the user. Returns `null` when the detail is empty\r\n * or unsafe to display.\r\n */\r\nexport function sanitizeServerDetail(detail: string | null | undefined): string | null {\r\n if (!detail) {\r\n return null;\r\n }\r\n const lowered = detail.toLowerCase();\r\n if (lowered.includes(\"bearer\") || lowered.includes(\"authorization\") || lowered.includes(\"api_key=\")) {\r\n return null;\r\n }\r\n return detail;\r\n}\r\n\r\n/**\r\n * Parse a numeric `Retry-After` header (delta-seconds), else `null`.\r\n *\r\n * Only the integer-seconds form is honored; an HTTP-date `Retry-After`\r\n * (rare for rate limits) is treated as absent rather than mis-parsed.\r\n */\r\nexport function retryAfterSeconds(headers: Headers): number | null {\r\n const raw = headers.get(\"Retry-After\");\r\n if (raw === null) {\r\n return null;\r\n }\r\n const trimmed = raw.trim();\r\n return /^\\d+$/.test(trimmed) ? parseInt(trimmed, 10) : null;\r\n}\r\n\r\n/**\r\n * Translate a non-2xx HTTP response into the matching Kagura error.\r\n *\r\n * Maps 401 → KaguraAuthError, 429 → KaguraRateLimitError (honoring a\r\n * numeric `Retry-After` header), and every other status →\r\n * KaguraConnectionError. The server-supplied detail is appended when\r\n * present, otherwise `fallbackMessage` is used so the status is never\r\n * left bare. This function always throws.\r\n */\r\nexport function throwForKaguraStatus(\r\n status: number,\r\n headers: Headers,\r\n bodyText: string,\r\n fallbackMessage?: string,\r\n): never {\r\n if (status === 401) {\r\n throw new KaguraAuthError(\"Authentication failed. Check your API key.\");\r\n }\r\n const detail = extractDetail(bodyText) || fallbackMessage || \"\";\r\n if (status === 429) {\r\n throw new KaguraRateLimitError(\r\n `Rate limit exceeded (HTTP 429): ${detail || `HTTP ${status}`}`,\r\n retryAfterSeconds(headers),\r\n );\r\n }\r\n // Avoid a doubled \"HTTP 500: HTTP 500\" when the body carries no detail.\r\n throw new KaguraConnectionError(detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}`);\r\n}\r\n\r\n// Plain-HTTP is permitted only for genuine loopback hosts. The host token must\r\n// be followed by a boundary — a port (:\\d+), a path/query/fragment delimiter,\r\n// or end-of-string — so a prefix-match attack like http://localhost.evil.com\r\n// or a userinfo trick like http://localhost@evil.com cannot smuggle an\r\n// external host past the check (#189).\r\n// Both patterns are case-insensitive: URL parsing lower-cases the scheme\r\n// and host, so `HTTP://EVIL.TEST` is fetched over plaintext exactly like\r\n// `http://evil.test`. A case-sensitive guard would wave it through.\r\nconst PLAIN_HTTP_RE = /^http:\\/\\//i;\r\nconst LOCALHOST_HTTP_RE = /^http:\\/\\/(?:localhost|127\\.0\\.0\\.1|\\[::1\\])(?::\\d+)?(?:[/?#]|$)/i;\r\n\r\n/**\r\n * Enforce HTTPS except for localhost development.\r\n *\r\n * @throws Error if the URL uses HTTP and is not a loopback host.\r\n */\r\nexport function validateHttpsUrl(url: string, label = \"URL\"): void {\r\n // WHATWG URL parsing strips surrounding whitespace, so `\" http://x\"`\r\n // reaches the network as plain HTTP. Both patterns are anchored, so\r\n // without trimming first they would never match it and the guard would\r\n // pass. Trim here rather than relying on callers to have done it.\r\n const candidate = url.trim();\r\n if (PLAIN_HTTP_RE.test(candidate) && !LOCALHOST_HTTP_RE.test(candidate)) {\r\n throw new Error(\r\n `${label} must use HTTPS for security (got: ${candidate}). ` +\r\n \"HTTP is only allowed for localhost development.\",\r\n );\r\n }\r\n}\r\n","/**\r\n * Persistent OAuth credentials for the Kagura SDK (port of\r\n * auth/credentials.py).\r\n *\r\n * This module owns three responsibilities:\r\n *\r\n * 1. The `OAuthCredentials` / `CredentialsFile` shapes and their JSON\r\n * (de)serialization. The on-disk format at `~/.kagura/credentials.json`\r\n * is SHARED with the Python CLI — keys stay snake_case on disk\r\n * (`default_profile`, `profiles`, `access_token`, ...), timestamps are\r\n * Z-suffixed UTC ISO-8601.\r\n * 2. Atomic, mode-0600 read/write of the credentials file with a mode-0700\r\n * parent directory (permissions are best-effort where the platform,\r\n * e.g. Windows/NTFS, does not honor POSIX bits).\r\n * 3. A process-wide cache (`getSharedState`) so concurrent clients pointing\r\n * at the same credentials file share a single in-process mutex, ensuring\r\n * only one `/oauth/token/` refresh fires per cycle even when many client\r\n * instances run side by side.\r\n *\r\n * Multi-process coordination is handled in two layers: the in-process\r\n * `AsyncMutex` coalesces refreshes *within* a process, and the\r\n * cross-process lock in `filelock.ts` (acquired inside the refresh path)\r\n * re-reads the on-disk token after locking and skips the `/oauth/token/`\r\n * round-trip when another process already rotated it.\r\n */\r\n\r\nimport * as crypto from \"node:crypto\";\r\nimport * as fs from \"node:fs\";\r\nimport * as os from \"node:os\";\r\nimport * as path from \"node:path\";\r\n\r\nimport { KaguraAuthExpiredError } from \"../errors.js\";\r\nimport { refreshAccessToken } from \"./deviceFlow.js\";\r\nimport { withFileLock } from \"./filelock.js\";\r\nimport type { AuthProvider } from \"./types.js\";\r\n\r\n/**\r\n * Refresh `accessToken` when within this many seconds of `expiresAt`.\r\n *\r\n * Default of 5 minutes mirrors common OAuth2 client conventions and gives\r\n * enough headroom for a slow refresh round-trip.\r\n */\r\nexport const REFRESH_SKEW_SEC = 300;\r\n\r\nexport const CREDENTIALS_FILE_MODE = 0o600;\r\nexport const CREDENTIALS_DIR_MODE = 0o700;\r\n\r\n/**\r\n * Default location of the credentials file: `~/.kagura/credentials.json`.\r\n * Tests pass an explicit `home`/path instead of touching the real one.\r\n */\r\nexport function defaultCredentialsPath(home?: string): string {\r\n return path.join(home ?? os.homedir(), \".kagura\", \"credentials.json\");\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Data shapes\r\n// ---------------------------------------------------------------------------\r\n\r\n/** A single profile's OAuth2 credentials (camelCase in memory, snake_case on disk). */\r\nexport interface OAuthCredentials {\r\n server: string;\r\n mcpUrl: string;\r\n clientId: string;\r\n accessToken: string;\r\n refreshToken: string;\r\n tokenType: string;\r\n expiresAt: Date;\r\n scope: string;\r\n workspaceId: string;\r\n workspaceName: string;\r\n userEmail: string;\r\n issuedAt: Date;\r\n}\r\n\r\n/** True when `accessToken` is past `expiresAt - skewSeconds`. */\r\nexport function isExpired(creds: OAuthCredentials, skewSeconds = 0): boolean {\r\n return Date.now() >= creds.expiresAt.getTime() - skewSeconds * 1000;\r\n}\r\n\r\n/**\r\n * Return a copy of `creds` with the rotated token fields applied.\r\n *\r\n * `refreshToken` is rotated when the server returns a new one (RFC 6749\r\n * §10.4 recommended) — pass `null`/omit to preserve the stored one.\r\n * `scope` is updated when the server narrows or widens the grant.\r\n */\r\nexport function withRefreshed(\r\n creds: OAuthCredentials,\r\n fields: {\r\n accessToken: string;\r\n refreshToken?: string | null;\r\n expiresAt: Date;\r\n scope?: string | null;\r\n },\r\n): OAuthCredentials {\r\n return {\r\n ...creds,\r\n accessToken: fields.accessToken,\r\n refreshToken: fields.refreshToken ?? creds.refreshToken,\r\n expiresAt: fields.expiresAt,\r\n scope: fields.scope ?? creds.scope,\r\n };\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Datetime helpers (Z-suffixed UTC ISO-8601 for human readability)\r\n// ---------------------------------------------------------------------------\r\n\r\n/** Serialize a Date as `YYYY-MM-DDTHH:MM:SSZ` (UTC, seconds precision). */\r\nexport function isoUtc(date: Date): string {\r\n return `${date.toISOString().slice(0, 19)}Z`;\r\n}\r\n\r\n/**\r\n * Parse ISO-8601, accepting `...Z`, `...+00:00`, and naive suffixes.\r\n *\r\n * Normalizes a missing timezone to UTC so a user-edited / legacy\r\n * credentials file with naive timestamps doesn't get parsed as local time\r\n * (JavaScript's `Date` parses a bare `YYYY-MM-DDTHH:MM:SS` as local).\r\n */\r\nexport function parseIso(s: string): Date {\r\n const normalized = /(?:Z|[+-]\\d{2}:?\\d{2})$/.test(s) ? s : `${s}Z`;\r\n const date = new Date(normalized);\r\n if (Number.isNaN(date.getTime())) {\r\n throw new Error(`invalid ISO-8601 timestamp: ${s}`);\r\n }\r\n return date;\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// JSON (de)serialization — snake_case on disk, shared with the Python CLI\r\n// ---------------------------------------------------------------------------\r\n\r\nexport function credentialsToDict(creds: OAuthCredentials): Record<string, unknown> {\r\n return {\r\n server: creds.server,\r\n mcp_url: creds.mcpUrl,\r\n client_id: creds.clientId,\r\n access_token: creds.accessToken,\r\n refresh_token: creds.refreshToken,\r\n token_type: creds.tokenType,\r\n expires_at: isoUtc(creds.expiresAt),\r\n scope: creds.scope,\r\n workspace_id: creds.workspaceId,\r\n workspace_name: creds.workspaceName,\r\n user_email: creds.userEmail,\r\n issued_at: isoUtc(creds.issuedAt),\r\n };\r\n}\r\n\r\nfunction requireString(d: Record<string, unknown>, key: string): string {\r\n const value = d[key];\r\n if (typeof value !== \"string\") {\r\n throw new Error(`credentials profile missing required field '${key}'`);\r\n }\r\n return value;\r\n}\r\n\r\nfunction stringOr(value: unknown, fallback: string): string {\r\n return typeof value === \"string\" ? value : fallback;\r\n}\r\n\r\n/** @throws Error when required fields are missing or timestamps invalid. */\r\nexport function credentialsFromDict(d: Record<string, unknown>): OAuthCredentials {\r\n const issuedAtRaw = d.issued_at;\r\n return {\r\n server: requireString(d, \"server\"),\r\n mcpUrl: requireString(d, \"mcp_url\"),\r\n clientId: requireString(d, \"client_id\"),\r\n accessToken: requireString(d, \"access_token\"),\r\n refreshToken: requireString(d, \"refresh_token\"),\r\n tokenType: stringOr(d.token_type, \"Bearer\"),\r\n expiresAt: parseIso(requireString(d, \"expires_at\")),\r\n scope: stringOr(d.scope, \"\"),\r\n workspaceId: stringOr(d.workspace_id, \"\"),\r\n workspaceName: stringOr(d.workspace_name, \"\"),\r\n userEmail: stringOr(d.user_email, \"\"),\r\n issuedAt: typeof issuedAtRaw === \"string\" && issuedAtRaw ? parseIso(issuedAtRaw) : new Date(),\r\n };\r\n}\r\n\r\n/** Top-level wrapper for `~/.kagura/credentials.json`. */\r\nexport interface CredentialsFile {\r\n version: number;\r\n defaultProfile: string;\r\n profiles: Record<string, OAuthCredentials>;\r\n}\r\n\r\nexport function emptyCredentialsFile(): CredentialsFile {\r\n return { version: 1, defaultProfile: \"default\", profiles: {} };\r\n}\r\n\r\n/** Return the named profile, or the default, or `null` if missing. */\r\nexport function getProfile(\r\n cf: CredentialsFile,\r\n name?: string | null,\r\n): OAuthCredentials | null {\r\n const key = name || cf.defaultProfile;\r\n return cf.profiles[key] ?? null;\r\n}\r\n\r\n/** Insert or replace a profile. The first profile becomes default. */\r\nexport function setProfile(cf: CredentialsFile, name: string, creds: OAuthCredentials): void {\r\n cf.profiles[name] = creds;\r\n if (!(cf.defaultProfile in cf.profiles)) {\r\n cf.defaultProfile = name;\r\n }\r\n}\r\n\r\n/** Remove a profile in memory if present; repoints a deleted default. */\r\nexport function removeProfile(cf: CredentialsFile, name: string): void {\r\n delete cf.profiles[name];\r\n const next = Object.keys(cf.profiles)[0];\r\n if (cf.defaultProfile === name && next !== undefined) {\r\n cf.defaultProfile = next;\r\n }\r\n}\r\n\r\nexport function credentialsFileToDict(cf: CredentialsFile): Record<string, unknown> {\r\n const profiles: Record<string, unknown> = {};\r\n for (const [name, creds] of Object.entries(cf.profiles)) {\r\n profiles[name] = credentialsToDict(creds);\r\n }\r\n return {\r\n version: cf.version,\r\n default_profile: cf.defaultProfile,\r\n profiles,\r\n };\r\n}\r\n\r\n/** @throws Error when any profile is malformed (caller treats file as empty). */\r\nexport function credentialsFileFromDict(d: Record<string, unknown>): CredentialsFile {\r\n const profilesRaw = d.profiles;\r\n const profiles: Record<string, OAuthCredentials> = {};\r\n if (typeof profilesRaw === \"object\" && profilesRaw !== null && !Array.isArray(profilesRaw)) {\r\n for (const [name, p] of Object.entries(profilesRaw)) {\r\n if (typeof p !== \"object\" || p === null || Array.isArray(p)) {\r\n throw new Error(`credentials profile '${name}' is not an object`);\r\n }\r\n profiles[name] = credentialsFromDict(p as Record<string, unknown>);\r\n }\r\n }\r\n return {\r\n version: typeof d.version === \"number\" ? d.version : 1,\r\n defaultProfile: stringOr(d.default_profile, \"default\"),\r\n profiles,\r\n };\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Filesystem IO\r\n// ---------------------------------------------------------------------------\r\n\r\n/** Force the directory to mode 0700 (best-effort; no-op where unsupported). */\r\nfunction enforceDirPerms(directory: string): void {\r\n try {\r\n const mode = fs.statSync(directory).mode & 0o777;\r\n if (mode !== CREDENTIALS_DIR_MODE) {\r\n fs.chmodSync(directory, CREDENTIALS_DIR_MODE);\r\n }\r\n } catch {\r\n // Best-effort: a directory we can't chmod is the user's problem, not\r\n // ours to abort over. Reads/writes will fail downstream with a clearer\r\n // error if perms genuinely block access.\r\n }\r\n}\r\n\r\n/** Force the credentials file to mode 0600 (defense in depth, best-effort). */\r\nfunction enforceFilePerms(filePath: string): void {\r\n try {\r\n const mode = fs.statSync(filePath).mode & 0o777;\r\n if (mode !== CREDENTIALS_FILE_MODE) {\r\n fs.chmodSync(filePath, CREDENTIALS_FILE_MODE);\r\n }\r\n } catch {\r\n // Best-effort — see enforceDirPerms.\r\n }\r\n}\r\n\r\n/**\r\n * Write `data` to `filePath` atomically.\r\n *\r\n * Steps: exclusive-create temp file in the same directory → write JSON →\r\n * fsync → chmod → rename over the target. A kill between any two steps\r\n * either leaves the original file untouched or replaces it cleanly.\r\n */\r\nfunction atomicWriteJson(\r\n filePath: string,\r\n data: unknown,\r\n mode: number = CREDENTIALS_FILE_MODE,\r\n): void {\r\n const dir = path.dirname(filePath);\r\n fs.mkdirSync(dir, { recursive: true });\r\n enforceDirPerms(dir);\r\n\r\n const tmp = path.join(\r\n dir,\r\n `.${path.basename(filePath)}.${crypto.randomBytes(6).toString(\"hex\")}.tmp`,\r\n );\r\n let fd: number | null = null;\r\n try {\r\n fd = fs.openSync(tmp, \"wx\", 0o600);\r\n fs.writeSync(fd, `${JSON.stringify(data, null, 2)}\\n`);\r\n fs.fsyncSync(fd);\r\n fs.closeSync(fd);\r\n fd = null;\r\n fs.chmodSync(tmp, mode);\r\n fs.renameSync(tmp, filePath);\r\n // fsync the parent directory so the rename itself is durable on crash /\r\n // power-loss. Best-effort: Windows and some filesystems don't support\r\n // fsync on a directory descriptor; the atomic rename already happened,\r\n // so the worst case is losing the most recent write, never file\r\n // integrity.\r\n try {\r\n const dirFd = fs.openSync(dir, \"r\");\r\n try {\r\n fs.fsyncSync(dirFd);\r\n } finally {\r\n fs.closeSync(dirFd);\r\n }\r\n } catch {\r\n // See comment above.\r\n }\r\n } catch (e) {\r\n if (fd !== null) {\r\n try {\r\n fs.closeSync(fd);\r\n } catch {\r\n // fd already closed / invalid — nothing more to release.\r\n }\r\n }\r\n fs.rmSync(tmp, { force: true });\r\n throw e;\r\n }\r\n}\r\n\r\nfunction resolvePath(p?: string): string {\r\n return p ?? defaultCredentialsPath();\r\n}\r\n\r\n/**\r\n * Read and parse the credentials file.\r\n *\r\n * Returns an empty `CredentialsFile` when the file is missing, unreadable,\r\n * or malformed — the caller can distinguish \"no profile\" via\r\n * `getProfile(cf) === null`. On a present file, parent directory and file\r\n * permissions are coerced to 0700/0600 (best-effort).\r\n */\r\nexport function loadCredentialsFile(credentialsPath?: string): CredentialsFile {\r\n const p = resolvePath(credentialsPath);\r\n if (!fs.existsSync(p)) {\r\n return emptyCredentialsFile();\r\n }\r\n\r\n enforceDirPerms(path.dirname(p));\r\n enforceFilePerms(p);\r\n\r\n let data: unknown;\r\n try {\r\n data = JSON.parse(fs.readFileSync(p, \"utf-8\"));\r\n } catch {\r\n return emptyCredentialsFile();\r\n }\r\n if (typeof data !== \"object\" || data === null || Array.isArray(data)) {\r\n return emptyCredentialsFile();\r\n }\r\n try {\r\n return credentialsFileFromDict(data as Record<string, unknown>);\r\n } catch {\r\n // Corrupt or partial file — treat as empty rather than crashing.\r\n return emptyCredentialsFile();\r\n }\r\n}\r\n\r\n/** Atomically persist a `CredentialsFile` to disk. */\r\nexport function saveCredentialsFile(cf: CredentialsFile, credentialsPath?: string): void {\r\n atomicWriteJson(resolvePath(credentialsPath), credentialsFileToDict(cf), CREDENTIALS_FILE_MODE);\r\n}\r\n\r\n/**\r\n * Load, mutate one profile, and atomically save back.\r\n *\r\n * The read-modify-write is wrapped in the cross-process lock from\r\n * `filelock.ts` so concurrent writers in *different* processes cannot lose\r\n * an update. The lock is on a sibling `credentials.json.lock`, not the\r\n * file itself, so it never races the atomic rename in\r\n * `saveCredentialsFile`.\r\n */\r\nexport async function updateProfile(\r\n profileName: string,\r\n creds: OAuthCredentials,\r\n credentialsPath?: string,\r\n): Promise<void> {\r\n const p = resolvePath(credentialsPath);\r\n await withFileLock(p, () => {\r\n const cf = loadCredentialsFile(p);\r\n setProfile(cf, profileName, creds);\r\n saveCredentialsFile(cf, p);\r\n });\r\n}\r\n\r\n/**\r\n * Set `default_profile` to an existing profile (backs `kagura auth use`).\r\n *\r\n * Unlike `setProfile`'s implicit first-wins promotion, this is a\r\n * *deliberate* default selection, wrapped in the same cross-process lock as\r\n * `updateProfile` so a concurrent refresh/login cannot clobber it.\r\n *\r\n * @throws Error if `profileName` is not an existing profile — selecting a\r\n * non-existent default would silently break resolution. (Python raises\r\n * `KeyError` here; a plain `Error` is the TS equivalent.)\r\n */\r\nexport async function setDefaultProfile(\r\n profileName: string,\r\n credentialsPath?: string,\r\n): Promise<void> {\r\n const p = resolvePath(credentialsPath);\r\n await withFileLock(p, () => {\r\n const cf = loadCredentialsFile(p);\r\n if (!(profileName in cf.profiles)) {\r\n throw new Error(`profile '${profileName}' not found in credentials file`);\r\n }\r\n cf.defaultProfile = profileName;\r\n saveCredentialsFile(cf, p);\r\n });\r\n}\r\n\r\n/**\r\n * Remove a profile and save. No-op if the profile is absent.\r\n *\r\n * The read-modify-write is wrapped in the cross-process lock so a logout\r\n * (delete) racing a concurrent token refresh (update) in a sibling process\r\n * cannot clobber a freshly written token. The absent-profile early return\r\n * runs *inside* the lock so the membership check and the save observe one\r\n * consistent snapshot (no TOCTOU).\r\n */\r\nexport async function deleteProfile(\r\n profileName: string,\r\n credentialsPath?: string,\r\n): Promise<void> {\r\n const p = resolvePath(credentialsPath);\r\n await withFileLock(p, () => {\r\n const cf = loadCredentialsFile(p);\r\n if (!(profileName in cf.profiles)) {\r\n return;\r\n }\r\n removeProfile(cf, profileName);\r\n saveCredentialsFile(cf, p);\r\n });\r\n}\r\n\r\n/**\r\n * Remove the entire credentials file (`kagura auth logout --all`).\r\n *\r\n * Missing file is treated as success — logout is idempotent.\r\n */\r\nexport function deleteCredentialsFile(credentialsPath?: string): void {\r\n fs.rmSync(resolvePath(credentialsPath), { force: true });\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Shared state cache (in-process single-flight)\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Minimal promise-chaining mutex — the `asyncio.Lock` equivalent.\r\n *\r\n * `runExclusive` calls are serialized in arrival order; a rejection inside\r\n * one critical section does not poison the chain for later callers.\r\n */\r\nexport class AsyncMutex {\r\n private tail: Promise<unknown> = Promise.resolve();\r\n\r\n runExclusive<T>(fn: () => T | Promise<T>): Promise<T> {\r\n const run = this.tail.then(() => fn());\r\n this.tail = run.catch(() => undefined);\r\n return run;\r\n }\r\n}\r\n\r\n/**\r\n * Mutable per-(path, profile) state shared across clients.\r\n *\r\n * The `mutex` is shared across **all profiles in the same file** — not\r\n * per-(path, profile) — so two profiles refreshing concurrently can't both\r\n * read-modify-write the file and clobber each other's update.\r\n */\r\nexport interface SharedCredentialsState {\r\n credentials: OAuthCredentials;\r\n profileName: string;\r\n /** Resolved absolute path of the credentials file. */\r\n path: string;\r\n mutex: AsyncMutex;\r\n}\r\n\r\nconst stateCache = new Map<string, SharedCredentialsState>();\r\n// One mutex per credentials file path, shared across profiles in the same\r\n// file so concurrent refreshes serialize at the file level.\r\nconst fileMutexes = new Map<string, AsyncMutex>();\r\n\r\nfunction getFileMutex(p: string): AsyncMutex {\r\n let mutex = fileMutexes.get(p);\r\n if (mutex === undefined) {\r\n mutex = new AsyncMutex();\r\n fileMutexes.set(p, mutex);\r\n }\r\n return mutex;\r\n}\r\n\r\n/**\r\n * Return the shared state for `(path, profile)`, loading lazily.\r\n *\r\n * Returns `null` if the credentials file is missing or has no matching\r\n * profile — the caller falls back to other credential sources (static API\r\n * key, `.kagura.json`, etc.) in that case.\r\n *\r\n * Concurrent clients that resolve to the same `(path, profile)` pair get\r\n * the same state object, which means they share a single mutex and any\r\n * refresh fired by one of them benefits all of them.\r\n */\r\nexport function getSharedState(\r\n credentialsPath?: string,\r\n profile?: string | null,\r\n): SharedCredentialsState | null {\r\n // Normalize the path once so the cache key and the persisted state path\r\n // stay consistent — a relative path could otherwise cause the cache\r\n // lookup and the refresh-time write to target different files.\r\n const p = path.resolve(resolvePath(credentialsPath));\r\n const cf = loadCredentialsFile(p);\r\n const creds = getProfile(cf, profile);\r\n if (creds === null) {\r\n return null;\r\n }\r\n\r\n const profileName = profile || cf.defaultProfile;\r\n // JSON-encode the pair so a path containing spaces can never collide\r\n // with another (path, profile) combination.\r\n const key = JSON.stringify([p, profileName]);\r\n let cached = stateCache.get(key);\r\n if (cached === undefined) {\r\n cached = {\r\n credentials: creds,\r\n profileName,\r\n path: p,\r\n mutex: getFileMutex(p),\r\n };\r\n stateCache.set(key, cached);\r\n } else {\r\n // Refresh in-memory creds from disk so a recent CLI login is visible\r\n // to clients already constructed in this process.\r\n cached.credentials = creds;\r\n }\r\n return cached;\r\n}\r\n\r\n/** Clear the module-level cache. Tests call this between cases. */\r\nexport function resetStateCache(): void {\r\n stateCache.clear();\r\n fileMutexes.clear();\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// KaguraOAuth — AuthProvider with single-flight refresh\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * `AuthProvider` that supplies the current access token as a Bearer header.\r\n *\r\n * Holds a reference to a shared `SharedCredentialsState`, so concurrent\r\n * client instances pointing at the same credentials file all coalesce\r\n * refresh calls through a single in-process mutex. When the access token\r\n * is within `REFRESH_SKEW_SEC` of expiry the mutex is acquired, the\r\n * refresh runs once, and every other in-flight `getAuthHeader` call waits\r\n * and then sees the rotated token.\r\n *\r\n * (The Python SDK expresses this as an `httpx.Auth` subclass; with `fetch`\r\n * there is no request-hook layer, so clients ask for a fresh header value\r\n * before each request instead.)\r\n */\r\nexport class KaguraOAuth implements AuthProvider {\r\n private readonly state: SharedCredentialsState;\r\n private readonly fetchImpl: typeof globalThis.fetch | undefined;\r\n\r\n constructor(\r\n state: SharedCredentialsState,\r\n options: { fetch?: typeof globalThis.fetch } = {},\r\n ) {\r\n this.state = state;\r\n this.fetchImpl = options.fetch;\r\n }\r\n\r\n /**\r\n * Return `Bearer <access_token>`, refreshing first when the token is\r\n * within the skew window.\r\n */\r\n async getAuthHeader(): Promise<string> {\r\n await this.maybeRefresh();\r\n return `Bearer ${this.state.credentials.accessToken}`;\r\n }\r\n\r\n /**\r\n * Refresh the access token if it's within the skew window.\r\n *\r\n * The mutex is held across the entire read-check-refresh-persist\r\n * sequence so a second caller waiting on it will find the token already\r\n * rotated when it acquires.\r\n */\r\n private async maybeRefresh(): Promise<void> {\r\n await this.state.mutex.runExclusive(async () => {\r\n if (!isExpired(this.state.credentials, REFRESH_SKEW_SEC)) {\r\n return;\r\n }\r\n await this.refreshLocked(null);\r\n });\r\n }\r\n\r\n /**\r\n * Unconditionally refresh the access token, ignoring the skew window.\r\n *\r\n * Used on an upstream 401: the token was rejected server-side (rotated /\r\n * revoked out-of-band) even though it is not yet within the skew window.\r\n * The same in-process mutex serializes this with skew-driven refreshes.\r\n * Cross-process dedup is handled in `refreshLocked` via the\r\n * rejected-token identity check.\r\n */\r\n async forceRefresh(options: { scope?: string } = {}): Promise<void> {\r\n // Capture the rejected token BEFORE the in-process mutex: if a peer\r\n // already rotated it while we waited, we must still compare against\r\n // the token that actually got the 401, otherwise the rotated token\r\n // would compare equal to disk and force a redundant refresh.\r\n const rejectedToken = this.state.credentials.accessToken;\r\n await this.state.mutex.runExclusive(() =>\r\n this.refreshLocked(rejectedToken, options.scope),\r\n );\r\n }\r\n\r\n /**\r\n * Refresh `/oauth/token/` once across all processes. Caller holds the\r\n * in-process mutex.\r\n *\r\n * After acquiring the cross-process file lock, re-read the credentials\r\n * from disk and **skip the network call when another process already\r\n * rotated the token** — \"skip\" means \"adopt the on-disk result\", never\r\n * \"leave the stale in-memory token in place\".\r\n *\r\n * `expectedStaleToken` governs the \"already rotated?\" predicate:\r\n * `null` (skew path) → skip when the on-disk token is no longer within\r\n * the skew window. A token string (401 path) → skip only when the\r\n * on-disk token *differs* from the rejected one (a 401 is independent of\r\n * `expiresAt`).\r\n */\r\n private async refreshLocked(\r\n expectedStaleToken: string | null,\r\n scope?: string,\r\n ): Promise<void> {\r\n const credPath = this.state.path;\r\n const profileName = this.state.profileName;\r\n await withFileLock(credPath, async () => {\r\n const disk = getProfile(loadCredentialsFile(credPath), profileName);\r\n // A scope change must never adopt a peer's rotation: that token was\r\n // issued for the *old* scope, so treating it as \"already done\" would\r\n // silently drop the change the caller asked for.\r\n if (scope === undefined && disk !== null && this.alreadyRotated(disk, expectedStaleToken)) {\r\n this.state.credentials = disk;\r\n return;\r\n }\r\n const base = disk ?? this.state.credentials;\r\n await this.networkRefreshAndSave(base, credPath, profileName, scope);\r\n });\r\n }\r\n\r\n /** Whether `disk` shows another process already produced a usable token. */\r\n private alreadyRotated(disk: OAuthCredentials, expectedStaleToken: string | null): boolean {\r\n if (expectedStaleToken === null) {\r\n // Skew path: a token outside the skew window is fresh enough.\r\n return !isExpired(disk, REFRESH_SKEW_SEC);\r\n }\r\n // 401 path: a different token means someone rotated; an identical token\r\n // means the rejected token is still current and we must refresh.\r\n return disk.accessToken !== expectedStaleToken;\r\n }\r\n\r\n /** Hit `/oauth/token/` from `base` and persist. Caller holds both locks. */\r\n private async networkRefreshAndSave(\r\n base: OAuthCredentials,\r\n credPath: string,\r\n profileName: string,\r\n scope?: string,\r\n ): Promise<void> {\r\n // A profile stored without a refresh token cannot be refreshed. Going\r\n // to the network first only earns an `invalid_grant`, whose message\r\n // (\"refresh token is no longer valid\") describes a token that never\r\n // existed — the actual cause is that the grant never carried offline\r\n // access. Fail here instead, naming that.\r\n if (!base.refreshToken) {\r\n throw new KaguraAuthExpiredError(\r\n \"This profile was stored without a refresh token, so it cannot be \" +\r\n \"refreshed — log in again to get one.\\n\" +\r\n \" Run: kagura auth login (or `npx kagura-memory auth login`)\",\r\n base.expiresAt,\r\n );\r\n }\r\n\r\n const token = await refreshAccessToken(base.server, {\r\n clientId: base.clientId,\r\n refreshToken: base.refreshToken,\r\n ...(scope !== undefined ? { scope } : {}),\r\n ...(this.fetchImpl ? { fetch: this.fetchImpl } : {}),\r\n });\r\n // Pass `null` when the server omits `refresh_token` so the stored token\r\n // is preserved: `TokenResponse.refreshToken` defaults to \"\" when\r\n // absent, and overwriting a valid stored token with an empty one would\r\n // break every subsequent refresh.\r\n this.state.credentials = withRefreshed(base, {\r\n accessToken: token.accessToken,\r\n refreshToken: token.refreshToken || null,\r\n expiresAt: token.expiresAt,\r\n // `||` not `??`: TokenResponse.scope defaults to \"\" when the server\r\n // omits it, and withRefreshed's `?? creds.scope` only catches\r\n // null/undefined — so an omitted scope used to blank the stored one.\r\n scope: token.scope || null,\r\n });\r\n // We already hold the cross-process lock; write directly rather than\r\n // via updateProfile (which would re-acquire the same lock and\r\n // deadlock). Re-load → set → save still preserves every other profile\r\n // in the file.\r\n const cf = loadCredentialsFile(credPath);\r\n setProfile(cf, profileName, this.state.credentials);\r\n saveCredentialsFile(cf, credPath);\r\n }\r\n}\r\n","/**\n * OAuth2 RFC 8628 device authorization grant — stateless async helpers\n * (port of auth/device_flow.py).\n *\n * Pure-function API: every entry point takes the server base URL plus the\n * relevant parameters and returns a plain object. No CLI, no terminal IO,\n * no global state.\n *\n * The Python SDK constructs a dedicated unauthenticated `httpx.AsyncClient`\n * so the SDK's `Authorization: Bearer` header cannot leak into `/oauth/*`\n * requests (device-flow uses `client_id` body-parameter authentication, RFC\n * 8628 §3.1 `token_endpoint_auth_method='none'`). With `fetch` there is no\n * client object; the same isolation holds because each request here sets\n * its own headers and never an `Authorization` header. The `fetch`\n * implementation is injectable on every function so tests can stub HTTP.\n */\n\nimport { setTimeout as sleepMs } from \"node:timers/promises\";\n\nimport {\n KaguraAuthDeniedError,\n KaguraAuthError,\n KaguraAuthExpiredError,\n KaguraConnectionError,\n excMessage,\n} from \"../errors.js\";\nimport { extractDetail } from \"../http.js\";\nimport { SDK_VERSION } from \"../version.js\";\n\n// OAuth2 endpoint paths under {server}.\n// The path prefix is /api/v1/oauth/ (NOT /oauth2/) per memory-cloud's\n// actual mount point; the token endpoint requires the trailing slash.\nconst PATH_DEVICE_AUTHORIZE = \"/api/v1/oauth/device/authorize\";\nconst PATH_TOKEN = \"/api/v1/oauth/token/\";\nconst PATH_REVOKE = \"/api/v1/oauth/revoke\";\n\n// RFC 8628 §3.5 — \"slow_down\" requires the client to add 5 seconds.\nconst SLOW_DOWN_INCREMENT_SEC = 5;\n\n/** The pre-registered public client ID seeded by memory-cloud #624. */\nexport const DEFAULT_CLIENT_ID = \"kagura-cli\";\n\nexport const DEVICE_FLOW_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:device_code\";\nexport const REFRESH_TOKEN_GRANT_TYPE = \"refresh_token\";\n\n/** RFC 8628 §3.2 device authorization response. */\nexport interface DeviceAuthorizationResponse {\n deviceCode: string;\n userCode: string;\n verificationUri: string;\n verificationUriComplete: string;\n expiresIn: number;\n /** Polling interval in seconds. */\n interval: number;\n /** = now + expiresIn. */\n expiresAt: Date;\n}\n\n/**\n * RFC 8628 §3.5 / RFC 6749 §5.1 successful token response.\n *\n * `expiresAt` is computed once at receipt time so a paused or suspended\n * laptop never sees a negative TTL after wake.\n */\nexport interface TokenResponse {\n accessToken: string;\n refreshToken: string;\n tokenType: string;\n expiresAt: Date;\n scope: string;\n userEmail: string;\n workspaceId: string;\n workspaceName: string;\n}\n\n/** Common HTTP knobs: injectable `fetch` so tests can stub the transport. */\nexport interface OAuthHttpOptions {\n fetch?: typeof globalThis.fetch;\n}\n\nfunction userAgent(): string {\n return `kagura-memory-sdk/${SDK_VERSION}`;\n}\n\nfunction tokenUrl(server: string): string {\n return `${server.replace(/\\/+$/, \"\")}${PATH_TOKEN}`;\n}\n\n/** Coerce an unknown JSON value to a whole number, or `null`. */\nfunction toInt(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return Math.trunc(value);\n }\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const n = Number(value);\n return Number.isFinite(n) ? Math.trunc(n) : null;\n }\n return null;\n}\n\nfunction stringOr(value: unknown, fallback: string): string {\n return typeof value === \"string\" ? value : fallback;\n}\n\n/**\n * Parse a 200 response body as a JSON object.\n *\n * Converts malformed / non-object success bodies into a `KaguraAuthError`\n * with HTTP status + truncated body, so a server that wedges and returns\n * HTML / a JSON array / a scalar doesn't surface as an unhelpful\n * `SyntaxError`.\n */\nfunction safeJsonObject(\n bodyText: string,\n status: number,\n endpoint: string,\n): Record<string, unknown> {\n let body: unknown;\n try {\n body = JSON.parse(bodyText);\n } catch (e) {\n const detail = bodyText.slice(0, 200);\n throw new KaguraAuthError(\n `${endpoint} returned HTTP ${status} but body is not JSON: ${excMessage(e)}. ` +\n `Body: ${detail}`,\n { cause: e },\n );\n }\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n throw new KaguraAuthError(\n `${endpoint} returned HTTP ${status} but body is not a JSON object ` +\n `(got ${Array.isArray(body) ? \"array\" : typeof body})`,\n );\n }\n return body as Record<string, unknown>;\n}\n\n/** Parse a response body as a JSON object, or `{}` if unparseable. */\nfunction safeJson(bodyText: string): Record<string, unknown> {\n let body: unknown;\n try {\n body = JSON.parse(bodyText);\n } catch {\n return {};\n }\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return {};\n }\n return body as Record<string, unknown>;\n}\n\n/**\n * Build a `TokenResponse` from a 200 `/oauth/token/` body.\n *\n * `expiresAt` is computed from `expires_in` at receipt time so laptop sleep\n * / clock skew won't yield a negative TTL after wake. Missing or invalid\n * required fields surface as `KaguraAuthError`.\n */\nfunction tokenResponseFromBody(bodyText: string, status: number): TokenResponse {\n const body = safeJsonObject(bodyText, status, \"Token endpoint\");\n const accessToken = body.access_token;\n const expiresIn = toInt(body.expires_in ?? 0);\n if (typeof accessToken !== \"string\" || expiresIn === null) {\n throw new KaguraAuthError(\n `Token endpoint returned HTTP ${status} but body is missing required fields. ` +\n `Body keys: ${Object.keys(body).sort().join(\", \")}`,\n );\n }\n return {\n accessToken,\n refreshToken: stringOr(body.refresh_token, \"\"),\n tokenType: stringOr(body.token_type, \"Bearer\"),\n expiresAt: new Date(Date.now() + expiresIn * 1000),\n scope: stringOr(body.scope, \"\"),\n userEmail: stringOr(body.user_email, \"\"),\n workspaceId: stringOr(body.workspace_id, \"\"),\n workspaceName: stringOr(body.workspace_name, \"\"),\n };\n}\n\n/**\n * POST `{server}/api/v1/oauth/device/authorize` and parse the response.\n *\n * memory-cloud's device/authorize accepts JSON, unlike the /oauth/token/ +\n * /oauth/revoke endpoints which take application/x-www-form-urlencoded.\n */\nexport async function authorizeDevice(\n server: string,\n options: OAuthHttpOptions & { clientId?: string; scope?: string } = {},\n): Promise<DeviceAuthorizationResponse> {\n const clientId = options.clientId ?? DEFAULT_CLIENT_ID;\n const scope = options.scope ?? \"memory:read\";\n const doFetch = options.fetch ?? globalThis.fetch;\n const url = `${server.replace(/\\/+$/, \"\")}${PATH_DEVICE_AUTHORIZE}`;\n\n let response: Response;\n let text: string;\n try {\n response = await doFetch(url, {\n method: \"POST\",\n headers: {\n \"User-Agent\": userAgent(),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ client_id: clientId, scope }),\n });\n text = await response.text();\n } catch (e) {\n throw new KaguraConnectionError(`Could not reach ${url}: ${excMessage(e)}`, { cause: e });\n }\n\n if (!response.ok) {\n const detail = extractDetail(text) || text;\n throw new KaguraAuthError(\n `Device authorization failed (HTTP ${response.status}): ${detail}\\n` +\n ` Verify the server URL and that '${clientId}' is registered.`,\n );\n }\n\n const body = safeJsonObject(text, response.status, \"Device authorization\");\n const deviceCode = body.device_code;\n const userCode = body.user_code;\n const verificationUri = body.verification_uri;\n const expiresIn = toInt(body.expires_in);\n if (\n typeof deviceCode !== \"string\" ||\n typeof userCode !== \"string\" ||\n typeof verificationUri !== \"string\" ||\n expiresIn === null\n ) {\n throw new KaguraAuthError(\n \"Device authorization returned HTTP 200 but body is missing required fields. \" +\n `Body keys: ${Object.keys(body).sort().join(\", \")}`,\n );\n }\n return {\n deviceCode,\n userCode,\n verificationUri,\n verificationUriComplete: stringOr(body.verification_uri_complete, verificationUri),\n expiresIn,\n interval: toInt(body.interval) ?? 5,\n expiresAt: new Date(Date.now() + expiresIn * 1000),\n };\n}\n\nexport interface PollForTokenOptions extends OAuthHttpOptions {\n clientId: string;\n deviceCode: string;\n /** RFC 8628 polling interval in seconds. */\n interval: number;\n expiresAt: Date;\n /**\n * Injectable sleep (milliseconds) so tests can supply a no-op or\n * counter-based stub without waiting real seconds.\n */\n sleep?: (ms: number) => Promise<void>;\n}\n\n/**\n * Poll `{server}/api/v1/oauth/token/` until the user approves or denies.\n *\n * The first poll fires immediately (no initial sleep) so a fast approval\n * never waits a whole interval; sleeps only happen between retries after\n * `authorization_pending` / `slow_down`.\n *\n * @throws KaguraAuthDeniedError user clicked \"Deny\" at the consent screen\n * (server returns `access_denied`).\n * @throws KaguraAuthExpiredError the `device_code` lifetime elapsed without\n * approval (server returns `expired_token`, or `expiresAt` passed locally).\n * @throws KaguraAuthError any other OAuth error or unexpected response.\n * @throws KaguraConnectionError network failure during polling.\n */\nexport async function pollForToken(\n server: string,\n options: PollForTokenOptions,\n): Promise<TokenResponse> {\n const doFetch = options.fetch ?? globalThis.fetch;\n const sleep = options.sleep ?? (async (ms: number): Promise<void> => void (await sleepMs(ms)));\n const url = tokenUrl(server);\n\n let currentInterval = options.interval;\n let firstPoll = true;\n\n for (;;) {\n if (Date.now() >= options.expiresAt.getTime()) {\n throw new KaguraAuthExpiredError(\n \"Device code expired before user approval. Run: kagura auth login\",\n options.expiresAt,\n );\n }\n\n // Skip the initial sleep so an immediate approval (or a fast\n // server-side error) doesn't wait one whole interval.\n if (firstPoll) {\n firstPoll = false;\n } else {\n await sleep(currentInterval * 1000);\n }\n\n let response: Response;\n let text: string;\n try {\n response = await doFetch(url, {\n method: \"POST\",\n headers: { \"User-Agent\": userAgent() },\n body: new URLSearchParams({\n grant_type: DEVICE_FLOW_GRANT_TYPE,\n device_code: options.deviceCode,\n client_id: options.clientId,\n }),\n });\n text = await response.text();\n } catch (e) {\n throw new KaguraConnectionError(\n `Lost connection while waiting for approval: ${excMessage(e)}\\n` +\n ` The login session may still be valid; re-run: kagura auth login`,\n { cause: e },\n );\n }\n\n if (response.status === 200) {\n return tokenResponseFromBody(text, response.status);\n }\n\n // RFC 8628 §3.5 — errors come as HTTP 4xx with JSON `error` field.\n const body = safeJson(text);\n const error = stringOr(body.error, \"\");\n\n if (error === \"authorization_pending\") {\n continue;\n }\n if (error === \"slow_down\") {\n currentInterval += SLOW_DOWN_INCREMENT_SEC;\n continue;\n }\n if (error === \"access_denied\") {\n throw new KaguraAuthDeniedError(\n \"Authorization denied at the consent screen.\\n\" +\n \" Re-run: kagura auth login\\n\" +\n \" To use a different workspace, log in with that account \" +\n \"in your browser first.\",\n );\n }\n if (error === \"expired_token\") {\n throw new KaguraAuthExpiredError(\n \"Device code expired before user approval. Run: kagura auth login\",\n options.expiresAt,\n );\n }\n\n // Unknown error — surface the HTTP status + raw response so the\n // operator can debug non-OAuth failures (HTML 5xx, proxy errors,\n // non-JSON bodies that make `error` come back empty).\n const description = stringOr(body.error_description, \"\");\n if (error || description) {\n throw new KaguraAuthError(\n `Token endpoint returned unexpected error '${error}': ${description}`,\n );\n }\n const detail = extractDetail(text) || text.slice(0, 200);\n throw new KaguraAuthError(\n `Token endpoint returned HTTP ${response.status} with no OAuth error code. ` +\n `Body: ${detail}`,\n );\n }\n}\n\nexport interface RefreshAccessTokenOptions extends OAuthHttpOptions {\n clientId: string;\n refreshToken: string;\n scope?: string | null;\n}\n\n/**\n * POST `{server}/api/v1/oauth/token/` with `grant_type=refresh_token`.\n *\n * When `scope` is supplied, the server may reject the call with\n * `insufficient_scope` / `invalid_scope` if the grant doesn't cover it.\n *\n * @throws KaguraAuthExpiredError refresh token is invalid or expired\n * (server returns `invalid_grant`).\n * @throws KaguraAuthError any other OAuth error.\n * @throws KaguraConnectionError network failure.\n */\nexport async function refreshAccessToken(\n server: string,\n options: RefreshAccessTokenOptions,\n): Promise<TokenResponse> {\n const doFetch = options.fetch ?? globalThis.fetch;\n const url = tokenUrl(server);\n const form = new URLSearchParams({\n grant_type: REFRESH_TOKEN_GRANT_TYPE,\n refresh_token: options.refreshToken,\n client_id: options.clientId,\n });\n if (options.scope !== undefined && options.scope !== null) {\n form.set(\"scope\", options.scope);\n }\n\n let response: Response;\n let text: string;\n try {\n response = await doFetch(url, {\n method: \"POST\",\n headers: { \"User-Agent\": userAgent() },\n body: form,\n });\n text = await response.text();\n } catch (e) {\n throw new KaguraConnectionError(`Could not reach ${url}: ${excMessage(e)}`, { cause: e });\n }\n\n if (response.status === 200) {\n return tokenResponseFromBody(text, response.status);\n }\n\n const body = safeJson(text);\n const error = stringOr(body.error, \"\");\n\n if (error === \"invalid_grant\") {\n throw new KaguraAuthExpiredError(\n \"Your login expired (refresh token is no longer valid).\\n\" +\n \" Run: kagura auth login\\n\" +\n \" Your server and workspace selection are preserved.\",\n );\n }\n\n const description = stringOr(body.error_description, \"\");\n if (error) {\n throw new KaguraAuthError(\n `Refresh failed: ${error}${description ? ` — ${description}` : \"\"}`,\n );\n }\n // Non-OAuth failure (HTML 5xx, network proxy returning text/plain, etc.).\n const detail = extractDetail(text) || text.slice(0, 200);\n throw new KaguraAuthError(\n `Refresh failed: HTTP ${response.status} with no OAuth error code. Body: ${detail}`,\n );\n}\n\n/**\n * POST `{server}/api/v1/oauth/revoke`. Best-effort — never throws.\n *\n * Returns `true` on success, `false` on any failure. The caller\n * (`kagura auth logout`) deletes the local profile regardless of the\n * return value, on the principle that local logout must succeed even when\n * the server is unreachable.\n */\nexport async function revokeToken(\n server: string,\n options: OAuthHttpOptions & { token: string; clientId?: string },\n): Promise<boolean> {\n const doFetch = options.fetch ?? globalThis.fetch;\n const url = `${server.replace(/\\/+$/, \"\")}${PATH_REVOKE}`;\n try {\n const response = await doFetch(url, {\n method: \"POST\",\n headers: { \"User-Agent\": userAgent() },\n body: new URLSearchParams({\n token: options.token,\n client_id: options.clientId ?? DEFAULT_CLIENT_ID,\n }),\n });\n return response.status === 200 || response.status === 204;\n } catch {\n return false;\n }\n}\n","/**\n * Cross-process file locking for `~/.kagura/credentials.json` (port of\n * _filelock.py).\n *\n * The in-process mutex in `auth/credentials` serializes credential refreshes\n * *within* a single process. When several processes own the same credentials\n * file at once — e.g. multiple `kagura-mcp` proxy children plus a stray\n * client — they need a *cross-process* gate so a concurrent\n * read-modify-write cannot lose an update.\n *\n * DEVIATION FROM PYTHON: the Python SDK uses OS advisory locks\n * (`fcntl.flock` on POSIX, `msvcrt.locking` on Windows), which Node's\n * builtins do not expose. This port instead uses an `O_EXCL` lockfile-create\n * loop: the lock is *held* while the sibling `<name>.lock` file exists, and\n * acquiring means winning the exclusive create. Consequences:\n *\n * - There is no shared/exclusive distinction — every lock is exclusive\n * (matching the Python Windows `msvcrt` backend, which has no shared mode).\n * - A kernel lock dies with its owner; a lockfile does not. A crashed holder\n * is therefore handled by *stale detection*: a lock file whose mtime is\n * older than `staleMs` is presumed abandoned and broken (deleted), and the\n * acquire loop retries. The stale threshold is sized above the OAuth\n * refresh round-trip (the only operation that holds the lock across a\n * network call), so it never trips on a live holder.\n * - The lockfile protocol is compatible with the Python CLI in the sense\n * that both lock a sibling of the credentials file, never the file itself,\n * so neither interferes with the other's atomic rename. (The Python CLI's\n * kernel lock does not observe our lockfile and vice versa; the atomic\n * rename in `credentials.ts` still guarantees the file is never torn, the\n * lock only adds serialization — same as the Python no-op fallback.)\n *\n * A contended acquire is bounded by `timeoutMs` (like the Python msvcrt\n * backend's 90 s ceiling) so a stuck peer cannot wedge a waiter forever.\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\n\n/** Poll interval while waiting for a contended lock (Python: 0.05 s). */\nexport const DEFAULT_LOCK_RETRY_MS = 50;\n\n/**\n * Safety ceiling on a *contended* acquire (Python: 90 s). Sized well above\n * the OAuth refresh round-trip so it only bounds the pathological case.\n */\nexport const DEFAULT_LOCK_TIMEOUT_MS = 90_000;\n\n/**\n * Age after which a held lock file is presumed abandoned (crashed holder)\n * and broken. Must exceed the longest legitimate hold (an OAuth refresh\n * round-trip, bounded by its ~30 s HTTP timeout) and stay below\n * `DEFAULT_LOCK_TIMEOUT_MS` so a crashed peer's lock is broken before a\n * healthy waiter times out.\n */\nexport const DEFAULT_LOCK_STALE_MS = 60_000;\n\n/** Thrown when a contended acquire exceeds its deadline. */\nexport class FileLockTimeoutError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FileLockTimeoutError\";\n }\n}\n\nexport interface FileLockOptions {\n /** Contended-acquire deadline in ms (default `DEFAULT_LOCK_TIMEOUT_MS`). */\n timeoutMs?: number;\n /** Poll interval between attempts in ms (default `DEFAULT_LOCK_RETRY_MS`). */\n retryMs?: number;\n /** Stale-lock age threshold in ms (default `DEFAULT_LOCK_STALE_MS`). */\n staleMs?: number;\n}\n\n/** A held lock. `release()` is idempotent. */\nexport interface FileLockHandle {\n /** Path of the lock file itself (the `<name>.lock` sibling). */\n readonly path: string;\n release(): void;\n}\n\n/**\n * Sibling `.lock` file for `target` (never the credentials file itself).\n *\n * Locking a dedicated sibling rather than the credentials file avoids\n * interfering with the atomic rename in `credentials.ts` (which swaps the\n * file out from under any handle open on the original).\n */\nexport function lockPath(target: string): string {\n return `${target}.lock`;\n}\n\nfunction isErrnoException(e: unknown): e is NodeJS.ErrnoException {\n return e instanceof Error && \"code\" in e;\n}\n\n/**\n * Acquire the cross-process lock for `target` (see module docs).\n *\n * The lock file is created with mode 0600 (where the platform honors it)\n * and contains `<pid> <iso-timestamp>` for debuggability. The caller must\n * call `release()` on the returned handle — prefer `withFileLock`, which\n * guarantees release in a `finally`.\n *\n * @throws FileLockTimeoutError when the lock stays contended past `timeoutMs`.\n */\nexport async function acquireFileLock(\n target: string,\n options: FileLockOptions = {},\n): Promise<FileLockHandle> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS;\n const retryMs = options.retryMs ?? DEFAULT_LOCK_RETRY_MS;\n const staleMs = options.staleMs ?? DEFAULT_LOCK_STALE_MS;\n\n const lockFile = lockPath(target);\n fs.mkdirSync(path.dirname(lockFile), { recursive: true });\n\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n // Attempt the exclusive create (\"wx\" = O_WRONLY | O_CREAT | O_EXCL).\n let fd: number | null = null;\n try {\n fd = fs.openSync(lockFile, \"wx\", 0o600);\n } catch (e) {\n if (!isErrnoException(e) || e.code !== \"EEXIST\") {\n // Permission failure, unsupported FS, etc. — a permanent failure\n // must surface instead of spinning forever (Python parity).\n throw e;\n }\n }\n if (fd !== null) {\n try {\n fs.writeSync(fd, `${process.pid} ${new Date().toISOString()}\\n`);\n } finally {\n fs.closeSync(fd);\n }\n let released = false;\n return {\n path: lockFile,\n release(): void {\n if (released) {\n return;\n }\n released = true;\n try {\n fs.unlinkSync(lockFile);\n } catch {\n // Already gone (broken as stale by a waiter) — release is\n // best-effort and idempotent.\n }\n },\n };\n }\n\n // Lock is held by someone else. Break it if it looks abandoned.\n let mtimeMs: number;\n try {\n mtimeMs = fs.statSync(lockFile).mtimeMs;\n } catch (e) {\n if (isErrnoException(e) && e.code === \"ENOENT\") {\n continue; // released between attempts — retry the create at once\n }\n throw e;\n }\n if (Date.now() - mtimeMs > staleMs) {\n try {\n fs.unlinkSync(lockFile);\n } catch (e) {\n if (!isErrnoException(e) || e.code !== \"ENOENT\") {\n throw e;\n }\n }\n continue; // retry the create at once\n }\n\n if (Date.now() >= deadline) {\n throw new FileLockTimeoutError(\n `could not acquire credentials lock within ${timeoutMs / 1000}s: ${lockFile}`,\n );\n }\n await sleep(retryMs);\n }\n}\n\n/**\n * Hold the cross-process lock for `target` for the duration of `fn`.\n *\n * The lock is always released — including when `fn` throws — via the\n * `finally` block (mirrors Python's `file_lock` context manager).\n */\nexport async function withFileLock<T>(\n target: string,\n fn: () => T | Promise<T>,\n options: FileLockOptions = {},\n): Promise<T> {\n const handle = await acquireFileLock(target, options);\n try {\n return await fn();\n } finally {\n handle.release();\n }\n}\n","/** Configuration loading for the Kagura Memory SDK (port of config.py). */\n\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\n/**\n * Shape of `.kagura.json` — the config file format is shared with the\n * Python SDK/CLI, so keys stay snake_case on disk. Additional keys are\n * preserved.\n */\nexport interface KaguraConfig {\n api_key?: string;\n mcp_url?: string;\n model?: string;\n context_id?: string | null;\n llm_api_key?: string;\n workspace_id?: string;\n [key: string]: unknown;\n}\n\nexport interface LoadConfigOptions {\n /** Directory searched for `./.kagura.json` (default: process.cwd()). */\n cwd?: string;\n /** Home directory searched for `~/.kagura.json` (default: os.homedir()). */\n home?: string;\n /** Environment source (default: process.env). */\n env?: Record<string, string | undefined>;\n}\n\nfunction readConfigFile(filePath: string, label: string): KaguraConfig {\n let text: string;\n try {\n text = fs.readFileSync(filePath, \"utf-8\");\n } catch (e) {\n throw new Error(`Failed to read ${label}: ${e instanceof Error ? e.message : String(e)}`);\n }\n try {\n const parsed: unknown = JSON.parse(text);\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(\"expected a JSON object\");\n }\n return parsed as KaguraConfig;\n } catch (e) {\n throw new Error(\n `Invalid JSON or encoding in ${label} (expected UTF-8): ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\n/**\n * Load configuration from `.kagura.json` or environment variables.\n *\n * Search order:\n * 1. `./.kagura.json` (current directory)\n * 2. `~/.kagura.json` (home directory)\n * 3. Environment variables (KAGURA_API_KEY, KAGURA_MCP_URL, KAGURA_MODEL)\n */\nexport function loadConfig(options: LoadConfigOptions = {}): KaguraConfig {\n const cwd = options.cwd ?? process.cwd();\n const home = options.home ?? os.homedir();\n const env = options.env ?? process.env;\n\n const localConfig = path.join(cwd, \".kagura.json\");\n if (fs.existsSync(localConfig)) {\n return readConfigFile(localConfig, \".kagura.json\");\n }\n\n const homeConfig = path.join(home, \".kagura.json\");\n if (fs.existsSync(homeConfig)) {\n return readConfigFile(homeConfig, \"~/.kagura.json\");\n }\n\n return {\n api_key: env.KAGURA_API_KEY ?? \"\",\n mcp_url: env.KAGURA_MCP_URL ?? \"https://memory.kagura-ai.com/mcp\",\n model: env.KAGURA_MODEL ?? \"gpt-5.4-nano\",\n context_id: env.KAGURA_CONTEXT_ID ?? null,\n };\n}\n","/**\n * Credential resolution shared by REST/MCP clients in this SDK (port of\n * _auth.py).\n *\n * Centralizes the precedence chain — explicit arg > `KAGURA_API_KEY` env >\n * OAuth profile in `~/.kagura/credentials.json` > `.kagura.json` config —\n * in one module so every client resolves credentials identically.\n *\n * Returns one of two result types (see `types.ts`):\n *\n * - `StaticAuthResult` — long-lived API key, baked into the client's\n * `Authorization` header at construction.\n * - `OAuthAuthResult` — a `KaguraOAuth` AuthProvider that injects a fresh\n * access token per request and coordinates refresh via a process-wide\n * mutex.\n *\n * This module imports only from `auth/credentials`, `config`, and\n * `errors` — never from `http`. The reverse direction (`http` importing\n * `resolve`) must also be avoided so the dependency stays one-way.\n */\n\nimport { loadConfig } from \"../config.js\";\nimport type { KaguraConfig } from \"../config.js\";\nimport { KaguraAuthError } from \"../errors.js\";\nimport {\n KaguraOAuth,\n defaultCredentialsPath,\n getSharedState,\n loadCredentialsFile,\n} from \"./credentials.js\";\nimport type { SharedCredentialsState } from \"./credentials.js\";\nimport type { ResolvedAuth } from \"./types.js\";\n\nexport const DEFAULT_MCP_URL = \"https://memory.kagura-ai.com/mcp\";\n\n/** Kept trivial on purpose; swap the sink here if the SDK ever grows one. */\nconst logger = {\n warn(message: string): void {\n console.warn(message);\n },\n};\n\n// (credentials-file path, profile name) pairs already warned about this\n// process, so the multi-profile ambiguity note fires at most once per active\n// profile per file per process rather than on every client construction.\n// Keyed by path too so two different credential files that share a default\n// name (e.g. \"default\") don't suppress each other.\nconst warnedProfiles = new Set<string>();\n\n/** Clear the once-per-process ambiguity-warning dedup set (test hook). */\nexport function resetProfileWarnings(): void {\n warnedProfiles.clear();\n}\n\nexport interface ResolveAuthOptions {\n apiKey?: string | null;\n mcpUrl?: string | null;\n profile?: string | null;\n /** Pre-loaded `.kagura.json`; skips the priority-4 disk read when set. */\n config?: KaguraConfig | null;\n /** Environment source (default: process.env). */\n env?: Record<string, string | undefined>;\n /** Home directory for `~/.kagura/credentials.json` (default: os.homedir()). */\n home?: string;\n}\n\n/** True when `KAGURA_REQUIRE_PROFILE` opts into strict resolution. */\nfunction strictProfileRequired(env: Record<string, string | undefined>): boolean {\n const raw = (env.KAGURA_REQUIRE_PROFILE ?? \"\").trim().toLowerCase();\n return raw === \"1\" || raw === \"true\" || raw === \"yes\";\n}\n\n/**\n * Warn (or, under strict mode, raise) on an implicit multi-profile default.\n *\n * Only fires when resolution fell back to `default_profile` (no explicit\n * `profile` arg and no `KAGURA_PROFILE`) AND more than one profile is\n * configured — a single-profile setup is unambiguous and stays silent. The\n * note names the active profile + workspace so a misdirected write to the\n * wrong account is caught. Honors `KAGURA_REQUIRE_PROFILE`.\n */\nfunction checkProfileAmbiguity(\n state: SharedCredentialsState,\n env: Record<string, string | undefined>,\n credentialsPath: string,\n): void {\n const cf = loadCredentialsFile(credentialsPath);\n if (Object.keys(cf.profiles).length < 2) {\n return; // single profile: unambiguous\n }\n\n const name = state.profileName;\n const creds = state.credentials;\n const workspace = creds.workspaceName || creds.workspaceId || \"unknown workspace\";\n\n // The strict check runs BEFORE the dedup-set check so a prior non-strict\n // warning can never swallow a strict raise.\n if (strictProfileRequired(env)) {\n const available = Object.keys(cf.profiles).sort().join(\", \");\n throw new KaguraAuthError(\n `Multiple profiles configured and none selected; refusing to use the ` +\n `implicit default '${name}' because KAGURA_REQUIRE_PROFILE is set.\\n` +\n ` Select one explicitly: kagura auth use <name>, --profile <name>, ` +\n `or KAGURA_PROFILE=<name>\\n` +\n ` Available profiles: ${available}`,\n );\n }\n\n const warnKey = JSON.stringify([state.path, name]);\n if (!warnedProfiles.has(warnKey)) {\n warnedProfiles.add(warnKey);\n logger.warn(\n `kagura: using profile '${name}' (workspace '${workspace}') — set a ` +\n `default with 'kagura auth use <name>' or pass --profile to silence ` +\n `this notice.`,\n );\n }\n}\n\n/**\n * Pick a credential source per the documented precedence chain:\n *\n * 1. Explicit `apiKey` argument (non-whitespace) — wins absolutely.\n * 2. `KAGURA_API_KEY` env var, with mcpUrl fallback\n * `mcpUrl arg > KAGURA_MCP_URL > DEFAULT_MCP_URL`.\n * 3. OAuth profile from credentials.json:\n * `profile arg > KAGURA_PROFILE > default_profile`. An explicitly named\n * profile that is missing raises rather than falling through (silently\n * authenticating with the wrong account is the bug class prevented).\n * 4. Legacy `.kagura.json` (pre-loaded via `options.config` or read from\n * disk), with the same whitespace-stripped api_key check.\n *\n * Empty / whitespace-only api_keys are treated the same as absent at every\n * step — sending `Authorization: Bearer ` would always 401 and is never\n * what the caller intended.\n *\n * @throws KaguraAuthError when no source produces credentials.\n */\nexport function resolveAuth(options: ResolveAuthOptions = {}): ResolvedAuth {\n const env = options.env ?? process.env;\n const mcpUrl = options.mcpUrl ?? null;\n\n // 1. Explicit constructor argument wins absolutely.\n const apiKey = options.apiKey;\n if (apiKey !== undefined && apiKey !== null && apiKey.trim()) {\n return {\n kind: \"static\",\n apiKey,\n mcpUrl: mcpUrl || DEFAULT_MCP_URL,\n source: \"explicit\",\n };\n }\n\n // 2. KAGURA_API_KEY env var (highest auto-resolution priority).\n const envKey = env.KAGURA_API_KEY;\n if (envKey && envKey.trim()) {\n return {\n kind: \"static\",\n apiKey: envKey,\n mcpUrl: mcpUrl || env.KAGURA_MCP_URL || DEFAULT_MCP_URL,\n source: \"env\",\n };\n }\n\n // 3. OAuth profile from credentials.json: explicit > KAGURA_PROFILE > default.\n const targetProfile = options.profile || env.KAGURA_PROFILE || null;\n const credentialsPath = defaultCredentialsPath(options.home);\n const state = getSharedState(credentialsPath, targetProfile);\n if (state !== null) {\n if (targetProfile === null) {\n // No explicit selection — resolution fell back to default_profile.\n // Warn (or hard-error under strict mode) when the default is\n // ambiguous because multiple profiles are configured.\n checkProfileAmbiguity(state, env, credentialsPath);\n }\n return {\n kind: \"oauth\",\n oauth: new KaguraOAuth(state),\n mcpUrl: mcpUrl || state.credentials.mcpUrl,\n workspaceId: state.credentials.workspaceId || null,\n };\n }\n if (targetProfile) {\n // An explicit profile name (via arg or KAGURA_PROFILE env) was\n // requested but credentials.json has no such profile. Falling through\n // to .kagura.json would silently authenticate with the wrong account,\n // so raise instead.\n const source = options.profile ? \"profile argument\" : \"KAGURA_PROFILE env\";\n throw new KaguraAuthError(\n `Profile '${targetProfile}' (from ${source}) not found in credentials.json.\\n` +\n ` Run: kagura auth login --profile ${targetProfile}\\n` +\n ` Or inspect ~/.kagura/credentials.json to see which profiles exist.`,\n );\n }\n\n // 4. Legacy .kagura.json (which itself env-falls-back internally).\n const cfg =\n options.config ?? loadConfig({ ...(options.home ? { home: options.home } : {}), env });\n const cfgKey = cfg.api_key;\n if (typeof cfgKey === \"string\" && cfgKey.trim()) {\n return {\n kind: \"static\",\n apiKey: cfgKey,\n mcpUrl: mcpUrl || cfg.mcp_url || DEFAULT_MCP_URL,\n source: \"config\",\n };\n }\n\n throw new KaguraAuthError(\n \"No credentials found.\\n\" +\n \" Run: kagura auth login\\n\" +\n \" Or set: KAGURA_API_KEY=<your key>\\n\" +\n ' Or create: .kagura.json with {\"api_key\": \"...\"}',\n );\n}\n","/**\r\n * Interactive OAuth login — the one step the SDK could not do on its own.\r\n *\r\n * `deviceFlow.ts` provides the stateless RFC 8628 primitives and\r\n * `credentials.ts` the Python-CLI-compatible store; this module is the thin\r\n * orchestrator that joins them: authorize → hand the user code to the host\r\n * app → poll → persist. It is what lets a TypeScript-only consumer (an\r\n * Electron app, a CLI of its own) obtain credentials instead of requiring\r\n * the user to install and run the Python `kagura auth login` first.\r\n *\r\n * Deliberately still no terminal IO and no browser launching: `onUserCode`\r\n * hands the code and verification URI back to the caller, which owns how it\r\n * is displayed. The only side effect is the credentials file write.\r\n */\r\n\r\nimport { baseUrlFromMcp, validateHttpsUrl } from \"../http.js\";\r\nimport type { OAuthCredentials } from \"./credentials.js\";\r\nimport { setDefaultProfile, updateProfile } from \"./credentials.js\";\r\nimport { authorizeDevice, pollForToken, DEFAULT_CLIENT_ID } from \"./deviceFlow.js\";\r\nimport type { DeviceAuthorizationResponse } from \"./deviceFlow.js\";\r\nimport { DEFAULT_MCP_URL } from \"./resolve.js\";\r\n\r\n/**\r\n * Scope requested when `login()` is called without one.\r\n *\r\n * Read **and** write, matching the Python CLI's `kagura auth login`\r\n * default. The credentials file is shared between both SDKs, so a profile\r\n * must not end up with different authority depending on which one wrote\r\n * it. Opt down with `scope: READ_ONLY_SCOPE` — the CLI's `--read-only`.\r\n */\r\nexport const DEFAULT_SCOPE = \"memory:read memory:write\";\r\n\r\n/** Read-only scope; the Python CLI's `--read-only`. */\r\nexport const READ_ONLY_SCOPE = \"memory:read\";\r\n\r\nexport interface LoginOptions {\r\n /**\r\n * MCP endpoint to log into. The OAuth endpoints are derived from it, and\r\n * both URLs are stored on the profile so the pair can never drift apart.\r\n *\r\n * Resolution mirrors the Python CLI's `--server` chain: this option,\r\n * then `KAGURA_MCP_URL`, then {@link DEFAULT_MCP_URL}. Plain HTTP is\r\n * rejected for non-loopback hosts — the flow carries a bearer token.\r\n */\r\n mcpUrl?: string;\r\n /** Environment source override (for tests; default: `process.env`). */\r\n env?: Record<string, string | undefined>;\r\n /** OAuth client ID (default {@link DEFAULT_CLIENT_ID}). */\r\n clientId?: string;\r\n /**\r\n * Requested scope. Defaults to {@link DEFAULT_SCOPE} (read + write), the\r\n * same default as the Python CLI's `kagura auth login`. Pass\r\n * {@link READ_ONLY_SCOPE} for the CLI's `--read-only` behaviour.\r\n */\r\n scope?: string;\r\n /** Profile name to store under (default `\"default\"`). */\r\n profile?: string;\r\n /** Credentials file path (default `~/.kagura/credentials.json`). */\r\n credentialsPath?: string;\r\n /**\r\n * Make this profile the default even when others already exist.\r\n *\r\n * Off by default: the first profile ever written is promoted\r\n * automatically, so adding a second one leaves the user's existing\r\n * default alone unless they ask for the switch.\r\n */\r\n setAsDefault?: boolean;\r\n /**\r\n * Called once with the device-authorization response before polling\r\n * starts — display `userCode` and `verificationUri` (or open\r\n * `verificationUriComplete`) here.\r\n *\r\n * Awaited, and a throw aborts the login before any polling or disk\r\n * write, so a host app that cannot show the code fails fast.\r\n */\r\n onUserCode?: (auth: DeviceAuthorizationResponse) => void | Promise<void>;\r\n /** Injectable fetch (tests / custom agents). */\r\n fetch?: typeof globalThis.fetch;\r\n /** Injectable sleep in milliseconds, used between polls. */\r\n sleep?: (ms: number) => Promise<void>;\r\n}\r\n\r\n/**\r\n * Run the full device-authorization login and persist the result.\r\n *\r\n * @returns the credentials that were written.\r\n * @throws KaguraAuthDeniedError the user denied at the consent screen.\r\n * @throws KaguraAuthExpiredError the device code expired before approval.\r\n * @throws KaguraAuthError propagated from the device-flow primitives on a\r\n * protocol/response failure.\r\n * @throws KaguraConnectionError the server was unreachable.\r\n *\r\n * Nothing is written unless the token exchange succeeds, so a failed login\r\n * never disturbs an existing profile. A response with no `refresh_token`\r\n * warns and still persists (matching the Python CLI); check the returned\r\n * `refreshToken` if the caller needs to react.\r\n */\r\nexport async function login(options: LoginOptions = {}): Promise<OAuthCredentials> {\r\n const env = options.env ?? process.env;\r\n // Explicit arg > KAGURA_MCP_URL > public default, matching the Python\r\n // CLI. Without the env step a self-hosted user with KAGURA_MCP_URL set\r\n // would be silently logged in to the public cloud instead.\r\n const mcpUrl = options.mcpUrl?.trim() || env.KAGURA_MCP_URL?.trim() || DEFAULT_MCP_URL;\r\n // The device flow carries a bearer token back over this connection, so\r\n // the destination is validated before any request goes out.\r\n validateHttpsUrl(mcpUrl, \"MCP URL\");\r\n const server = baseUrlFromMcp(mcpUrl);\r\n const clientId = options.clientId ?? DEFAULT_CLIENT_ID;\r\n const profile = options.profile ?? \"default\";\r\n\r\n const authorization = await authorizeDevice(server, {\r\n clientId,\r\n scope: options.scope ?? DEFAULT_SCOPE,\r\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\r\n });\r\n\r\n await options.onUserCode?.(authorization);\r\n\r\n const token = await pollForToken(server, {\r\n clientId,\r\n deviceCode: authorization.deviceCode,\r\n interval: authorization.interval,\r\n expiresAt: authorization.expiresAt,\r\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\r\n ...(options.sleep !== undefined ? { sleep: options.sleep } : {}),\r\n });\r\n\r\n // A response with no refresh_token yields a profile that cannot\r\n // auto-refresh. Python treats that as a legitimate degraded state — it\r\n // writes the profile and reports `refreshable: false` from\r\n // `kagura auth status` — so this SDK must not reject a state the other\r\n // one considers valid on the file they share. Warn instead: the caller\r\n // can also branch on the returned `refreshToken`.\r\n if (!token.refreshToken) {\r\n console.warn(\r\n \"Logged in, but the token response carried no refresh_token: this \" +\r\n \"profile cannot auto-refresh and will need another login when the \" +\r\n `access token expires. Verify the '${clientId}' client is allowed ` +\r\n `offline access on ${server}.`,\r\n );\r\n }\r\n\r\n const credentials: OAuthCredentials = {\r\n server,\r\n mcpUrl,\r\n clientId,\r\n accessToken: token.accessToken,\r\n refreshToken: token.refreshToken,\r\n tokenType: token.tokenType,\r\n expiresAt: token.expiresAt,\r\n scope: token.scope,\r\n workspaceId: token.workspaceId,\r\n workspaceName: token.workspaceName,\r\n userEmail: token.userEmail,\r\n issuedAt: new Date(),\r\n };\r\n\r\n await updateProfile(profile, credentials, options.credentialsPath);\r\n if (options.setAsDefault) {\r\n await setDefaultProfile(profile, options.credentialsPath);\r\n }\r\n return credentials;\r\n}\r\n","/**\r\n * Explicit credential refresh — the `kagura auth refresh` counterpart.\r\n *\r\n * Auto-refresh already happens inside {@link KaguraOAuth} as tokens near\r\n * expiry, so this is for the cases that skew-driven rotation cannot cover:\r\n * a token revoked out-of-band (rejected server-side while still outside\r\n * the skew window), a deliberate scope change, or a pre-flight refresh\r\n * before a long batch.\r\n *\r\n * Like `login()`, this owns no terminal IO — the device-flow fallback\r\n * hands the user code back through `onUserCode`.\r\n */\r\n\r\nimport { KaguraAuthError } from \"../errors.js\";\r\nimport type { OAuthCredentials } from \"./credentials.js\";\r\nimport {\r\n KaguraOAuth,\r\n getSharedState,\r\n loadCredentialsFile,\r\n updateProfile,\r\n} from \"./credentials.js\";\r\nimport { authorizeDevice, pollForToken } from \"./deviceFlow.js\";\r\nimport type { DeviceAuthorizationResponse } from \"./deviceFlow.js\";\r\n\r\nexport interface RefreshOptions {\r\n /** Profile to refresh (default: the file's default profile). */\r\n profile?: string;\r\n /** Credentials file path (default `~/.kagura/credentials.json`). */\r\n credentialsPath?: string;\r\n /**\r\n * Request a different scope.\r\n *\r\n * Narrowing goes through the refresh grant silently. Widening needs\r\n * fresh consent, so a server rejection triggers a full device flow —\r\n * see {@link RefreshOptions.onUserCode}.\r\n */\r\n scope?: string;\r\n /**\r\n * Called with the device-authorization response when a scope widening\r\n * forces re-consent. Required in practice for that path: without it the\r\n * user is never shown the code, and polling times out.\r\n */\r\n onUserCode?: (auth: DeviceAuthorizationResponse) => void | Promise<void>;\r\n /** Injectable fetch (tests / custom agents). */\r\n fetch?: typeof globalThis.fetch;\r\n /** Injectable sleep in milliseconds, used between device-flow polls. */\r\n sleep?: (ms: number) => Promise<void>;\r\n}\r\n\r\n/** Whether an auth failure is the server refusing a wider grant. */\r\nfunction isScopeRejection(error: unknown): boolean {\r\n if (!(error instanceof KaguraAuthError)) {\r\n return false;\r\n }\r\n const message = error.message.toLowerCase();\r\n return message.includes(\"insufficient_scope\") || message.includes(\"invalid_scope\");\r\n}\r\n\r\n/**\r\n * Refresh a stored profile's access token and persist the result.\r\n *\r\n * @returns the credentials that were written.\r\n * @throws Error if the named profile does not exist.\r\n * @throws KaguraAuthExpiredError the refresh token is no longer valid —\r\n * the stored profile is left untouched so it can still be inspected.\r\n * @throws KaguraAuthError other protocol/response failures.\r\n * @throws KaguraConnectionError the server was unreachable.\r\n */\r\nexport async function refresh(options: RefreshOptions = {}): Promise<OAuthCredentials> {\r\n const cf = loadCredentialsFile(options.credentialsPath);\r\n const target = options.profile || cf.defaultProfile;\r\n const stored = cf.profiles[target];\r\n if (stored === undefined) {\r\n throw new Error(`No profile named '${target}'. Run a login first.`);\r\n }\r\n\r\n const httpOptions = options.fetch !== undefined ? { fetch: options.fetch } : {};\r\n\r\n // Delegate to KaguraOAuth rather than driving refreshAccessToken here:\r\n // it holds the cross-process file lock across the whole\r\n // read-check-refresh-persist sequence, so a peer that rotated while we\r\n // waited is adopted instead of racing us into an `invalid_grant` on a\r\n // token that is already stale on disk.\r\n const state = getSharedState(options.credentialsPath, target);\r\n if (state === null) {\r\n throw new Error(`No profile named '${target}'. Run a login first.`);\r\n }\r\n const provider = new KaguraOAuth(state, httpOptions);\r\n\r\n try {\r\n await provider.forceRefresh(options.scope !== undefined ? { scope: options.scope } : {});\r\n return state.credentials;\r\n } catch (e) {\r\n // A rejection only means \"widen\" when the caller actually asked for a\r\n // different scope; otherwise re-consent would be the wrong response\r\n // to what is simply a failed refresh.\r\n if (options.scope === undefined || !isScopeRejection(e)) {\r\n throw e;\r\n }\r\n // Runs outside the lock — forceRefresh released it on the way out, and\r\n // updateProfile below re-acquires it, so there is no deadlock.\r\n const next = await consentToWiderScope(state.credentials, options.scope, options, httpOptions);\r\n await updateProfile(target, next, options.credentialsPath);\r\n state.credentials = next;\r\n return next;\r\n }\r\n}\r\n\r\n/**\r\n * Re-run the device flow to collect consent for a wider grant.\r\n *\r\n * Mirrors the Python CLI's fallback: narrowing succeeds through the\r\n * refresh grant, widening needs the user to approve again. Diverging here\r\n * would make `--scope` widening behave differently between the two SDKs\r\n * on the credentials file they share.\r\n */\r\nasync function consentToWiderScope(\r\n stored: OAuthCredentials,\r\n scope: string,\r\n options: RefreshOptions,\r\n httpOptions: { fetch?: typeof globalThis.fetch },\r\n): Promise<OAuthCredentials> {\r\n // Without a way to show the code, polling would just run until the\r\n // device code expires. Fail now, while the cause is still legible.\r\n if (options.onUserCode === undefined) {\r\n throw new KaguraAuthError(\r\n `Widening the scope to '${scope}' needs fresh consent, which requires ` +\r\n \"showing the user a device code — pass onUserCode to refresh(). \" +\r\n \"Narrowing a scope does not need consent and works without it.\",\r\n );\r\n }\r\n\r\n const authorization = await authorizeDevice(stored.server, {\r\n clientId: stored.clientId,\r\n scope,\r\n ...httpOptions,\r\n });\r\n\r\n await options.onUserCode(authorization);\r\n\r\n const token = await pollForToken(stored.server, {\r\n clientId: stored.clientId,\r\n deviceCode: authorization.deviceCode,\r\n interval: authorization.interval,\r\n expiresAt: authorization.expiresAt,\r\n ...httpOptions,\r\n ...(options.sleep !== undefined ? { sleep: options.sleep } : {}),\r\n });\r\n\r\n // A fresh grant carries its own identity fields; fall back to the\r\n // stored ones only where the response is silent.\r\n return {\r\n ...stored,\r\n accessToken: token.accessToken,\r\n refreshToken: token.refreshToken || stored.refreshToken,\r\n tokenType: token.tokenType,\r\n expiresAt: token.expiresAt,\r\n scope: token.scope || scope,\r\n workspaceId: token.workspaceId || stored.workspaceId,\r\n workspaceName: token.workspaceName || stored.workspaceName,\r\n userEmail: token.userEmail || stored.userEmail,\r\n issuedAt: new Date(),\r\n };\r\n}\r\n","/**\r\n * Best-effort browser launch for the device-flow prompt.\r\n *\r\n * Never throws. The URL and code are always printed first, so failing to\r\n * open a browser is cosmetic — but it must be *reported* as a failure so\r\n * the CLI can say \"use the URL above\" instead of leaving the operator\r\n * waiting for a window that will never appear.\r\n */\r\n\r\nimport { spawn } from \"node:child_process\";\r\n\r\nimport { validateHttpsUrl } from \"../http.js\";\r\n\r\ntype SpawnLike = typeof spawn;\r\n\r\n/** The platform's URL opener and its arguments. */\r\nexport function browserCommand(platform: NodeJS.Platform, url: string): [string, string[]] {\r\n if (platform === \"win32\") {\r\n // Deliberately NOT `cmd /c start \"\" <url>`: spawning cmd hands the\r\n // URL to a shell that reinterprets & | < > ^, which breaks any\r\n // verification_uri_complete carrying a query string and lets a\r\n // hostile OAuth server smuggle a command into the URL it returns.\r\n // explorer.exe receives the URL as a plain argument and opens the\r\n // default browser without any shell in between.\r\n return [\"explorer.exe\", [url]];\r\n }\r\n if (platform === \"darwin\") {\r\n return [\"open\", [url]];\r\n }\r\n return [\"xdg-open\", [url]];\r\n}\r\n\r\n/**\r\n * Whether this URL may be handed to a system opener.\r\n *\r\n * The URL comes from the OAuth server, so it is untrusted input — and\r\n * `--server` / `KAGURA_MCP_URL` decide which server that is. Two gates:\r\n *\r\n * 1. Scheme must be web. Openers dispatch `file:` and script schemes to\r\n * whatever is registered for them.\r\n * 2. The same HTTPS policy the SDK applies to every other endpoint, via\r\n * {@link validateHttpsUrl} rather than a second copy of the rule —\r\n * plain HTTP only for loopback. Auto-opening a downgraded non-loopback\r\n * URL would undercut the guard the rest of the SDK enforces.\r\n */\r\nfunction isOpenableUrl(url: string): boolean {\r\n try {\r\n const protocol = new URL(url).protocol;\r\n if (protocol !== \"https:\" && protocol !== \"http:\") {\r\n return false;\r\n }\r\n validateHttpsUrl(url, \"Verification URL\");\r\n return true;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Launch the platform browser.\r\n *\r\n * @returns whether the process actually started. `spawn` reports a missing\r\n * opener asynchronously through the `error` event, so this waits for\r\n * `spawn`/`error` rather than assuming the call succeeded.\r\n */\r\nexport async function openBrowser(url: string, spawnImpl: SpawnLike = spawn): Promise<boolean> {\r\n if (!isOpenableUrl(url)) {\r\n return false;\r\n }\r\n const [command, args] = browserCommand(process.platform, url);\r\n\r\n return new Promise<boolean>((resolve) => {\r\n let settled = false;\r\n const settle = (ok: boolean): void => {\r\n if (!settled) {\r\n settled = true;\r\n resolve(ok);\r\n }\r\n };\r\n\r\n try {\r\n const child = spawnImpl(command, args, { stdio: \"ignore\", detached: true });\r\n child.once(\"spawn\", () => settle(true));\r\n child.once(\"error\", () => settle(false));\r\n // Don't hold the event loop open waiting for the browser to close.\r\n child.unref();\r\n } catch {\r\n settle(false);\r\n }\r\n });\r\n}\r\n","/**\r\n * Minimal argv parser for the `auth` bin.\r\n *\r\n * Hand-rolled because this package's zero-runtime-dependency invariant is\r\n * deliberate — pulling in commander to read six flags would trade that\r\n * away for very little. Scope is correspondingly small: long flags,\r\n * `-h`, and positionals. No short-flag clustering, no `--`, no negation.\r\n *\r\n * Unknown and value-less flags are *reported* rather than ignored or\r\n * thrown on, so the caller can print one message listing everything wrong\r\n * instead of failing on the first problem.\r\n */\r\n\r\n/** Flags that take a value; everything else is a boolean switch. */\r\nconst VALUE_FLAGS = new Set([\"profile\", \"server\", \"scope\"]);\r\n\r\n/**\r\n * Boolean switches, so a following token is never mistaken for a value.\r\n *\r\n * Only flags a command actually reads belong here: an entry with no\r\n * implementation is accepted and silently ignored, which is worse than\r\n * being reported as unknown.\r\n */\r\nconst SWITCHES = new Set([\"read-only\", \"no-browser\", \"all\", \"yes\", \"help\"]);\r\n\r\nexport interface ParsedArgs {\r\n /** First non-flag token, or `\"\"` when absent. */\r\n command: string;\r\n /** Remaining non-flag tokens. */\r\n positionals: string[];\r\n /** Boolean switches that were present. */\r\n flags: Set<string>;\r\n /** Values for flags in {@link VALUE_FLAGS}. */\r\n values: Record<string, string | undefined>;\r\n /** Flags that match neither set, verbatim (e.g. `--porfile`). */\r\n unknown: string[];\r\n /** Value flags that ran out of argv before their value. */\r\n missingValue: string[];\r\n}\r\n\r\nexport function parseArgs(argv: string[]): ParsedArgs {\r\n const positionals: string[] = [];\r\n const flags = new Set<string>();\r\n const values: Record<string, string | undefined> = {};\r\n const unknown: string[] = [];\r\n const missingValue: string[] = [];\r\n\r\n for (let i = 0; i < argv.length; i++) {\r\n const token = argv[i]!;\r\n\r\n if (token === \"-h\") {\r\n flags.add(\"help\");\r\n continue;\r\n }\r\n if (!token.startsWith(\"--\")) {\r\n // A single-dash token is an attempted short flag, not a value.\r\n // Letting it fall through to positionals means most subcommands\r\n // ignore it and run with defaults — silently, which is the same\r\n // failure mode as a switch that is accepted but never read.\r\n if (token.startsWith(\"-\") && token.length > 1) {\r\n unknown.push(token);\r\n continue;\r\n }\r\n positionals.push(token);\r\n continue;\r\n }\r\n\r\n const eq = token.indexOf(\"=\");\r\n const name = eq === -1 ? token.slice(2) : token.slice(2, eq);\r\n\r\n if (VALUE_FLAGS.has(name)) {\r\n if (eq !== -1) {\r\n // `--profile=` is an explicit empty value, not a missing one.\r\n values[name] = token.slice(eq + 1);\r\n continue;\r\n }\r\n const next = argv[i + 1];\r\n // Any following flag means the value was omitted, not that the flag\r\n // is the value — `--profile --yes` must not set profile=\"--yes\",\r\n // and `--profile -h` is a request for help, not a profile named\r\n // \"-h\". Short flags count: checking only \"--\" swallowed them.\r\n if (next === undefined || next.startsWith(\"-\")) {\r\n missingValue.push(token);\r\n continue;\r\n }\r\n values[name] = next;\r\n i++;\r\n continue;\r\n }\r\n\r\n if (SWITCHES.has(name)) {\r\n flags.add(name);\r\n continue;\r\n }\r\n unknown.push(token);\r\n }\r\n\r\n return {\r\n command: positionals.shift() ?? \"\",\r\n positionals,\r\n flags,\r\n values,\r\n unknown,\r\n missingValue,\r\n };\r\n}\r\n","/**\r\n * `kagura-memory auth …` — the subcommands, with every side effect\r\n * injected so they can be exercised without a terminal or a network.\r\n *\r\n * Deliberately only `auth`. Memory operations stay library-only: the\r\n * credentials file is the artifact both SDKs share, so converging there is\r\n * the point, whereas duplicating the whole Python CLI surface would just\r\n * multiply the parity drift this repo has already spent several PRs\r\n * fixing.\r\n *\r\n * Flag names match `kagura auth …` exactly so documentation and muscle\r\n * memory transfer.\r\n */\r\n\r\nimport {\r\n DEFAULT_SCOPE,\r\n READ_ONLY_SCOPE,\r\n login,\r\n type LoginOptions,\r\n} from \"../auth/login.js\";\r\nimport { refresh, type RefreshOptions } from \"../auth/refresh.js\";\r\nimport {\r\n deleteCredentialsFile,\r\n deleteProfile,\r\n isExpired,\r\n loadCredentialsFile,\r\n setDefaultProfile,\r\n type OAuthCredentials,\r\n} from \"../auth/credentials.js\";\r\nimport type { DeviceAuthorizationResponse } from \"../auth/deviceFlow.js\";\r\nimport { excMessage } from \"../errors.js\";\r\nimport { parseArgs } from \"./parseArgs.js\";\r\n\r\nexport interface CliDeps {\r\n write: (line: string) => void;\r\n writeError: (line: string) => void;\r\n /** Ask a yes/no question; resolves true to proceed. */\r\n confirm: (question: string) => Promise<boolean>;\r\n /** Best-effort browser launch; returns false when it could not open. */\r\n openBrowser: (url: string) => Promise<boolean>;\r\n login: typeof login;\r\n refresh: typeof refresh;\r\n /** Overrides for tests; production passes nothing. */\r\n credentialsPath?: string;\r\n}\r\n\r\nconst USAGE = `kagura-memory auth — manage Kagura Memory credentials\r\n\r\nUsage:\r\n kagura-memory auth login [--profile <name>] [--server <url>]\r\n [--scope \"<scopes>\" | --read-only] [--no-browser]\r\n kagura-memory auth refresh [--profile <name>] [--scope \"<scopes>\"] [--no-browser]\r\n kagura-memory auth status [--profile <name>]\r\n kagura-memory auth use <profile>\r\n kagura-memory auth logout [--profile <name>] [--all] [--yes]\r\n\r\nCredentials live in ~/.kagura/credentials.json and are shared with the\r\nPython CLI, so either tool can create or use a profile.\r\n\r\nScopes:\r\n memory:read read memories, contexts, files\r\n memory:write create/update/delete memories, contexts, files\r\n\r\nDefault scope is \"${DEFAULT_SCOPE}\"; --read-only requests \"${READ_ONLY_SCOPE}\".\r\nNarrowing a scope on refresh is silent; widening needs consent, so it\r\nre-runs the device flow.`;\r\n\r\n/** Print the code and URL, then optionally try to open a browser. */\r\nfunction devicePrompt(deps: CliDeps, openBrowserFlag: boolean) {\r\n return async (auth: DeviceAuthorizationResponse): Promise<void> => {\r\n const url = auth.verificationUriComplete || auth.verificationUri;\r\n // Unconditionally, and before any launch attempt: if the browser opens\r\n // silently or fails, the operator can still copy the code by eye.\r\n deps.write(\"\");\r\n deps.write(` First copy your one-time code: ${auth.userCode}`);\r\n deps.write(\" Then approve at:\");\r\n deps.write(` ${url}`);\r\n deps.write(\"\");\r\n\r\n if (!openBrowserFlag) {\r\n deps.write(\" (--no-browser: not opening a browser; still polling here.)\");\r\n return;\r\n }\r\n if (!(await deps.openBrowser(url))) {\r\n deps.write(\" (Could not open a browser — use the URL above.)\");\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * A human label for the workspace.\r\n *\r\n * `workspace_name` is optional in the token response and parses to `\"\"`\r\n * when absent, so printing it bare yields \"workspace .\" — fall back to the\r\n * id, which the response does carry.\r\n */\r\nfunction workspaceLabel(creds: OAuthCredentials): string {\r\n return creds.workspaceName || creds.workspaceId || \"(unknown)\";\r\n}\r\n\r\nfunction describeProfile(name: string, creds: OAuthCredentials, isDefault: boolean): string[] {\r\n const expired = isExpired(creds);\r\n const refreshable = Boolean(creds.refreshToken);\r\n // A profile whose access token has expired is still usable when it can\r\n // refresh; only one that cannot is genuinely dead.\r\n const state = !expired ? \"active\" : refreshable ? \"expired (refreshable)\" : \"expired\";\r\n return [\r\n `${isDefault ? \"*\" : \" \"} ${name}`,\r\n ` account: ${creds.userEmail || \"(unknown)\"}`,\r\n ` workspace: ${workspaceLabel(creds)}`,\r\n ` server: ${creds.server}`,\r\n ` scope: ${creds.scope || \"(unknown)\"}`,\r\n ` expires: ${creds.expiresAt.toISOString()}`,\r\n ` state: ${state}`,\r\n ` refreshable: ${refreshable}`,\r\n ];\r\n}\r\n\r\nasync function cmdLogin(deps: CliDeps, args: ReturnType<typeof parseArgs>): Promise<number> {\r\n const readOnly = args.flags.has(\"read-only\");\r\n const scope = args.values.scope;\r\n if (readOnly && scope !== undefined) {\r\n deps.writeError(\"--read-only and --scope are mutually exclusive; pick one.\");\r\n return 2;\r\n }\r\n\r\n const options: LoginOptions = {\r\n onUserCode: devicePrompt(deps, !args.flags.has(\"no-browser\")),\r\n };\r\n if (args.values.profile !== undefined) options.profile = args.values.profile;\r\n if (args.values.server !== undefined) options.mcpUrl = args.values.server;\r\n if (readOnly) options.scope = READ_ONLY_SCOPE;\r\n else if (scope !== undefined) options.scope = scope;\r\n if (deps.credentialsPath !== undefined) options.credentialsPath = deps.credentialsPath;\r\n\r\n const creds = await deps.login(options);\r\n deps.write(\r\n `Logged in as ${creds.userEmail || \"(unknown)\"} — workspace ${workspaceLabel(creds)}.`,\r\n );\r\n deps.write(`Profile '${args.values.profile ?? \"default\"}' saved. Scope: ${creds.scope}`);\r\n return 0;\r\n}\r\n\r\nasync function cmdRefresh(deps: CliDeps, args: ReturnType<typeof parseArgs>): Promise<number> {\r\n const options: RefreshOptions = {\r\n onUserCode: devicePrompt(deps, !args.flags.has(\"no-browser\")),\r\n };\r\n if (args.values.profile !== undefined) options.profile = args.values.profile;\r\n if (args.values.scope !== undefined) options.scope = args.values.scope;\r\n if (deps.credentialsPath !== undefined) options.credentialsPath = deps.credentialsPath;\r\n\r\n const creds = await deps.refresh(options);\r\n deps.write(`Refreshed. Expires ${creds.expiresAt.toISOString()}. Scope: ${creds.scope}`);\r\n return 0;\r\n}\r\n\r\nfunction cmdStatus(deps: CliDeps, args: ReturnType<typeof parseArgs>): number {\r\n const cf = loadCredentialsFile(deps.credentialsPath);\r\n const names = Object.keys(cf.profiles);\r\n if (names.length === 0) {\r\n deps.write(\"No profiles. Run: kagura-memory auth login\");\r\n return 0;\r\n }\r\n\r\n const only = args.values.profile;\r\n if (only !== undefined) {\r\n const creds = cf.profiles[only];\r\n if (creds === undefined) {\r\n deps.writeError(`No profile named '${only}'.`);\r\n return 1;\r\n }\r\n for (const line of describeProfile(only, creds, cf.defaultProfile === only)) {\r\n deps.write(line);\r\n }\r\n return 0;\r\n }\r\n\r\n for (const name of names) {\r\n for (const line of describeProfile(name, cf.profiles[name]!, cf.defaultProfile === name)) {\r\n deps.write(line);\r\n }\r\n }\r\n return 0;\r\n}\r\n\r\nasync function cmdUse(deps: CliDeps, args: ReturnType<typeof parseArgs>): Promise<number> {\r\n const name = args.positionals[0];\r\n if (name === undefined) {\r\n deps.writeError(\"Usage: kagura-memory auth use <profile>\");\r\n return 2;\r\n }\r\n // setDefaultProfile rejects an unknown name under the lock, so a typo\r\n // cannot leave the file pointing at a profile that does not exist.\r\n await setDefaultProfile(name, deps.credentialsPath);\r\n deps.write(`Default profile is now '${name}'.`);\r\n return 0;\r\n}\r\n\r\nasync function cmdLogout(deps: CliDeps, args: ReturnType<typeof parseArgs>): Promise<number> {\r\n const all = args.flags.has(\"all\");\r\n const target = args.values.profile;\r\n if (all && target !== undefined) {\r\n deps.writeError(\"--all and --profile are mutually exclusive; pick one.\");\r\n return 2;\r\n }\r\n\r\n const cf = loadCredentialsFile(deps.credentialsPath);\r\n\r\n // emptyCredentialsFile() names a default profile even when none are\r\n // stored, so an untargeted logout would otherwise report \"No profile\r\n // named 'default'\" and exit 1 on a fresh machine — breaking\r\n // `logout --yes` in idempotent setup scripts. Nothing to remove is the\r\n // desired end state, not a failure. An explicitly named profile is\r\n // still a real mismatch and reported below.\r\n if (!all && target === undefined && Object.keys(cf.profiles).length === 0) {\r\n deps.write(\"No profiles stored; nothing to do.\");\r\n return 0;\r\n }\r\n\r\n const name = target ?? cf.defaultProfile;\r\n const question = all\r\n ? \"Remove ALL stored profiles?\"\r\n : `Remove profile '${name}'?`;\r\n if (!args.flags.has(\"yes\") && !(await deps.confirm(question))) {\r\n deps.write(\"Cancelled.\");\r\n return 1;\r\n }\r\n\r\n if (all) {\r\n deleteCredentialsFile(deps.credentialsPath);\r\n deps.write(\"All profiles removed.\");\r\n return 0;\r\n }\r\n // deleteProfile is a no-op on an absent profile; say so rather than\r\n // reporting a removal that did not happen.\r\n const existed = cf.profiles[name] !== undefined;\r\n await deleteProfile(name, deps.credentialsPath);\r\n deps.write(existed ? `Profile '${name}' removed.` : `No profile named '${name}'.`);\r\n return existed ? 0 : 1;\r\n}\r\n\r\n/**\r\n * Run one CLI invocation.\r\n *\r\n * @returns the process exit code. Never throws for expected failures —\r\n * auth errors are reported on stderr with their guidance intact.\r\n */\r\nexport async function runCli(argv: string[], deps: CliDeps): Promise<number> {\r\n const args = parseArgs(argv);\r\n\r\n // An empty value is almost always a typo (`--profile=`), and it is not\r\n // harmless: \"\" is a usable profile name, so it would create a nameless\r\n // profile, and an empty scope would be sent to the server verbatim.\r\n const empty = Object.entries(args.values)\r\n .filter(([, value]) => value !== undefined && value.trim() === \"\")\r\n .map(([name]) => `--${name}`);\r\n\r\n if (args.unknown.length > 0 || args.missingValue.length > 0 || empty.length > 0) {\r\n for (const flag of args.unknown) {\r\n deps.writeError(`Unknown option: ${flag}`);\r\n }\r\n for (const flag of args.missingValue) {\r\n deps.writeError(`Option ${flag} needs a value.`);\r\n }\r\n for (const flag of empty) {\r\n deps.writeError(`Option ${flag} needs a non-empty value.`);\r\n }\r\n deps.writeError(USAGE);\r\n return 2;\r\n }\r\n\r\n if (args.flags.has(\"help\") || args.command === \"\" || args.command === \"help\") {\r\n deps.write(USAGE);\r\n return args.command === \"\" && !args.flags.has(\"help\") ? 2 : 0;\r\n }\r\n\r\n // The bin exists only for auth, but accept the `auth` prefix so the\r\n // command reads the same as its Python counterpart.\r\n let args2 = args;\r\n if (args.command === \"auth\") {\r\n const next = args.positionals[0];\r\n args2 = { ...args, command: next ?? \"\", positionals: args.positionals.slice(1) };\r\n if (args2.command === \"\") {\r\n deps.write(USAGE);\r\n return 2;\r\n }\r\n }\r\n\r\n try {\r\n switch (args2.command) {\r\n case \"login\":\r\n return await cmdLogin(deps, args2);\r\n case \"refresh\":\r\n return await cmdRefresh(deps, args2);\r\n case \"status\":\r\n return cmdStatus(deps, args2);\r\n case \"use\":\r\n return await cmdUse(deps, args2);\r\n case \"logout\":\r\n return await cmdLogout(deps, args2);\r\n default:\r\n deps.writeError(`Unknown command: ${args2.command}`);\r\n deps.writeError(USAGE);\r\n return 2;\r\n }\r\n } catch (e) {\r\n // Kagura auth errors carry their own next-step guidance (\"Run: kagura\r\n // auth login\", …); surface the message rather than a stack trace.\r\n deps.writeError(excMessage(e));\r\n return 1;\r\n }\r\n}\r\n"],"mappings":";;;AAQA,YAAY,cAAc;;;ACSnB,SAAS,WAAW,GAAoB;AAC7C,MAAI,aAAa,OAAO;AACtB,WAAO,EAAE,WAAW,EAAE,YAAY;AAAA,EACpC;AACA,QAAM,IAAI,OAAO,CAAC;AAClB,SAAO,MAAM,OAAO,MAAM,YAAY,MAAM,OAAO,EAAE,YAAY,OAAO;AAC1E;AAGO,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAY,SAAiB,SAA8B;AACzD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO,WAAW;AAAA,EACzB;AACF;AAGO,IAAM,kBAAN,cAA8B,YAAY;AAAC;AAS3C,IAAM,yBAAN,cAAqC,gBAAgB;AAAA,EACjD;AAAA,EAET,YAAY,SAAiB,YAAyB,MAAM,SAA8B;AACxF,UAAM,SAAS,OAAO;AACtB,SAAK,YAAY;AAAA,EACnB;AACF;AAGO,IAAM,wBAAN,cAAoC,gBAAgB;AAAC;AAGrD,IAAM,wBAAN,cAAoC,YAAY;AAAC;;;ACpDjD,IAAM,cAAc;;;ACWpB,SAAS,eAAe,QAAwB;AACrD,QAAM,IAAI,gBAAgB,KAAK,MAAM;AACrC,SAAO,IAAI,OAAO,MAAM,GAAG,EAAE,KAAK,IAAI;AACxC;AAEA,SAAS,uBAAuB,QAA2B;AAEzD,QAAM,QAAkB,CAAC;AACzB,aAAW,SAAS,QAAQ;AAC1B,QAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG;AACvE;AAAA,IACF;AACA,UAAM,MAAM;AACZ,UAAM,MAAM,IAAI;AAChB,QAAI,OAAO,QAAQ,YAAY,CAAC,KAAK;AACnC;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