kagura-memory 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js.map CHANGED
@@ -1 +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). */\r\n\r\n/**\r\n * Subset of the standard DOM/Node `ErrorOptions`. Declared locally so the\r\n * published `.d.ts` does not force consumers onto an ES2022 `lib` just to\r\n * reference our error constructors.\r\n */\r\nexport interface KaguraErrorOptions {\r\n cause?: unknown;\r\n}\r\n\r\n/**\r\n * Return `String(e)` when non-empty, otherwise the constructor name.\r\n *\r\n * Defensive fallback so an unmessaged error still produces a non-empty\r\n * diagnostic when interpolated into a user-facing error string.\r\n */\r\nexport function excMessage(e: unknown): string {\r\n if (e instanceof Error) {\r\n return e.message || e.constructor.name;\r\n }\r\n const s = String(e);\r\n return s || (typeof e === \"object\" && e !== null ? e.constructor.name : \"unknown error\");\r\n}\r\n\r\n/** Base error for the Kagura SDK. */\r\nexport class KaguraError extends Error {\r\n constructor(message: string, options?: KaguraErrorOptions) {\r\n super(message, options);\r\n this.name = new.target.name;\r\n }\r\n}\r\n\r\n/** Authentication failed. */\r\nexport class KaguraAuthError extends KaguraError {}\r\n\r\n/**\r\n * OAuth refresh token expired or invalid.\r\n *\r\n * Raised when an attempted refresh returns `invalid_grant` (or the server\r\n * otherwise indicates that the stored refresh token can no longer be used).\r\n * The caller must re-authenticate via `kagura auth login`.\r\n */\r\nexport class KaguraAuthExpiredError extends KaguraAuthError {\r\n readonly expiresAt: Date | null;\r\n\r\n constructor(message: string, expiresAt: Date | null = null, options?: KaguraErrorOptions) {\r\n super(message, options);\r\n this.expiresAt = expiresAt;\r\n }\r\n}\r\n\r\n/** User denied authorization at the device-flow consent screen. */\r\nexport class KaguraAuthDeniedError extends KaguraAuthError {}\r\n\r\n/** Connection to Kagura server failed. */\r\nexport class KaguraConnectionError extends KaguraError {}\r\n\r\n/** Requested resource not found (HTTP 404). */\r\nexport class KaguraNotFoundError extends KaguraError {}\r\n\r\n/** Rate limit exceeded. */\r\nexport class KaguraRateLimitError extends KaguraError {\r\n readonly retryAfter: number | null;\r\n\r\n constructor(message: string, retryAfter: number | null = null, options?: KaguraErrorOptions) {\r\n super(message, options);\r\n this.retryAfter = retryAfter;\r\n }\r\n}\r\n\r\n/** LLM call failed. */\r\nexport class KaguraLLMError extends KaguraError {}\r\n\r\n/** Context not found or invalid. */\r\nexport class KaguraContextError extends KaguraError {}\r\n\r\n/** Resource token quota exceeded (events per hour). */\r\nexport class KaguraQuotaError extends KaguraError {\r\n readonly retryAfter: number | null;\r\n\r\n constructor(message: string, retryAfter: number | null = null, options?: KaguraErrorOptions) {\r\n super(message, options);\r\n this.retryAfter = retryAfter;\r\n }\r\n}\r\n\r\n/**\r\n * Object store rejected an upload with HTTP 400.\r\n *\r\n * Raised for any HTTP 400 response from the object store on a presigned\r\n * PUT — most commonly R2 `BadDigest` (the body's sha256 did not match the\r\n * value bound into the presigned PUT URL), but also covers other 400\r\n * causes such as a malformed presigned URL or a Content-Length mismatch.\r\n */\r\nexport class KaguraIntegrityError extends KaguraError {}\r\n\r\n/**\r\n * URL or file fetch failed (SSRF guard, byte cap, redirect loop, etc.).\r\n *\r\n * The original URL/path is exposed via the `url` property so callers can\r\n * present it without re-parsing the message.\r\n */\r\nexport class KaguraFetchError extends KaguraError {\r\n readonly url: string | null;\r\n\r\n constructor(message: string, url: string | null = null, options?: KaguraErrorOptions) {\r\n super(message, options);\r\n this.url = url;\r\n }\r\n}\r\n\r\n/** File ingestion orchestration failed for a non-fetch reason. */\r\nexport class KaguraIngestError extends KaguraError {}\r\n\r\n/**\r\n * Secret-store operation failed for a non-HTTP reason (#28).\r\n *\r\n * The base of the secret hierarchy: a client-side contract violation, such\r\n * as putting a secret with no recipients or with a recipient whose\r\n * advertised fingerprint does not match its pubkey.\r\n */\r\nexport class KaguraSecretError extends KaguraError {}\r\n\r\n/**\r\n * age encryption/decryption failed, or its input was malformed.\r\n *\r\n * Also raised when the optional `age-encryption` peer dependency is not\r\n * installed — the message names the install command, since the base SDK\r\n * deliberately ships with no runtime dependencies.\r\n */\r\nexport class KaguraCryptoError extends KaguraSecretError {}\r\n\r\n/**\r\n * The age private key could not be stored or retrieved.\r\n *\r\n * Custody is fail-closed: refusing to hold the key is an error, never a\r\n * silent fallback to a less secure location.\r\n */\r\nexport class KaguraKeyCustodyError extends KaguraSecretError {}\r\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.7.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","/**\r\n * OAuth2 RFC 8628 device authorization grant — stateless async helpers\r\n * (port of auth/device_flow.py).\r\n *\r\n * Pure-function API: every entry point takes the server base URL plus the\r\n * relevant parameters and returns a plain object. No CLI, no terminal IO,\r\n * no global state.\r\n *\r\n * The Python SDK constructs a dedicated unauthenticated `httpx.AsyncClient`\r\n * so the SDK's `Authorization: Bearer` header cannot leak into `/oauth/*`\r\n * requests (device-flow uses `client_id` body-parameter authentication, RFC\r\n * 8628 §3.1 `token_endpoint_auth_method='none'`). With `fetch` there is no\r\n * client object; the same isolation holds because each request here sets\r\n * its own headers and never an `Authorization` header. The `fetch`\r\n * implementation is injectable on every function so tests can stub HTTP.\r\n */\r\n\r\nimport { setTimeout as sleepMs } from \"node:timers/promises\";\r\n\r\nimport {\r\n KaguraAuthDeniedError,\r\n KaguraAuthError,\r\n KaguraAuthExpiredError,\r\n KaguraConnectionError,\r\n excMessage,\r\n} from \"../errors.js\";\r\nimport { extractDetail } from \"../http.js\";\r\nimport { SDK_VERSION } from \"../version.js\";\r\n\r\n// OAuth2 endpoint paths under {server}.\r\n// The path prefix is /api/v1/oauth/ (NOT /oauth2/) per memory-cloud's\r\n// actual mount point; the token endpoint requires the trailing slash.\r\nconst PATH_DEVICE_AUTHORIZE = \"/api/v1/oauth/device/authorize\";\r\nconst PATH_TOKEN = \"/api/v1/oauth/token/\";\r\nconst PATH_REVOKE = \"/api/v1/oauth/revoke\";\r\n\r\n// RFC 8628 §3.5 — \"slow_down\" requires the client to add 5 seconds.\r\nconst SLOW_DOWN_INCREMENT_SEC = 5;\r\n\r\n/** The pre-registered public client ID seeded by memory-cloud #624. */\r\nexport const DEFAULT_CLIENT_ID = \"kagura-cli\";\r\n\r\nexport const DEVICE_FLOW_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:device_code\";\r\nexport const REFRESH_TOKEN_GRANT_TYPE = \"refresh_token\";\r\n\r\n/** RFC 8628 §3.2 device authorization response. */\r\nexport interface DeviceAuthorizationResponse {\r\n deviceCode: string;\r\n userCode: string;\r\n verificationUri: string;\r\n verificationUriComplete: string;\r\n expiresIn: number;\r\n /** Polling interval in seconds. */\r\n interval: number;\r\n /** = now + expiresIn. */\r\n expiresAt: Date;\r\n}\r\n\r\n/**\r\n * RFC 8628 §3.5 / RFC 6749 §5.1 successful token response.\r\n *\r\n * `expiresAt` is computed once at receipt time so a paused or suspended\r\n * laptop never sees a negative TTL after wake.\r\n */\r\nexport interface TokenResponse {\r\n accessToken: string;\r\n refreshToken: string;\r\n tokenType: string;\r\n expiresAt: Date;\r\n scope: string;\r\n userEmail: string;\r\n workspaceId: string;\r\n workspaceName: string;\r\n}\r\n\r\n/** Common HTTP knobs: injectable `fetch` so tests can stub the transport. */\r\nexport interface OAuthHttpOptions {\r\n fetch?: typeof globalThis.fetch;\r\n}\r\n\r\nfunction userAgent(): string {\r\n return `kagura-memory-sdk/${SDK_VERSION}`;\r\n}\r\n\r\nfunction tokenUrl(server: string): string {\r\n return `${server.replace(/\\/+$/, \"\")}${PATH_TOKEN}`;\r\n}\r\n\r\n/** Coerce an unknown JSON value to a whole number, or `null`. */\r\nfunction toInt(value: unknown): number | null {\r\n if (typeof value === \"number\" && Number.isFinite(value)) {\r\n return Math.trunc(value);\r\n }\r\n if (typeof value === \"string\" && value.trim() !== \"\") {\r\n const n = Number(value);\r\n return Number.isFinite(n) ? Math.trunc(n) : null;\r\n }\r\n return null;\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/**\r\n * Parse a 200 response body as a JSON object.\r\n *\r\n * Converts malformed / non-object success bodies into a `KaguraAuthError`\r\n * with HTTP status + truncated body, so a server that wedges and returns\r\n * HTML / a JSON array / a scalar doesn't surface as an unhelpful\r\n * `SyntaxError`.\r\n */\r\nfunction safeJsonObject(\r\n bodyText: string,\r\n status: number,\r\n endpoint: string,\r\n): Record<string, unknown> {\r\n let body: unknown;\r\n try {\r\n body = JSON.parse(bodyText);\r\n } catch (e) {\r\n const detail = bodyText.slice(0, 200);\r\n throw new KaguraAuthError(\r\n `${endpoint} returned HTTP ${status} but body is not JSON: ${excMessage(e)}. ` +\r\n `Body: ${detail}`,\r\n { cause: e },\r\n );\r\n }\r\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\r\n throw new KaguraAuthError(\r\n `${endpoint} returned HTTP ${status} but body is not a JSON object ` +\r\n `(got ${Array.isArray(body) ? \"array\" : typeof body})`,\r\n );\r\n }\r\n return body as Record<string, unknown>;\r\n}\r\n\r\n/** Parse a response body as a JSON object, or `{}` if unparseable. */\r\nfunction safeJson(bodyText: string): Record<string, unknown> {\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 return body as Record<string, unknown>;\r\n}\r\n\r\n/**\r\n * Build a `TokenResponse` from a 200 `/oauth/token/` body.\r\n *\r\n * `expiresAt` is computed from `expires_in` at receipt time so laptop sleep\r\n * / clock skew won't yield a negative TTL after wake. Missing or invalid\r\n * required fields surface as `KaguraAuthError`.\r\n */\r\nfunction tokenResponseFromBody(bodyText: string, status: number): TokenResponse {\r\n const body = safeJsonObject(bodyText, status, \"Token endpoint\");\r\n const accessToken = body.access_token;\r\n const expiresIn = toInt(body.expires_in ?? 0);\r\n if (typeof accessToken !== \"string\" || expiresIn === null) {\r\n throw new KaguraAuthError(\r\n `Token endpoint returned HTTP ${status} but body is missing required fields. ` +\r\n `Body keys: ${Object.keys(body).sort().join(\", \")}`,\r\n );\r\n }\r\n return {\r\n accessToken,\r\n refreshToken: stringOr(body.refresh_token, \"\"),\r\n tokenType: stringOr(body.token_type, \"Bearer\"),\r\n expiresAt: new Date(Date.now() + expiresIn * 1000),\r\n scope: stringOr(body.scope, \"\"),\r\n userEmail: stringOr(body.user_email, \"\"),\r\n workspaceId: stringOr(body.workspace_id, \"\"),\r\n workspaceName: stringOr(body.workspace_name, \"\"),\r\n };\r\n}\r\n\r\n/**\r\n * POST `{server}/api/v1/oauth/device/authorize` and parse the response.\r\n *\r\n * memory-cloud's device/authorize accepts JSON, unlike the /oauth/token/ +\r\n * /oauth/revoke endpoints which take application/x-www-form-urlencoded.\r\n */\r\nexport async function authorizeDevice(\r\n server: string,\r\n options: OAuthHttpOptions & { clientId?: string; scope?: string } = {},\r\n): Promise<DeviceAuthorizationResponse> {\r\n const clientId = options.clientId ?? DEFAULT_CLIENT_ID;\r\n const scope = options.scope ?? \"memory:read\";\r\n const doFetch = options.fetch ?? globalThis.fetch;\r\n const url = `${server.replace(/\\/+$/, \"\")}${PATH_DEVICE_AUTHORIZE}`;\r\n\r\n let response: Response;\r\n let text: string;\r\n try {\r\n response = await doFetch(url, {\r\n method: \"POST\",\r\n headers: {\r\n \"User-Agent\": userAgent(),\r\n \"Content-Type\": \"application/json\",\r\n },\r\n body: JSON.stringify({ client_id: clientId, scope }),\r\n });\r\n text = await response.text();\r\n } catch (e) {\r\n throw new KaguraConnectionError(`Could not reach ${url}: ${excMessage(e)}`, { cause: e });\r\n }\r\n\r\n if (!response.ok) {\r\n const detail = extractDetail(text) || text;\r\n throw new KaguraAuthError(\r\n `Device authorization failed (HTTP ${response.status}): ${detail}\\n` +\r\n ` Verify the server URL and that '${clientId}' is registered.`,\r\n );\r\n }\r\n\r\n const body = safeJsonObject(text, response.status, \"Device authorization\");\r\n const deviceCode = body.device_code;\r\n const userCode = body.user_code;\r\n const verificationUri = body.verification_uri;\r\n const expiresIn = toInt(body.expires_in);\r\n if (\r\n typeof deviceCode !== \"string\" ||\r\n typeof userCode !== \"string\" ||\r\n typeof verificationUri !== \"string\" ||\r\n expiresIn === null\r\n ) {\r\n throw new KaguraAuthError(\r\n \"Device authorization returned HTTP 200 but body is missing required fields. \" +\r\n `Body keys: ${Object.keys(body).sort().join(\", \")}`,\r\n );\r\n }\r\n return {\r\n deviceCode,\r\n userCode,\r\n verificationUri,\r\n verificationUriComplete: stringOr(body.verification_uri_complete, verificationUri),\r\n expiresIn,\r\n interval: toInt(body.interval) ?? 5,\r\n expiresAt: new Date(Date.now() + expiresIn * 1000),\r\n };\r\n}\r\n\r\nexport interface PollForTokenOptions extends OAuthHttpOptions {\r\n clientId: string;\r\n deviceCode: string;\r\n /** RFC 8628 polling interval in seconds. */\r\n interval: number;\r\n expiresAt: Date;\r\n /**\r\n * Injectable sleep (milliseconds) so tests can supply a no-op or\r\n * counter-based stub without waiting real seconds.\r\n */\r\n sleep?: (ms: number) => Promise<void>;\r\n}\r\n\r\n/**\r\n * Poll `{server}/api/v1/oauth/token/` until the user approves or denies.\r\n *\r\n * The first poll fires immediately (no initial sleep) so a fast approval\r\n * never waits a whole interval; sleeps only happen between retries after\r\n * `authorization_pending` / `slow_down`.\r\n *\r\n * @throws KaguraAuthDeniedError user clicked \"Deny\" at the consent screen\r\n * (server returns `access_denied`).\r\n * @throws KaguraAuthExpiredError the `device_code` lifetime elapsed without\r\n * approval (server returns `expired_token`, or `expiresAt` passed locally).\r\n * @throws KaguraAuthError any other OAuth error or unexpected response.\r\n * @throws KaguraConnectionError network failure during polling.\r\n */\r\nexport async function pollForToken(\r\n server: string,\r\n options: PollForTokenOptions,\r\n): Promise<TokenResponse> {\r\n const doFetch = options.fetch ?? globalThis.fetch;\r\n const sleep = options.sleep ?? (async (ms: number): Promise<void> => void (await sleepMs(ms)));\r\n const url = tokenUrl(server);\r\n\r\n let currentInterval = options.interval;\r\n let firstPoll = true;\r\n\r\n for (;;) {\r\n if (Date.now() >= options.expiresAt.getTime()) {\r\n throw new KaguraAuthExpiredError(\r\n \"Device code expired before user approval. Run: kagura auth login\",\r\n options.expiresAt,\r\n );\r\n }\r\n\r\n // Skip the initial sleep so an immediate approval (or a fast\r\n // server-side error) doesn't wait one whole interval.\r\n if (firstPoll) {\r\n firstPoll = false;\r\n } else {\r\n await sleep(currentInterval * 1000);\r\n }\r\n\r\n let response: Response;\r\n let text: string;\r\n try {\r\n response = await doFetch(url, {\r\n method: \"POST\",\r\n headers: { \"User-Agent\": userAgent() },\r\n body: new URLSearchParams({\r\n grant_type: DEVICE_FLOW_GRANT_TYPE,\r\n device_code: options.deviceCode,\r\n client_id: options.clientId,\r\n }),\r\n });\r\n text = await response.text();\r\n } catch (e) {\r\n throw new KaguraConnectionError(\r\n `Lost connection while waiting for approval: ${excMessage(e)}\\n` +\r\n ` The login session may still be valid; re-run: kagura auth login`,\r\n { cause: e },\r\n );\r\n }\r\n\r\n if (response.status === 200) {\r\n return tokenResponseFromBody(text, response.status);\r\n }\r\n\r\n // RFC 8628 §3.5 — errors come as HTTP 4xx with JSON `error` field.\r\n const body = safeJson(text);\r\n const error = stringOr(body.error, \"\");\r\n\r\n if (error === \"authorization_pending\") {\r\n continue;\r\n }\r\n if (error === \"slow_down\") {\r\n currentInterval += SLOW_DOWN_INCREMENT_SEC;\r\n continue;\r\n }\r\n if (error === \"access_denied\") {\r\n throw new KaguraAuthDeniedError(\r\n \"Authorization denied at the consent screen.\\n\" +\r\n \" Re-run: kagura auth login\\n\" +\r\n \" To use a different workspace, log in with that account \" +\r\n \"in your browser first.\",\r\n );\r\n }\r\n if (error === \"expired_token\") {\r\n throw new KaguraAuthExpiredError(\r\n \"Device code expired before user approval. Run: kagura auth login\",\r\n options.expiresAt,\r\n );\r\n }\r\n\r\n // Unknown error — surface the HTTP status + raw response so the\r\n // operator can debug non-OAuth failures (HTML 5xx, proxy errors,\r\n // non-JSON bodies that make `error` come back empty).\r\n const description = stringOr(body.error_description, \"\");\r\n if (error || description) {\r\n throw new KaguraAuthError(\r\n `Token endpoint returned unexpected error '${error}': ${description}`,\r\n );\r\n }\r\n const detail = extractDetail(text) || text.slice(0, 200);\r\n throw new KaguraAuthError(\r\n `Token endpoint returned HTTP ${response.status} with no OAuth error code. ` +\r\n `Body: ${detail}`,\r\n );\r\n }\r\n}\r\n\r\nexport interface RefreshAccessTokenOptions extends OAuthHttpOptions {\r\n clientId: string;\r\n refreshToken: string;\r\n scope?: string | null;\r\n}\r\n\r\n/**\r\n * POST `{server}/api/v1/oauth/token/` with `grant_type=refresh_token`.\r\n *\r\n * When `scope` is supplied, the server may reject the call with\r\n * `insufficient_scope` / `invalid_scope` if the grant doesn't cover it.\r\n *\r\n * @throws KaguraAuthExpiredError refresh token is invalid or expired\r\n * (server returns `invalid_grant`).\r\n * @throws KaguraAuthError any other OAuth error.\r\n * @throws KaguraConnectionError network failure.\r\n */\r\nexport async function refreshAccessToken(\r\n server: string,\r\n options: RefreshAccessTokenOptions,\r\n): Promise<TokenResponse> {\r\n const doFetch = options.fetch ?? globalThis.fetch;\r\n const url = tokenUrl(server);\r\n const form = new URLSearchParams({\r\n grant_type: REFRESH_TOKEN_GRANT_TYPE,\r\n refresh_token: options.refreshToken,\r\n client_id: options.clientId,\r\n });\r\n if (options.scope !== undefined && options.scope !== null) {\r\n form.set(\"scope\", options.scope);\r\n }\r\n\r\n let response: Response;\r\n let text: string;\r\n try {\r\n response = await doFetch(url, {\r\n method: \"POST\",\r\n headers: { \"User-Agent\": userAgent() },\r\n body: form,\r\n });\r\n text = await response.text();\r\n } catch (e) {\r\n throw new KaguraConnectionError(`Could not reach ${url}: ${excMessage(e)}`, { cause: e });\r\n }\r\n\r\n if (response.status === 200) {\r\n return tokenResponseFromBody(text, response.status);\r\n }\r\n\r\n const body = safeJson(text);\r\n const error = stringOr(body.error, \"\");\r\n\r\n if (error === \"invalid_grant\") {\r\n throw new KaguraAuthExpiredError(\r\n \"Your login expired (refresh token is no longer valid).\\n\" +\r\n \" Run: kagura auth login\\n\" +\r\n \" Your server and workspace selection are preserved.\",\r\n );\r\n }\r\n\r\n const description = stringOr(body.error_description, \"\");\r\n if (error) {\r\n throw new KaguraAuthError(\r\n `Refresh failed: ${error}${description ? ` — ${description}` : \"\"}`,\r\n );\r\n }\r\n // Non-OAuth failure (HTML 5xx, network proxy returning text/plain, etc.).\r\n const detail = extractDetail(text) || text.slice(0, 200);\r\n throw new KaguraAuthError(\r\n `Refresh failed: HTTP ${response.status} with no OAuth error code. Body: ${detail}`,\r\n );\r\n}\r\n\r\n/**\r\n * POST `{server}/api/v1/oauth/revoke`. Best-effort — never throws.\r\n *\r\n * Returns `true` on success, `false` on any failure. The caller\r\n * (`kagura auth logout`) deletes the local profile regardless of the\r\n * return value, on the principle that local logout must succeed even when\r\n * the server is unreachable.\r\n */\r\nexport async function revokeToken(\r\n server: string,\r\n options: OAuthHttpOptions & { token: string; clientId?: string },\r\n): Promise<boolean> {\r\n const doFetch = options.fetch ?? globalThis.fetch;\r\n const url = `${server.replace(/\\/+$/, \"\")}${PATH_REVOKE}`;\r\n try {\r\n const response = await doFetch(url, {\r\n method: \"POST\",\r\n headers: { \"User-Agent\": userAgent() },\r\n body: new URLSearchParams({\r\n token: options.token,\r\n client_id: options.clientId ?? DEFAULT_CLIENT_ID,\r\n }),\r\n });\r\n return response.status === 200 || response.status === 204;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n","/**\r\n * Cross-process file locking for `~/.kagura/credentials.json` (port of\r\n * _filelock.py).\r\n *\r\n * The in-process mutex in `auth/credentials` serializes credential refreshes\r\n * *within* a single process. When several processes own the same credentials\r\n * file at once — e.g. multiple `kagura-mcp` proxy children plus a stray\r\n * client — they need a *cross-process* gate so a concurrent\r\n * read-modify-write cannot lose an update.\r\n *\r\n * DEVIATION FROM PYTHON: the Python SDK uses OS advisory locks\r\n * (`fcntl.flock` on POSIX, `msvcrt.locking` on Windows), which Node's\r\n * builtins do not expose. This port instead uses an `O_EXCL` lockfile-create\r\n * loop: the lock is *held* while the sibling `<name>.lock` file exists, and\r\n * acquiring means winning the exclusive create. Consequences:\r\n *\r\n * - There is no shared/exclusive distinction — every lock is exclusive\r\n * (matching the Python Windows `msvcrt` backend, which has no shared mode).\r\n * - A kernel lock dies with its owner; a lockfile does not. A crashed holder\r\n * is therefore handled by *stale detection*: a lock file whose mtime is\r\n * older than `staleMs` is presumed abandoned and broken (deleted), and the\r\n * acquire loop retries. The stale threshold is sized above the OAuth\r\n * refresh round-trip (the only operation that holds the lock across a\r\n * network call), so it never trips on a live holder.\r\n * - The lockfile protocol is compatible with the Python CLI in the sense\r\n * that both lock a sibling of the credentials file, never the file itself,\r\n * so neither interferes with the other's atomic rename. (The Python CLI's\r\n * kernel lock does not observe our lockfile and vice versa; the atomic\r\n * rename in `credentials.ts` still guarantees the file is never torn, the\r\n * lock only adds serialization — same as the Python no-op fallback.)\r\n *\r\n * A contended acquire is bounded by `timeoutMs` (like the Python msvcrt\r\n * backend's 90 s ceiling) so a stuck peer cannot wedge a waiter forever.\r\n */\r\n\r\nimport * as fs from \"node:fs\";\r\nimport * as path from \"node:path\";\r\nimport { setTimeout as sleep } from \"node:timers/promises\";\r\n\r\n/** Poll interval while waiting for a contended lock (Python: 0.05 s). */\r\nexport const DEFAULT_LOCK_RETRY_MS = 50;\r\n\r\n/**\r\n * Safety ceiling on a *contended* acquire (Python: 90 s). Sized well above\r\n * the OAuth refresh round-trip so it only bounds the pathological case.\r\n */\r\nexport const DEFAULT_LOCK_TIMEOUT_MS = 90_000;\r\n\r\n/**\r\n * Age after which a held lock file is presumed abandoned (crashed holder)\r\n * and broken. Must exceed the longest legitimate hold (an OAuth refresh\r\n * round-trip, bounded by its ~30 s HTTP timeout) and stay below\r\n * `DEFAULT_LOCK_TIMEOUT_MS` so a crashed peer's lock is broken before a\r\n * healthy waiter times out.\r\n */\r\nexport const DEFAULT_LOCK_STALE_MS = 60_000;\r\n\r\n/** Thrown when a contended acquire exceeds its deadline. */\r\nexport class FileLockTimeoutError extends Error {\r\n constructor(message: string) {\r\n super(message);\r\n this.name = \"FileLockTimeoutError\";\r\n }\r\n}\r\n\r\nexport interface FileLockOptions {\r\n /** Contended-acquire deadline in ms (default `DEFAULT_LOCK_TIMEOUT_MS`). */\r\n timeoutMs?: number;\r\n /** Poll interval between attempts in ms (default `DEFAULT_LOCK_RETRY_MS`). */\r\n retryMs?: number;\r\n /** Stale-lock age threshold in ms (default `DEFAULT_LOCK_STALE_MS`). */\r\n staleMs?: number;\r\n}\r\n\r\n/** A held lock. `release()` is idempotent. */\r\nexport interface FileLockHandle {\r\n /** Path of the lock file itself (the `<name>.lock` sibling). */\r\n readonly path: string;\r\n release(): void;\r\n}\r\n\r\n/**\r\n * Sibling `.lock` file for `target` (never the credentials file itself).\r\n *\r\n * Locking a dedicated sibling rather than the credentials file avoids\r\n * interfering with the atomic rename in `credentials.ts` (which swaps the\r\n * file out from under any handle open on the original).\r\n */\r\nexport function lockPath(target: string): string {\r\n return `${target}.lock`;\r\n}\r\n\r\nfunction isErrnoException(e: unknown): e is NodeJS.ErrnoException {\r\n return e instanceof Error && \"code\" in e;\r\n}\r\n\r\n/**\r\n * Acquire the cross-process lock for `target` (see module docs).\r\n *\r\n * The lock file is created with mode 0600 (where the platform honors it)\r\n * and contains `<pid> <iso-timestamp>` for debuggability. The caller must\r\n * call `release()` on the returned handle — prefer `withFileLock`, which\r\n * guarantees release in a `finally`.\r\n *\r\n * @throws FileLockTimeoutError when the lock stays contended past `timeoutMs`.\r\n */\r\nexport async function acquireFileLock(\r\n target: string,\r\n options: FileLockOptions = {},\r\n): Promise<FileLockHandle> {\r\n const timeoutMs = options.timeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS;\r\n const retryMs = options.retryMs ?? DEFAULT_LOCK_RETRY_MS;\r\n const staleMs = options.staleMs ?? DEFAULT_LOCK_STALE_MS;\r\n\r\n const lockFile = lockPath(target);\r\n fs.mkdirSync(path.dirname(lockFile), { recursive: true });\r\n\r\n const deadline = Date.now() + timeoutMs;\r\n for (;;) {\r\n // Attempt the exclusive create (\"wx\" = O_WRONLY | O_CREAT | O_EXCL).\r\n let fd: number | null = null;\r\n try {\r\n fd = fs.openSync(lockFile, \"wx\", 0o600);\r\n } catch (e) {\r\n if (!isErrnoException(e) || e.code !== \"EEXIST\") {\r\n // Permission failure, unsupported FS, etc. — a permanent failure\r\n // must surface instead of spinning forever (Python parity).\r\n throw e;\r\n }\r\n }\r\n if (fd !== null) {\r\n try {\r\n fs.writeSync(fd, `${process.pid} ${new Date().toISOString()}\\n`);\r\n } finally {\r\n fs.closeSync(fd);\r\n }\r\n let released = false;\r\n return {\r\n path: lockFile,\r\n release(): void {\r\n if (released) {\r\n return;\r\n }\r\n released = true;\r\n try {\r\n fs.unlinkSync(lockFile);\r\n } catch {\r\n // Already gone (broken as stale by a waiter) — release is\r\n // best-effort and idempotent.\r\n }\r\n },\r\n };\r\n }\r\n\r\n // Lock is held by someone else. Break it if it looks abandoned.\r\n let mtimeMs: number;\r\n try {\r\n mtimeMs = fs.statSync(lockFile).mtimeMs;\r\n } catch (e) {\r\n if (isErrnoException(e) && e.code === \"ENOENT\") {\r\n continue; // released between attempts — retry the create at once\r\n }\r\n throw e;\r\n }\r\n if (Date.now() - mtimeMs > staleMs) {\r\n try {\r\n fs.unlinkSync(lockFile);\r\n } catch (e) {\r\n if (!isErrnoException(e) || e.code !== \"ENOENT\") {\r\n throw e;\r\n }\r\n }\r\n continue; // retry the create at once\r\n }\r\n\r\n if (Date.now() >= deadline) {\r\n throw new FileLockTimeoutError(\r\n `could not acquire credentials lock within ${timeoutMs / 1000}s: ${lockFile}`,\r\n );\r\n }\r\n await sleep(retryMs);\r\n }\r\n}\r\n\r\n/**\r\n * Hold the cross-process lock for `target` for the duration of `fn`.\r\n *\r\n * The lock is always released — including when `fn` throws — via the\r\n * `finally` block (mirrors Python's `file_lock` context manager).\r\n */\r\nexport async function withFileLock<T>(\r\n target: string,\r\n fn: () => T | Promise<T>,\r\n options: FileLockOptions = {},\r\n): Promise<T> {\r\n const handle = await acquireFileLock(target, options);\r\n try {\r\n return await fn();\r\n } finally {\r\n handle.release();\r\n }\r\n}\r\n","/** Configuration loading for the Kagura Memory SDK (port of config.py). */\r\n\r\nimport * as fs from \"node:fs\";\r\nimport * as os from \"node:os\";\r\nimport * as path from \"node:path\";\r\n\r\n/**\r\n * Shape of `.kagura.json` — the config file format is shared with the\r\n * Python SDK/CLI, so keys stay snake_case on disk. Additional keys are\r\n * preserved.\r\n */\r\nexport interface KaguraConfig {\r\n api_key?: string;\r\n mcp_url?: string;\r\n model?: string;\r\n context_id?: string | null;\r\n llm_api_key?: string;\r\n workspace_id?: string;\r\n [key: string]: unknown;\r\n}\r\n\r\nexport interface LoadConfigOptions {\r\n /** Directory searched for `./.kagura.json` (default: process.cwd()). */\r\n cwd?: string;\r\n /** Home directory searched for `~/.kagura.json` (default: os.homedir()). */\r\n home?: string;\r\n /** Environment source (default: process.env). */\r\n env?: Record<string, string | undefined>;\r\n}\r\n\r\nfunction readConfigFile(filePath: string, label: string): KaguraConfig {\r\n let text: string;\r\n try {\r\n text = fs.readFileSync(filePath, \"utf-8\");\r\n } catch (e) {\r\n throw new Error(`Failed to read ${label}: ${e instanceof Error ? e.message : String(e)}`);\r\n }\r\n try {\r\n const parsed: unknown = JSON.parse(text);\r\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\r\n throw new Error(\"expected a JSON object\");\r\n }\r\n return parsed as KaguraConfig;\r\n } catch (e) {\r\n throw new Error(\r\n `Invalid JSON or encoding in ${label} (expected UTF-8): ${e instanceof Error ? e.message : String(e)}`,\r\n );\r\n }\r\n}\r\n\r\n/**\r\n * Load configuration from `.kagura.json` or environment variables.\r\n *\r\n * Search order:\r\n * 1. `./.kagura.json` (current directory)\r\n * 2. `~/.kagura.json` (home directory)\r\n * 3. Environment variables (KAGURA_API_KEY, KAGURA_MCP_URL, KAGURA_MODEL)\r\n */\r\nexport function loadConfig(options: LoadConfigOptions = {}): KaguraConfig {\r\n const cwd = options.cwd ?? process.cwd();\r\n const home = options.home ?? os.homedir();\r\n const env = options.env ?? process.env;\r\n\r\n const localConfig = path.join(cwd, \".kagura.json\");\r\n if (fs.existsSync(localConfig)) {\r\n return readConfigFile(localConfig, \".kagura.json\");\r\n }\r\n\r\n const homeConfig = path.join(home, \".kagura.json\");\r\n if (fs.existsSync(homeConfig)) {\r\n return readConfigFile(homeConfig, \"~/.kagura.json\");\r\n }\r\n\r\n return {\r\n api_key: env.KAGURA_API_KEY ?? \"\",\r\n mcp_url: env.KAGURA_MCP_URL ?? \"https://memory.kagura-ai.com/mcp\",\r\n model: env.KAGURA_MODEL ?? \"gpt-5.4-nano\",\r\n context_id: env.KAGURA_CONTEXT_ID ?? null,\r\n };\r\n}\r\n","/**\r\n * Credential resolution shared by REST/MCP clients in this SDK (port of\r\n * _auth.py).\r\n *\r\n * Centralizes the precedence chain — explicit arg > `KAGURA_API_KEY` env >\r\n * OAuth profile in `~/.kagura/credentials.json` > `.kagura.json` config —\r\n * in one module so every client resolves credentials identically.\r\n *\r\n * Returns one of two result types (see `types.ts`):\r\n *\r\n * - `StaticAuthResult` — long-lived API key, baked into the client's\r\n * `Authorization` header at construction.\r\n * - `OAuthAuthResult` — a `KaguraOAuth` AuthProvider that injects a fresh\r\n * access token per request and coordinates refresh via a process-wide\r\n * mutex.\r\n *\r\n * This module imports only from `auth/credentials`, `config`, and\r\n * `errors` — never from `http`. The reverse direction (`http` importing\r\n * `resolve`) must also be avoided so the dependency stays one-way.\r\n */\r\n\r\nimport { loadConfig } from \"../config.js\";\r\nimport type { KaguraConfig } from \"../config.js\";\r\nimport { KaguraAuthError } from \"../errors.js\";\r\nimport {\r\n KaguraOAuth,\r\n defaultCredentialsPath,\r\n getSharedState,\r\n loadCredentialsFile,\r\n} from \"./credentials.js\";\r\nimport type { SharedCredentialsState } from \"./credentials.js\";\r\nimport type { ResolvedAuth } from \"./types.js\";\r\n\r\nexport const DEFAULT_MCP_URL = \"https://memory.kagura-ai.com/mcp\";\r\n\r\n/** Kept trivial on purpose; swap the sink here if the SDK ever grows one. */\r\nconst logger = {\r\n warn(message: string): void {\r\n console.warn(message);\r\n },\r\n};\r\n\r\n// (credentials-file path, profile name) pairs already warned about this\r\n// process, so the multi-profile ambiguity note fires at most once per active\r\n// profile per file per process rather than on every client construction.\r\n// Keyed by path too so two different credential files that share a default\r\n// name (e.g. \"default\") don't suppress each other.\r\nconst warnedProfiles = new Set<string>();\r\n\r\n/** Clear the once-per-process ambiguity-warning dedup set (test hook). */\r\nexport function resetProfileWarnings(): void {\r\n warnedProfiles.clear();\r\n}\r\n\r\nexport interface ResolveAuthOptions {\r\n apiKey?: string | null;\r\n mcpUrl?: string | null;\r\n profile?: string | null;\r\n /** Pre-loaded `.kagura.json`; skips the priority-4 disk read when set. */\r\n config?: KaguraConfig | null;\r\n /** Environment source (default: process.env). */\r\n env?: Record<string, string | undefined>;\r\n /** Home directory for `~/.kagura/credentials.json` (default: os.homedir()). */\r\n home?: string;\r\n}\r\n\r\n/** True when `KAGURA_REQUIRE_PROFILE` opts into strict resolution. */\r\nfunction strictProfileRequired(env: Record<string, string | undefined>): boolean {\r\n const raw = (env.KAGURA_REQUIRE_PROFILE ?? \"\").trim().toLowerCase();\r\n return raw === \"1\" || raw === \"true\" || raw === \"yes\";\r\n}\r\n\r\n/**\r\n * Warn (or, under strict mode, raise) on an implicit multi-profile default.\r\n *\r\n * Only fires when resolution fell back to `default_profile` (no explicit\r\n * `profile` arg and no `KAGURA_PROFILE`) AND more than one profile is\r\n * configured — a single-profile setup is unambiguous and stays silent. The\r\n * note names the active profile + workspace so a misdirected write to the\r\n * wrong account is caught. Honors `KAGURA_REQUIRE_PROFILE`.\r\n */\r\nfunction checkProfileAmbiguity(\r\n state: SharedCredentialsState,\r\n env: Record<string, string | undefined>,\r\n credentialsPath: string,\r\n): void {\r\n const cf = loadCredentialsFile(credentialsPath);\r\n if (Object.keys(cf.profiles).length < 2) {\r\n return; // single profile: unambiguous\r\n }\r\n\r\n const name = state.profileName;\r\n const creds = state.credentials;\r\n const workspace = creds.workspaceName || creds.workspaceId || \"unknown workspace\";\r\n\r\n // The strict check runs BEFORE the dedup-set check so a prior non-strict\r\n // warning can never swallow a strict raise.\r\n if (strictProfileRequired(env)) {\r\n const available = Object.keys(cf.profiles).sort().join(\", \");\r\n throw new KaguraAuthError(\r\n `Multiple profiles configured and none selected; refusing to use the ` +\r\n `implicit default '${name}' because KAGURA_REQUIRE_PROFILE is set.\\n` +\r\n ` Select one explicitly: kagura auth use <name>, --profile <name>, ` +\r\n `or KAGURA_PROFILE=<name>\\n` +\r\n ` Available profiles: ${available}`,\r\n );\r\n }\r\n\r\n const warnKey = JSON.stringify([state.path, name]);\r\n if (!warnedProfiles.has(warnKey)) {\r\n warnedProfiles.add(warnKey);\r\n logger.warn(\r\n `kagura: using profile '${name}' (workspace '${workspace}') — set a ` +\r\n `default with 'kagura auth use <name>' or pass --profile to silence ` +\r\n `this notice.`,\r\n );\r\n }\r\n}\r\n\r\n/**\r\n * Pick a credential source per the documented precedence chain:\r\n *\r\n * 1. Explicit `apiKey` argument (non-whitespace) — wins absolutely.\r\n * 2. `KAGURA_API_KEY` env var, with mcpUrl fallback\r\n * `mcpUrl arg > KAGURA_MCP_URL > DEFAULT_MCP_URL`.\r\n * 3. OAuth profile from credentials.json:\r\n * `profile arg > KAGURA_PROFILE > default_profile`. An explicitly named\r\n * profile that is missing raises rather than falling through (silently\r\n * authenticating with the wrong account is the bug class prevented).\r\n * 4. Legacy `.kagura.json` (pre-loaded via `options.config` or read from\r\n * disk), with the same whitespace-stripped api_key check.\r\n *\r\n * Empty / whitespace-only api_keys are treated the same as absent at every\r\n * step — sending `Authorization: Bearer ` would always 401 and is never\r\n * what the caller intended.\r\n *\r\n * @throws KaguraAuthError when no source produces credentials.\r\n */\r\nexport function resolveAuth(options: ResolveAuthOptions = {}): ResolvedAuth {\r\n const env = options.env ?? process.env;\r\n const mcpUrl = options.mcpUrl ?? null;\r\n\r\n // 1. Explicit constructor argument wins absolutely.\r\n const apiKey = options.apiKey;\r\n if (apiKey !== undefined && apiKey !== null && apiKey.trim()) {\r\n return {\r\n kind: \"static\",\r\n apiKey,\r\n mcpUrl: mcpUrl || DEFAULT_MCP_URL,\r\n source: \"explicit\",\r\n };\r\n }\r\n\r\n // 2. KAGURA_API_KEY env var (highest auto-resolution priority).\r\n const envKey = env.KAGURA_API_KEY;\r\n if (envKey && envKey.trim()) {\r\n return {\r\n kind: \"static\",\r\n apiKey: envKey,\r\n mcpUrl: mcpUrl || env.KAGURA_MCP_URL || DEFAULT_MCP_URL,\r\n source: \"env\",\r\n };\r\n }\r\n\r\n // 3. OAuth profile from credentials.json: explicit > KAGURA_PROFILE > default.\r\n const targetProfile = options.profile || env.KAGURA_PROFILE || null;\r\n const credentialsPath = defaultCredentialsPath(options.home);\r\n const state = getSharedState(credentialsPath, targetProfile);\r\n if (state !== null) {\r\n if (targetProfile === null) {\r\n // No explicit selection — resolution fell back to default_profile.\r\n // Warn (or hard-error under strict mode) when the default is\r\n // ambiguous because multiple profiles are configured.\r\n checkProfileAmbiguity(state, env, credentialsPath);\r\n }\r\n return {\r\n kind: \"oauth\",\r\n oauth: new KaguraOAuth(state),\r\n mcpUrl: mcpUrl || state.credentials.mcpUrl,\r\n workspaceId: state.credentials.workspaceId || null,\r\n };\r\n }\r\n if (targetProfile) {\r\n // An explicit profile name (via arg or KAGURA_PROFILE env) was\r\n // requested but credentials.json has no such profile. Falling through\r\n // to .kagura.json would silently authenticate with the wrong account,\r\n // so raise instead.\r\n const source = options.profile ? \"profile argument\" : \"KAGURA_PROFILE env\";\r\n throw new KaguraAuthError(\r\n `Profile '${targetProfile}' (from ${source}) not found in credentials.json.\\n` +\r\n ` Run: kagura auth login --profile ${targetProfile}\\n` +\r\n ` Or inspect ~/.kagura/credentials.json to see which profiles exist.`,\r\n );\r\n }\r\n\r\n // 4. Legacy .kagura.json (which itself env-falls-back internally).\r\n const cfg =\r\n options.config ?? loadConfig({ ...(options.home ? { home: options.home } : {}), env });\r\n const cfgKey = cfg.api_key;\r\n if (typeof cfgKey === \"string\" && cfgKey.trim()) {\r\n return {\r\n kind: \"static\",\r\n apiKey: cfgKey,\r\n mcpUrl: mcpUrl || cfg.mcp_url || DEFAULT_MCP_URL,\r\n source: \"config\",\r\n };\r\n }\r\n\r\n throw new KaguraAuthError(\r\n \"No credentials found.\\n\" +\r\n \" Run: kagura auth login\\n\" +\r\n \" Or set: KAGURA_API_KEY=<your key>\\n\" +\r\n ' Or create: .kagura.json with {\"api_key\": \"...\"}',\r\n );\r\n}\r\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","/**\n * Explicit credential refresh — the `kagura auth refresh` counterpart.\n *\n * Auto-refresh already happens inside {@link KaguraOAuth} as tokens near\n * expiry, so this is for the cases that skew-driven rotation cannot cover:\n * a token revoked out-of-band (rejected server-side while still outside\n * the skew window), a deliberate scope change, or a pre-flight refresh\n * before a long batch.\n *\n * Like `login()`, this owns no terminal IO — the device-flow fallback\n * hands the user code back through `onUserCode`.\n */\n\nimport { KaguraAuthError } from \"../errors.js\";\nimport type { OAuthCredentials } from \"./credentials.js\";\nimport {\n KaguraOAuth,\n getSharedState,\n loadCredentialsFile,\n updateProfile,\n} from \"./credentials.js\";\nimport { authorizeDevice, pollForToken } from \"./deviceFlow.js\";\nimport type { DeviceAuthorizationResponse } from \"./deviceFlow.js\";\n\nexport interface RefreshOptions {\n /** Profile to refresh (default: the file's default profile). */\n profile?: string;\n /** Credentials file path (default `~/.kagura/credentials.json`). */\n credentialsPath?: string;\n /**\n * Request a different scope.\n *\n * Narrowing goes through the refresh grant silently. Widening needs\n * fresh consent, so a server rejection triggers a full device flow —\n * see {@link RefreshOptions.onUserCode}.\n */\n scope?: string;\n /**\n * Called with the device-authorization response when a scope widening\n * forces re-consent. Required in practice for that path: without it the\n * user is never shown the code, and polling times out.\n */\n onUserCode?: (auth: DeviceAuthorizationResponse) => void | Promise<void>;\n /** Injectable fetch (tests / custom agents). */\n fetch?: typeof globalThis.fetch;\n /** Injectable sleep in milliseconds, used between device-flow polls. */\n sleep?: (ms: number) => Promise<void>;\n}\n\n/** Whether an auth failure is the server refusing a wider grant. */\nfunction isScopeRejection(error: unknown): boolean {\n if (!(error instanceof KaguraAuthError)) {\n return false;\n }\n const message = error.message.toLowerCase();\n return message.includes(\"insufficient_scope\") || message.includes(\"invalid_scope\");\n}\n\n/**\n * Refresh a stored profile's access token and persist the result.\n *\n * @returns the credentials that were written.\n * @throws Error if the named profile does not exist.\n * @throws KaguraAuthExpiredError the refresh token is no longer valid —\n * the stored profile is left untouched so it can still be inspected.\n * @throws KaguraAuthError other protocol/response failures.\n * @throws KaguraConnectionError the server was unreachable.\n */\nexport async function refresh(options: RefreshOptions = {}): Promise<OAuthCredentials> {\n const cf = loadCredentialsFile(options.credentialsPath);\n const target = options.profile || cf.defaultProfile;\n const stored = cf.profiles[target];\n if (stored === undefined) {\n throw new Error(`No profile named '${target}'. Run a login first.`);\n }\n\n const httpOptions = options.fetch !== undefined ? { fetch: options.fetch } : {};\n\n // Delegate to KaguraOAuth rather than driving refreshAccessToken here:\n // it holds the cross-process file lock across the whole\n // read-check-refresh-persist sequence, so a peer that rotated while we\n // waited is adopted instead of racing us into an `invalid_grant` on a\n // token that is already stale on disk.\n const state = getSharedState(options.credentialsPath, target);\n if (state === null) {\n throw new Error(`No profile named '${target}'. Run a login first.`);\n }\n const provider = new KaguraOAuth(state, httpOptions);\n\n try {\n await provider.forceRefresh(options.scope !== undefined ? { scope: options.scope } : {});\n return state.credentials;\n } catch (e) {\n // A rejection only means \"widen\" when the caller actually asked for a\n // different scope; otherwise re-consent would be the wrong response\n // to what is simply a failed refresh.\n if (options.scope === undefined || !isScopeRejection(e)) {\n throw e;\n }\n // Runs outside the lock — forceRefresh released it on the way out, and\n // updateProfile below re-acquires it, so there is no deadlock.\n const next = await consentToWiderScope(state.credentials, options.scope, options, httpOptions);\n await updateProfile(target, next, options.credentialsPath);\n state.credentials = next;\n return next;\n }\n}\n\n/**\n * Re-run the device flow to collect consent for a wider grant.\n *\n * Mirrors the Python CLI's fallback: narrowing succeeds through the\n * refresh grant, widening needs the user to approve again. Diverging here\n * would make `--scope` widening behave differently between the two SDKs\n * on the credentials file they share.\n */\nasync function consentToWiderScope(\n stored: OAuthCredentials,\n scope: string,\n options: RefreshOptions,\n httpOptions: { fetch?: typeof globalThis.fetch },\n): Promise<OAuthCredentials> {\n // Without a way to show the code, polling would just run until the\n // device code expires. Fail now, while the cause is still legible.\n if (options.onUserCode === undefined) {\n throw new KaguraAuthError(\n `Widening the scope to '${scope}' needs fresh consent, which requires ` +\n \"showing the user a device code — pass onUserCode to refresh(). \" +\n \"Narrowing a scope does not need consent and works without it.\",\n );\n }\n\n const authorization = await authorizeDevice(stored.server, {\n clientId: stored.clientId,\n scope,\n ...httpOptions,\n });\n\n await options.onUserCode(authorization);\n\n const token = await pollForToken(stored.server, {\n clientId: stored.clientId,\n deviceCode: authorization.deviceCode,\n interval: authorization.interval,\n expiresAt: authorization.expiresAt,\n ...httpOptions,\n ...(options.sleep !== undefined ? { sleep: options.sleep } : {}),\n });\n\n // A fresh grant carries its own identity fields; fall back to the\n // stored ones only where the response is silent.\n return {\n ...stored,\n accessToken: token.accessToken,\n refreshToken: token.refreshToken || stored.refreshToken,\n tokenType: token.tokenType,\n expiresAt: token.expiresAt,\n scope: token.scope || scope,\n workspaceId: token.workspaceId || stored.workspaceId,\n workspaceName: token.workspaceName || stored.workspaceName,\n userEmail: token.userEmail || stored.userEmail,\n issuedAt: new Date(),\n };\n}\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;AAA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AAA,EACA;AACF,CAAC;AAED,QAAQ,WAAW;","names":["fs","path","sleep","stringOr","fs","os","path","resolve"]}
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/parse.ts","../src/cli/command.ts","../src/cli/output.ts","../src/cli/runClientCommand.ts","../src/cli/commands/context.ts","../src/cli/commands/doctor.ts","../src/cli/commands/files.ts","../src/cli/commands/graph.ts","../src/cli/commands/memory.ts","../src/cli/commands/resource.ts","../src/cli/commands/importFormats.ts","../src/cli/commands/secret.ts","../src/secrets/crypto.ts","../src/cli/commands/setup.ts","../src/cli/run.ts","../src/agentBootstrap.ts","../src/client.ts","../src/filesClient.ts","../src/auth/types.ts","../src/restBase.ts","../src/uuid.ts","../src/resourceClient.ts","../src/secrets/client.ts"],"sourcesContent":["/**\n * `kagura-memory` bin — the thin shim around {@link runCli}.\n *\n * Everything testable lives in `cli/run.ts` behind injected dependencies;\n * this file holds only what needs a real terminal, a real browser, and a\n * real process exit.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { constants } from \"node:os\";\nimport { readFileSync } from \"node:fs\";\nimport * as readline from \"node:readline/promises\";\n\nimport { login } from \"./auth/login.js\";\nimport { refresh } from \"./auth/refresh.js\";\nimport { openBrowser } from \"./cli/openBrowser.js\";\nimport { runCli } from \"./cli/run.js\";\nimport { KaguraClient } from \"./client.js\";\nimport { loadConfig } from \"./config.js\";\nimport { FilesClient } from \"./filesClient.js\";\nimport { ResourceClient } from \"./resourceClient.js\";\nimport { SecretClient } from \"./secrets/client.js\";\n\nasync function confirm(question: string): Promise<boolean> {\n // A non-interactive stdin (CI, a pipe) must not hang waiting for input\n // that will never arrive; treat it as a decline and let --yes be the\n // explicit opt-in.\n if (!process.stdin.isTTY) {\n process.stderr.write(\"Refusing to prompt on a non-interactive stdin. Re-run with --yes.\\n\");\n return false;\n }\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n try {\n const answer = await rl.question(`${question} [y/N] `);\n return /^y(es)?$/i.test(answer.trim());\n } finally {\n rl.close();\n }\n}\n\nconst code = await runCli(process.argv.slice(2), {\n write: (line) => {\n process.stdout.write(`${line}\\n`);\n },\n writeError: (line) => {\n process.stderr.write(`${line}\\n`);\n },\n confirm,\n openBrowser,\n login,\n refresh,\n loadConfig,\n makeClient: (options) => new KaguraClient(options),\n // `fromMcpUrl`, not bare construction: it runs the credential chain\n // (env > OAuth profile > .kagura.json) and stamps the MCP URL the chosen\n // branch belongs to. Passing nothing lets each branch pair its credential\n // with its own URL, which is what Python does and why an OAuth profile\n // bound to a non-default server still reaches the right host.\n makeFilesClient: () => FilesClient.fromMcpUrl({}),\n makeResourceClient: () => ResourceClient.fromMcpUrl({}),\n makeSecretClient: () => SecretClient.fromMcpUrl({}),\n isTty: () => Boolean(process.stdout.isTTY),\n readStdin: () => {\n // A terminal stdin would block forever waiting for input that is not\n // coming; treat it as \"nothing piped in\".\n if (process.stdin.isTTY) return null;\n try {\n return readFileSync(0, \"utf-8\");\n } catch {\n return null;\n }\n },\n spawnChild: (command, argv, extraEnv, unset) =>\n new Promise((resolve) => {\n const childEnv: NodeJS.ProcessEnv = { ...process.env, ...extraEnv };\n // Remove before spawning, not after: the child inherits a snapshot.\n for (const name of unset) delete childEnv[name];\n const child = spawn(command, argv, { stdio: \"inherit\", env: childEnv });\n child.on(\"error\", (e) => {\n // 127 is the shell's \"command not found\", which is what this is.\n process.stderr.write(`Error: cannot run ${command}: ${e.message}\\n`);\n resolve(127);\n });\n // A child killed by a signal has no numeric code; 128+n is the shell\n // convention and keeps \"it died\" distinguishable from \"it exited 0\".\n child.on(\"close\", (code, signal) =>\n resolve(code ?? (signal === null ? 1 : 128 + (constants.signals[signal] ?? 0))),\n );\n }),\n});\n\nprocess.exitCode = code;\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\n/**\n * Secret-store operation failed for a non-HTTP reason (#28).\n *\n * The base of the secret hierarchy: a client-side contract violation, such\n * as putting a secret with no recipients or with a recipient whose\n * advertised fingerprint does not match its pubkey.\n */\nexport class KaguraSecretError extends KaguraError {}\n\n/**\n * age encryption/decryption failed, or its input was malformed.\n *\n * Also raised when the optional `age-encryption` peer dependency is not\n * installed — the message names the install command, since the base SDK\n * deliberately ships with no runtime dependencies.\n */\nexport class KaguraCryptoError extends KaguraSecretError {}\n\n/**\n * The age private key could not be stored or retrieved.\n *\n * Custody is fail-closed: refusing to hold the key is an error, never a\n * silent fallback to a less secure location.\n */\nexport class KaguraKeyCustodyError extends KaguraSecretError {}\n","/**\n * Package version string, shared across client modules (User-Agent, MCP\n * clientInfo). Kept in sync with package.json by the release process.\n */\nexport const SDK_VERSION = \"0.8.0\";\n","/** Shared HTTP utilities for Kagura Memory SDK clients (port of _http.py). */\n\nimport {\n KaguraAuthError,\n KaguraConnectionError,\n KaguraRateLimitError,\n} from \"./errors.js\";\n\nexport { SDK_VERSION } from \"./version.js\";\n\n/**\n * Derive the REST API base URL from an MCP URL.\n *\n * Strips `/mcp` and everything after it (e.g. `/mcp/w/{workspace}`).\n */\nexport function baseUrlFromMcp(mcpUrl: string): string {\n const m = /\\/mcp(?=\\/|$)/.exec(mcpUrl);\n return m ? mcpUrl.slice(0, m.index) : mcpUrl;\n}\n\nfunction formatValidationErrors(errors: unknown[]): string {\n // Silent-skip malformed entries so a single bad entry doesn't blank the line.\n const parts: string[] = [];\n for (const entry of errors) {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n continue;\n }\n const rec = entry as Record<string, unknown>;\n const msg = rec.msg;\n if (typeof msg !== \"string\" || !msg) {\n continue;\n }\n const loc = rec.loc;\n if (Array.isArray(loc) && loc.length > 0) {\n parts.push(`${loc.map(String).join(\".\")}: ${msg}`);\n } else {\n parts.push(msg);\n }\n }\n return parts.join(\"; \");\n}\n\n/**\n * Return a useful server-supplied error string from a response body.\n *\n * Handles four response shapes:\n * - `{\"detail\": \"string\"}` — returned as-is (FastAPI HTTPException default).\n * - `{\"detail\": [{\"loc\": [...], \"msg\": \"...\", ...}, ...]}` — FastAPI's\n * validation-error format; each entry becomes `\"<loc.path>: <msg>\"`.\n * - `{\"error\": \"<CODE>\", \"message\": \"string\", \"details\": {...}}` — the\n * memory-cloud canonical envelope; returns `message`, appending\n * `details.errors` validation entries when present.\n * - Anything else — returns an empty string so callers can fall back.\n */\nexport function extractDetail(bodyText: string): string {\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 const rec = body as Record<string, unknown>;\n const detail = rec.detail;\n if (typeof detail === \"string\") {\n return detail;\n }\n if (Array.isArray(detail)) {\n return formatValidationErrors(detail);\n }\n const message = rec.message;\n if (typeof message === \"string\" && message) {\n const details = rec.details;\n if (typeof details === \"object\" && details !== null && !Array.isArray(details)) {\n const errors = (details as Record<string, unknown>).errors;\n if (Array.isArray(errors)) {\n const formatted = formatValidationErrors(errors);\n if (formatted) {\n return `${message}: ${formatted}`;\n }\n }\n }\n return message;\n }\n return \"\";\n}\n\n/**\n * Drop server-provided detail strings that contain credential markers.\n *\n * A future server bug echoing back the Bearer header or api_key must not\n * be passed straight to the user. Returns `null` when the detail is empty\n * or unsafe to display.\n */\nexport function sanitizeServerDetail(detail: string | null | undefined): string | null {\n if (!detail) {\n return null;\n }\n const lowered = detail.toLowerCase();\n if (lowered.includes(\"bearer\") || lowered.includes(\"authorization\") || lowered.includes(\"api_key=\")) {\n return null;\n }\n return detail;\n}\n\n/**\n * Parse a numeric `Retry-After` header (delta-seconds), else `null`.\n *\n * Only the integer-seconds form is honored; an HTTP-date `Retry-After`\n * (rare for rate limits) is treated as absent rather than mis-parsed.\n */\nexport function retryAfterSeconds(headers: Headers): number | null {\n const raw = headers.get(\"Retry-After\");\n if (raw === null) {\n return null;\n }\n const trimmed = raw.trim();\n return /^\\d+$/.test(trimmed) ? parseInt(trimmed, 10) : null;\n}\n\n/**\n * Translate a non-2xx HTTP response into the matching Kagura error.\n *\n * Maps 401 → KaguraAuthError, 429 → KaguraRateLimitError (honoring a\n * numeric `Retry-After` header), and every other status →\n * KaguraConnectionError. The server-supplied detail is appended when\n * present, otherwise `fallbackMessage` is used so the status is never\n * left bare. This function always throws.\n */\nexport function throwForKaguraStatus(\n status: number,\n headers: Headers,\n bodyText: string,\n fallbackMessage?: string,\n): never {\n if (status === 401) {\n throw new KaguraAuthError(\"Authentication failed. Check your API key.\");\n }\n const detail = extractDetail(bodyText) || fallbackMessage || \"\";\n if (status === 429) {\n throw new KaguraRateLimitError(\n `Rate limit exceeded (HTTP 429): ${detail || `HTTP ${status}`}`,\n retryAfterSeconds(headers),\n );\n }\n // Avoid a doubled \"HTTP 500: HTTP 500\" when the body carries no detail.\n throw new KaguraConnectionError(detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}`);\n}\n\n// Plain-HTTP is permitted only for genuine loopback hosts. The host token must\n// be followed by a boundary — a port (:\\d+), a path/query/fragment delimiter,\n// or end-of-string — so a prefix-match attack like http://localhost.evil.com\n// or a userinfo trick like http://localhost@evil.com cannot smuggle an\n// external host past the check (#189).\n// Both patterns are case-insensitive: URL parsing lower-cases the scheme\n// and host, so `HTTP://EVIL.TEST` is fetched over plaintext exactly like\n// `http://evil.test`. A case-sensitive guard would wave it through.\nconst PLAIN_HTTP_RE = /^http:\\/\\//i;\nconst LOCALHOST_HTTP_RE = /^http:\\/\\/(?:localhost|127\\.0\\.0\\.1|\\[::1\\])(?::\\d+)?(?:[/?#]|$)/i;\n\n/**\n * Enforce HTTPS except for localhost development.\n *\n * @throws Error if the URL uses HTTP and is not a loopback host.\n */\nexport function validateHttpsUrl(url: string, label = \"URL\"): void {\n // WHATWG URL parsing strips surrounding whitespace, so `\" http://x\"`\n // reaches the network as plain HTTP. Both patterns are anchored, so\n // without trimming first they would never match it and the guard would\n // pass. Trim here rather than relying on callers to have done it.\n const candidate = url.trim();\n if (PLAIN_HTTP_RE.test(candidate) && !LOCALHOST_HTTP_RE.test(candidate)) {\n throw new Error(\n `${label} must use HTTPS for security (got: ${candidate}). ` +\n \"HTTP is only allowed for localhost development.\",\n );\n }\n}\n","/**\n * Persistent OAuth credentials for the Kagura SDK (port of\n * auth/credentials.py).\n *\n * This module owns three responsibilities:\n *\n * 1. The `OAuthCredentials` / `CredentialsFile` shapes and their JSON\n * (de)serialization. The on-disk format at `~/.kagura/credentials.json`\n * is SHARED with the Python CLI — keys stay snake_case on disk\n * (`default_profile`, `profiles`, `access_token`, ...), timestamps are\n * Z-suffixed UTC ISO-8601.\n * 2. Atomic, mode-0600 read/write of the credentials file with a mode-0700\n * parent directory (permissions are best-effort where the platform,\n * e.g. Windows/NTFS, does not honor POSIX bits).\n * 3. A process-wide cache (`getSharedState`) so concurrent clients pointing\n * at the same credentials file share a single in-process mutex, ensuring\n * only one `/oauth/token/` refresh fires per cycle even when many client\n * instances run side by side.\n *\n * Multi-process coordination is handled in two layers: the in-process\n * `AsyncMutex` coalesces refreshes *within* a process, and the\n * cross-process lock in `filelock.ts` (acquired inside the refresh path)\n * re-reads the on-disk token after locking and skips the `/oauth/token/`\n * round-trip when another process already rotated it.\n */\n\nimport * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { KaguraAuthExpiredError } from \"../errors.js\";\nimport { refreshAccessToken } from \"./deviceFlow.js\";\nimport { withFileLock } from \"./filelock.js\";\nimport type { AuthProvider } from \"./types.js\";\n\n/**\n * Refresh `accessToken` when within this many seconds of `expiresAt`.\n *\n * Default of 5 minutes mirrors common OAuth2 client conventions and gives\n * enough headroom for a slow refresh round-trip.\n */\nexport const REFRESH_SKEW_SEC = 300;\n\nexport const CREDENTIALS_FILE_MODE = 0o600;\nexport const CREDENTIALS_DIR_MODE = 0o700;\n\n/**\n * Default location of the credentials file: `~/.kagura/credentials.json`.\n * Tests pass an explicit `home`/path instead of touching the real one.\n */\nexport function defaultCredentialsPath(home?: string): string {\n return path.join(home ?? os.homedir(), \".kagura\", \"credentials.json\");\n}\n\n// ---------------------------------------------------------------------------\n// Data shapes\n// ---------------------------------------------------------------------------\n\n/** A single profile's OAuth2 credentials (camelCase in memory, snake_case on disk). */\nexport interface OAuthCredentials {\n server: string;\n mcpUrl: string;\n clientId: string;\n accessToken: string;\n refreshToken: string;\n tokenType: string;\n expiresAt: Date;\n scope: string;\n workspaceId: string;\n workspaceName: string;\n userEmail: string;\n issuedAt: Date;\n}\n\n/** True when `accessToken` is past `expiresAt - skewSeconds`. */\nexport function isExpired(creds: OAuthCredentials, skewSeconds = 0): boolean {\n return Date.now() >= creds.expiresAt.getTime() - skewSeconds * 1000;\n}\n\n/**\n * Return a copy of `creds` with the rotated token fields applied.\n *\n * `refreshToken` is rotated when the server returns a new one (RFC 6749\n * §10.4 recommended) — pass `null`/omit to preserve the stored one.\n * `scope` is updated when the server narrows or widens the grant.\n */\nexport function withRefreshed(\n creds: OAuthCredentials,\n fields: {\n accessToken: string;\n refreshToken?: string | null;\n expiresAt: Date;\n scope?: string | null;\n },\n): OAuthCredentials {\n return {\n ...creds,\n accessToken: fields.accessToken,\n refreshToken: fields.refreshToken ?? creds.refreshToken,\n expiresAt: fields.expiresAt,\n scope: fields.scope ?? creds.scope,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Datetime helpers (Z-suffixed UTC ISO-8601 for human readability)\n// ---------------------------------------------------------------------------\n\n/** Serialize a Date as `YYYY-MM-DDTHH:MM:SSZ` (UTC, seconds precision). */\nexport function isoUtc(date: Date): string {\n return `${date.toISOString().slice(0, 19)}Z`;\n}\n\n/**\n * Parse ISO-8601, accepting `...Z`, `...+00:00`, and naive suffixes.\n *\n * Normalizes a missing timezone to UTC so a user-edited / legacy\n * credentials file with naive timestamps doesn't get parsed as local time\n * (JavaScript's `Date` parses a bare `YYYY-MM-DDTHH:MM:SS` as local).\n */\nexport function parseIso(s: string): Date {\n const normalized = /(?:Z|[+-]\\d{2}:?\\d{2})$/.test(s) ? s : `${s}Z`;\n const date = new Date(normalized);\n if (Number.isNaN(date.getTime())) {\n throw new Error(`invalid ISO-8601 timestamp: ${s}`);\n }\n return date;\n}\n\n// ---------------------------------------------------------------------------\n// JSON (de)serialization — snake_case on disk, shared with the Python CLI\n// ---------------------------------------------------------------------------\n\nexport function credentialsToDict(creds: OAuthCredentials): Record<string, unknown> {\n return {\n server: creds.server,\n mcp_url: creds.mcpUrl,\n client_id: creds.clientId,\n access_token: creds.accessToken,\n refresh_token: creds.refreshToken,\n token_type: creds.tokenType,\n expires_at: isoUtc(creds.expiresAt),\n scope: creds.scope,\n workspace_id: creds.workspaceId,\n workspace_name: creds.workspaceName,\n user_email: creds.userEmail,\n issued_at: isoUtc(creds.issuedAt),\n };\n}\n\nfunction requireString(d: Record<string, unknown>, key: string): string {\n const value = d[key];\n if (typeof value !== \"string\") {\n throw new Error(`credentials profile missing required field '${key}'`);\n }\n return value;\n}\n\nfunction stringOr(value: unknown, fallback: string): string {\n return typeof value === \"string\" ? value : fallback;\n}\n\n/** @throws Error when required fields are missing or timestamps invalid. */\nexport function credentialsFromDict(d: Record<string, unknown>): OAuthCredentials {\n const issuedAtRaw = d.issued_at;\n return {\n server: requireString(d, \"server\"),\n mcpUrl: requireString(d, \"mcp_url\"),\n clientId: requireString(d, \"client_id\"),\n accessToken: requireString(d, \"access_token\"),\n refreshToken: requireString(d, \"refresh_token\"),\n tokenType: stringOr(d.token_type, \"Bearer\"),\n expiresAt: parseIso(requireString(d, \"expires_at\")),\n scope: stringOr(d.scope, \"\"),\n workspaceId: stringOr(d.workspace_id, \"\"),\n workspaceName: stringOr(d.workspace_name, \"\"),\n userEmail: stringOr(d.user_email, \"\"),\n issuedAt: typeof issuedAtRaw === \"string\" && issuedAtRaw ? parseIso(issuedAtRaw) : new Date(),\n };\n}\n\n/** Top-level wrapper for `~/.kagura/credentials.json`. */\nexport interface CredentialsFile {\n version: number;\n defaultProfile: string;\n profiles: Record<string, OAuthCredentials>;\n}\n\nexport function emptyCredentialsFile(): CredentialsFile {\n return { version: 1, defaultProfile: \"default\", profiles: {} };\n}\n\n/** Return the named profile, or the default, or `null` if missing. */\nexport function getProfile(\n cf: CredentialsFile,\n name?: string | null,\n): OAuthCredentials | null {\n const key = name || cf.defaultProfile;\n return cf.profiles[key] ?? null;\n}\n\n/** Insert or replace a profile. The first profile becomes default. */\nexport function setProfile(cf: CredentialsFile, name: string, creds: OAuthCredentials): void {\n cf.profiles[name] = creds;\n if (!(cf.defaultProfile in cf.profiles)) {\n cf.defaultProfile = name;\n }\n}\n\n/** Remove a profile in memory if present; repoints a deleted default. */\nexport function removeProfile(cf: CredentialsFile, name: string): void {\n delete cf.profiles[name];\n const next = Object.keys(cf.profiles)[0];\n if (cf.defaultProfile === name && next !== undefined) {\n cf.defaultProfile = next;\n }\n}\n\nexport function credentialsFileToDict(cf: CredentialsFile): Record<string, unknown> {\n const profiles: Record<string, unknown> = {};\n for (const [name, creds] of Object.entries(cf.profiles)) {\n profiles[name] = credentialsToDict(creds);\n }\n return {\n version: cf.version,\n default_profile: cf.defaultProfile,\n profiles,\n };\n}\n\n/** @throws Error when any profile is malformed (caller treats file as empty). */\nexport function credentialsFileFromDict(d: Record<string, unknown>): CredentialsFile {\n const profilesRaw = d.profiles;\n const profiles: Record<string, OAuthCredentials> = {};\n if (typeof profilesRaw === \"object\" && profilesRaw !== null && !Array.isArray(profilesRaw)) {\n for (const [name, p] of Object.entries(profilesRaw)) {\n if (typeof p !== \"object\" || p === null || Array.isArray(p)) {\n throw new Error(`credentials profile '${name}' is not an object`);\n }\n profiles[name] = credentialsFromDict(p as Record<string, unknown>);\n }\n }\n return {\n version: typeof d.version === \"number\" ? d.version : 1,\n defaultProfile: stringOr(d.default_profile, \"default\"),\n profiles,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Filesystem IO\n// ---------------------------------------------------------------------------\n\n/** Force the directory to mode 0700 (best-effort; no-op where unsupported). */\nfunction enforceDirPerms(directory: string): void {\n try {\n const mode = fs.statSync(directory).mode & 0o777;\n if (mode !== CREDENTIALS_DIR_MODE) {\n fs.chmodSync(directory, CREDENTIALS_DIR_MODE);\n }\n } catch {\n // Best-effort: a directory we can't chmod is the user's problem, not\n // ours to abort over. Reads/writes will fail downstream with a clearer\n // error if perms genuinely block access.\n }\n}\n\n/** Force the credentials file to mode 0600 (defense in depth, best-effort). */\nfunction enforceFilePerms(filePath: string): void {\n try {\n const mode = fs.statSync(filePath).mode & 0o777;\n if (mode !== CREDENTIALS_FILE_MODE) {\n fs.chmodSync(filePath, CREDENTIALS_FILE_MODE);\n }\n } catch {\n // Best-effort — see enforceDirPerms.\n }\n}\n\n/**\n * Write `data` to `filePath` atomically.\n *\n * Steps: exclusive-create temp file in the same directory → write JSON →\n * fsync → chmod → rename over the target. A kill between any two steps\n * either leaves the original file untouched or replaces it cleanly.\n */\nfunction atomicWriteJson(\n filePath: string,\n data: unknown,\n mode: number = CREDENTIALS_FILE_MODE,\n): void {\n const dir = path.dirname(filePath);\n fs.mkdirSync(dir, { recursive: true });\n enforceDirPerms(dir);\n\n const tmp = path.join(\n dir,\n `.${path.basename(filePath)}.${crypto.randomBytes(6).toString(\"hex\")}.tmp`,\n );\n let fd: number | null = null;\n try {\n fd = fs.openSync(tmp, \"wx\", 0o600);\n fs.writeSync(fd, `${JSON.stringify(data, null, 2)}\\n`);\n fs.fsyncSync(fd);\n fs.closeSync(fd);\n fd = null;\n fs.chmodSync(tmp, mode);\n fs.renameSync(tmp, filePath);\n // fsync the parent directory so the rename itself is durable on crash /\n // power-loss. Best-effort: Windows and some filesystems don't support\n // fsync on a directory descriptor; the atomic rename already happened,\n // so the worst case is losing the most recent write, never file\n // integrity.\n try {\n const dirFd = fs.openSync(dir, \"r\");\n try {\n fs.fsyncSync(dirFd);\n } finally {\n fs.closeSync(dirFd);\n }\n } catch {\n // See comment above.\n }\n } catch (e) {\n if (fd !== null) {\n try {\n fs.closeSync(fd);\n } catch {\n // fd already closed / invalid — nothing more to release.\n }\n }\n fs.rmSync(tmp, { force: true });\n throw e;\n }\n}\n\nfunction resolvePath(p?: string): string {\n return p ?? defaultCredentialsPath();\n}\n\n/**\n * Read and parse the credentials file.\n *\n * Returns an empty `CredentialsFile` when the file is missing, unreadable,\n * or malformed — the caller can distinguish \"no profile\" via\n * `getProfile(cf) === null`. On a present file, parent directory and file\n * permissions are coerced to 0700/0600 (best-effort).\n */\nexport function loadCredentialsFile(credentialsPath?: string): CredentialsFile {\n const p = resolvePath(credentialsPath);\n if (!fs.existsSync(p)) {\n return emptyCredentialsFile();\n }\n\n enforceDirPerms(path.dirname(p));\n enforceFilePerms(p);\n\n let data: unknown;\n try {\n data = JSON.parse(fs.readFileSync(p, \"utf-8\"));\n } catch {\n return emptyCredentialsFile();\n }\n if (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n return emptyCredentialsFile();\n }\n try {\n return credentialsFileFromDict(data as Record<string, unknown>);\n } catch {\n // Corrupt or partial file — treat as empty rather than crashing.\n return emptyCredentialsFile();\n }\n}\n\n/** Atomically persist a `CredentialsFile` to disk. */\nexport function saveCredentialsFile(cf: CredentialsFile, credentialsPath?: string): void {\n atomicWriteJson(resolvePath(credentialsPath), credentialsFileToDict(cf), CREDENTIALS_FILE_MODE);\n}\n\n/**\n * Load, mutate one profile, and atomically save back.\n *\n * The read-modify-write is wrapped in the cross-process lock from\n * `filelock.ts` so concurrent writers in *different* processes cannot lose\n * an update. The lock is on a sibling `credentials.json.lock`, not the\n * file itself, so it never races the atomic rename in\n * `saveCredentialsFile`.\n */\nexport async function updateProfile(\n profileName: string,\n creds: OAuthCredentials,\n credentialsPath?: string,\n): Promise<void> {\n const p = resolvePath(credentialsPath);\n await withFileLock(p, () => {\n const cf = loadCredentialsFile(p);\n setProfile(cf, profileName, creds);\n saveCredentialsFile(cf, p);\n });\n}\n\n/**\n * Set `default_profile` to an existing profile (backs `kagura auth use`).\n *\n * Unlike `setProfile`'s implicit first-wins promotion, this is a\n * *deliberate* default selection, wrapped in the same cross-process lock as\n * `updateProfile` so a concurrent refresh/login cannot clobber it.\n *\n * @throws Error if `profileName` is not an existing profile — selecting a\n * non-existent default would silently break resolution. (Python raises\n * `KeyError` here; a plain `Error` is the TS equivalent.)\n */\nexport async function setDefaultProfile(\n profileName: string,\n credentialsPath?: string,\n): Promise<void> {\n const p = resolvePath(credentialsPath);\n await withFileLock(p, () => {\n const cf = loadCredentialsFile(p);\n if (!(profileName in cf.profiles)) {\n throw new Error(`profile '${profileName}' not found in credentials file`);\n }\n cf.defaultProfile = profileName;\n saveCredentialsFile(cf, p);\n });\n}\n\n/**\n * Remove a profile and save. No-op if the profile is absent.\n *\n * The read-modify-write is wrapped in the cross-process lock so a logout\n * (delete) racing a concurrent token refresh (update) in a sibling process\n * cannot clobber a freshly written token. The absent-profile early return\n * runs *inside* the lock so the membership check and the save observe one\n * consistent snapshot (no TOCTOU).\n */\nexport async function deleteProfile(\n profileName: string,\n credentialsPath?: string,\n): Promise<void> {\n const p = resolvePath(credentialsPath);\n await withFileLock(p, () => {\n const cf = loadCredentialsFile(p);\n if (!(profileName in cf.profiles)) {\n return;\n }\n removeProfile(cf, profileName);\n saveCredentialsFile(cf, p);\n });\n}\n\n/**\n * Remove the entire credentials file (`kagura auth logout --all`).\n *\n * Missing file is treated as success — logout is idempotent.\n */\nexport function deleteCredentialsFile(credentialsPath?: string): void {\n fs.rmSync(resolvePath(credentialsPath), { force: true });\n}\n\n// ---------------------------------------------------------------------------\n// Shared state cache (in-process single-flight)\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal promise-chaining mutex — the `asyncio.Lock` equivalent.\n *\n * `runExclusive` calls are serialized in arrival order; a rejection inside\n * one critical section does not poison the chain for later callers.\n */\nexport class AsyncMutex {\n private tail: Promise<unknown> = Promise.resolve();\n\n runExclusive<T>(fn: () => T | Promise<T>): Promise<T> {\n const run = this.tail.then(() => fn());\n this.tail = run.catch(() => undefined);\n return run;\n }\n}\n\n/**\n * Mutable per-(path, profile) state shared across clients.\n *\n * The `mutex` is shared across **all profiles in the same file** — not\n * per-(path, profile) — so two profiles refreshing concurrently can't both\n * read-modify-write the file and clobber each other's update.\n */\nexport interface SharedCredentialsState {\n credentials: OAuthCredentials;\n profileName: string;\n /** Resolved absolute path of the credentials file. */\n path: string;\n mutex: AsyncMutex;\n}\n\nconst stateCache = new Map<string, SharedCredentialsState>();\n// One mutex per credentials file path, shared across profiles in the same\n// file so concurrent refreshes serialize at the file level.\nconst fileMutexes = new Map<string, AsyncMutex>();\n\nfunction getFileMutex(p: string): AsyncMutex {\n let mutex = fileMutexes.get(p);\n if (mutex === undefined) {\n mutex = new AsyncMutex();\n fileMutexes.set(p, mutex);\n }\n return mutex;\n}\n\n/**\n * Return the shared state for `(path, profile)`, loading lazily.\n *\n * Returns `null` if the credentials file is missing or has no matching\n * profile — the caller falls back to other credential sources (static API\n * key, `.kagura.json`, etc.) in that case.\n *\n * Concurrent clients that resolve to the same `(path, profile)` pair get\n * the same state object, which means they share a single mutex and any\n * refresh fired by one of them benefits all of them.\n */\nexport function getSharedState(\n credentialsPath?: string,\n profile?: string | null,\n): SharedCredentialsState | null {\n // Normalize the path once so the cache key and the persisted state path\n // stay consistent — a relative path could otherwise cause the cache\n // lookup and the refresh-time write to target different files.\n const p = path.resolve(resolvePath(credentialsPath));\n const cf = loadCredentialsFile(p);\n const creds = getProfile(cf, profile);\n if (creds === null) {\n return null;\n }\n\n const profileName = profile || cf.defaultProfile;\n // JSON-encode the pair so a path containing spaces can never collide\n // with another (path, profile) combination.\n const key = JSON.stringify([p, profileName]);\n let cached = stateCache.get(key);\n if (cached === undefined) {\n cached = {\n credentials: creds,\n profileName,\n path: p,\n mutex: getFileMutex(p),\n };\n stateCache.set(key, cached);\n } else {\n // Refresh in-memory creds from disk so a recent CLI login is visible\n // to clients already constructed in this process.\n cached.credentials = creds;\n }\n return cached;\n}\n\n/** Clear the module-level cache. Tests call this between cases. */\nexport function resetStateCache(): void {\n stateCache.clear();\n fileMutexes.clear();\n}\n\n// ---------------------------------------------------------------------------\n// KaguraOAuth — AuthProvider with single-flight refresh\n// ---------------------------------------------------------------------------\n\n/**\n * `AuthProvider` that supplies the current access token as a Bearer header.\n *\n * Holds a reference to a shared `SharedCredentialsState`, so concurrent\n * client instances pointing at the same credentials file all coalesce\n * refresh calls through a single in-process mutex. When the access token\n * is within `REFRESH_SKEW_SEC` of expiry the mutex is acquired, the\n * refresh runs once, and every other in-flight `getAuthHeader` call waits\n * and then sees the rotated token.\n *\n * (The Python SDK expresses this as an `httpx.Auth` subclass; with `fetch`\n * there is no request-hook layer, so clients ask for a fresh header value\n * before each request instead.)\n */\nexport class KaguraOAuth implements AuthProvider {\n private readonly state: SharedCredentialsState;\n private readonly fetchImpl: typeof globalThis.fetch | undefined;\n\n constructor(\n state: SharedCredentialsState,\n options: { fetch?: typeof globalThis.fetch } = {},\n ) {\n this.state = state;\n this.fetchImpl = options.fetch;\n }\n\n /**\n * Return `Bearer <access_token>`, refreshing first when the token is\n * within the skew window.\n */\n async getAuthHeader(): Promise<string> {\n await this.maybeRefresh();\n return `Bearer ${this.state.credentials.accessToken}`;\n }\n\n /**\n * Refresh the access token if it's within the skew window.\n *\n * The mutex is held across the entire read-check-refresh-persist\n * sequence so a second caller waiting on it will find the token already\n * rotated when it acquires.\n */\n private async maybeRefresh(): Promise<void> {\n await this.state.mutex.runExclusive(async () => {\n if (!isExpired(this.state.credentials, REFRESH_SKEW_SEC)) {\n return;\n }\n await this.refreshLocked(null);\n });\n }\n\n /**\n * Unconditionally refresh the access token, ignoring the skew window.\n *\n * Used on an upstream 401: the token was rejected server-side (rotated /\n * revoked out-of-band) even though it is not yet within the skew window.\n * The same in-process mutex serializes this with skew-driven refreshes.\n * Cross-process dedup is handled in `refreshLocked` via the\n * rejected-token identity check.\n */\n async forceRefresh(options: { scope?: string } = {}): Promise<void> {\n // Capture the rejected token BEFORE the in-process mutex: if a peer\n // already rotated it while we waited, we must still compare against\n // the token that actually got the 401, otherwise the rotated token\n // would compare equal to disk and force a redundant refresh.\n const rejectedToken = this.state.credentials.accessToken;\n await this.state.mutex.runExclusive(() =>\n this.refreshLocked(rejectedToken, options.scope),\n );\n }\n\n /**\n * Refresh `/oauth/token/` once across all processes. Caller holds the\n * in-process mutex.\n *\n * After acquiring the cross-process file lock, re-read the credentials\n * from disk and **skip the network call when another process already\n * rotated the token** — \"skip\" means \"adopt the on-disk result\", never\n * \"leave the stale in-memory token in place\".\n *\n * `expectedStaleToken` governs the \"already rotated?\" predicate:\n * `null` (skew path) → skip when the on-disk token is no longer within\n * the skew window. A token string (401 path) → skip only when the\n * on-disk token *differs* from the rejected one (a 401 is independent of\n * `expiresAt`).\n */\n private async refreshLocked(\n expectedStaleToken: string | null,\n scope?: string,\n ): Promise<void> {\n const credPath = this.state.path;\n const profileName = this.state.profileName;\n await withFileLock(credPath, async () => {\n const disk = getProfile(loadCredentialsFile(credPath), profileName);\n // A scope change must never adopt a peer's rotation: that token was\n // issued for the *old* scope, so treating it as \"already done\" would\n // silently drop the change the caller asked for.\n if (scope === undefined && disk !== null && this.alreadyRotated(disk, expectedStaleToken)) {\n this.state.credentials = disk;\n return;\n }\n const base = disk ?? this.state.credentials;\n await this.networkRefreshAndSave(base, credPath, profileName, scope);\n });\n }\n\n /** Whether `disk` shows another process already produced a usable token. */\n private alreadyRotated(disk: OAuthCredentials, expectedStaleToken: string | null): boolean {\n if (expectedStaleToken === null) {\n // Skew path: a token outside the skew window is fresh enough.\n return !isExpired(disk, REFRESH_SKEW_SEC);\n }\n // 401 path: a different token means someone rotated; an identical token\n // means the rejected token is still current and we must refresh.\n return disk.accessToken !== expectedStaleToken;\n }\n\n /** Hit `/oauth/token/` from `base` and persist. Caller holds both locks. */\n private async networkRefreshAndSave(\n base: OAuthCredentials,\n credPath: string,\n profileName: string,\n scope?: string,\n ): Promise<void> {\n // A profile stored without a refresh token cannot be refreshed. Going\n // to the network first only earns an `invalid_grant`, whose message\n // (\"refresh token is no longer valid\") describes a token that never\n // existed — the actual cause is that the grant never carried offline\n // access. Fail here instead, naming that.\n if (!base.refreshToken) {\n throw new KaguraAuthExpiredError(\n \"This profile was stored without a refresh token, so it cannot be \" +\n \"refreshed — log in again to get one.\\n\" +\n \" Run: kagura auth login (or `npx kagura-memory auth login`)\",\n base.expiresAt,\n );\n }\n\n const token = await refreshAccessToken(base.server, {\n clientId: base.clientId,\n refreshToken: base.refreshToken,\n ...(scope !== undefined ? { scope } : {}),\n ...(this.fetchImpl ? { fetch: this.fetchImpl } : {}),\n });\n // Pass `null` when the server omits `refresh_token` so the stored token\n // is preserved: `TokenResponse.refreshToken` defaults to \"\" when\n // absent, and overwriting a valid stored token with an empty one would\n // break every subsequent refresh.\n this.state.credentials = withRefreshed(base, {\n accessToken: token.accessToken,\n refreshToken: token.refreshToken || null,\n expiresAt: token.expiresAt,\n // `||` not `??`: TokenResponse.scope defaults to \"\" when the server\n // omits it, and withRefreshed's `?? creds.scope` only catches\n // null/undefined — so an omitted scope used to blank the stored one.\n scope: token.scope || null,\n });\n // We already hold the cross-process lock; write directly rather than\n // via updateProfile (which would re-acquire the same lock and\n // deadlock). Re-load → set → save still preserves every other profile\n // in the file.\n const cf = loadCredentialsFile(credPath);\n setProfile(cf, profileName, this.state.credentials);\n saveCredentialsFile(cf, credPath);\n }\n}\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","/**\n * Interactive OAuth login — the one step the SDK could not do on its own.\n *\n * `deviceFlow.ts` provides the stateless RFC 8628 primitives and\n * `credentials.ts` the Python-CLI-compatible store; this module is the thin\n * orchestrator that joins them: authorize → hand the user code to the host\n * app → poll → persist. It is what lets a TypeScript-only consumer (an\n * Electron app, a CLI of its own) obtain credentials instead of requiring\n * the user to install and run the Python `kagura auth login` first.\n *\n * Deliberately still no terminal IO and no browser launching: `onUserCode`\n * hands the code and verification URI back to the caller, which owns how it\n * is displayed. The only side effect is the credentials file write.\n */\n\nimport { baseUrlFromMcp, validateHttpsUrl } from \"../http.js\";\nimport type { OAuthCredentials } from \"./credentials.js\";\nimport { setDefaultProfile, updateProfile } from \"./credentials.js\";\nimport { authorizeDevice, pollForToken, DEFAULT_CLIENT_ID } from \"./deviceFlow.js\";\nimport type { DeviceAuthorizationResponse } from \"./deviceFlow.js\";\nimport { DEFAULT_MCP_URL } from \"./resolve.js\";\n\n/**\n * Scope requested when `login()` is called without one.\n *\n * Read **and** write, matching the Python CLI's `kagura auth login`\n * default. The credentials file is shared between both SDKs, so a profile\n * must not end up with different authority depending on which one wrote\n * it. Opt down with `scope: READ_ONLY_SCOPE` — the CLI's `--read-only`.\n */\nexport const DEFAULT_SCOPE = \"memory:read memory:write\";\n\n/** Read-only scope; the Python CLI's `--read-only`. */\nexport const READ_ONLY_SCOPE = \"memory:read\";\n\nexport interface LoginOptions {\n /**\n * MCP endpoint to log into. The OAuth endpoints are derived from it, and\n * both URLs are stored on the profile so the pair can never drift apart.\n *\n * Resolution mirrors the Python CLI's `--server` chain: this option,\n * then `KAGURA_MCP_URL`, then {@link DEFAULT_MCP_URL}. Plain HTTP is\n * rejected for non-loopback hosts — the flow carries a bearer token.\n */\n mcpUrl?: string;\n /** Environment source override (for tests; default: `process.env`). */\n env?: Record<string, string | undefined>;\n /** OAuth client ID (default {@link DEFAULT_CLIENT_ID}). */\n clientId?: string;\n /**\n * Requested scope. Defaults to {@link DEFAULT_SCOPE} (read + write), the\n * same default as the Python CLI's `kagura auth login`. Pass\n * {@link READ_ONLY_SCOPE} for the CLI's `--read-only` behaviour.\n */\n scope?: string;\n /** Profile name to store under (default `\"default\"`). */\n profile?: string;\n /** Credentials file path (default `~/.kagura/credentials.json`). */\n credentialsPath?: string;\n /**\n * Make this profile the default even when others already exist.\n *\n * Off by default: the first profile ever written is promoted\n * automatically, so adding a second one leaves the user's existing\n * default alone unless they ask for the switch.\n */\n setAsDefault?: boolean;\n /**\n * Called once with the device-authorization response before polling\n * starts — display `userCode` and `verificationUri` (or open\n * `verificationUriComplete`) here.\n *\n * Awaited, and a throw aborts the login before any polling or disk\n * write, so a host app that cannot show the code fails fast.\n */\n onUserCode?: (auth: DeviceAuthorizationResponse) => void | Promise<void>;\n /** Injectable fetch (tests / custom agents). */\n fetch?: typeof globalThis.fetch;\n /** Injectable sleep in milliseconds, used between polls. */\n sleep?: (ms: number) => Promise<void>;\n}\n\n/**\n * Run the full device-authorization login and persist the result.\n *\n * @returns the credentials that were written.\n * @throws KaguraAuthDeniedError the user denied at the consent screen.\n * @throws KaguraAuthExpiredError the device code expired before approval.\n * @throws KaguraAuthError propagated from the device-flow primitives on a\n * protocol/response failure.\n * @throws KaguraConnectionError the server was unreachable.\n *\n * Nothing is written unless the token exchange succeeds, so a failed login\n * never disturbs an existing profile. A response with no `refresh_token`\n * warns and still persists (matching the Python CLI); check the returned\n * `refreshToken` if the caller needs to react.\n */\nexport async function login(options: LoginOptions = {}): Promise<OAuthCredentials> {\n const env = options.env ?? process.env;\n // Explicit arg > KAGURA_MCP_URL > public default, matching the Python\n // CLI. Without the env step a self-hosted user with KAGURA_MCP_URL set\n // would be silently logged in to the public cloud instead.\n const mcpUrl = options.mcpUrl?.trim() || env.KAGURA_MCP_URL?.trim() || DEFAULT_MCP_URL;\n // The device flow carries a bearer token back over this connection, so\n // the destination is validated before any request goes out.\n validateHttpsUrl(mcpUrl, \"MCP URL\");\n const server = baseUrlFromMcp(mcpUrl);\n const clientId = options.clientId ?? DEFAULT_CLIENT_ID;\n const profile = options.profile ?? \"default\";\n\n const authorization = await authorizeDevice(server, {\n clientId,\n scope: options.scope ?? DEFAULT_SCOPE,\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\n });\n\n await options.onUserCode?.(authorization);\n\n const token = await pollForToken(server, {\n clientId,\n deviceCode: authorization.deviceCode,\n interval: authorization.interval,\n expiresAt: authorization.expiresAt,\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\n ...(options.sleep !== undefined ? { sleep: options.sleep } : {}),\n });\n\n // A response with no refresh_token yields a profile that cannot\n // auto-refresh. Python treats that as a legitimate degraded state — it\n // writes the profile and reports `refreshable: false` from\n // `kagura auth status` — so this SDK must not reject a state the other\n // one considers valid on the file they share. Warn instead: the caller\n // can also branch on the returned `refreshToken`.\n if (!token.refreshToken) {\n console.warn(\n \"Logged in, but the token response carried no refresh_token: this \" +\n \"profile cannot auto-refresh and will need another login when the \" +\n `access token expires. Verify the '${clientId}' client is allowed ` +\n `offline access on ${server}.`,\n );\n }\n\n const credentials: OAuthCredentials = {\n server,\n mcpUrl,\n clientId,\n accessToken: token.accessToken,\n refreshToken: token.refreshToken,\n tokenType: token.tokenType,\n expiresAt: token.expiresAt,\n scope: token.scope,\n workspaceId: token.workspaceId,\n workspaceName: token.workspaceName,\n userEmail: token.userEmail,\n issuedAt: new Date(),\n };\n\n await updateProfile(profile, credentials, options.credentialsPath);\n if (options.setAsDefault) {\n await setDefaultProfile(profile, options.credentialsPath);\n }\n return credentials;\n}\n","/**\n * Explicit credential refresh — the `kagura auth refresh` counterpart.\n *\n * Auto-refresh already happens inside {@link KaguraOAuth} as tokens near\n * expiry, so this is for the cases that skew-driven rotation cannot cover:\n * a token revoked out-of-band (rejected server-side while still outside\n * the skew window), a deliberate scope change, or a pre-flight refresh\n * before a long batch.\n *\n * Like `login()`, this owns no terminal IO — the device-flow fallback\n * hands the user code back through `onUserCode`.\n */\n\nimport { KaguraAuthError } from \"../errors.js\";\nimport type { OAuthCredentials } from \"./credentials.js\";\nimport {\n KaguraOAuth,\n getSharedState,\n loadCredentialsFile,\n updateProfile,\n} from \"./credentials.js\";\nimport { authorizeDevice, pollForToken } from \"./deviceFlow.js\";\nimport type { DeviceAuthorizationResponse } from \"./deviceFlow.js\";\n\nexport interface RefreshOptions {\n /** Profile to refresh (default: the file's default profile). */\n profile?: string;\n /** Credentials file path (default `~/.kagura/credentials.json`). */\n credentialsPath?: string;\n /**\n * Request a different scope.\n *\n * Narrowing goes through the refresh grant silently. Widening needs\n * fresh consent, so a server rejection triggers a full device flow —\n * see {@link RefreshOptions.onUserCode}.\n */\n scope?: string;\n /**\n * Called with the device-authorization response when a scope widening\n * forces re-consent. Required in practice for that path: without it the\n * user is never shown the code, and polling times out.\n */\n onUserCode?: (auth: DeviceAuthorizationResponse) => void | Promise<void>;\n /** Injectable fetch (tests / custom agents). */\n fetch?: typeof globalThis.fetch;\n /** Injectable sleep in milliseconds, used between device-flow polls. */\n sleep?: (ms: number) => Promise<void>;\n}\n\n/** Whether an auth failure is the server refusing a wider grant. */\nfunction isScopeRejection(error: unknown): boolean {\n if (!(error instanceof KaguraAuthError)) {\n return false;\n }\n const message = error.message.toLowerCase();\n return message.includes(\"insufficient_scope\") || message.includes(\"invalid_scope\");\n}\n\n/**\n * Refresh a stored profile's access token and persist the result.\n *\n * @returns the credentials that were written.\n * @throws Error if the named profile does not exist.\n * @throws KaguraAuthExpiredError the refresh token is no longer valid —\n * the stored profile is left untouched so it can still be inspected.\n * @throws KaguraAuthError other protocol/response failures.\n * @throws KaguraConnectionError the server was unreachable.\n */\nexport async function refresh(options: RefreshOptions = {}): Promise<OAuthCredentials> {\n const cf = loadCredentialsFile(options.credentialsPath);\n const target = options.profile || cf.defaultProfile;\n const stored = cf.profiles[target];\n if (stored === undefined) {\n throw new Error(`No profile named '${target}'. Run a login first.`);\n }\n\n const httpOptions = options.fetch !== undefined ? { fetch: options.fetch } : {};\n\n // Delegate to KaguraOAuth rather than driving refreshAccessToken here:\n // it holds the cross-process file lock across the whole\n // read-check-refresh-persist sequence, so a peer that rotated while we\n // waited is adopted instead of racing us into an `invalid_grant` on a\n // token that is already stale on disk.\n const state = getSharedState(options.credentialsPath, target);\n if (state === null) {\n throw new Error(`No profile named '${target}'. Run a login first.`);\n }\n const provider = new KaguraOAuth(state, httpOptions);\n\n try {\n await provider.forceRefresh(options.scope !== undefined ? { scope: options.scope } : {});\n return state.credentials;\n } catch (e) {\n // A rejection only means \"widen\" when the caller actually asked for a\n // different scope; otherwise re-consent would be the wrong response\n // to what is simply a failed refresh.\n if (options.scope === undefined || !isScopeRejection(e)) {\n throw e;\n }\n // Runs outside the lock — forceRefresh released it on the way out, and\n // updateProfile below re-acquires it, so there is no deadlock.\n const next = await consentToWiderScope(state.credentials, options.scope, options, httpOptions);\n await updateProfile(target, next, options.credentialsPath);\n state.credentials = next;\n return next;\n }\n}\n\n/**\n * Re-run the device flow to collect consent for a wider grant.\n *\n * Mirrors the Python CLI's fallback: narrowing succeeds through the\n * refresh grant, widening needs the user to approve again. Diverging here\n * would make `--scope` widening behave differently between the two SDKs\n * on the credentials file they share.\n */\nasync function consentToWiderScope(\n stored: OAuthCredentials,\n scope: string,\n options: RefreshOptions,\n httpOptions: { fetch?: typeof globalThis.fetch },\n): Promise<OAuthCredentials> {\n // Without a way to show the code, polling would just run until the\n // device code expires. Fail now, while the cause is still legible.\n if (options.onUserCode === undefined) {\n throw new KaguraAuthError(\n `Widening the scope to '${scope}' needs fresh consent, which requires ` +\n \"showing the user a device code — pass onUserCode to refresh(). \" +\n \"Narrowing a scope does not need consent and works without it.\",\n );\n }\n\n const authorization = await authorizeDevice(stored.server, {\n clientId: stored.clientId,\n scope,\n ...httpOptions,\n });\n\n await options.onUserCode(authorization);\n\n const token = await pollForToken(stored.server, {\n clientId: stored.clientId,\n deviceCode: authorization.deviceCode,\n interval: authorization.interval,\n expiresAt: authorization.expiresAt,\n ...httpOptions,\n ...(options.sleep !== undefined ? { sleep: options.sleep } : {}),\n });\n\n // A fresh grant carries its own identity fields; fall back to the\n // stored ones only where the response is silent.\n return {\n ...stored,\n accessToken: token.accessToken,\n refreshToken: token.refreshToken || stored.refreshToken,\n tokenType: token.tokenType,\n expiresAt: token.expiresAt,\n scope: token.scope || scope,\n workspaceId: token.workspaceId || stored.workspaceId,\n workspaceName: token.workspaceName || stored.workspaceName,\n userEmail: token.userEmail || stored.userEmail,\n issuedAt: new Date(),\n };\n}\n","/**\n * Best-effort browser launch for the device-flow prompt.\n *\n * Never throws. The URL and code are always printed first, so failing to\n * open a browser is cosmetic — but it must be *reported* as a failure so\n * the CLI can say \"use the URL above\" instead of leaving the operator\n * waiting for a window that will never appear.\n */\n\nimport { spawn } from \"node:child_process\";\n\nimport { validateHttpsUrl } from \"../http.js\";\n\ntype SpawnLike = typeof spawn;\n\n/** The platform's URL opener and its arguments. */\nexport function browserCommand(platform: NodeJS.Platform, url: string): [string, string[]] {\n if (platform === \"win32\") {\n // Deliberately NOT `cmd /c start \"\" <url>`: spawning cmd hands the\n // URL to a shell that reinterprets & | < > ^, which breaks any\n // verification_uri_complete carrying a query string and lets a\n // hostile OAuth server smuggle a command into the URL it returns.\n // explorer.exe receives the URL as a plain argument and opens the\n // default browser without any shell in between.\n return [\"explorer.exe\", [url]];\n }\n if (platform === \"darwin\") {\n return [\"open\", [url]];\n }\n return [\"xdg-open\", [url]];\n}\n\n/**\n * Whether this URL may be handed to a system opener.\n *\n * The URL comes from the OAuth server, so it is untrusted input — and\n * `--server` / `KAGURA_MCP_URL` decide which server that is. Two gates:\n *\n * 1. Scheme must be web. Openers dispatch `file:` and script schemes to\n * whatever is registered for them.\n * 2. The same HTTPS policy the SDK applies to every other endpoint, via\n * {@link validateHttpsUrl} rather than a second copy of the rule —\n * plain HTTP only for loopback. Auto-opening a downgraded non-loopback\n * URL would undercut the guard the rest of the SDK enforces.\n */\nfunction isOpenableUrl(url: string): boolean {\n try {\n const protocol = new URL(url).protocol;\n if (protocol !== \"https:\" && protocol !== \"http:\") {\n return false;\n }\n validateHttpsUrl(url, \"Verification URL\");\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Launch the platform browser.\n *\n * @returns whether the process actually started. `spawn` reports a missing\n * opener asynchronously through the `error` event, so this waits for\n * `spawn`/`error` rather than assuming the call succeeded.\n */\nexport async function openBrowser(url: string, spawnImpl: SpawnLike = spawn): Promise<boolean> {\n if (!isOpenableUrl(url)) {\n return false;\n }\n const [command, args] = browserCommand(process.platform, url);\n\n return new Promise<boolean>((resolve) => {\n let settled = false;\n const settle = (ok: boolean): void => {\n if (!settled) {\n settled = true;\n resolve(ok);\n }\n };\n\n try {\n const child = spawnImpl(command, args, { stdio: \"ignore\", detached: true });\n child.once(\"spawn\", () => settle(true));\n child.once(\"error\", () => settle(false));\n // Don't hold the event loop open waiting for the browser to close.\n child.unref();\n } catch {\n settle(false);\n }\n });\n}\n","/**\n * Minimal argv parser for the `kagura-memory` bin.\n *\n * Hand-rolled because this package's zero-runtime-dependency invariant is\n * deliberate — pulling in commander to read flags would trade that away.\n * Scope is correspondingly small: long flags, registered short flags,\n * repeatable count and multiple flags, positionals, and `--` as the\n * end-of-options marker. No general short-flag clustering, no negation.\n *\n * Each command passes its own {@link ParseSpec}. That is the point: a flag\n * that is real for `auth login` must still be *rejected* by `recall`,\n * which has no such option. A single global flag set would accept it and\n * silently ignore it, which is the failure mode this parser exists to\n * prevent.\n *\n * Unknown and value-less flags are *reported* rather than ignored or\n * thrown on, so the caller can print one message listing everything wrong\n * instead of failing on the first problem.\n */\n\n/**\n * One option a command accepts.\n *\n * Help text lives here rather than in a parallel table so a flag is\n * declared exactly once: a spec entry with no help line, or a help line\n * for a flag that was never registered, is not a state this can reach.\n */\nexport interface FlagSpec {\n /** Long name, written without the leading `--`. */\n name: string;\n /** Optional single-character alias, written without the leading `-`. */\n short?: string;\n /**\n * `value` takes an argument, `switch` is a boolean, `count` is a\n * repeatable verbosity dial, `multiple` accumulates every occurrence\n * (click's `multiple=True`). Defaults to `switch`.\n */\n type?: \"value\" | \"switch\" | \"count\" | \"multiple\";\n /** One-line description for `--help`. */\n help?: string;\n /** Value placeholder shown in `--help` (default: `TEXT` for value flags). */\n metavar?: string;\n /** Rendered as `[default: …]` in `--help`. */\n defaultLabel?: string;\n /** Reported as missing when absent; see `requireOption`. */\n required?: boolean;\n /**\n * Reject `--flag=` (an explicitly empty value).\n *\n * Off by default, because Python accepts an empty value everywhere and\n * several options *rely* on it: `--context-id=` falls through to the\n * config via Python's `or` chain, and `--tags=` / `--details=` treat\n * blank as unset so an unset shell variable is not a hard error.\n *\n * On only where an empty value would do damage rather than nothing —\n * `--profile=` would create a nameless profile and `--scope=` would send\n * an empty scope to the server. That is a deliberate divergence from\n * click, inherited from the auth-only bin, and it stays scoped to the\n * flags that motivated it.\n */\n rejectEmpty?: boolean;\n /**\n * Register only the short form.\n *\n * `kagura recall -k 5` is declared in Python as `@click.option(\"-k\")`\n * with no long form, so `--k` is an unknown option there. Accepting it\n * here would be a superset — small, but the kind of drift that makes\n * \"the two CLIs take the same flags\" stop being literally true.\n */\n shortOnly?: boolean;\n}\n\nexport interface ParseSpec {\n flags: readonly FlagSpec[];\n}\n\nexport interface ParseOptions {\n /**\n * Stop parsing options at the first positional and hand the remainder\n * back untouched in {@link ParsedArgs.rest}.\n *\n * This is click's `allow_interspersed_args=False` +\n * `ignore_unknown_options=True`, which `secret exec` needs: the tokens\n * after the command name belong to the *child*, so `-la` in\n * `secret exec --as A=s -- ls -la` is an argument to `ls`, not an\n * unknown option of ours.\n */\n stopAtPositional?: boolean;\n}\n\nexport interface ParsedArgs {\n /** First non-flag token, or `\"\"` when absent. */\n command: string;\n /** Remaining non-flag tokens. */\n positionals: string[];\n /** Switches that were present, keyed by long name. */\n flags: Set<string>;\n /** Values for `value` flags, keyed by long name. */\n values: Record<string, string | undefined>;\n /** Accumulated values for `multiple` flags, keyed by long name. */\n many: Record<string, string[]>;\n /** Occurrence counts for `count` flags, keyed by long name; 0 when absent. */\n counts: Record<string, number>;\n /** Flags that match nothing in the spec, verbatim (e.g. `--porfile`). */\n unknown: string[];\n /** Value flags that ran out of argv before their value. */\n missingValue: string[];\n /**\n * Unparsed remainder, when `stopAtPositional` was set. Empty otherwise.\n * A leading `--` separator is stripped; anything after it is verbatim.\n */\n rest: string[];\n}\n\n/** `--help` works on every command, so it never needs declaring. */\nconst HELP: FlagSpec = { name: \"help\", type: \"switch\" };\n\n/**\n * Python's `float()` grammar, shared with `parse.ts`.\n *\n * Lives here because the parser needs it too: a dash-prefixed token that\n * is a number is a *value*, not a flag.\n */\nexport const PY_FLOAT =\n /^[+-]?(?:\\d+\\.?\\d*(?:[eE][+-]?\\d+)?|\\.\\d+(?:[eE][+-]?\\d+)?|inf(?:inity)?|nan)$/i;\n\ninterface Index {\n long: Map<string, FlagSpec>;\n short: Map<string, FlagSpec>;\n}\n\nfunction indexSpec(spec: ParseSpec): Index {\n const long = new Map<string, FlagSpec>([[HELP.name, HELP]]);\n const short = new Map<string, FlagSpec>();\n for (const flag of spec.flags) {\n if (flag.shortOnly !== true) long.set(flag.name, flag);\n if (flag.short !== undefined) short.set(flag.short, flag);\n }\n return { long, short };\n}\n\nexport function parseArgs(\n argv: string[],\n spec: ParseSpec,\n options: ParseOptions = {},\n): ParsedArgs {\n const { long, short } = indexSpec(spec);\n const stopAtPositional = options.stopAtPositional === true;\n let rest: string[] = [];\n\n const positionals: string[] = [];\n const flags = new Set<string>();\n const values: Record<string, string | undefined> = {};\n const counts: Record<string, number> = {};\n const many: Record<string, string[]> = {};\n const unknown: string[] = [];\n const missingValue: string[] = [];\n\n // Registered count and multiple flags read as 0 / [] rather than\n // undefined, so callers can use them without a `?? 0` at every site.\n for (const flag of spec.flags) {\n if (flag.type === \"count\") counts[flag.name] = 0;\n if (flag.type === \"multiple\") many[flag.name] = [];\n }\n\n /**\n * Consume the value for `flag`, given how it was written.\n *\n * @returns the number of extra argv tokens eaten (0 or 1), or -1 when the\n * value was missing.\n */\n const store = (flag: FlagSpec, value: string) => {\n if (flag.type === \"multiple\") many[flag.name]!.push(value);\n else values[flag.name] = value;\n };\n\n const takeValue = (flag: FlagSpec, inline: string | null, next: string | undefined): number => {\n if (inline !== null) {\n // `--profile=` is an explicit empty value, not a missing one.\n store(flag, inline);\n return 0;\n }\n // Any following flag means the value was omitted, not that the flag is\n // the value — `--profile --yes` must not set profile=\"--yes\", and\n // `--profile -h` is a request for help, not a profile named \"-h\".\n //\n // A negative number is the exception: `--bm25 -0.1` and `--limit -5`\n // are values, and click accepts them. (Click is in fact laxer still —\n // it consumes whatever follows, so `--reranker -x` sets the value to\n // \"-x\" — but that turns a typo into a silent wrong value, so the\n // stricter rule stays.)\n if (next === undefined || (next.startsWith(\"-\") && next.length > 1 && !PY_FLOAT.test(next))) {\n return -1;\n }\n store(flag, next);\n return 1;\n };\n\n const record = (flag: FlagSpec, inline: string | null, next: string | undefined, token: string) => {\n if (flag.type === \"value\" || flag.type === \"multiple\") {\n const eaten = takeValue(flag, inline, next);\n if (eaten === -1) {\n missingValue.push(token);\n return 0;\n }\n return eaten;\n }\n if (inline !== null) {\n // `--json=true` is not something this parser understands; accepting\n // it would silently discard the value.\n unknown.push(token);\n return 0;\n }\n if (flag.type === \"count\") counts[flag.name] = (counts[flag.name] ?? 0) + 1;\n else flags.add(flag.name);\n return 0;\n };\n\n for (let i = 0; i < argv.length; i++) {\n const token = argv[i]!;\n\n if (token === \"--\") {\n if (stopAtPositional) {\n // Everything from here belongs to whoever we are handing off to.\n rest = argv.slice(i + 1);\n break;\n }\n // Click's end-of-options marker, on every command: what follows is\n // positional even when it starts with a dash, which is the only way\n // to pass `-5` or a filename beginning with one. The `--` itself is\n // consumed rather than kept, or every command would see an extra\n // argument it did not ask for.\n positionals.push(...argv.slice(i + 1));\n break;\n }\n\n if (!token.startsWith(\"-\") || token === \"-\") {\n if (stopAtPositional) {\n rest = argv.slice(i);\n break;\n }\n // A bare `-` is a conventional stdin placeholder, not a flag.\n positionals.push(token);\n continue;\n }\n\n if (token.startsWith(\"--\")) {\n const eq = token.indexOf(\"=\");\n const name = eq === -1 ? token.slice(2) : token.slice(2, eq);\n const inline = eq === -1 ? null : token.slice(eq + 1);\n const flag = long.get(name);\n if (flag === undefined) {\n unknown.push(token);\n continue;\n }\n i += record(flag, inline, argv[i + 1], token);\n continue;\n }\n\n // --- single dash ------------------------------------------------------\n const eq = token.indexOf(\"=\");\n const body = eq === -1 ? token.slice(1) : token.slice(1, eq);\n const inline = eq === -1 ? null : token.slice(eq + 1);\n\n // `-h` is reserved for help on every command; no command registers it\n // for anything else. The `inline` check matters: `-h=x` is a malformed\n // option, not a request for help, and must fall through to be\n // reported.\n if (body === \"h\" && inline === null && !short.has(\"h\")) {\n flags.add(\"help\");\n continue;\n }\n\n const flag = short.get(body);\n if (flag !== undefined) {\n i += record(flag, inline, argv[i + 1], token);\n continue;\n }\n\n // `-vvv` — repetition of one registered count flag. Only same-letter\n // runs are understood; a mixed cluster like `-vx` is reported rather\n // than half-applied.\n if (inline === null && body.length > 1) {\n const first = body[0]!;\n const repeated = short.get(first);\n if (repeated?.type === \"count\" && body === first.repeat(body.length)) {\n counts[repeated.name] = (counts[repeated.name] ?? 0) + body.length;\n continue;\n }\n }\n\n // Silently demoting `-p work` to positionals means the flag is ignored\n // and the command runs with defaults — the same failure mode as an\n // accepted-but-unread switch.\n unknown.push(token);\n }\n\n return {\n command: positionals.shift() ?? \"\",\n positionals,\n flags,\n values,\n counts,\n many,\n unknown,\n missingValue,\n rest,\n };\n}\n","/**\n * Value parsing shared by the data subcommands — the port of `_parse_tags`,\n * `_parse_details`, `_parse_location` and `_build_details` in the Python\n * CLI's `cli.py`, plus the numeric coercion click performs for\n * `type=int` / `type=float` options.\n *\n * Every message here is quoted from the Python CLI so an operator moving\n * between the two tools reads the same guidance.\n */\n\nimport { PY_FLOAT, type FlagSpec } from \"./parseArgs.js\";\n\n/**\n * A usage error: bad input, detected before anything is sent.\n *\n * Click exits **2** for these (`UsageError`) and **1** for a runtime\n * failure (`ClickException`); the distinction is worth keeping because a\n * script can tell \"I invoked it wrong\" from \"the call failed\".\n */\nexport class CliUsageError extends Error {\n readonly exitCode = 2;\n constructor(message: string) {\n super(message);\n this.name = \"CliUsageError\";\n }\n}\n\n/** A runtime failure surfaced with click's `ClickException` exit code. */\nexport class CliError extends Error {\n readonly exitCode = 1;\n constructor(message: string) {\n super(message);\n this.name = \"CliError\";\n }\n}\n\n/** `'--importance' / '-i'`, the way click names an option in its errors. */\nexport function flagLabel(flag: FlagSpec): string {\n return flag.short === undefined ? `'--${flag.name}'` : `'--${flag.name}' / '-${flag.short}'`;\n}\n\n/**\n * Split a comma-separated option into a list.\n *\n * Port of `_parse_tags`: strip each item, drop empties, and collapse an\n * all-empty result back to \"unset\" so the key is omitted from the payload\n * rather than sent as `[]`. A shell expansion of an empty variable is\n * therefore not an error and not a destructive \"clear this field\".\n */\nexport function parseTags(raw: string | undefined): string[] | undefined {\n if (!raw) return undefined;\n const parsed = raw\n .split(\",\")\n .map((t) => t.trim())\n .filter((t) => t.length > 0);\n return parsed.length > 0 ? parsed : undefined;\n}\n\n/**\n * Python's `int()` grammar. The float counterpart lives in `parseArgs.ts`\n * because the parser needs it to tell `-0.1` (a value) from `-x` (a flag).\n *\n * `Number()` is not a substitute for either: it accepts `0x10`, `0b11` and\n * `\"\"`, all of which Python rejects, so the CLI would silently accept\n * input the Python CLI refuses.\n */\nconst PY_INT = /^[+-]?\\d+$/;\n\n/** Coerce a `type=float` option, or raise click's message for it. */\nexport function parseFloatOption(flag: FlagSpec, raw: string): number {\n const text = raw.trim();\n if (!PY_FLOAT.test(text)) {\n throw new CliUsageError(\n `Invalid value for ${flagLabel(flag)}: ${quote(raw)} is not a valid float.`,\n );\n }\n return Number(text.replace(/^([+-]?)inf(inity)?$/i, \"$1Infinity\"));\n}\n\n/** Coerce a `type=int` option, or raise click's message for it. */\nexport function parseIntOption(flag: FlagSpec, raw: string): number {\n const text = raw.trim();\n if (!PY_INT.test(text)) {\n throw new CliUsageError(\n `Invalid value for ${flagLabel(flag)}: ${quote(raw)} is not a valid integer.`,\n );\n }\n return Number(text);\n}\n\n/**\n * Coerce a `click.IntRange` / `click.FloatRange` option.\n *\n * `rangeLabel` is passed rather than derived because click renders the\n * bounds as the Python literals they were declared with: `0.0<=x<=1.0`,\n * where JS would produce `0<=x<=1`.\n */\nexport function parseRanged(\n flag: FlagSpec,\n raw: string,\n options: { min: number; max: number; rangeLabel: string; integer?: boolean },\n): number {\n const integer = options.integer === true;\n let value: number;\n try {\n value = integer ? parseIntOption(flag, raw) : parseFloatOption(flag, raw);\n } catch {\n // A ranged option reports \"not a valid float range\", not \"not a valid\n // float\" — click names the *type* it declared, which is the Range.\n throw new CliUsageError(\n `Invalid value for ${flagLabel(flag)}: ${quote(raw)} is not a valid ${integer ? \"integer\" : \"float\"} range.`,\n );\n }\n if (!(value >= options.min && value <= options.max)) {\n throw new CliUsageError(\n `Invalid value for ${flagLabel(flag)}: ${raw.trim()} is not in the range ${options.rangeLabel}.`,\n );\n }\n return value;\n}\n\n/** Coerce a `click.Choice` option, matching case-insensitively. */\nexport function parseChoice<T extends string>(\n flag: FlagSpec,\n raw: string,\n choices: readonly T[],\n): T {\n const match = choices.find((c) => c === raw.toLowerCase());\n if (match === undefined) {\n throw new CliUsageError(\n `Invalid value for ${flagLabel(flag)}: ${quote(raw)} is not one of ${choices.map(quote).join(\", \")}.`,\n );\n }\n return match;\n}\n\n/**\n * Resolve a `--flag / --no-flag` pair into a tri-state.\n *\n * Click models these as one option with `default=None`, so \"neither given\"\n * has to stay distinguishable from `false` — the key is omitted entirely\n * and the stored value is left alone.\n */\nexport function pairedFlag(\n present: boolean,\n absent: boolean,\n labels: [string, string],\n): boolean | undefined {\n if (present && absent) {\n throw new CliUsageError(`${labels[0]} and ${labels[1]} are mutually exclusive; pick one.`);\n }\n if (present) return true;\n if (absent) return false;\n return undefined;\n}\n\n/**\n * Python's `repr()` of a string, which click interpolates into errors.\n *\n * Escapes matter: a value containing a newline would otherwise split the\n * error across lines, and a Windows path would lose its backslashes.\n * Pinned against the real `repr()` output in the tests.\n *\n * 'a\\n b' -> 'a\\\\n b' (control characters escaped)\n * 'C:\\\\Users' -> 'C:\\\\\\\\Users' (backslash doubled)\n * \"it's\" -> \"it's\" (double-quoted to avoid escaping)\n * \"both ' and \\\"\" -> 'both \\\\' and \"' (single-quoted, apostrophe escaped)\n */\nexport function quote(value: string): string {\n // Python prefers single quotes, switching to double only when the value\n // contains an apostrophe and no double quote.\n const double = value.includes(\"'\") && !value.includes('\"');\n const quoteChar = double ? '\"' : \"'\";\n\n let out = \"\";\n for (const ch of value) {\n const code = ch.codePointAt(0)!;\n if (ch === \"\\\\\") out += \"\\\\\\\\\";\n else if (ch === quoteChar) out += `\\\\${ch}`;\n else if (ch === \"\\n\") out += \"\\\\n\";\n else if (ch === \"\\r\") out += \"\\\\r\";\n else if (ch === \"\\t\") out += \"\\\\t\";\n else if (code < 0x20 || code === 0x7f) out += `\\\\x${code.toString(16).padStart(2, \"0\")}`;\n else out += ch;\n }\n return `${quoteChar}${out}${quoteChar}`;\n}\n\n/**\n * Parse `--details`, a JSON *object*.\n *\n * Port of `_parse_details`. Blank means unset rather than a usage error,\n * so `--details \"$MAYBE_EMPTY\"` behaves.\n */\nexport function parseDetails(raw: string | undefined): Record<string, unknown> | undefined {\n if (raw === undefined || !raw.trim()) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (e) {\n throw new CliUsageError(\n `Invalid JSON for --details: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new CliUsageError(\n `--details must be a JSON object, got ${jsonTypeName(parsed)}. ` +\n `Example: --details '{\"location\": {\"lat\": 35.68, \"lon\": 139.76}}'`,\n );\n }\n return parsed as Record<string, unknown>;\n}\n\n/** The Python type name click reports for a non-object `--details`. */\nfunction jsonTypeName(value: unknown): string {\n if (value === null) return \"NoneType\";\n if (Array.isArray(value)) return \"list\";\n switch (typeof value) {\n case \"string\":\n return \"str\";\n case \"boolean\":\n return \"bool\";\n case \"number\":\n return Number.isInteger(value) ? \"int\" : \"float\";\n default:\n return typeof value;\n }\n}\n\nexport interface LocationPayload {\n lat: number;\n lon: number;\n label?: string;\n}\n\n/**\n * Reject coordinates the server would reject anyway.\n *\n * The comparison is written as a range containment rather than\n * `value < -limit || value > limit` because the latter evaluates false for\n * NaN and would let it through.\n */\nfunction validateLatLon(lat: number, lon: number): void {\n for (const [label, value, limit] of [\n [\"lat\", lat, 90],\n [\"lon\", lon, 180],\n ] as const) {\n if (!(value >= -limit && value <= limit)) {\n throw new CliUsageError(`--location ${label} must be between -${limit} and ${limit}, got ${value}`);\n }\n }\n}\n\n/**\n * Parse `--location`: `lat,lon` or `lat,lon,label`.\n *\n * Port of `_parse_location`.\n */\nexport function parseLocation(raw: string | undefined): LocationPayload | undefined {\n if (raw === undefined || !raw.trim()) return undefined;\n const parts = raw.split(\",\").map((p) => p.trim());\n if (parts.length !== 2 && parts.length !== 3) {\n throw new CliUsageError(\n `--location must be 'lat,lon' or 'lat,lon,label', got ${quote(raw)}`,\n );\n }\n const [rawLat, rawLon] = parts as [string, string];\n if (!PY_FLOAT.test(rawLat) || !PY_FLOAT.test(rawLon)) {\n throw new CliUsageError(\n `--location lat/lon must be numbers, got ${quote(rawLat)},${quote(rawLon)}`,\n );\n }\n const lat = Number(rawLat);\n const lon = Number(rawLon);\n validateLatLon(lat, lon);\n\n const payload: LocationPayload = { lat, lon };\n if (parts.length === 3 && parts[2]) payload.label = parts[2];\n return payload;\n}\n\n/**\n * Combine `--details` and `--location` into one payload.\n *\n * Port of `_build_details`. Supplying both a `location` key inside\n * `--details` and a `--location` is rejected rather than silently\n * resolved, so neither value is quietly dropped.\n */\nexport function buildDetails(\n details: string | undefined,\n location: string | undefined,\n): Record<string, unknown> | undefined {\n const parsed = parseDetails(details);\n const loc = parseLocation(location);\n if (loc === undefined) return parsed;\n if (parsed && \"location\" in parsed) {\n throw new CliUsageError(\n \"--location conflicts with the 'location' key in --details. Use one or the other.\",\n );\n }\n return { ...(parsed ?? {}), location: loc };\n}\n","/**\n * The command registry shape and the small helpers every command needs.\n *\n * A command is data plus one `run` function, so `run.ts` can dispatch and\n * render help generically instead of carrying a switch with 61 arms.\n */\n\nimport { CliUsageError, flagLabel } from \"./parse.js\";\nimport type { FlagSpec, ParseSpec, ParsedArgs } from \"./parseArgs.js\";\nimport type { ClientCommandContext } from \"./runClientCommand.js\";\n\nexport interface CommandDeps extends ClientCommandContext {\n /** Ask a yes/no question; resolves true to proceed. */\n confirm: (question: string) => Promise<boolean>;\n}\n\nexport interface Command {\n /** One line, shown in the parent listing. */\n summary: string;\n /** Positional display, e.g. `QUERY` or `CONTEXT_ID MEMORY_ID`. */\n args?: string;\n /** Extra paragraphs for `--help`, after the option list. */\n description?: string;\n spec: ParseSpec;\n /**\n * Stop option parsing at the first positional and pass the remainder\n * through verbatim — click's `ignore_unknown_options` +\n * `allow_interspersed_args=False`. `secret exec` needs it so the child's\n * own flags reach the child instead of being rejected as ours.\n */\n passthrough?: boolean;\n run: (deps: CommandDeps, args: ParsedArgs) => Promise<number>;\n}\n\nexport interface CommandGroup {\n summary: string;\n /** Nestable: `resource tokens list` is a group inside a group. */\n commands: Record<string, Command | CommandGroup>;\n}\n\nexport function isGroup(entry: Command | CommandGroup): entry is CommandGroup {\n return \"commands\" in entry;\n}\n\n/**\n * Read a required option, or raise click's message for its absence.\n *\n * Exit 2 rather than 1: the invocation was wrong, nothing was attempted.\n */\nexport function requireOption(args: ParsedArgs, flag: FlagSpec): string {\n const value = args.values[flag.name];\n if (value === undefined) {\n throw new CliUsageError(`Missing option ${flagLabel(flag)}.`);\n }\n return value;\n}\n\n/** Read a required positional, or raise click's `Missing argument` message. */\nexport function requireArg(args: ParsedArgs, index: number, name: string): string {\n const value = args.positionals[index];\n if (value === undefined) {\n throw new CliUsageError(`Missing argument '${name}'.`);\n }\n return value;\n}\n\n/**\n * Reject positionals a command does not take.\n *\n * Click errors on these; ignoring them would silently discard a\n * mistyped-flag-turned-positional such as `--tags foo bar`, where `bar`\n * was meant to be part of the tag list.\n */\nexport function rejectExtraArgs(args: ParsedArgs, allowed = 0): void {\n const extra = args.positionals.slice(allowed);\n if (extra.length > 0) {\n throw new CliUsageError(`Got unexpected extra argument${extra.length > 1 ? \"s\" : \"\"} (${extra.join(\" \")})`);\n }\n}\n\nconst INDENT = \" \";\n\n/** `-c, --context-id TEXT` — how click lays out an option's forms. */\nfunction renderFlag(flag: FlagSpec): string {\n // A short-only option must not advertise a long form the parser will\n // reject; `-k` is declared without one in Python.\n const forms =\n flag.shortOnly === true\n ? `-${flag.short}`\n : flag.short === undefined\n ? ` --${flag.name}`\n : `-${flag.short}, --${flag.name}`;\n if (flag.type !== \"value\" && flag.type !== \"multiple\") return forms;\n return `${forms} ${flag.metavar ?? \"TEXT\"}`;\n}\n\n/** Render `--help` for one command from its own declaration. */\nexport function renderHelp(path: string, command: Command): string {\n const lines = [`Usage: ${path} [OPTIONS]${command.args ? ` ${command.args}` : \"\"}`, \"\"];\n if (command.summary) lines.push(` ${command.summary}`, \"\");\n if (command.description) lines.push(command.description, \"\");\n\n const rendered = command.spec.flags.map((f) => [renderFlag(f), f] as const);\n const width = Math.max(24, ...rendered.map(([text]) => text.length + 2));\n\n lines.push(\"Options:\");\n for (const [text, flag] of rendered) {\n const suffix = flag.defaultLabel === undefined ? \"\" : ` [default: ${flag.defaultLabel}]`;\n const help = `${flag.help ?? \"\"}${suffix}`;\n lines.push(`${INDENT}${text.padEnd(width)}${help}`.trimEnd());\n }\n lines.push(`${INDENT}${\"--help\".padEnd(width)}Show this message and exit.`);\n return lines.join(\"\\n\");\n}\n\n/** Render the listing for a group (or the root), click-style. */\nexport function renderGroupHelp(\n path: string,\n summary: string,\n entries: Record<string, Command | CommandGroup>,\n): string {\n const names = Object.keys(entries).sort();\n const width = Math.max(10, ...names.map((n) => n.length + 2));\n const lines = [`Usage: ${path} [OPTIONS] COMMAND [ARGS]...`, \"\", ` ${summary}`, \"\", \"Commands:\"];\n for (const name of names) {\n lines.push(`${INDENT}${name.padEnd(width)}${entries[name]!.summary}`);\n }\n return lines.join(\"\\n\");\n}\n","/**\n * Output helpers shared by every `kagura-memory` subcommand.\n *\n * The Python CLI prints results with\n * `click.echo(json.dumps(result, indent=2, ensure_ascii=False))`. The two\n * serializers were compared byte-for-byte on a payload covering Japanese\n * text, an em dash, an emoji, an astral-plane character, escapes, control\n * characters, nested empty containers, null and booleans: identical\n * output. Three numeric shapes differ and cannot be reconciled because\n * they are language-level, not formatting choices:\n *\n * Python `1.0` → JS `1` (no int/float distinction)\n * Python `1e-07` → JS `1e-7`\n * integers beyond 2^53 → JS loses precision\n *\n * The last one happens at `JSON.parse` time, so it is a property of the\n * whole SDK rather than of this module.\n */\n\n/**\n * Serialize a value the way the Python CLI does.\n *\n * Total by construction: a command that cannot print its result is worse\n * than one that prints an approximation, so bigints, circular references\n * and `undefined` are handled rather than thrown on.\n */\nexport function formatJson(value: unknown): string {\n // JSON.stringify(undefined) returns the *value* `undefined`, so writing\n // its result would print the literal text \"undefined\" — not JSON, and\n // enough to break a consumer piping into jq. Python has no undefined;\n // `null` is the faithful counterpart.\n if (value === undefined) return \"null\";\n\n const seen = new WeakSet<object>();\n const replacer = (_key: string, v: unknown): unknown => {\n // JSON.stringify throws TypeError on a bigint. A server response can\n // only produce one if a caller passed it in, but a crash with a stack\n // trace is never the right answer to \"print this\".\n if (typeof v === \"bigint\") return Number(v);\n if (typeof v === \"object\" && v !== null) {\n if (seen.has(v)) return \"[Circular]\";\n seen.add(v);\n }\n return v;\n };\n\n const text = JSON.stringify(value, replacer, 2);\n // Still possible: a value that is entirely unserializable (a bare\n // function or symbol) yields undefined from JSON.stringify.\n return text === undefined ? \"null\" : text;\n}\n","/**\n * The boilerplate every data subcommand shares — a port of\n * `_run_client_command` in the Python CLI's `cli.py`.\n *\n * Config load, context resolution, client lifecycle, JSON output and\n * error-to-exit-code mapping live here so that the commands themselves are\n * one call each and cannot drift apart in how they report failure.\n */\n\nimport type { KaguraClient, KaguraClientOptions } from \"../client.js\";\nimport { loadConfig as loadConfigImpl, type KaguraConfig } from \"../config.js\";\nimport type { FilesClient } from \"../filesClient.js\";\nimport type { ResourceClient } from \"../resourceClient.js\";\nimport type { SecretClient } from \"../secrets/client.js\";\nimport { excMessage } from \"../errors.js\";\nimport { formatJson } from \"./output.js\";\nimport { CliError, CliUsageError } from \"./parse.js\";\n\n/** Verbatim from the Python CLI, so the fix instruction is identical. */\nexport const NO_CONTEXT_MESSAGE = \"context_id required. Use --context-id or set in .kagura.json\";\n\nexport interface ClientCommandContext {\n write: (line: string) => void;\n writeError: (line: string) => void;\n /** Injected so tests need no `.kagura.json` on disk. */\n loadConfig: typeof loadConfigImpl;\n /** Injected so tests can supply a fetch stub. */\n makeClient: (options: KaguraClientOptions) => KaguraClient;\n /**\n * REST counterparts, for the `files`, `resource` and `secret` groups.\n *\n * They take nothing on purpose: a REST client has to be built through\n * `fromMcpUrl`, which runs the full credential chain (env > OAuth\n * profile > .kagura.json) and stamps the MCP URL the chosen branch\n * belongs to. Bare construction throws without a static api_key — so\n * every REST command would fail for anyone who authenticated with\n * `auth login` — and leaves `resource setup` permanently broken, since\n * it needs that stamped URL.\n *\n * Python is explicit here and carries a note from its own review: pass\n * no mcp_url, so each resolver branch pairs its credential with its own\n * URL source. Forwarding the config file's mcp_url would override an\n * OAuth profile bound to a non-default server.\n */\n makeFilesClient: () => FilesClient;\n makeResourceClient: () => ResourceClient;\n makeSecretClient: () => SecretClient;\n /**\n * True when stdout is a terminal.\n *\n * The secret commands refuse to print plaintext to one; injected so a\n * test can assert both sides of that guard.\n */\n isTty: () => boolean;\n /** Read all of stdin, or null when it is a terminal / already closed. */\n readStdin: () => string | null;\n /**\n * Run a child with extra environment; resolves to its exit code.\n *\n * `unset` names variables to REMOVE from the inherited environment. It\n * exists for the age identity: a tool handed one secret through `--as`\n * must not also receive the key that decrypts every other secret.\n */\n spawnChild: (\n command: string,\n argv: string[],\n env: Record<string, string>,\n unset: readonly string[],\n ) => Promise<number>;\n}\n\n/**\n * Resolve config + context the way `_run_client_command` does, without\n * building an MCP client — the REST groups need the same front half.\n *\n * @throws CliError with the Python message when no context resolves.\n */\nexport function resolveConfig(\n ctx: ClientCommandContext,\n contextId: string | undefined,\n needsContext = true,\n): { config: KaguraConfig; contextId: string } {\n let config: KaguraConfig;\n try {\n config = ctx.loadConfig();\n } catch (e) {\n // A malformed .kagura.json is a real failure; reporting it here beats\n // letting it surface later as an unrelated auth error.\n throw new CliError(excMessage(e));\n }\n if (!needsContext) return { config, contextId: \"\" };\n\n // Python: `context_id or config.get(\"context_id\") or \"\"`. An empty\n // string is falsy there, so `--context-id=` falls through to the config\n // rather than being sent as a blank context.\n const resolved = contextId || config.context_id || \"\";\n if (!resolved) throw new CliError(NO_CONTEXT_MESSAGE);\n return { config, contextId: resolved };\n}\n\n/**\n * The MCP-client options a config produces.\n *\n * Only the MCP client takes options: the REST clients go through\n * `fromMcpUrl`, which resolves everything itself. This one needs\n * `mcp_url` explicitly, and forgetting it silently drops a self-hosted\n * server and sends the call to the default cloud one.\n */\nexport function mcpOptions(config: KaguraConfig): KaguraClientOptions {\n // Python: `api_key=config.get(\"api_key\") or None`. An empty value must be\n // omitted, not forwarded — `Authorization: Bearer ` always 401s, and\n // omitting lets the OAuth profile resolve instead.\n const options: KaguraClientOptions = {};\n if (config.api_key) options.apiKey = config.api_key;\n if (config.mcp_url) options.mcpUrl = config.mcp_url;\n return options;\n}\n\n/**\n * Run an operation and print its result, mapping failures the same way\n * `runClientCommand` does. For commands that build their own client.\n */\nexport async function runAndPrint(\n ctx: ClientCommandContext,\n operation: () => Promise<unknown>,\n): Promise<number> {\n try {\n const result = await operation();\n ctx.write(formatJson(result));\n return 0;\n } catch (e) {\n throw e instanceof CliError || e instanceof CliUsageError ? e : new CliError(excMessage(e));\n }\n}\n\nexport interface RunClientCommandOptions {\n /**\n * `false` for commands that operate on the workspace rather than one\n * context (`list_contexts`, `get_usage`, …), matching the Python\n * helper's `needs_context` keyword.\n */\n needsContext?: boolean;\n}\n\n/**\n * Run one client operation and print it.\n *\n * @returns 0, with the result printed as JSON on stdout.\n * @throws CliError for every expected failure. Reporting is the router's\n * job so the `Error: ` prefix and the exit code are decided in exactly\n * one place; Kagura errors carry their own next-step guidance and are\n * forwarded verbatim rather than as a stack trace.\n */\nexport async function runClientCommand(\n ctx: ClientCommandContext,\n contextId: string | undefined,\n operation: (client: KaguraClient, contextId: string) => Promise<unknown>,\n options: RunClientCommandOptions = {},\n): Promise<number> {\n const { config, contextId: resolvedContext } = resolveConfig(\n ctx,\n contextId,\n options.needsContext ?? true,\n );\n\n const client = ctx.makeClient(mcpOptions(config));\n try {\n const result = await operation(client, resolvedContext);\n ctx.write(formatJson(result));\n return 0;\n } catch (e) {\n throw e instanceof CliError || e instanceof CliUsageError ? e : new CliError(excMessage(e));\n } finally {\n // The Python helper uses `async with client:`; a leaked MCP session\n // keeps the process alive past the command.\n await client.close();\n }\n}\n","/**\n * `kagura-memory context …` plus the `contexts` and `config` groups.\n *\n * Two shapes here differ from every other group and are easy to get wrong:\n *\n * - the context id is a **positional** argument, not `-c/--context-id`,\n * and there is no `.kagura.json` fallback for it;\n * - `context create --public` is inverted on the wire (`is_private = not\n * public`), so omitting it creates a *private* context.\n */\n\nimport { requireArg, requireOption, rejectExtraArgs, type Command, type CommandGroup } from \"../command.js\";\nimport { formatJson } from \"../output.js\";\nimport { CliError, pairedFlag, parseChoice, parseRanged } from \"../parse.js\";\nimport type { FlagSpec } from \"../parseArgs.js\";\nimport { runClientCommand } from \"../runClientCommand.js\";\n\nconst NAME: FlagSpec = {\n name: \"name\",\n short: \"n\",\n type: \"value\",\n help: \"Context name (lowercase, hyphens, underscores)\",\n};\nconst DISPLAY_NAME: FlagSpec = { name: \"display-name\", type: \"value\", help: \"Human-readable display name\" };\nconst DESCRIPTION: FlagSpec = { name: \"description\", short: \"d\", type: \"value\", help: \"Context description\" };\nconst SUMMARY: FlagSpec = {\n name: \"summary\",\n short: \"s\",\n type: \"value\",\n help: \"LLM-oriented summary (200-500 chars)\",\n};\nconst USAGE_GUIDE: FlagSpec = { name: \"usage-guide\", type: \"value\", help: \"LLM-oriented usage guidelines\" };\nconst YES: FlagSpec = { name: \"yes\", short: \"y\", type: \"switch\", help: \"Skip confirmation prompt\" };\n\nconst list: Command = {\n summary: \"List available contexts.\",\n spec: { flags: [] },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n return runClientCommand(deps, undefined, (client) => client.listContexts(), {\n needsContext: false,\n });\n },\n};\n\nconst create: Command = {\n summary: \"Create a new context.\",\n spec: {\n flags: [\n { ...NAME, required: true },\n DISPLAY_NAME,\n DESCRIPTION,\n SUMMARY,\n USAGE_GUIDE,\n { name: \"public\", type: \"switch\", help: \"Accessible to workspace members\" },\n ],\n },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const name = requireOption(args, NAME);\n const displayName = args.values[\"display-name\"];\n const description = args.values.description;\n const summary = args.values.summary;\n const usageGuide = args.values[\"usage-guide\"];\n return runClientCommand(\n deps,\n undefined,\n (client) =>\n client.createContext({\n name,\n ...(displayName !== undefined ? { displayName } : {}),\n ...(description !== undefined ? { description } : {}),\n ...(summary !== undefined ? { summary } : {}),\n ...(usageGuide !== undefined ? { usageGuide } : {}),\n // Inverted: the flag says \"public\", the wire field says private.\n isPrivate: !args.flags.has(\"public\"),\n }),\n { needsContext: false },\n );\n },\n};\n\nconst deleteContext: Command = {\n summary: \"Soft-delete a context and all its memories.\",\n args: \"CONTEXT_ID\",\n spec: { flags: [YES] },\n run: async (deps, args) => {\n const contextId = requireArg(args, 0, \"CONTEXT_ID\");\n rejectExtraArgs(args, 1);\n if (!args.flags.has(\"yes\") && !(await deps.confirm(`Delete context ${contextId}?`))) {\n throw new CliError(\"Aborted!\");\n }\n return runClientCommand(deps, undefined, (client) => client.deleteContext(contextId), {\n needsContext: false,\n });\n },\n};\n\nconst update: Command = {\n summary: \"Update a context's settings.\",\n args: \"CONTEXT_ID\",\n spec: {\n flags: [\n { ...DISPLAY_NAME, help: \"Updated display name\" },\n { ...DESCRIPTION, help: \"Updated description\" },\n { ...SUMMARY, help: \"Updated LLM-oriented summary\" },\n { ...USAGE_GUIDE, help: \"Updated LLM-oriented usage guidelines\" },\n { name: \"lock\", type: \"switch\", help: \"Lock the context (no writes)\" },\n { name: \"unlock\", type: \"switch\", help: \"Unlock the context\" },\n ],\n },\n run: async (deps, args) => {\n const contextId = requireArg(args, 0, \"CONTEXT_ID\");\n rejectExtraArgs(args, 1);\n const displayName = args.values[\"display-name\"];\n const description = args.values.description;\n const summary = args.values.summary;\n const usageGuide = args.values[\"usage-guide\"];\n const isLocked = pairedFlag(args.flags.has(\"lock\"), args.flags.has(\"unlock\"), [\n \"--lock\",\n \"--unlock\",\n ]);\n const patch = {\n ...(displayName !== undefined ? { displayName } : {}),\n ...(description !== undefined ? { description } : {}),\n ...(summary !== undefined ? { summary } : {}),\n ...(usageGuide !== undefined ? { usageGuide } : {}),\n ...(isLocked !== undefined ? { isLocked } : {}),\n };\n if (Object.keys(patch).length === 0) {\n // ClickException in Python: exit 1, not the usage code.\n throw new CliError(\"At least one update option is required\");\n }\n return runClientCommand(\n deps,\n undefined,\n (client) => client.updateContext({ contextId, ...patch }),\n { needsContext: false },\n );\n },\n};\n\nconst SEMANTIC: FlagSpec = {\n name: \"semantic\",\n type: \"value\",\n metavar: \"FLOAT\",\n help: \"Semantic weight (0.0-1.0)\",\n};\nconst BM25: FlagSpec = { name: \"bm25\", type: \"value\", metavar: \"FLOAT\", help: \"BM25 weight (0.0-1.0)\" };\nconst FETCH_FACTOR: FlagSpec = {\n name: \"fetch-factor\",\n type: \"value\",\n metavar: \"INTEGER\",\n help: \"Fetch multiplier (1-10)\",\n};\nconst RERANKER: FlagSpec = {\n name: \"reranker\",\n type: \"value\",\n metavar: \"[voyage|cohere]\",\n help: \"Reranker provider\",\n};\n\nconst searchConfig: Command = {\n summary: \"Update search configuration for a context.\",\n args: \"CONTEXT_ID\",\n spec: {\n flags: [\n SEMANTIC,\n BM25,\n FETCH_FACTOR,\n { name: \"rerank\", type: \"switch\", help: \"Enable reranking\" },\n { name: \"no-rerank\", type: \"switch\", help: \"Disable reranking\" },\n RERANKER,\n { name: \"reranker-model\", type: \"value\", help: \"Reranker model name\" },\n ],\n },\n run: async (deps, args) => {\n const contextId = requireArg(args, 0, \"CONTEXT_ID\");\n rejectExtraArgs(args, 1);\n\n const ranged = (flag: FlagSpec, min: number, max: number, label: string, integer = false) => {\n const raw = args.values[flag.name];\n return raw === undefined\n ? undefined\n : parseRanged(flag, raw, { min, max, rangeLabel: label, integer });\n };\n const semanticWeight = ranged(SEMANTIC, 0, 1, \"0.0<=x<=1.0\");\n const bm25Weight = ranged(BM25, 0, 1, \"0.0<=x<=1.0\");\n const fetchFactor = ranged(FETCH_FACTOR, 1, 10, \"1<=x<=10\", true);\n const useRerank = pairedFlag(args.flags.has(\"rerank\"), args.flags.has(\"no-rerank\"), [\n \"--rerank\",\n \"--no-rerank\",\n ]);\n const rawReranker = args.values.reranker;\n const rerankerProvider =\n rawReranker === undefined ? undefined : parseChoice(RERANKER, rawReranker, [\"voyage\", \"cohere\"]);\n const rerankerModel = args.values[\"reranker-model\"];\n\n const patch = {\n ...(semanticWeight !== undefined ? { semanticWeight } : {}),\n ...(bm25Weight !== undefined ? { bm25Weight } : {}),\n ...(fetchFactor !== undefined ? { fetchFactor } : {}),\n ...(useRerank !== undefined ? { useRerank } : {}),\n ...(rerankerProvider !== undefined ? { rerankerProvider } : {}),\n ...(rerankerModel !== undefined ? { rerankerModel } : {}),\n };\n if (Object.keys(patch).length === 0) {\n throw new CliError(\"At least one option is required\");\n }\n // Both weights given must sum to 1.0; the server rejects otherwise, but\n // saying so locally saves a round trip and names both numbers.\n if (semanticWeight !== undefined && bm25Weight !== undefined) {\n const sum = semanticWeight + bm25Weight;\n if (Math.abs(sum - 1) > 1e-9) {\n throw new CliError(\n `Weights must sum to 1.0 (got ${semanticWeight} + ${bm25Weight} = ${sum})`,\n );\n }\n }\n\n return runClientCommand(\n deps,\n undefined,\n (client) => client.updateSearchConfig({ contextId, ...patch }),\n { needsContext: false },\n );\n },\n};\n\nexport const CONTEXT_GROUP: CommandGroup = {\n summary: \"Manage contexts (list, create, update).\",\n commands: {\n list,\n create,\n delete: deleteContext,\n update,\n \"search-config\": searchConfig,\n },\n};\n\n/** `kagura contexts` — the backward-compatible alias for `context list`. */\nexport const CONTEXTS_ALIAS: Command = {\n ...list,\n summary: \"List available contexts (alias for 'context list').\",\n};\n\n/**\n * `kagura config show`.\n *\n * The only command in the CLI that touches no network and no credentials.\n */\nconst configShow: Command = {\n summary: \"Show current configuration.\",\n spec: { flags: [] },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n let config;\n try {\n config = deps.loadConfig();\n } catch (e) {\n // Python prints \"Error loading config: …\" here rather than click's\n // \"Error: \" — the one place in the CLI with its own prefix.\n throw new CliError(`loading config: ${e instanceof Error ? e.message : String(e)}`);\n }\n const shown: Record<string, unknown> = { ...config };\n if (typeof config.api_key === \"string\" && config.api_key) {\n shown.api_key = maskKey(config.api_key);\n }\n deps.write(formatJson(shown));\n return 0;\n },\n};\n\n/**\n * Mask an API key for display.\n *\n * Python slices `key[:8] + \"...\" + key[-4:]`, whose halves *overlap* for\n * anything shorter than 12 characters — `\"abc\"` renders as `\"abc...abc\"`,\n * printing the whole secret twice. That is not reproduced: a mask that\n * echoes its input is not a mask, and the divergence is only visible for\n * keys too short to be real.\n */\nfunction maskKey(key: string): string {\n if (key.length < 12) return \"***\";\n return `${key.slice(0, 8)}...${key.slice(-4)}`;\n}\n\nexport const CONFIG_GROUP: CommandGroup = {\n summary: \"Manage configuration.\",\n commands: { show: configShow },\n};\n","/**\n * `kagura-memory doctor` — diagnose setup, auth, MCP and connectivity.\n *\n * Structure is a port of `doctor.py`: a flat list of checks, each tagged\n * with a section and a status, rendered one per line as `STATUS message`,\n * or as JSON with `--json`. Exit is 1 if any check failed; warnings never\n * affect it.\n *\n * Two of Python's sections have no counterpart here and are reported as\n * such rather than faked: `llm` and `security` inspect litellm and the\n * provider API keys used by `KaguraAgent`, which this SDK does not ship.\n */\n\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { defaultCredentialsPath, loadCredentialsFile, isExpired } from \"../../auth/credentials.js\";\nimport type { KaguraConfig } from \"../../config.js\";\nimport { rejectExtraArgs, type Command, type CommandDeps } from \"../command.js\";\nimport { formatJson } from \"../output.js\";\nimport type { FlagSpec } from \"../parseArgs.js\";\nimport { mcpOptions } from \"../runClientCommand.js\";\n\ntype Status = \"pass\" | \"warn\" | \"fail\" | \"info\";\n\ninterface DoctorCheck {\n section: string;\n status: Status;\n message: string;\n details?: Record<string, unknown>;\n}\n\n/** Python's `_STATUS_ORDER`; a section takes its worst check's status. */\nconst STATUS_ORDER: Record<Status, number> = { fail: 3, warn: 2, pass: 1, info: 0 };\n\nconst PROFILE: FlagSpec = { name: \"profile\", type: \"value\", help: \"OAuth profile to inspect\" };\nconst JSON_FLAG: FlagSpec = { name: \"json\", type: \"switch\", help: \"Emit machine-readable JSON\" };\n\nfunction checkAuth(deps: CommandDeps, profile: string | undefined): DoctorCheck[] {\n const checks: DoctorCheck[] = [];\n const credsPath = defaultCredentialsPath();\n\n if (!fs.existsSync(credsPath)) {\n checks.push({\n section: \"auth\",\n status: \"warn\",\n message: `no credentials file at ${credsPath}; run: kagura-memory auth login`,\n });\n } else {\n let file;\n try {\n file = loadCredentialsFile(credsPath);\n } catch (e) {\n checks.push({\n section: \"auth\",\n status: \"fail\",\n message: `credentials file is unreadable: ${e instanceof Error ? e.message : String(e)}`,\n });\n file = undefined;\n }\n if (file !== undefined) {\n const names = Object.keys(file.profiles);\n if (names.length === 0) {\n checks.push({ section: \"auth\", status: \"warn\", message: \"credentials file has no profiles\" });\n } else {\n const target = profile ?? file.defaultProfile;\n const creds = file.profiles[target];\n if (creds === undefined) {\n checks.push({\n section: \"auth\",\n status: \"fail\",\n message: `no profile named '${target}'; available: ${names.sort().join(\", \")}`,\n });\n } else if (!isExpired(creds)) {\n checks.push({\n section: \"auth\",\n status: \"pass\",\n message: `profile '${target}' is active until ${creds.expiresAt.toISOString()}`,\n details: { workspace: creds.workspaceName || creds.workspaceId || null },\n });\n } else if (creds.refreshToken) {\n checks.push({\n section: \"auth\",\n status: \"warn\",\n message: `profile '${target}' has expired but can refresh`,\n });\n } else {\n checks.push({\n section: \"auth\",\n status: \"fail\",\n message: `profile '${target}' has expired and has no refresh token; run: kagura-memory auth login`,\n });\n }\n if (names.length > 1 && profile === undefined) {\n // The SDK warns about this at construction time too; saying it\n // here is what makes \"why did it write to the wrong workspace\"\n // answerable before the fact.\n checks.push({\n section: \"auth\",\n status: \"warn\",\n message: `${names.length} profiles configured and none selected; the default '${file.defaultProfile}' is implicit`,\n });\n }\n }\n }\n }\n\n const envKey = process.env.KAGURA_API_KEY;\n if (envKey !== undefined && envKey.trim()) {\n // The env var beats every OAuth profile, which surprises people who\n // just ran `auth login` and still reach the wrong workspace.\n checks.push({\n section: \"auth\",\n status: \"warn\",\n message: \"KAGURA_API_KEY is set and takes precedence over any OAuth profile\",\n });\n }\n\n const config = safeConfig(deps);\n if (typeof config?.api_key === \"string\" && config.api_key.trim()) {\n checks.push({\n section: \"auth\",\n status: \"info\",\n message: \".kagura.json carries an api_key (used only when no env key and no profile resolve)\",\n });\n }\n return checks;\n}\n\nfunction safeConfig(deps: CommandDeps): Record<string, unknown> | null {\n try {\n return deps.loadConfig() as unknown as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\nfunction checkMcp(deps: CommandDeps): DoctorCheck[] {\n const checks: DoctorCheck[] = [];\n const config = safeConfig(deps);\n const url = typeof config?.mcp_url === \"string\" ? config.mcp_url : \"\";\n if (url) {\n // A plaintext MCP URL means the bearer token crosses the wire in the\n // clear; localhost is the one place that is a deliberate dev choice.\n const isLocal = /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|\\[::1\\])(:|\\/|$)/.test(url);\n if (url.startsWith(\"https://\") || isLocal) {\n checks.push({ section: \"mcp\", status: \"pass\", message: `mcp_url is ${url}` });\n } else {\n checks.push({\n section: \"mcp\",\n status: \"fail\",\n message: `mcp_url is not HTTPS: ${url} — credentials would be sent in the clear`,\n });\n }\n } else {\n checks.push({ section: \"mcp\", status: \"info\", message: \"no mcp_url configured; the default is used\" });\n }\n\n const mcpJson = path.join(process.cwd(), \".mcp.json\");\n if (!fs.existsSync(mcpJson)) {\n checks.push({ section: \"mcp\", status: \"info\", message: \"no .mcp.json in this directory\" });\n return checks;\n }\n try {\n const parsed = JSON.parse(fs.readFileSync(mcpJson, \"utf-8\")) as {\n mcpServers?: Record<string, unknown>;\n };\n const entry = parsed.mcpServers?.[\"kagura-memory\"];\n if (entry === undefined) {\n checks.push({\n section: \"mcp\",\n status: \"warn\",\n message: \".mcp.json has no 'kagura-memory' server; run: kagura-memory setup claude\",\n });\n } else {\n checks.push({ section: \"mcp\", status: \"pass\", message: \".mcp.json configures kagura-memory\" });\n }\n } catch (e) {\n checks.push({\n section: \"mcp\",\n status: \"fail\",\n message: `.mcp.json is not valid JSON: ${e instanceof Error ? e.message : String(e)}`,\n });\n }\n return checks;\n}\n\nasync function checkExtras(): Promise<DoctorCheck[]> {\n try {\n await import(\"age-encryption\");\n return [\n { section: \"extras\", status: \"pass\", message: \"age-encryption is installed; `secret` commands are available\" },\n ];\n } catch {\n return [\n {\n section: \"extras\",\n status: \"info\",\n message:\n \"age-encryption is not installed; `secret` commands need it (npm install age-encryption)\",\n },\n ];\n }\n}\n\nfunction checkKeyCustody(): DoctorCheck[] {\n const inline = process.env.KAGURA_AGE_IDENTITY?.trim();\n const file = process.env.KAGURA_AGE_IDENTITY_FILE?.trim();\n if (!inline && !file) {\n return [\n {\n section: \"security\",\n status: \"info\",\n message:\n \"no age identity configured (KAGURA_AGE_IDENTITY / KAGURA_AGE_IDENTITY_FILE); secret decryption is unavailable\",\n },\n ];\n }\n if (inline) {\n // The value lives in the process environment, which is visible to\n // anything that can read /proc or run `ps e` as the same user.\n return [\n {\n section: \"security\",\n status: \"warn\",\n message: \"KAGURA_AGE_IDENTITY holds the private key in the environment; a file is safer\",\n },\n ];\n }\n const checks: DoctorCheck[] = [];\n try {\n const stat = fs.statSync(file!);\n // Mode bits are meaningless on Windows, so only report where they are.\n if (os.platform() !== \"win32\" && (stat.mode & 0o077) !== 0) {\n checks.push({\n section: \"security\",\n status: \"fail\",\n message: `${file} is readable by others (mode ${(stat.mode & 0o777).toString(8)}); chmod 600 it`,\n });\n } else {\n checks.push({ section: \"security\", status: \"pass\", message: `age identity file present: ${file}` });\n }\n } catch {\n checks.push({ section: \"security\", status: \"fail\", message: `KAGURA_AGE_IDENTITY_FILE is unreadable: ${file}` });\n }\n return checks;\n}\n\nasync function checkServer(deps: CommandDeps): Promise<DoctorCheck[]> {\n const clientOptions = mcpOptions((safeConfig(deps) ?? {}) as KaguraConfig);\n\n // Construction is inside the try because it validates the URL and can\n // throw — and a check whose job is to *report* a bad URL must not be the\n // thing that dies on one.\n let client;\n try {\n client = deps.makeClient(clientOptions);\n } catch (e) {\n return [\n {\n section: \"server\",\n status: \"fail\",\n message: `cannot build a client: ${e instanceof Error ? e.message : String(e)}`,\n },\n ];\n }\n try {\n const info = await client.getServerInfo();\n return [\n {\n section: \"server\",\n status: \"pass\",\n message: `server reachable (version ${info.version ?? \"unknown\"})`,\n details: info as unknown as Record<string, unknown>,\n },\n ];\n } catch (e) {\n return [\n {\n section: \"server\",\n status: \"fail\",\n message: `cannot reach the server: ${e instanceof Error ? e.message : String(e)}`,\n },\n ];\n } finally {\n await client.close();\n }\n}\n\nexport const DOCTOR: Command = {\n summary: \"Diagnose common setup, auth, MCP, and connectivity issues.\",\n spec: { flags: [PROFILE, JSON_FLAG] },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const checks: DoctorCheck[] = [\n ...checkAuth(deps, args.values.profile),\n ...checkMcp(deps),\n ...(await checkExtras()),\n ...checkKeyCustody(),\n {\n section: \"llm\",\n status: \"info\",\n message: \"this SDK ships no LLM layer; `process` and `ingest` live in the Python package\",\n },\n ...(await checkServer(deps)),\n ];\n\n // Section status is the worst of its checks.\n const sections: Record<string, Status> = {};\n for (const check of checks) {\n const current = sections[check.section];\n if (current === undefined || STATUS_ORDER[check.status] > STATUS_ORDER[current]) {\n sections[check.section] = check.status;\n }\n }\n const exitCode = checks.some((c) => c.status === \"fail\") ? 1 : 0;\n\n if (args.flags.has(\"json\")) {\n // Python's to_dict() also spreads each section as a TOP-LEVEL key.\n // It reads like a bug, but a script written against the Python CLI\n // reads those keys, so the shape is reproduced rather than tidied.\n deps.write(formatJson({ sections, checks, exit_code: exitCode, ...sections }));\n } else {\n for (const check of checks) {\n deps.write(`${check.status.toUpperCase()} ${check.message}`);\n }\n }\n return exitCode;\n },\n};\n","/**\n * `kagura-memory files …` — R2 uploads with sha256 integrity binding.\n *\n * These are REST rather than MCP, so they take the shared config front\n * half (`resolveConfig`) and build a `FilesClient` instead of a\n * `KaguraClient`. Note the two different context ids: `--context-id` is\n * the *workspace*, `--binding-context-id` is the owning context used for\n * access control.\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { requireArg, rejectExtraArgs, type Command, type CommandGroup } from \"../command.js\";\nimport { CliUsageError, parseRanged, parseTags } from \"../parse.js\";\nimport type { FlagSpec } from \"../parseArgs.js\";\nimport { mcpOptions, resolveConfig, runAndPrint } from \"../runClientCommand.js\";\n\nconst CONTEXT_ID: FlagSpec = {\n name: \"context-id\",\n short: \"c\",\n type: \"value\",\n help: \"Context (workspace) UUID\",\n};\n\nconst IMPORTANCE: FlagSpec = {\n name: \"importance\",\n type: \"value\",\n metavar: \"FLOAT\",\n help: \"Importance 0.0-1.0 for --remember\",\n defaultLabel: \"0.5\",\n};\n\nconst upload: Command = {\n summary: \"Upload a file to Kagura Memory Cloud.\",\n args: \"PATH\",\n description:\n \" With --remember, also creates one summary memory linked to the\\n\" +\n \" uploaded file object. No LLM is involved: the summary is either the\\n\" +\n \" one you pass or is derived from the filename.\",\n spec: {\n flags: [\n { ...CONTEXT_ID, help: \"Target context (workspace) UUID\" },\n { name: \"content-type\", short: \"t\", type: \"value\", help: \"MIME type override (default: sniffed)\" },\n {\n name: \"binding-context-id\",\n type: \"value\",\n help: \"Owning context UUID to bind the file to for access control\",\n },\n {\n name: \"remember\",\n type: \"switch\",\n help: \"Also create a summary memory linked to the file (no LLM)\",\n },\n { name: \"summary\", type: \"value\", help: \"Summary for --remember (default: from the filename)\" },\n { name: \"type\", type: \"value\", help: \"Memory type for --remember\", defaultLabel: \"note\" },\n IMPORTANCE,\n { name: \"tags\", type: \"value\", help: \"Comma-separated tags for --remember\" },\n ],\n },\n run: async (deps, args) => {\n const source = requireArg(args, 0, \"PATH\");\n rejectExtraArgs(args, 1);\n\n // Click declares `click.Path(exists=True, dir_okay=False)`, so the\n // check runs before anything else and reads as a usage error.\n let stat: fs.Stats;\n try {\n stat = fs.statSync(source);\n } catch {\n throw new CliUsageError(\n `Invalid value for 'PATH': Path '${source}' does not exist.`,\n );\n }\n if (stat.isDirectory()) {\n throw new CliUsageError(`Invalid value for 'PATH': Path '${source}' is a directory.`);\n }\n\n const rawImportance = args.values.importance;\n const importance =\n rawImportance === undefined\n ? 0.5\n : parseRanged(IMPORTANCE, rawImportance, { min: 0, max: 1, rangeLabel: \"0.0<=x<=1.0\" });\n\n const { config, contextId } = resolveConfig(deps, args.values[\"context-id\"]);\n const contentType = args.values[\"content-type\"];\n const bindingContextId = args.values[\"binding-context-id\"];\n const wantsMemory = args.flags.has(\"remember\");\n const summary = args.values.summary ?? `File: ${path.basename(source)}`;\n const memoryType = args.values.type ?? \"note\";\n const tags = parseTags(args.values.tags);\n\n return runAndPrint(deps, async () => {\n const files = deps.makeFilesClient();\n const uploaded = await files.upload({\n contextId,\n source,\n ...(contentType !== undefined ? { contentType } : {}),\n ...(bindingContextId !== undefined ? { bindingContextId } : {}),\n });\n if (!wantsMemory) return uploaded;\n\n // The memory is a second, separate call; a failure here must not\n // read as \"the upload failed\", so it names itself.\n const client = deps.makeClient(mcpOptions(config));\n try {\n const memory = await client.remember({\n contextId,\n summary,\n content: `Uploaded file ${uploaded.filename} (${uploaded.size_bytes} bytes, ${uploaded.content_type}).`,\n type: memoryType,\n importance,\n ...(tags ? { tags } : {}),\n details: { file_id: uploaded.id },\n });\n return { file: uploaded, memory };\n } finally {\n await client.close();\n }\n });\n },\n};\n\nconst LIMIT: FlagSpec = {\n name: \"limit\",\n short: \"l\",\n type: \"value\",\n metavar: \"INTEGER\",\n help: \"Max results (1-500)\",\n defaultLabel: \"50\",\n};\n\nconst list: Command = {\n summary: \"List uploaded files in a context, newest first.\",\n spec: {\n flags: [\n { ...CONTEXT_ID, help: \"Context (workspace) UUID to list\" },\n LIMIT,\n { name: \"cursor\", type: \"value\", help: \"Forward-compat cursor (server v0.16+)\" },\n ],\n },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const raw = args.values.limit;\n const limit =\n raw === undefined\n ? 50\n : parseRanged(LIMIT, raw, { min: 1, max: 500, rangeLabel: \"1<=x<=500\", integer: true });\n const cursor = args.values.cursor;\n const { config, contextId } = resolveConfig(deps, args.values[\"context-id\"]);\n return runAndPrint(deps, () =>\n deps\n .makeFilesClient()\n .list({ contextId, limit, ...(cursor !== undefined ? { cursor } : {}) }),\n );\n },\n};\n\nconst deleteFile: Command = {\n summary: \"Soft-delete a file by id.\",\n args: \"FILE_ID\",\n spec: { flags: [{ ...CONTEXT_ID, help: \"Context (workspace) UUID the file belongs to\" }] },\n run: async (deps, args) => {\n const fileId = requireArg(args, 0, \"FILE_ID\");\n rejectExtraArgs(args, 1);\n const { config, contextId } = resolveConfig(deps, args.values[\"context-id\"]);\n return runAndPrint(deps, async () => {\n await deps.makeFilesClient().delete(fileId, { contextId });\n // The REST call returns 204; Python prints the same confirmation\n // rather than an empty line.\n return { status: \"success\", file_id: fileId };\n });\n },\n};\n\nconst downloadUrl: Command = {\n summary: \"Print a short-lived presigned GET URL for a file.\",\n args: \"FILE_ID\",\n spec: { flags: [{ ...CONTEXT_ID, help: \"Context (workspace) UUID the file belongs to\" }] },\n run: async (deps, args) => {\n const fileId = requireArg(args, 0, \"FILE_ID\");\n rejectExtraArgs(args, 1);\n const { config, contextId } = resolveConfig(deps, args.values[\"context-id\"]);\n return runAndPrint(deps, () =>\n deps.makeFilesClient().downloadUrl(fileId, { contextId }),\n );\n },\n};\n\nexport const FILES_GROUP: CommandGroup = {\n summary: \"Upload, list, and manage files in Kagura Memory Cloud.\",\n commands: { upload, list, delete: deleteFile, \"download-url\": downloadUrl },\n};\n","/**\n * `kagura-memory edge …` and `kagura-memory sleep …`.\n *\n * Both take the context id as a **positional**, with no `.kagura.json`\n * fallback — these commands name every id they touch explicitly, because\n * an edge or a rollback aimed at the wrong context is not recoverable by\n * re-running with the right one.\n */\n\nimport { requireArg, rejectExtraArgs, type Command, type CommandGroup } from \"../command.js\";\nimport { CliError, parseFloatOption, parseIntOption, parseRanged, parseTags } from \"../parse.js\";\nimport type { FlagSpec, ParsedArgs } from \"../parseArgs.js\";\nimport { runClientCommand } from \"../runClientCommand.js\";\n\nconst YES: FlagSpec = { name: \"yes\", short: \"y\", type: \"switch\", help: \"Skip confirmation prompt\" };\n\nconst MIN_WEIGHT: FlagSpec = {\n name: \"min-weight\",\n type: \"value\",\n metavar: \"FLOAT\",\n help: \"Minimum edge weight (0.0-3.0)\",\n defaultLabel: \"0.0\",\n};\nconst EDGE_TYPES: FlagSpec = {\n name: \"type\",\n type: \"value\",\n help: \"Comma-separated edge types to filter (e.g. 'related_to,depends_on')\",\n};\nconst LIMIT: FlagSpec = {\n name: \"limit\",\n type: \"value\",\n metavar: \"INTEGER\",\n help: \"Max edges per direction (effective max: 2x limit, dedup'd)\",\n};\n\nfunction optionalFloat(args: ParsedArgs, flag: FlagSpec): number | undefined {\n const raw = args.values[flag.name];\n return raw === undefined ? undefined : parseFloatOption(flag, raw);\n}\n\nconst edgeList: Command = {\n summary: \"List edges connected to a memory.\",\n args: \"CONTEXT_ID MEMORY_ID\",\n spec: { flags: [MIN_WEIGHT, EDGE_TYPES, LIMIT] },\n run: async (deps, args) => {\n const contextId = requireArg(args, 0, \"CONTEXT_ID\");\n const memoryId = requireArg(args, 1, \"MEMORY_ID\");\n rejectExtraArgs(args, 2);\n // Click's default is 0.0, not None, so this is always on the wire.\n const minWeight = optionalFloat(args, MIN_WEIGHT) ?? 0;\n const edgeTypes = parseTags(args.values.type);\n const rawLimit = args.values.limit;\n const limit = rawLimit === undefined ? undefined : parseIntOption(LIMIT, rawLimit);\n return runClientCommand(\n deps,\n undefined,\n (client) =>\n client.listEdges({\n contextId,\n memoryId,\n minWeight,\n ...(edgeTypes ? { edgeTypes } : {}),\n ...(limit !== undefined ? { limit } : {}),\n }),\n { needsContext: false },\n );\n },\n};\n\nconst EDGE_TYPE: FlagSpec = { name: \"type\", type: \"value\", help: \"Edge type\", defaultLabel: \"related_to\" };\nconst WEIGHT: FlagSpec = {\n name: \"weight\",\n type: \"value\",\n metavar: \"FLOAT\",\n help: \"Edge weight 0.0-3.0\",\n defaultLabel: \"0.5\",\n};\nconst CONFIDENCE: FlagSpec = {\n name: \"confidence\",\n type: \"value\",\n metavar: \"FLOAT\",\n help: \"Edge confidence 0.0-1.0\",\n defaultLabel: \"1.0\",\n};\n\nconst edgeCreate: Command = {\n summary: \"Create or upsert an edge from SOURCE_ID to TARGET_ID.\",\n args: \"CONTEXT_ID SOURCE_ID TARGET_ID\",\n spec: { flags: [EDGE_TYPE, WEIGHT, CONFIDENCE] },\n run: async (deps, args) => {\n const contextId = requireArg(args, 0, \"CONTEXT_ID\");\n const sourceId = requireArg(args, 1, \"SOURCE_ID\");\n const targetId = requireArg(args, 2, \"TARGET_ID\");\n rejectExtraArgs(args, 3);\n const edgeType = args.values.type ?? \"related_to\";\n const weight = optionalFloat(args, WEIGHT) ?? 0.5;\n const confidence = optionalFloat(args, CONFIDENCE) ?? 1;\n return runClientCommand(\n deps,\n undefined,\n (client) => client.createEdge({ contextId, sourceId, targetId, edgeType, weight, confidence }),\n { needsContext: false },\n );\n },\n};\n\nconst edgeUpdate: Command = {\n summary: \"Update an existing edge's weight and/or type.\",\n args: \"CONTEXT_ID SOURCE_ID TARGET_ID\",\n spec: {\n flags: [\n { ...WEIGHT, help: \"New edge weight 0.0-3.0\", defaultLabel: undefined },\n { ...EDGE_TYPE, help: \"New edge type\", defaultLabel: undefined },\n ],\n },\n run: async (deps, args) => {\n const contextId = requireArg(args, 0, \"CONTEXT_ID\");\n const sourceId = requireArg(args, 1, \"SOURCE_ID\");\n const targetId = requireArg(args, 2, \"TARGET_ID\");\n rejectExtraArgs(args, 3);\n const weight = optionalFloat(args, WEIGHT);\n const edgeType = args.values.type;\n if (weight === undefined && edgeType === undefined) {\n // ClickException, so exit 1 rather than the usage code — pinned by\n // the Python suite.\n throw new CliError(\"At least one of --weight or --type must be provided\");\n }\n return runClientCommand(\n deps,\n undefined,\n (client) =>\n client.updateEdge({\n contextId,\n sourceId,\n targetId,\n ...(weight !== undefined ? { weight } : {}),\n ...(edgeType !== undefined ? { edgeType } : {}),\n }),\n { needsContext: false },\n );\n },\n};\n\nconst edgeDelete: Command = {\n summary: \"Delete the edge between SOURCE_ID and TARGET_ID.\",\n args: \"CONTEXT_ID SOURCE_ID TARGET_ID\",\n spec: { flags: [YES] },\n run: async (deps, args) => {\n const contextId = requireArg(args, 0, \"CONTEXT_ID\");\n const sourceId = requireArg(args, 1, \"SOURCE_ID\");\n const targetId = requireArg(args, 2, \"TARGET_ID\");\n rejectExtraArgs(args, 3);\n if (\n !args.flags.has(\"yes\") &&\n !(await deps.confirm(`Delete edge ${sourceId} -> ${targetId}?`))\n ) {\n throw new CliError(\"Aborted!\");\n }\n return runClientCommand(\n deps,\n undefined,\n (client) => client.deleteEdge({ contextId, sourceId, targetId }),\n { needsContext: false },\n );\n },\n};\n\nexport const EDGE_GROUP: CommandGroup = {\n summary: \"Manage neural memory edges (list, create, update, delete).\",\n commands: { list: edgeList, create: edgeCreate, update: edgeUpdate, delete: edgeDelete },\n};\n\nconst SLEEP_LIMIT: FlagSpec = {\n name: \"limit\",\n type: \"value\",\n metavar: \"INTEGER\",\n help: \"Max runs to return (1-50)\",\n defaultLabel: \"10\",\n};\n\nconst sleepHistory: Command = {\n summary: \"List recent Sleep Maintenance runs for a context.\",\n args: \"CONTEXT_ID\",\n spec: { flags: [SLEEP_LIMIT] },\n run: async (deps, args) => {\n const contextId = requireArg(args, 0, \"CONTEXT_ID\");\n rejectExtraArgs(args, 1);\n const raw = args.values.limit;\n const limit =\n raw === undefined\n ? 10\n : parseRanged(SLEEP_LIMIT, raw, { min: 1, max: 50, rangeLabel: \"1<=x<=50\", integer: true });\n return runClientCommand(\n deps,\n undefined,\n (client) => client.getSleepHistory({ contextId, limit }),\n { needsContext: false },\n );\n },\n};\n\nconst sleepReport: Command = {\n summary: \"Get a detailed Sleep Maintenance report including audit log.\",\n args: \"CONTEXT_ID REPORT_ID\",\n spec: { flags: [] },\n run: async (deps, args) => {\n const contextId = requireArg(args, 0, \"CONTEXT_ID\");\n const reportId = requireArg(args, 1, \"REPORT_ID\");\n rejectExtraArgs(args, 2);\n return runClientCommand(\n deps,\n undefined,\n (client) => client.getSleepReport({ contextId, reportId }),\n { needsContext: false },\n );\n },\n};\n\nconst sleepRollback: Command = {\n summary: \"Roll back a completed Sleep Maintenance run.\",\n args: \"CONTEXT_ID REPORT_ID\",\n description:\n \" Reverses edge creation, memory merges and importance updates made by\\n\" +\n \" the run. Without --yes the report is fetched first so the prompt can\\n\" +\n \" say what is about to be undone.\",\n spec: { flags: [{ ...YES, help: \"Skip confirmation prompt.\" }] },\n run: async (deps, args) => {\n const contextId = requireArg(args, 0, \"CONTEXT_ID\");\n const reportId = requireArg(args, 1, \"REPORT_ID\");\n rejectExtraArgs(args, 2);\n const skipPrompt = args.flags.has(\"yes\");\n return runClientCommand(\n deps,\n undefined,\n async (client) => {\n if (!skipPrompt) {\n // Python pre-fetches only when it is going to prompt, so `--yes`\n // is exactly one round trip.\n const report = await client.getSleepReport({ contextId, reportId });\n const actions = (report as { action_count?: number }).action_count;\n const detail = actions === undefined ? \"\" : ` (${actions} actions)`;\n if (!(await deps.confirm(`Roll back sleep run ${reportId}${detail}?`))) {\n throw new CliError(\"Aborted!\");\n }\n }\n return client.rollbackSleepRun({ contextId, reportId });\n },\n { needsContext: false },\n );\n },\n};\n\nexport const SLEEP_GROUP: CommandGroup = {\n summary: \"Inspect and roll back Sleep Maintenance runs.\",\n commands: { history: sleepHistory, report: sleepReport, rollback: sleepRollback },\n};\n","/**\n * The direct MCP tool commands — `remember`, `recall`, `reference`,\n * `forget`, `update-memory` and `explore`.\n *\n * Ported flag-for-flag from the Python CLI's `cli.py`. Two details are\n * easy to get wrong and are pinned by tests:\n *\n * - `-k` has no `--k` long form, and its default differs between\n * `recall` (5) and `forget` (10);\n * - `remember` always sends `type` and `importance` (they have\n * defaults) while `update-memory` sends neither unless asked, because\n * an omitted field there means \"leave unchanged\".\n */\n\nimport type { SourceType } from \"../../client.js\";\nimport { requireArg, requireOption, rejectExtraArgs, type Command } from \"../command.js\";\nimport {\n CliError,\n CliUsageError,\n buildDetails,\n parseFloatOption,\n parseIntOption,\n parseTags,\n quote,\n} from \"../parse.js\";\nimport type { FlagSpec, ParsedArgs } from \"../parseArgs.js\";\nimport { runClientCommand } from \"../runClientCommand.js\";\n\nconst CONTEXT_ID: FlagSpec = {\n name: \"context-id\",\n short: \"c\",\n type: \"value\",\n help: \"Context ID (or set in .kagura.json)\",\n};\n\nconst SUMMARY: FlagSpec = {\n name: \"summary\",\n short: \"s\",\n type: \"value\",\n help: \"Memory summary (for search)\",\n};\nconst CONTENT: FlagSpec = { name: \"content\", type: \"value\", help: \"Memory content (full text)\" };\nconst TYPE: FlagSpec = { name: \"type\", short: \"t\", type: \"value\", help: \"Memory type\" };\nconst IMPORTANCE: FlagSpec = {\n name: \"importance\",\n short: \"i\",\n type: \"value\",\n metavar: \"FLOAT\",\n help: \"Importance 0.0-1.0\",\n};\nconst TAGS: FlagSpec = {\n name: \"tags\",\n type: \"value\",\n help: \"Comma-separated tags (e.g., 'python,fastapi')\",\n};\nconst MEMORY_ID: FlagSpec = { name: \"memory-id\", short: \"m\", type: \"value\" };\n\n/** `-k` is short-only in Python; see FlagSpec.shortOnly. */\nconst kFlag = (help: string, defaultLabel: string): FlagSpec => ({\n name: \"k\",\n short: \"k\",\n shortOnly: true,\n type: \"value\",\n metavar: \"INTEGER\",\n help,\n defaultLabel,\n});\n\nconst SOURCE_TYPES: readonly SourceType[] = [\"file\", \"url\", \"vault\", \"api\", \"manual\"];\n\n/**\n * `click.Choice(..., case_sensitive=False)` — match case-insensitively but\n * send the canonical lowercase value.\n */\nfunction parseSourceType(raw: string | undefined): SourceType | undefined {\n if (raw === undefined) return undefined;\n const match = SOURCE_TYPES.find((t) => t === raw.toLowerCase());\n if (match === undefined) {\n throw new CliUsageError(\n `Invalid value for '--source-type': ${quote(raw)} is not one of ${SOURCE_TYPES.map(quote).join(\", \")}.`,\n );\n }\n return match;\n}\n\n/** Read a `type=float` option, or undefined when it was not passed. */\nfunction optionalFloat(args: ParsedArgs, flag: FlagSpec): number | undefined {\n const raw = args.values[flag.name];\n return raw === undefined ? undefined : parseFloatOption(flag, raw);\n}\n\n/** Read a `type=int` option, falling back to the Python default. */\nfunction intOr(args: ParsedArgs, flag: FlagSpec, fallback: number): number {\n const raw = args.values[flag.name];\n return raw === undefined ? fallback : parseIntOption(flag, raw);\n}\n\nconst remember: Command = {\n summary: \"Store a memory directly (without AI analysis).\",\n spec: {\n flags: [\n CONTEXT_ID,\n { ...SUMMARY, required: true },\n { ...CONTENT, required: true },\n { ...TYPE, defaultLabel: \"note\" },\n { ...IMPORTANCE, defaultLabel: \"0.5\" },\n TAGS,\n {\n name: \"source-uri\",\n type: \"value\",\n help: \"Origin URI (e.g., file:///path/to/note.md, vault://my-vault/note)\",\n },\n {\n name: \"source-type\",\n type: \"value\",\n metavar: \"[file|url|vault|api|manual]\",\n help: \"Origin classification. Opt-in: omitted means no provenance is stamped.\",\n },\n {\n name: \"linked-memory-ids\",\n type: \"value\",\n help: \"Comma-separated memory UUIDs to link via declared_link edges\",\n },\n {\n name: \"linked-source-uris\",\n type: \"value\",\n help: \"Comma-separated source URIs to resolve to memories and link\",\n },\n {\n name: \"details\",\n type: \"value\",\n help: \"Structured details as an inline JSON object\",\n },\n {\n name: \"location\",\n type: \"value\",\n help: \"Shorthand for details.location: 'lat,lon' or 'lat,lon,label'\",\n },\n ],\n },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const summary = requireOption(args, SUMMARY);\n const content = requireOption(args, CONTENT);\n const details = buildDetails(args.values.details, args.values.location);\n const tags = parseTags(args.values.tags);\n const linkedMemoryIds = parseTags(args.values[\"linked-memory-ids\"]);\n const linkedSourceUris = parseTags(args.values[\"linked-source-uris\"]);\n const sourceType = parseSourceType(args.values[\"source-type\"]);\n const sourceUri = args.values[\"source-uri\"];\n // Defaults are applied here, not left to the client, because Python\n // declares them on the option and therefore always sends them.\n const type = args.values.type ?? \"note\";\n const importance = optionalFloat(args, IMPORTANCE) ?? 0.5;\n\n return runClientCommand(deps, args.values[\"context-id\"], (client, contextId) =>\n client.remember({\n contextId,\n summary,\n content,\n type,\n importance,\n ...(tags ? { tags } : {}),\n ...(sourceUri !== undefined ? { sourceUri } : {}),\n ...(sourceType !== undefined ? { sourceType } : {}),\n ...(linkedMemoryIds ? { linkedMemoryIds } : {}),\n ...(linkedSourceUris ? { linkedSourceUris } : {}),\n ...(details !== undefined ? { details } : {}),\n }),\n );\n },\n};\n\nconst RECALL_K = kFlag(\"Number of results\", \"5\");\n\nconst recall: Command = {\n summary: \"Search memories directly (without AI analysis).\",\n args: \"QUERY\",\n spec: { flags: [CONTEXT_ID, RECALL_K] },\n run: async (deps, args) => {\n const query = requireArg(args, 0, \"QUERY\");\n rejectExtraArgs(args, 1);\n const k = intOr(args, RECALL_K, 5);\n return runClientCommand(deps, args.values[\"context-id\"], (client, contextId) =>\n client.recall({ contextId, query, k }),\n );\n },\n};\n\nconst reference: Command = {\n summary: \"Get full details of a specific memory.\",\n spec: {\n flags: [CONTEXT_ID, { ...MEMORY_ID, required: true, help: \"Memory ID to get full details\" }],\n },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const memoryId = requireOption(args, MEMORY_ID);\n return runClientCommand(deps, args.values[\"context-id\"], (client, contextId) =>\n client.reference({ contextId, memoryId }),\n );\n },\n};\n\nconst FORGET_K = kFlag(\"Max memories to delete in query mode\", \"10\");\n\nconst forget: Command = {\n summary: \"Delete memories (soft delete, recoverable for 30 days).\",\n spec: {\n flags: [\n CONTEXT_ID,\n { ...MEMORY_ID, help: \"Memory ID to delete (specific deletion)\" },\n { name: \"query\", short: \"q\", type: \"value\", help: \"Query to find memories to delete (bulk deletion)\" },\n FORGET_K,\n ],\n },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const memoryId = args.values[\"memory-id\"];\n const query = args.values.query;\n if (!memoryId && !query) {\n // ClickException, not UsageError: exit 1, matching Python.\n throw new CliError(\"Either --memory-id or --query is required\");\n }\n const k = intOr(args, FORGET_K, 10);\n return runClientCommand(deps, args.values[\"context-id\"], (client, contextId) =>\n client.forget({\n contextId,\n ...(memoryId !== undefined ? { memoryId } : {}),\n ...(query !== undefined ? { query } : {}),\n k,\n }),\n );\n },\n};\n\nconst updateMemory: Command = {\n summary: \"Update an existing memory or upsert by external ID.\",\n spec: {\n flags: [\n CONTEXT_ID,\n { ...MEMORY_ID, help: \"Memory UUID to update in-place\" },\n { name: \"external-id\", type: \"value\", help: \"External ID for upsert lookup\" },\n { ...SUMMARY, help: \"Updated summary\" },\n { ...CONTENT, help: \"Updated content\" },\n { ...TYPE, help: \"Updated memory type\" },\n { ...IMPORTANCE, help: \"Updated importance 0.0-1.0\" },\n { ...TAGS, help: \"Comma-separated tags\" },\n ],\n },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const memoryId = args.values[\"memory-id\"];\n const externalId = args.values[\"external-id\"];\n if (!memoryId && !externalId) {\n throw new CliError(\"Either --memory-id or --external-id is required\");\n }\n if (memoryId && externalId) {\n throw new CliError(\"Provide only one of --memory-id or --external-id\");\n }\n const summary = args.values.summary;\n const content = args.values.content;\n const type = args.values.type;\n const importance = optionalFloat(args, IMPORTANCE);\n const tags = parseTags(args.values.tags);\n\n return runClientCommand(deps, args.values[\"context-id\"], (client, contextId) =>\n client.updateMemory({\n contextId,\n // Every field is omitted unless given: an absent key means \"leave\n // unchanged\", so forwarding undefined defaults would silently\n // overwrite the stored value.\n ...(memoryId !== undefined ? { memoryId } : {}),\n ...(externalId !== undefined ? { externalId } : {}),\n ...(summary !== undefined ? { summary } : {}),\n ...(content !== undefined ? { content } : {}),\n ...(type !== undefined ? { type } : {}),\n ...(importance !== undefined ? { importance } : {}),\n ...(tags ? { tags } : {}),\n }),\n );\n },\n};\n\nconst DEPTH: FlagSpec = {\n name: \"depth\",\n short: \"d\",\n type: \"value\",\n metavar: \"INTEGER\",\n help: \"Traversal depth 1-5\",\n defaultLabel: \"2\",\n};\nconst MIN_WEIGHT: FlagSpec = {\n name: \"min-weight\",\n short: \"w\",\n type: \"value\",\n metavar: \"FLOAT\",\n help: \"Min edge weight\",\n defaultLabel: \"0.05\",\n};\n\nconst explore: Command = {\n summary: \"Explore related memories via Neural Memory graph.\",\n spec: {\n flags: [\n CONTEXT_ID,\n { ...MEMORY_ID, required: true, help: \"Seed memory ID to explore from\" },\n DEPTH,\n MIN_WEIGHT,\n ],\n },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const memoryId = requireOption(args, MEMORY_ID);\n // The documented 1-5 range is not enforced locally in Python either —\n // plain `type=int`, so the server is what rejects an absurd depth.\n const depth = intOr(args, DEPTH, 2);\n const minWeight = optionalFloat(args, MIN_WEIGHT) ?? 0.05;\n return runClientCommand(deps, args.values[\"context-id\"], (client, contextId) =>\n client.explore({ contextId, memoryId, depth, minWeight }),\n );\n },\n};\n\nexport const MEMORY_COMMANDS: Record<string, Command> = {\n remember,\n recall,\n reference,\n forget,\n \"update-memory\": updateMemory,\n explore,\n};\n","/**\n * `kagura-memory resource …` — resource tokens and external-data ingest.\n *\n * The largest group, and the one with the most flag traps. Three worth\n * naming, all of them pinned by tests:\n *\n * - `-V` (capital) is `--version` on `ingest`, `events` and `import`,\n * while `-v` (lowercase) is `--version` on `schema` but `--verbose`\n * on `import`. Same letter, three meanings.\n * - `-c` is `--cursor` on `events`, NOT `--context-id`.\n * - `events` takes RESOURCE_ID positionally; every other command in the\n * group takes `-r/--resource-id`.\n */\n\nimport * as fs from \"node:fs\";\n\nimport { requireArg, rejectExtraArgs, type Command, type CommandGroup } from \"../command.js\";\nimport {\n CliError,\n CliUsageError,\n parseChoice,\n parseFloatOption,\n parseIntOption,\n parseRanged,\n quote,\n} from \"../parse.js\";\nimport type { FlagSpec, ParsedArgs } from \"../parseArgs.js\";\nimport type { ResourceEventInput } from \"../../resourceClient.js\";\nimport { resolveConfig, runAndPrint } from \"../runClientCommand.js\";\nimport { parseRecords } from \"./importFormats.js\";\n\nconst RESOURCE_ID: FlagSpec = {\n name: \"resource-id\",\n short: \"r\",\n type: \"value\",\n required: true,\n help: \"Resource ID\",\n};\nconst API_KEY: FlagSpec = {\n name: \"api-key\",\n short: \"k\",\n type: \"value\",\n required: true,\n help: \"Resource API key\",\n};\n/** Capital V. Lowercase `-v` means something else on these commands. */\nconst VERSION: FlagSpec = {\n name: \"version\",\n short: \"V\",\n type: \"value\",\n metavar: \"INTEGER\",\n help: \"Document version\",\n};\nconst OP: FlagSpec = { name: \"op\", type: \"value\", metavar: \"[upsert|delete]\", help: \"Operation\" };\n\nconst OPS = [\"upsert\", \"delete\"] as const;\n\nfunction requiredValue(args: ParsedArgs, flag: FlagSpec): string {\n const value = args.values[flag.name];\n if (value === undefined) {\n throw new CliUsageError(\n `Missing option '--${flag.name}'${flag.short === undefined ? \"\" : ` / '-${flag.short}'`}.`,\n );\n }\n return value;\n}\n\nfunction optionalInt(args: ParsedArgs, flag: FlagSpec): number | undefined {\n const raw = args.values[flag.name];\n return raw === undefined ? undefined : parseIntOption(flag, raw);\n}\n\n// ---------------------------------------------------------------------\n// tokens\n// ---------------------------------------------------------------------\n\nconst DESCRIPTION: FlagSpec = { name: \"description\", short: \"d\", type: \"value\", help: \"Description\" };\nconst QUOTA: FlagSpec = {\n name: \"quota\",\n short: \"q\",\n type: \"value\",\n metavar: \"INTEGER\",\n help: \"Events per hour (1-10000)\",\n};\nconst LIMIT: FlagSpec = {\n name: \"limit\",\n short: \"l\",\n type: \"value\",\n metavar: \"INTEGER\",\n help: \"Results per page (max 100)\",\n defaultLabel: \"50\",\n};\n\nconst tokensList: Command = {\n summary: \"List resource tokens.\",\n spec: { flags: [{ ...RESOURCE_ID, required: false, help: \"Filter by resource ID\" }, LIMIT] },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const resourceId = args.values[\"resource-id\"];\n const limit = optionalInt(args, LIMIT) ?? 50;\n const { config } = resolveConfig(deps, undefined, false);\n return runAndPrint(deps, () =>\n deps\n .makeResourceClient()\n .listTokens({ ...(resourceId !== undefined ? { resourceId } : {}), limit }),\n );\n },\n};\n\nconst tokensCreate: Command = {\n summary: \"Create a resource token.\",\n spec: {\n flags: [\n { ...RESOURCE_ID, help: \"Resource ID to scope the token to\" },\n DESCRIPTION,\n { ...QUOTA, defaultLabel: \"1000\" },\n ],\n },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const resourceId = requiredValue(args, RESOURCE_ID);\n const description = args.values.description;\n // Plain `type=int` in Python — the 1-10000 bound is pydantic's, on the\n // server side, so an out-of-range value must still be sent.\n const quotaEventsPerHour = optionalInt(args, QUOTA) ?? 1000;\n const { config } = resolveConfig(deps, undefined, false);\n return runAndPrint(deps, () =>\n deps.makeResourceClient().createToken({\n resourceId,\n ...(description !== undefined ? { description } : {}),\n quotaEventsPerHour,\n }),\n );\n },\n};\n\nconst tokensUpdate: Command = {\n summary: \"Update a resource token.\",\n args: \"TOKEN_ID\",\n spec: { flags: [DESCRIPTION, QUOTA] },\n run: async (deps, args) => {\n const tokenId = parseTokenId(requireArg(args, 0, \"TOKEN_ID\"));\n rejectExtraArgs(args, 1);\n const description = args.values.description;\n const quotaEventsPerHour = optionalInt(args, QUOTA);\n if (description === undefined && quotaEventsPerHour === undefined) {\n // Python guards this; without it a shell typo that eats --quota sends\n // an empty PATCH and exits 0, so a script reads \"updated\".\n throw new CliError(\"At least --description or --quota is required\");\n }\n const { config } = resolveConfig(deps, undefined, false);\n return runAndPrint(deps, () =>\n deps.makeResourceClient().updateToken(tokenId, {\n ...(description !== undefined ? { description } : {}),\n ...(quotaEventsPerHour !== undefined ? { quotaEventsPerHour } : {}),\n }),\n );\n },\n};\n\nconst tokensRevoke: Command = {\n summary: \"Revoke (soft-delete) a resource token.\",\n args: \"TOKEN_ID\",\n spec: { flags: [] },\n run: async (deps, args) => {\n const tokenId = parseTokenId(requireArg(args, 0, \"TOKEN_ID\"));\n rejectExtraArgs(args, 1);\n const { config } = resolveConfig(deps, undefined, false);\n return runAndPrint(deps, async () => {\n await deps.makeResourceClient().revokeToken(tokenId);\n return { status: \"success\", token_id: tokenId };\n });\n },\n};\n\n/** `@click.argument(\"token_id\", type=int)` — a usage error, not a 422. */\nfunction parseTokenId(raw: string): number {\n if (!/^[+-]?\\d+$/.test(raw.trim())) {\n throw new CliUsageError(`Invalid value for 'TOKEN_ID': ${quote(raw)} is not a valid integer.`);\n }\n return Number(raw.trim());\n}\n\nconst TOKENS_GROUP: CommandGroup = {\n summary: \"Manage resource tokens (CRUD).\",\n commands: { list: tokensList, create: tokensCreate, update: tokensUpdate, revoke: tokensRevoke },\n};\n\n// ---------------------------------------------------------------------\n// read-only inspection\n// ---------------------------------------------------------------------\n\nconst resourceList: Command = {\n summary: \"List all resources in the workspace (owner only).\",\n spec: { flags: [] },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const { config } = resolveConfig(deps, undefined, false);\n return runAndPrint(deps, () => deps.makeResourceClient().listResources());\n },\n};\n\nconst stats: Command = {\n summary: \"Show resource impact statistics.\",\n spec: { flags: [RESOURCE_ID] },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const resourceId = requiredValue(args, RESOURCE_ID);\n const { config } = resolveConfig(deps, undefined, false);\n return runAndPrint(deps, () =>\n deps.makeResourceClient().getResourceImpact(resourceId),\n );\n },\n};\n\nconst indexerStatus: Command = {\n summary: \"Show indexer state and recent ingest events for a resource.\",\n spec: { flags: [RESOURCE_ID] },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const resourceId = requiredValue(args, RESOURCE_ID);\n const { config } = resolveConfig(deps, undefined, false);\n return runAndPrint(deps, () =>\n deps.makeResourceClient().getIndexerStatus(resourceId),\n );\n },\n};\n\n/** Lowercase `-v` here means the *schema* version, not verbosity. */\nconst SCHEMA_VERSION: FlagSpec = {\n name: \"version\",\n short: \"v\",\n type: \"value\",\n metavar: \"INTEGER\",\n help: \"Schema version\",\n};\n\nconst schema: Command = {\n summary: \"Show resource field definitions (schema).\",\n spec: { flags: [RESOURCE_ID, SCHEMA_VERSION] },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const resourceId = requiredValue(args, RESOURCE_ID);\n const version = optionalInt(args, SCHEMA_VERSION);\n const { config } = resolveConfig(deps, undefined, false);\n return runAndPrint(deps, () =>\n deps.makeResourceClient().getResourceSchema(resourceId, version),\n );\n },\n};\n\nconst EVENTS_LIMIT: FlagSpec = {\n name: \"limit\",\n short: \"l\",\n type: \"value\",\n metavar: \"INTEGER\",\n help: \"Max events (1-100)\",\n defaultLabel: \"50\",\n};\n\nconst events: Command = {\n summary: \"List ingested events for a resource (cursor-paginated).\",\n args: \"RESOURCE_ID\",\n spec: {\n flags: [\n EVENTS_LIMIT,\n // `-c` is the CURSOR here, not a context id.\n { name: \"cursor\", short: \"c\", type: \"value\", help: \"Pagination cursor from a prior next_cursor\" },\n OP,\n { name: \"doc-id\", type: \"value\", help: \"Filter by document ID\" },\n VERSION,\n { name: \"since\", type: \"value\", help: \"ISO 8601 instant, e.g. 2026-06-01T00:00:00Z\" },\n ],\n },\n run: async (deps, args) => {\n const resourceId = requireArg(args, 0, \"RESOURCE_ID\");\n rejectExtraArgs(args, 1);\n const raw = args.values.limit;\n const limit =\n raw === undefined\n ? 50\n : parseRanged(EVENTS_LIMIT, raw, { min: 1, max: 100, rangeLabel: \"1<=x<=100\", integer: true });\n const cursor = args.values.cursor;\n const rawOp = args.values.op;\n const op = rawOp === undefined ? undefined : parseChoice(OP, rawOp, OPS);\n const docId = args.values[\"doc-id\"];\n const version = optionalInt(args, VERSION);\n const since = parseSince(args.values.since);\n\n const { config } = resolveConfig(deps, undefined, false);\n return runAndPrint(deps, () =>\n deps.makeResourceClient().listResourceEvents(resourceId, {\n limit,\n ...(cursor !== undefined ? { cursor } : {}),\n ...(op !== undefined ? { op } : {}),\n ...(docId !== undefined ? { docId } : {}),\n ...(version !== undefined ? { version } : {}),\n ...(since !== undefined ? { since } : {}),\n }),\n );\n },\n};\n\n/**\n * Validate `--since` locally.\n *\n * Python parses it with `datetime.fromisoformat` at command scope, so a\n * malformed value fails before any request. `new Date(\"garbage\")` yields\n * an Invalid Date that would serialize to null and silently drop the\n * filter — returning everything instead of erroring.\n */\nfunction parseSince(raw: string | undefined): Date | undefined {\n if (raw === undefined) return undefined;\n const parsed = new Date(raw);\n if (Number.isNaN(parsed.getTime())) {\n throw new CliUsageError(`Invalid value for '--since': ${quote(raw)} is not a valid ISO 8601 instant.`);\n }\n return parsed;\n}\n\n// ---------------------------------------------------------------------\n// setup + ingest\n// ---------------------------------------------------------------------\n\nconst setup: Command = {\n summary: \"One-shot resource setup: create context + token.\",\n spec: {\n flags: [\n { ...RESOURCE_ID, help: \"Resource identifier\" },\n { name: \"summary\", short: \"s\", type: \"value\", help: \"Context summary\" },\n { ...DESCRIPTION, help: \"Token description\" },\n { ...QUOTA, help: \"Events/hour (1-10000)\", defaultLabel: \"1000\" },\n ],\n },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const resourceId = requiredValue(args, RESOURCE_ID);\n const summary = args.values.summary;\n const description = args.values.description;\n const raw = args.values.quota;\n // Unlike `tokens create`, this one IS range-checked locally in Python.\n const quotaEventsPerHour =\n raw === undefined\n ? 1000\n : parseRanged(QUOTA, raw, { min: 1, max: 10000, rangeLabel: \"1<=x<=10000\", integer: true });\n const { config } = resolveConfig(deps, undefined, false);\n return runAndPrint(deps, () =>\n deps.makeResourceClient().setupResource({\n resourceId,\n ...(summary !== undefined ? { summary } : {}),\n ...(description !== undefined ? { description } : {}),\n quotaEventsPerHour,\n }),\n );\n },\n};\n\nconst DOC_ID: FlagSpec = { name: \"doc-id\", type: \"value\", required: true, help: \"Document ID\" };\nconst PAYLOAD: FlagSpec = { name: \"payload\", short: \"p\", type: \"value\", help: \"JSON payload object\" };\nconst IMPORTANCE: FlagSpec = {\n name: \"importance\",\n short: \"i\",\n type: \"value\",\n metavar: \"FLOAT\",\n help: \"Importance 0.0-1.0\",\n};\n\nconst ingest: Command = {\n summary: \"Ingest a single resource event.\",\n spec: {\n flags: [\n RESOURCE_ID,\n API_KEY,\n DOC_ID,\n { ...OP, defaultLabel: \"upsert\" },\n VERSION,\n PAYLOAD,\n IMPORTANCE,\n ],\n },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const resourceId = requiredValue(args, RESOURCE_ID);\n const apiKey = requiredValue(args, API_KEY);\n const docId = requiredValue(args, DOC_ID);\n const rawOp = args.values.op;\n const op = rawOp === undefined ? \"upsert\" : parseChoice(OP, rawOp, OPS);\n const version = optionalInt(args, VERSION);\n const payload = parsePayload(args.values.payload);\n const rawImportance = args.values.importance;\n // parseFloatOption, not Number.parseFloat: the latter yields NaN for\n // \"abc\", the NaN survives the `!== undefined` guard, and JSON.stringify\n // serializes it as null — so a typo would silently clear importance.\n const importance =\n rawImportance === undefined ? undefined : parseFloatOption(IMPORTANCE, rawImportance);\n\n const { config } = resolveConfig(deps, undefined, false);\n return runAndPrint(deps, () =>\n deps.makeResourceClient().ingestEvent(resourceId, apiKey, {\n docId,\n op,\n ...(version !== undefined ? { version } : {}),\n ...(payload !== undefined ? { payload } : {}),\n ...(importance !== undefined ? { importance } : {}),\n }),\n );\n },\n};\n\n/** `-p` must parse to a JSON *object*; an array is a usage error. */\nfunction parsePayload(raw: string | undefined): Record<string, unknown> | undefined {\n if (raw === undefined) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (e) {\n throw new CliUsageError(\n `Invalid value for '--payload' / '-p': ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new CliUsageError(\"--payload must be a JSON object.\");\n }\n return parsed as Record<string, unknown>;\n}\n\nconst FILE: FlagSpec = {\n name: \"file\",\n short: \"f\",\n type: \"value\",\n metavar: \"FILENAME\",\n help: \"File containing a JSON array of event objects\",\n};\n\nconst ingestBatch: Command = {\n summary: \"Ingest a batch of resource events from a JSON file.\",\n spec: { flags: [RESOURCE_ID, API_KEY, { ...FILE, required: true }] },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const resourceId = requiredValue(args, RESOURCE_ID);\n const apiKey = requiredValue(args, API_KEY);\n const file = requiredValue(args, FILE);\n const text = readInput(file);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (e) {\n throw new CliUsageError(`Invalid JSON in ${file}: ${e instanceof Error ? e.message : String(e)}`);\n }\n if (!Array.isArray(parsed)) {\n throw new CliUsageError(`${file} must contain a JSON array of event objects.`);\n }\n const events_ = parsed as Record<string, unknown>[];\n const { config } = resolveConfig(deps, undefined, false);\n return runAndPrint(deps, () =>\n deps\n .makeResourceClient()\n .ingestEvents(resourceId, apiKey, events_.map(toEventInput)),\n );\n },\n};\n\n/** Accept the wire (snake_case) shape a batch file naturally carries. */\nfunction toEventInput(row: Record<string, unknown>): ResourceEventInput {\n const docId = (row.doc_id ?? row.docId) as string;\n const op = (row.op ?? \"upsert\") as \"upsert\" | \"delete\";\n const version = (row.version ?? undefined) as number | undefined;\n const payload = (row.payload ?? undefined) as Record<string, unknown> | undefined;\n const importance = (row.importance ?? undefined) as number | undefined;\n return {\n docId,\n op,\n ...(version !== undefined ? { version } : {}),\n ...(payload !== undefined ? { payload } : {}),\n ...(importance !== undefined ? { importance } : {}),\n };\n}\n\n/** The server's per-request event cap; Python chunks at the same size. */\nconst BATCH_SIZE = 100;\n\nconst FORMAT: FlagSpec = {\n name: \"format\",\n type: \"value\",\n metavar: \"[auto|csv|json|jsonl]\",\n help: \"Input format\",\n defaultLabel: \"auto\",\n};\n\nconst importCmd: Command = {\n summary: \"Import data from CSV, JSON, or JSONL file.\",\n spec: {\n flags: [\n RESOURCE_ID,\n API_KEY,\n { ...FILE, help: \"Input file, or - for stdin\", defaultLabel: \"-\" },\n FORMAT,\n { name: \"id-column\", type: \"value\", help: \"Column whose value becomes doc_id\" },\n { ...VERSION, help: \"Document version (>=1)\", defaultLabel: \"1\" },\n ],\n },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const resourceId = requiredValue(args, RESOURCE_ID);\n const apiKey = requiredValue(args, API_KEY);\n const file = args.values.file ?? \"-\";\n const rawFormat = args.values.format ?? \"auto\";\n // click.Choice here is case-SENSITIVE, unlike --progress elsewhere.\n if (![\"auto\", \"csv\", \"json\", \"jsonl\"].includes(rawFormat)) {\n throw new CliUsageError(\n `Invalid value for '--format': ${quote(rawFormat)} is not one of 'auto', 'csv', 'json', 'jsonl'.`,\n );\n }\n const idColumn = args.values[\"id-column\"];\n const rawVersion = args.values.version;\n const version =\n rawVersion === undefined\n ? 1\n : parseRanged(VERSION, rawVersion, {\n min: 1,\n max: Number.MAX_SAFE_INTEGER,\n rangeLabel: \"x>=1\",\n integer: true,\n });\n\n const text = readInput(file);\n const rows = parseRecords(text, rawFormat as \"auto\" | \"csv\" | \"json\" | \"jsonl\", file);\n const events_ = rows.map((row, index) => {\n if (idColumn !== undefined && (row[idColumn] === undefined || row[idColumn] === \"\")) {\n // Falling back to the row number here would look like a successful\n // import while every doc_id was wrong — and on a re-run with the\n // column spelled right, the same rows would be inserted a second\n // time under different ids.\n throw new CliUsageError(\n `--id-column ${quote(idColumn)} is missing on row ${index + 1} of ${file}.`,\n );\n }\n return {\n // Python falls back to the 1-based row number as a string.\n docId: idColumn === undefined ? String(index + 1) : String(row[idColumn]),\n op: \"upsert\" as const,\n version,\n payload: row,\n };\n });\n\n const { config } = resolveConfig(deps, undefined, false);\n return runAndPrint(deps, async () => {\n // The endpoint takes 1-100 events; Python chunks at 100 and this must\n // too, or any import over 100 rows is rejected wholesale.\n const client = deps.makeResourceClient();\n let created = 0;\n let failed = 0;\n const errors: unknown[] = [];\n for (let i = 0; i < events_.length; i += BATCH_SIZE) {\n const result = await client.ingestEvents(\n resourceId,\n apiKey,\n events_.slice(i, i + BATCH_SIZE),\n );\n created += result.created_count ?? 0;\n failed += result.failed_count ?? 0;\n // Python keeps the first five errors per batch and prints ten in\n // total; a full dump of a bad 10k-row file is unreadable.\n if (Array.isArray(result.errors)) errors.push(...result.errors.slice(0, 5));\n }\n // One aggregate for the whole import, matching Python's shape — a\n // per-batch array would make a script parse a different result for\n // 99 rows than for 101.\n const output: Record<string, unknown> = { created, failed, total: events_.length };\n if (errors.length > 0) output.errors = errors.slice(0, 10);\n return output;\n });\n },\n};\n\n/** Read a `click.File(\"r\")` argument, where `-` means stdin. */\nfunction readInput(file: string): string {\n try {\n return fs.readFileSync(file === \"-\" ? 0 : file, \"utf-8\");\n } catch (e) {\n throw new CliUsageError(\n `Invalid value for '--file' / '-f': ${quote(file)}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\nexport const RESOURCE_GROUP: CommandGroup = {\n summary: \"Manage resource tokens and ingest external data.\",\n commands: {\n tokens: TOKENS_GROUP,\n list: resourceList,\n stats,\n \"indexer-status\": indexerStatus,\n schema,\n events,\n setup,\n ingest,\n \"ingest-batch\": ingestBatch,\n import: importCmd,\n },\n};\n","/**\n * Record readers for `kagura-memory resource import`.\n *\n * Python leans on `csv.DictReader`; there is no such thing in Node and\n * this package takes no runtime dependencies, so the CSV reader is\n * hand-written to RFC 4180: quoted fields, `\"\"` as an escaped quote, and\n * embedded commas and newlines inside quotes. A naive `line.split(\",\")`\n * silently corrupts any row containing a quoted comma, which is most real\n * exports.\n */\n\nimport { CliUsageError, quote } from \"../parse.js\";\n\nexport type ImportFormat = \"auto\" | \"csv\" | \"json\" | \"jsonl\";\n\n/** Split CSV text into rows of raw fields. */\nexport function parseCsvRows(text: string): string[][] {\n const rows: string[][] = [];\n let row: string[] = [];\n let field = \"\";\n let quoted = false;\n let started = false;\n\n const endField = () => {\n row.push(field);\n field = \"\";\n };\n const endRow = () => {\n endField();\n rows.push(row);\n row = [];\n started = false;\n };\n\n for (let i = 0; i < text.length; i++) {\n const ch = text[i]!;\n if (quoted) {\n if (ch === '\"') {\n if (text[i + 1] === '\"') {\n // `\"\"` inside a quoted field is one literal quote.\n field += '\"';\n i += 1;\n } else {\n quoted = false;\n }\n } else {\n field += ch;\n }\n continue;\n }\n if (ch === '\"' && field === \"\") {\n quoted = true;\n started = true;\n continue;\n }\n if (ch === \",\") {\n endField();\n started = true;\n continue;\n }\n if (ch === \"\\r\") {\n // Normalize CRLF; a bare CR is treated as a line break too.\n if (text[i + 1] === \"\\n\") i += 1;\n endRow();\n continue;\n }\n if (ch === \"\\n\") {\n endRow();\n continue;\n }\n field += ch;\n started = true;\n }\n // A trailing newline must not produce a phantom empty row, but a final\n // row without one must not be dropped.\n if (started || field !== \"\" || row.length > 0) endRow();\n return rows;\n}\n\n/** CSV text to objects, keyed by the header row — `csv.DictReader`. */\nexport function parseCsv(text: string): Record<string, unknown>[] {\n const rows = parseCsvRows(text);\n const header = rows.shift();\n if (header === undefined || header.length === 0) return [];\n return rows.map((cells) => {\n const record: Record<string, unknown> = {};\n header.forEach((name, i) => {\n // DictReader leaves missing trailing cells as None; an empty string\n // is closer to what the server stores and avoids a null payload key.\n record[name] = cells[i] ?? \"\";\n });\n return record;\n });\n}\n\n/** One JSON object per line, blank lines skipped. */\nexport function parseJsonl(text: string, label: string): Record<string, unknown>[] {\n const out: Record<string, unknown>[] = [];\n const lines = text.split(/\\r?\\n/);\n lines.forEach((line, index) => {\n if (!line.trim()) return;\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch (e) {\n throw new CliUsageError(\n `Invalid JSON on line ${index + 1} of ${label}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n out.push(asRecord(parsed, `line ${index + 1} of ${label}`));\n });\n return out;\n}\n\nfunction asRecord(value: unknown, where: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new CliUsageError(`Expected a JSON object at ${where}.`);\n }\n return value as Record<string, unknown>;\n}\n\n/**\n * Guess the format from the content.\n *\n * Content rather than filename, because `--file -` (stdin, the default)\n * has no name to go on.\n */\nexport function detectFormat(text: string): Exclude<ImportFormat, \"auto\"> {\n const trimmed = text.trimStart();\n if (trimmed.startsWith(\"[\")) return \"json\";\n if (trimmed.startsWith(\"{\")) {\n // One object is JSON; several newline-separated objects are JSONL.\n const firstLine = trimmed.split(/\\r?\\n/, 1)[0] ?? \"\";\n return firstLine.trimEnd().endsWith(\"}\") && /\\n\\s*\\{/.test(trimmed) ? \"jsonl\" : \"json\";\n }\n return \"csv\";\n}\n\n/** Read `--file` content into records, honouring `--format`. */\nexport function parseRecords(\n text: string,\n format: ImportFormat,\n label: string,\n): Record<string, unknown>[] {\n const resolved = format === \"auto\" ? detectFormat(text) : format;\n if (resolved === \"csv\") return parseCsv(text);\n if (resolved === \"jsonl\") return parseJsonl(text, label);\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (e) {\n throw new CliUsageError(\n `Invalid JSON in ${quote(label)}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n if (Array.isArray(parsed)) return parsed.map((row, i) => asRecord(row, `index ${i} of ${label}`));\n // A single object is one record, not an error — the same courtesy\n // DictReader-style importers usually extend.\n return [asRecord(parsed, label)];\n}\n","/**\n * `kagura-memory secret …` — the zero-knowledge secret store.\n *\n * Two things make this group unlike the others.\n *\n * **The optional peer dependency.** Encryption lives in `age-encryption`,\n * which this package declares as an *optional* peer so the zero-dependency\n * promise survives. Python does the same with its `[secret]` extra and\n * degrades to a stub that names the install command; so does this, via the\n * message `KaguraCryptoError` already carries.\n *\n * **Key custody.** Python custodies the age private key in the OS keychain\n * through `keyring`. Node has no stdlib keychain and every binding is a\n * native module, so `KeyManager` ships no default backend — a decision\n * recorded in `secrets/keyManager.ts`, which explicitly rejects both a\n * native dependency and a plaintext file. The CLI therefore reads the\n * identity from an environment variable or a file the operator names:\n *\n * KAGURA_AGE_IDENTITY the AGE-SECRET-KEY-1… value itself\n * KAGURA_AGE_IDENTITY_FILE a path to read it from\n *\n * With neither set, every command that needs the private key fails closed\n * with instructions. **A key custodied by the Python CLI's keyring is not\n * visible here, and vice versa** — that is the cost of not adding a native\n * dependency, and it is stated rather than papered over.\n */\n\nimport * as fs from \"node:fs\";\n\nimport { decrypt, fingerprint, generateKeypair, recipientFromIdentity } from \"../../secrets/crypto.js\";\nimport type { PubkeyResponse } from \"../../models.js\";\nimport { requireArg, rejectExtraArgs, type Command, type CommandDeps, type CommandGroup } from \"../command.js\";\nimport { formatJson } from \"../output.js\";\nimport { CliError, CliUsageError, parseIntOption } from \"../parse.js\";\nimport type { FlagSpec, ParsedArgs } from \"../parseArgs.js\";\nimport { runAndPrint } from \"../runClientCommand.js\";\n\nconst PROFILE: FlagSpec = {\n name: \"profile\",\n type: \"value\",\n help: \"Your key profile\",\n defaultLabel: \"default\",\n};\nconst TO_MULTI: FlagSpec = {\n name: \"to\",\n type: \"multiple\",\n metavar: \"PUBKEY_ID\",\n help: \"Recipient pubkey id (repeatable). Default: yourself.\",\n};\nconst TO_ONE: FlagSpec = { name: \"to\", type: \"value\", metavar: \"PUBKEY_ID\", required: true };\nconst FROM_FILE: FlagSpec = {\n name: \"from-file\",\n type: \"value\",\n metavar: \"PATH\",\n help: \"Read the value from a file instead of stdin\",\n};\n\n/**\n * Environment carrying the age private key.\n *\n * Stripped from any child `secret exec` launches: `--as` is a scoping\n * mechanism, and a child that inherits the identity could decrypt every\n * other secret in the workspace, which is exactly what the scoping was\n * for. Python does not have this exposure because it reads the key from\n * the OS keychain, so nothing is in the environment to inherit.\n */\nconst IDENTITY_ENV = [\"KAGURA_AGE_IDENTITY\", \"KAGURA_AGE_IDENTITY_FILE\"] as const;\n\nconst IDENTITY_HELP =\n \"No age private key available.\\n\" +\n \" Set KAGURA_AGE_IDENTITY to the AGE-SECRET-KEY-1… value, or\\n\" +\n \" KAGURA_AGE_IDENTITY_FILE to a file containing it.\\n\" +\n \" Generate one with: kagura-memory secret keygen\\n\" +\n \" (Keys custodied by the Python CLI's keyring are not readable from Node.)\";\n\n/** Read the operator-provided identity, or fail closed. */\nfunction readIdentity(env: NodeJS.ProcessEnv = process.env): string {\n const inline = env.KAGURA_AGE_IDENTITY?.trim();\n if (inline) return inline;\n const file = env.KAGURA_AGE_IDENTITY_FILE?.trim();\n if (file) {\n let text: string;\n try {\n text = fs.readFileSync(file, \"utf-8\");\n } catch (e) {\n throw new CliError(\n `cannot read KAGURA_AGE_IDENTITY_FILE (${file}): ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n const line = text\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .find((l) => l.startsWith(\"AGE-SECRET-KEY-1\"));\n if (line === undefined) {\n // Never echo the file's contents: it is a private key.\n throw new CliError(`${file} contains no AGE-SECRET-KEY-1 line.`);\n }\n return line;\n }\n throw new CliError(IDENTITY_HELP);\n}\n\n// ---------------------------------------------------------------------\n// commands that need no private key\n// ---------------------------------------------------------------------\n\nconst list: Command = {\n summary: \"List secret metadata (never the values).\",\n spec: { flags: [] },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n return runAndPrint(deps, () => makeSecretClient(deps).listSecrets());\n },\n};\n\nconst pubkeys: Command = {\n summary: \"List recipient pubkeys.\",\n spec: { flags: [{ name: \"mine\", type: \"switch\", help: \"Only your own pubkeys\" }] },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const mine = args.flags.has(\"mine\");\n return runAndPrint(deps, () => {\n const client = makeSecretClient(deps);\n return mine ? client.listMyPubkeys() : client.listPubkeys();\n });\n },\n};\n\nconst approve: Command = {\n summary: \"Approve a pending pubkey (owner only).\",\n args: \"PUBKEY_ID\",\n spec: { flags: [] },\n run: async (deps, args) => {\n const pubkeyId = requireArg(args, 0, \"PUBKEY_ID\");\n rejectExtraArgs(args, 1);\n return runAndPrint(deps, () => makeSecretClient(deps).approvePubkey(pubkeyId));\n },\n};\n\nconst revoke: Command = {\n summary: \"Revoke one recipient's grant.\",\n args: \"NAME\",\n spec: { flags: [{ ...TO_ONE, help: \"Recipient pubkey id to revoke\" }] },\n run: async (deps, args) => {\n const name = requireArg(args, 0, \"NAME\");\n rejectExtraArgs(args, 1);\n const to = requireValue(args, TO_ONE);\n return runAndPrint(deps, () => makeSecretClient(deps).revokeGrant(name, to));\n },\n};\n\nconst deleteSecret: Command = {\n summary: \"Hard-delete a secret and all its versions + grants (owner only).\",\n args: \"NAME\",\n spec: { flags: [{ name: \"yes\", short: \"y\", type: \"switch\", help: \"Skip the confirmation prompt\" }] },\n run: async (deps, args) => {\n const name = requireArg(args, 0, \"NAME\");\n rejectExtraArgs(args, 1);\n if (!args.flags.has(\"yes\") && !(await deps.confirm(`Hard-delete secret '${name}' and all versions?`))) {\n throw new CliError(\"Aborted!\");\n }\n return runAndPrint(deps, async () => {\n await makeSecretClient(deps).deleteSecret(name);\n return { status: \"success\", name };\n });\n },\n};\n\nconst auditVerify: Command = {\n summary: \"Verify the tamper-evident audit chain (owner/admin).\",\n spec: { flags: [] },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n return runAndPrint(deps, () => makeSecretClient(deps).verifyAudit());\n },\n};\n\n// ---------------------------------------------------------------------\n// commands that need the private key\n// ---------------------------------------------------------------------\n\nconst keygen: Command = {\n summary: \"Generate an age keypair and register the public half.\",\n description:\n \" The private key is PRINTED, not stored: this SDK takes no native\\n\" +\n \" keychain dependency, so custody is yours. Save it somewhere your\\n\" +\n \" secret manager controls and point KAGURA_AGE_IDENTITY_FILE at it.\\n\" +\n \" Output is refused on a TTY unless --reveal is given.\",\n spec: {\n flags: [\n PROFILE,\n { name: \"label\", type: \"value\", help: \"Human-readable label for this pubkey\" },\n { name: \"no-register\", type: \"switch\", help: \"Generate only; skip server registration\" },\n { name: \"reveal\", type: \"switch\", help: \"Allow printing the private key to a terminal\" },\n ],\n },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const label = args.values.label;\n const { identity, recipient } = await generateKeypair();\n\n if (deps.isTty() && !args.flags.has(\"reveal\")) {\n throw new CliError(\n \"refusing to print a private key to a terminal. Redirect to a file \" +\n \"(umask 077 first), or pass --reveal if you really mean it.\",\n );\n }\n\n if (args.flags.has(\"no-register\")) {\n deps.write(formatJson({ recipient, fingerprint: fingerprint(recipient), identity }));\n return 0;\n }\n return runAndPrint(deps, async () => {\n const registered = await makeSecretClient(deps).registerPubkey(recipient, label);\n return { pubkey: registered, identity };\n });\n },\n};\n\nconst put: Command = {\n summary: \"Store a secret.\",\n args: \"NAME\",\n spec: { flags: [TO_MULTI, FROM_FILE, PROFILE] },\n run: async (deps, args) => {\n const name = requireArg(args, 0, \"NAME\");\n rejectExtraArgs(args, 1);\n const value = readSecretValue(deps, args.values[\"from-file\"]);\n const toIds = args.many.to ?? [];\n\n return runAndPrint(deps, async () => {\n const client = makeSecretClient(deps);\n const all = await client.listPubkeys();\n const recipients = await selectRecipients(all, toIds);\n return client.putSecretForRecipients({ name, plaintext: value, recipients });\n });\n },\n};\n\nconst get: Command = {\n summary: \"Fetch a secret and decrypt it locally with your key.\",\n args: \"NAME\",\n spec: {\n flags: [\n { name: \"output\", short: \"o\", type: \"value\", metavar: \"FILE\", help: \"Write to FILE (mode 0600)\" },\n { name: \"reveal\", type: \"switch\", help: \"Allow printing to a terminal\" },\n { name: \"version\", type: \"value\", metavar: \"INTEGER\", help: \"Pin a version (default: latest)\" },\n PROFILE,\n ],\n },\n run: async (deps, args) => {\n const name = requireArg(args, 0, \"NAME\");\n rejectExtraArgs(args, 1);\n const output = args.values.output;\n const rawVersion = args.values.version;\n const version =\n rawVersion === undefined\n ? undefined\n : parseIntOption({ name: \"version\", type: \"value\" }, rawVersion);\n\n // The TTY guard runs before the fetch: shoulder-surfing is the threat,\n // and there is no point decrypting something we will refuse to show.\n if (output === undefined && deps.isTty() && !args.flags.has(\"reveal\")) {\n throw new CliError(\n \"refusing to print a secret to a terminal. Use --output FILE, pipe it, or pass --reveal.\",\n );\n }\n\n const identity = readIdentity();\n const client = makeSecretClient(deps);\n const fetched = await client.fetchSecret(name, version);\n const plaintext = await decrypt(fetched.ciphertext, identity);\n\n if (output === undefined) {\n // stdout is text; a binary secret belongs in --output.\n deps.write(new TextDecoder().decode(plaintext));\n return 0;\n }\n // Bytes, not a decoded string: a signing key or keytab would otherwise\n // have every non-UTF-8 byte replaced with U+FFFD and be silently\n // corrupted on the way to disk.\n writePrivateFile(output, plaintext);\n deps.write(formatJson({ status: \"success\", name, written_to: output }));\n return 0;\n },\n};\n\nconst grant: Command = {\n summary: \"Grant a recipient access (re-encrypts the secret to them).\",\n args: \"NAME\",\n spec: { flags: [{ ...TO_ONE, help: \"Pubkey id to grant\" }, PROFILE] },\n run: async (deps, args) => {\n const name = requireArg(args, 0, \"NAME\");\n rejectExtraArgs(args, 1);\n const to = requireValue(args, TO_ONE);\n const identity = readIdentity();\n\n return runAndPrint(deps, async () => {\n const client = makeSecretClient(deps);\n // Only a current recipient can decrypt, which is what makes this a\n // grant rather than a server-side re-key.\n const fetched = await client.fetchSecret(name);\n const plaintext = await decrypt(fetched.ciphertext, identity);\n const all = await client.listPubkeys();\n // The server records recipients as FINGERPRINTS, not pubkey ids, so\n // the existing set is resolved by fingerprint and the new one by id.\n const keep = byFingerprint(all, fetched.recipients_snapshot);\n const added = all.find((p) => p.id === to);\n if (added === undefined) throw new CliError(`no such pubkey id: ${to}`);\n const recipients = dedupe([...keep, added]);\n return client.putSecretForRecipients({ name, plaintext, recipients });\n });\n },\n};\n\nconst rotate: Command = {\n summary: \"Rotate a secret: encrypt a NEW value to the remaining recipients.\",\n args: \"NAME\",\n spec: { flags: [FROM_FILE, PROFILE] },\n run: async (deps, args) => {\n const name = requireArg(args, 0, \"NAME\");\n rejectExtraArgs(args, 1);\n const value = readSecretValue(deps, args.values[\"from-file\"]);\n\n return runAndPrint(deps, async () => {\n const client = makeSecretClient(deps);\n // Rotation needs the current recipient *set*, not the current value,\n // so it never decrypts — which is why Python's --profile is unused\n // here. The set comes from the stored snapshot of fingerprints.\n const current = await client.fetchSecret(name);\n const all = await client.listPubkeys();\n const recipients = byFingerprint(all, current.recipients_snapshot);\n if (recipients.length === 0) {\n throw new CliError(\n `none of '${name}'’s recipients are still registered; rotating would orphan it.`,\n );\n }\n return client.putSecretForRecipients({ name, plaintext: value, recipients });\n });\n },\n};\n\nconst exec: Command = {\n summary: \"Run COMMAND with secrets injected into its environment.\",\n args: \"-- COMMAND [ARGS]...\",\n description:\n \" Secrets are decrypted locally and passed to the child through its\\n\" +\n \" environment only — they never touch disk and never appear in argv.\\n\" +\n \" The child's exit code becomes this command's exit code.\",\n passthrough: true,\n spec: {\n flags: [\n { name: \"as\", type: \"multiple\", metavar: \"ENV=NAME\", help: \"ENV_NAME=secret_name (repeatable)\" },\n PROFILE,\n ],\n },\n run: async (deps, args) => {\n const specs = args.many.as ?? [];\n if (specs.length === 0) throw new CliUsageError(\"Missing option '--as'.\");\n // The router stopped parsing at the first positional and stripped a\n // leading `--`, so these are the child's argv verbatim.\n const argv = args.positionals;\n if (argv.length === 0) throw new CliUsageError(\"Missing argument 'COMMAND'.\");\n\n const mapping = specs.map((spec) => {\n const eq = spec.indexOf(\"=\");\n if (eq <= 0) {\n throw new CliUsageError(`--as expects ENV_NAME=secret_name, got ${JSON.stringify(spec)}.`);\n }\n return { envName: spec.slice(0, eq), secretName: spec.slice(eq + 1) };\n });\n\n const identity = readIdentity();\n const client = makeSecretClient(deps);\n\n const injected: Record<string, string> = {};\n const decoder = new TextDecoder();\n for (const { envName, secretName } of mapping) {\n const fetched = await client.fetchSecret(secretName);\n injected[envName] = decoder.decode(await decrypt(fetched.ciphertext, identity));\n }\n return deps.spawnChild(argv[0]!, argv.slice(1), injected, IDENTITY_ENV);\n },\n};\n\n// ---------------------------------------------------------------------\n// helpers\n// ---------------------------------------------------------------------\n\nfunction requireValue(args: ParsedArgs, flag: FlagSpec): string {\n const value = args.values[flag.name];\n if (value === undefined) throw new CliUsageError(`Missing option '--${flag.name}'.`);\n return value;\n}\n\nfunction makeSecretClient(deps: CommandDeps) {\n return deps.makeSecretClient();\n}\n\n/** Read the secret value from `--from-file` or stdin, never from argv. */\nfunction readSecretValue(deps: CommandDeps, fromFile: string | undefined): string {\n if (fromFile !== undefined) {\n try {\n return fs.readFileSync(fromFile, \"utf-8\").replace(/\\r?\\n$/, \"\");\n } catch (e) {\n throw new CliUsageError(\n `Invalid value for '--from-file': ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n }\n // A value on the command line would land in the shell history and in\n // every `ps` listing, so there is deliberately no --value flag.\n const stdin = deps.readStdin();\n if (stdin === null) {\n throw new CliUsageError(\"no value on stdin; pipe one in or use --from-file PATH.\");\n }\n return stdin.replace(/\\r?\\n$/, \"\");\n}\n\n/** Resolve pubkey ids to the active recipients, defaulting to yourself. */\nasync function selectRecipients(\n all: PubkeyResponse[],\n ids: string[],\n): Promise<PubkeyResponse[]> {\n if (ids.length === 0) {\n const recipient = await recipientFromIdentity(readIdentity());\n const mine = all.find((p) => p.pubkey === recipient);\n if (mine === undefined) {\n throw new CliError(\n \"your pubkey is not registered on this workspace; run `kagura-memory secret keygen` first.\",\n );\n }\n return [mine];\n }\n const byId = new Map(all.map((p) => [p.id, p]));\n return ids.map((id) => {\n const found = byId.get(id);\n if (found === undefined) throw new CliError(`no such pubkey id: ${id}`);\n return found;\n });\n}\n\n/** Resolve a stored fingerprint snapshot back to live pubkey rows. */\nfunction byFingerprint(all: PubkeyResponse[], fingerprints: string[]): PubkeyResponse[] {\n const wanted = new Set(fingerprints);\n return all.filter((p) => wanted.has(p.fingerprint));\n}\n\nfunction dedupe(rows: PubkeyResponse[]): PubkeyResponse[] {\n const seen = new Set<string>();\n return rows.filter((r) => (seen.has(r.id) ? false : (seen.add(r.id), true)));\n}\n\n/**\n * Write plaintext to a file that is 0600 *before* any of it lands there.\n *\n * `writeFileSync(..., {mode})` applies the mode only when it creates the\n * file, so writing over an existing 0644 file would leave the secret\n * world-readable for the window between the write and a later chmod.\n * Opening the descriptor first closes that window, and O_NOFOLLOW refuses\n * a symlink planted where the output was meant to go.\n */\nfunction writePrivateFile(target: string, contents: Uint8Array): void {\n const NOFOLLOW = fs.constants.O_NOFOLLOW ?? 0;\n let fd: number | undefined;\n try {\n fd = fs.openSync(\n target,\n fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_TRUNC | NOFOLLOW,\n 0o600,\n );\n // An existing file keeps its old mode through open(); tighten before\n // writing, not after.\n fs.fchmodSync(fd, 0o600);\n // writeFileSync on the descriptor, not writeSync: the latter returns\n // the number of bytes written and may be short, which would truncate\n // the secret silently. writeFileSync loops until the buffer is done.\n fs.writeFileSync(fd, contents);\n } catch (e) {\n throw new CliError(`cannot write ${target}: ${e instanceof Error ? e.message : String(e)}`);\n } finally {\n if (fd !== undefined) fs.closeSync(fd);\n }\n}\n\nexport const SECRET_GROUP: CommandGroup = {\n summary: \"Zero-knowledge secret store — age recipient encryption.\",\n commands: {\n keygen,\n list,\n put,\n get,\n grant,\n revoke,\n rotate,\n delete: deleteSecret,\n pubkeys,\n approve,\n \"audit-verify\": auditVerify,\n exec,\n },\n};\n","/**\n * age (X25519) crypto primitives for the zero-knowledge secret client\n * (port of secrets/crypto.py, #28).\n *\n * All cryptography is delegated to `age-encryption`\n * ([typage](https://github.com/FiloSottile/typage), by age's author) — the\n * TypeScript counterpart of the audited `pyrage` binding the Python SDK\n * uses. Nothing here implements crypto.\n *\n * **`age-encryption` is an optional peer dependency.** The base SDK ships\n * with zero runtime dependencies and that is a promise, not an accident, so\n * the crypto package is opt-in exactly as it is in Python (`pip install\n * 'kagura-memory[secret]'`). It is loaded lazily on first use; without it,\n * {@link encrypt} and {@link decrypt} throw a {@link KaguraCryptoError}\n * naming the install command. Everything that does not need it —\n * {@link fingerprint}, {@link armorEncode}, {@link armorDecode}, and the\n * whole of {@link SecretClient} except `putSecretForRecipients` — keeps\n * working on a bare install.\n *\n * Armoring is implemented here rather than taken from `age-encryption`, for\n * the same reason the Python port implements it: it is a transport encoding\n * (base64 + PEM framing), not crypto, and keeping it dependency-free means a\n * caller can inspect or relay a ciphertext without installing the crypto\n * package at all.\n *\n * Contract invariants enforced here, all three verified against the Python\n * SDK by round-tripping real ciphertext in both directions:\n *\n * - `fingerprint(pubkey) === sha256_hex(pubkey)` over the `age1` string;\n * - recipients match {@link RECIPIENT_RE} (plain X25519, no plugins);\n * - armored ciphertext is `<=` {@link MAX_CIPHERTEXT_BYTES}.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { excMessage, KaguraCryptoError } from \"../errors.js\";\n\n/**\n * Plain X25519 age recipient. Plugin recipients (`age1yubikey1...`), the\n * post-quantum hybrid form (`age1pq1...`), and tag recipients\n * (`age1tag1...`) are all rejected: the server contract is X25519-only, and\n * more importantly the Python SDK — which reads the same secrets — cannot\n * decrypt anything else.\n *\n * The character class is bech32's 32-symbol alphabet, which excludes `1`,\n * `b`, `i` and `o`. That one detail is what does the work: every non-X25519\n * form carries a second `1` (its plugin/type separator), so excluding `1`\n * from the data part rejects the whole family without a prefix allowlist to\n * keep up to date.\n *\n * This is deliberately **stricter than Python's `RECIPIENT_RE`**\n * (`^age1[0-9a-z]{20,110}\\\\Z`), which does match `age1pq1...`. Python is\n * still safe because the very next line hands the string to\n * `pyrage.x25519.Recipient.from_str`, which refuses anything but X25519.\n * The TypeScript equivalent does not: `age-encryption`'s `addRecipient`\n * *accepts* `age1pq1...` and would happily produce ciphertext the Python CLI\n * cannot open. Matching Python's effective behaviour therefore means\n * tightening the regex, not copying it.\n *\n * Unlike Python's `$`, JavaScript's `$` does not match before a final\n * newline, so `age1...\\n` is rejected here without needing `\\Z`. There is a\n * test pinning that, because it is the kind of thing a \"harmless\" regex\n * tidy-up silently reverses.\n */\nexport const RECIPIENT_RE = /^age1[02-9ac-hj-np-z]{20,110}$/;\n\n/** Server cap on stored ciphertext (256 KiB). `blob_ref` (R2) is future work. */\nexport const MAX_CIPHERTEXT_BYTES = 262144;\n\nconst ARMOR_BEGIN = \"-----BEGIN AGE ENCRYPTED FILE-----\";\nconst ARMOR_END = \"-----END AGE ENCRYPTED FILE-----\";\n\n/** Minimal shape this module uses from `age-encryption`. */\ninterface AgeModule {\n generateX25519Identity(): Promise<string>;\n identityToRecipient(identity: string): Promise<string>;\n Encrypter: new () => {\n addRecipient(s: string): void;\n encrypt(file: Uint8Array): Promise<Uint8Array>;\n };\n Decrypter: new () => {\n addIdentity(s: string): void;\n decrypt(file: Uint8Array): Promise<Uint8Array>;\n };\n}\n\nlet agePromise: Promise<AgeModule> | null = null;\n\n/**\n * Make `globalThis.crypto` exist, for Node 18.\n *\n * WebCrypto only became a global in Node 19. `age-encryption` reaches\n * `@noble/*`, which reads `globalThis.crypto.getRandomValues` for the file\n * key and for keygen — so on Node 18 every encrypt and every\n * {@link generateKeypair} fails with \"crypto.getRandomValues must be\n * defined\", while decryption (which needs no randomness) works fine. CI\n * caught exactly that asymmetry.\n *\n * `package.json` says `engines.node >= 18`, so the fix belongs here rather\n * than in the engines field: `node:crypto` has exposed `webcrypto` since\n * Node 15, and installing it is precisely what Node 19+ does for you.\n *\n * Scoped as tightly as a global assignment can be: only when nothing is\n * there, only on the way into the crypto package, and `configurable` so a\n * host that wants its own implementation can still replace it.\n */\nasync function ensureWebCrypto(): Promise<void> {\n if (globalThis.crypto !== undefined) {\n return;\n }\n const { webcrypto } = await import(\"node:crypto\");\n Object.defineProperty(globalThis, \"crypto\", {\n value: webcrypto,\n configurable: true,\n enumerable: false,\n writable: false,\n });\n}\n\n/**\n * Load `age-encryption` on first use.\n *\n * @throws KaguraCryptoError if the optional peer dependency is not installed.\n */\nasync function loadAge(): Promise<AgeModule> {\n agePromise ??= (async () => {\n // Kept outside the try below so a WebCrypto problem is never reported as\n // \"the package is not installed\" — the two need different fixes.\n await ensureWebCrypto();\n try {\n return (await import(\"age-encryption\")) as AgeModule;\n } catch (e) {\n throw new KaguraCryptoError(\n \"The secret store needs the optional 'age-encryption' package, which \" +\n \"is not installed. The base SDK has zero runtime dependencies, so \" +\n \"the crypto package is opt-in.\\n\" +\n \" Install it with: npm install age-encryption\\n\" +\n ` (original error: ${excMessage(e)})`,\n { cause: e },\n );\n }\n })().catch((e: unknown) => {\n // Never memoize a failure: a caller who installs the package mid-process,\n // or a host that supplies its own WebCrypto after the first attempt,\n // must get a real retry rather than the cached rejection.\n agePromise = null;\n throw e;\n });\n return agePromise;\n}\n\n/** Reset the memoized module handle. Test seam; not part of the public API. */\nexport function resetAgeCache(): void {\n agePromise = null;\n}\n\n/**\n * Generate a fresh X25519 age keypair.\n *\n * @returns `identity` — the `AGE-SECRET-KEY-1...` private key, to be placed\n * in custody (see {@link KeyManager}) and never sent anywhere — and\n * `recipient`, the public `age1...` string registered with the server.\n *\n * Python returns these as a `(identity, recipient)` tuple; the object form\n * here is the same two values, named, so the order cannot be swapped at a\n * call site.\n */\nexport async function generateKeypair(): Promise<{ identity: string; recipient: string }> {\n const age = await loadAge();\n const identity = await age.generateX25519Identity();\n return { identity, recipient: await age.identityToRecipient(identity) };\n}\n\n/**\n * Derive the public `age1` recipient from an `AGE-SECRET-KEY-1` identity.\n *\n * @throws KaguraCryptoError if `identity` is not a valid age identity.\n */\nexport async function recipientFromIdentity(identity: string): Promise<string> {\n const age = await loadAge();\n try {\n return await age.identityToRecipient(identity);\n } catch (e) {\n throw identityParseError(e);\n }\n}\n\n/**\n * The error for a malformed `AGE-SECRET-KEY-1` string — deliberately\n * carrying **nothing** from the underlying failure.\n *\n * `@scure/base`, under `age-encryption`, puts the whole offending string in\n * its bech32 messages:\n *\n * Invalid checksum in AGE-SECRET-KEY-18L790E7K3SJJY...: expected \"zshwqn\"\n *\n * Interpolating that — or attaching it as `cause`, which Node prints when\n * an error is logged — writes the private key into logs, CI output, and\n * whatever error reporter is downstream. The cause chain is dropped for the\n * same reason; nothing about a malformed string is worth that.\n *\n * Note this is a TypeScript-only hazard: `pyrage` answers \"invalid Bech32\n * encoding\" and echoes nothing, so the Python port interpolates its error\n * safely. Verified against both implementations rather than assumed.\n */\nfunction identityParseError(_cause: unknown): KaguraCryptoError {\n return new KaguraCryptoError(\n \"invalid age identity: the identity string is not a well-formed \" +\n \"AGE-SECRET-KEY-1 value. The underlying parser error is withheld \" +\n \"because it echoes the input, which would write the private key to \" +\n \"logs.\",\n );\n}\n\n/**\n * The server fingerprint: `sha256` hex of the recipient string.\n *\n * Mirrors Python's `hashlib.sha256(pubkey.encode(\"utf-8\")).hexdigest()`\n * exactly, so a locally computed value can be compared against\n * `PubkeyResponse.fingerprint` byte for byte. Needs no crypto package —\n * `node:crypto` is enough.\n */\nexport function fingerprint(pubkey: string): string {\n return createHash(\"sha256\").update(pubkey, \"utf8\").digest(\"hex\");\n}\n\n/** Wrap a binary age file in RFC 7468 PEM armor (64-column base64). */\nexport function armorEncode(binary: Uint8Array): string {\n const b64 = Buffer.from(binary).toString(\"base64\");\n const lines: string[] = [];\n for (let i = 0; i < b64.length; i += 64) {\n lines.push(b64.slice(i, i + 64));\n }\n // An empty body would otherwise emit a blank line, which is not valid PEM.\n const body = lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\";\n return `${ARMOR_BEGIN}\\n${body}${ARMOR_END}\\n`;\n}\n\n/**\n * Reverse {@link armorEncode}. Tolerant of CRLF and surrounding blanks.\n *\n * @throws KaguraCryptoError if the input is not a well-formed armored age file.\n */\nexport function armorDecode(armored: string): Uint8Array {\n const lines = armored\n .trim()\n .split(/\\r?\\n/)\n .map((line) => line.trim());\n if (lines.length < 2 || lines[0] !== ARMOR_BEGIN || lines[lines.length - 1] !== ARMOR_END) {\n throw new KaguraCryptoError(\"not an armored age file (missing PEM header/footer)\");\n }\n const body = lines.slice(1, -1).join(\"\");\n // Buffer.from(..., \"base64\") silently discards non-base64 characters, so\n // validate first — Python passes validate=True for the same reason. A\n // corrupt body must be an error, not a shorter plaintext.\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(body) || body.length % 4 !== 0) {\n throw new KaguraCryptoError(\"corrupt armored age body: invalid base64\");\n }\n return new Uint8Array(Buffer.from(body, \"base64\"));\n}\n\n/**\n * Encrypt `plaintext` to one or more age recipients; return armored age.\n *\n * @throws KaguraCryptoError on empty or malformed recipients, an age\n * failure, or an armored result over {@link MAX_CIPHERTEXT_BYTES}.\n */\nexport async function encrypt(plaintext: Uint8Array, recipients: string[]): Promise<string> {\n if (recipients.length === 0) {\n throw new KaguraCryptoError(\"at least one recipient is required to encrypt\");\n }\n for (const r of recipients) {\n if (!RECIPIENT_RE.test(r)) {\n throw new KaguraCryptoError(`malformed age recipient: ${JSON.stringify(r)}`);\n }\n }\n\n const age = await loadAge();\n let binary: Uint8Array;\n try {\n const encrypter = new age.Encrypter();\n for (const r of recipients) {\n encrypter.addRecipient(r);\n }\n binary = await encrypter.encrypt(plaintext);\n } catch (e) {\n throw new KaguraCryptoError(`age encryption failed: ${excMessage(e)}`, { cause: e });\n }\n\n const armored = armorEncode(binary);\n // Armor is ASCII, so byte length and character count agree; measured in\n // bytes to match Python's `len(armored.encode(\"ascii\"))`.\n const size = Buffer.byteLength(armored, \"ascii\");\n if (size > MAX_CIPHERTEXT_BYTES) {\n throw new KaguraCryptoError(\n `ciphertext is ${size} bytes, exceeds the ${MAX_CIPHERTEXT_BYTES}-byte cap`,\n );\n }\n return armored;\n}\n\n/**\n * Decrypt an armored age ciphertext with an `AGE-SECRET-KEY-1` identity.\n *\n * @throws KaguraCryptoError on input over the size cap, malformed armor, a\n * bad identity, or a decrypt failure (wrong identity / corrupt ciphertext).\n */\nexport async function decrypt(armored: string, identity: string): Promise<Uint8Array> {\n // Inbound cap first, symmetric with encrypt, so an oversized blob is\n // rejected before armor parsing walks the whole string.\n //\n // Measured in bytes, not `armored.length`. Python writes `len(armored)`,\n // which counts code points, and for valid input the two agree exactly —\n // armor is ASCII — so this is identical in both SDKs for anything that\n // could actually decrypt. It differs only for input that is already\n // invalid, where a byte count is both truer to the message and stricter.\n const size = Buffer.byteLength(armored, \"utf8\");\n if (size > MAX_CIPHERTEXT_BYTES) {\n throw new KaguraCryptoError(\n `ciphertext is ${size} bytes, exceeds the ${MAX_CIPHERTEXT_BYTES}-byte cap`,\n );\n }\n const binary = armorDecode(armored);\n const age = await loadAge();\n\n // Split from the decrypt below so a bad identity string does not get\n // reported as \"decryption failed\" — `addIdentity` parses eagerly, and the\n // two causes need different fixes. Same split as Python's\n // `Identity.from_str` / `pyrage.decrypt` pair.\n const decrypter = new age.Decrypter();\n try {\n decrypter.addIdentity(identity);\n } catch (e) {\n // Message and cause both withheld — see identityParseError.\n throw identityParseError(e);\n }\n\n try {\n return await decrypter.decrypt(binary);\n } catch (e) {\n throw new KaguraCryptoError(`age decryption failed: ${excMessage(e)}`, { cause: e });\n }\n}\n","/**\n * `kagura-memory setup claude` — wire Claude Code to Kagura Memory.\n *\n * Writes `.kagura.json` and `.mcp.json` in the project directory, merging\n * with whatever is already there, and makes sure both are gitignored.\n *\n * Python has a second, OAuth path that writes a *stdio* `.mcp.json`\n * launching its `kagura-mcp` proxy so no API key is ever written to disk.\n * That proxy is a Python console script with no counterpart in this\n * package, so `--profile` reports that rather than writing a config that\n * would name a binary the user does not have.\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { rejectExtraArgs, type Command, type CommandGroup } from \"../command.js\";\nimport { formatJson } from \"../output.js\";\nimport { CliError, CliUsageError } from \"../parse.js\";\nimport type { FlagSpec } from \"../parseArgs.js\";\nimport { resolveConfig } from \"../runClientCommand.js\";\n\nconst API_KEY: FlagSpec = { name: \"api-key\", type: \"value\", help: \"Kagura API key (skip prompt)\" };\nconst MCP_URL: FlagSpec = { name: \"mcp-url\", type: \"value\", metavar: \"URL\", help: \"MCP URL\" };\nconst CONTEXT_ID: FlagSpec = { name: \"context-id\", short: \"c\", type: \"value\", help: \"Context ID\" };\nconst PROFILE: FlagSpec = { name: \"profile\", type: \"value\", help: \"OAuth profile name\" };\nconst PROJECT_DIR: FlagSpec = {\n name: \"project-dir\",\n type: \"value\",\n metavar: \"DIR\",\n help: \"Project directory\",\n defaultLabel: \".\",\n};\n\n/** Parse a JSON file, treating \"absent\" and \"empty\" as `{}`. */\nfunction readJsonSafe(target: string): Record<string, unknown> {\n if (!fs.existsSync(target)) return {};\n let text: string;\n try {\n text = fs.readFileSync(target, \"utf-8\");\n } catch (e) {\n throw new CliError(`cannot read ${target}: ${e instanceof Error ? e.message : String(e)}`);\n }\n if (!text.trim()) return {};\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 Record<string, unknown>;\n } catch (e) {\n // Overwriting a file we could not understand would discard whatever\n // the operator had configured there.\n throw new CliError(\n `refusing to rewrite ${target}: it is not a JSON object (${e instanceof Error ? e.message : String(e)})`,\n );\n }\n}\n\n/**\n * Write a config file that carries credentials.\n *\n * Both files this command writes hold the API key, so they are created\n * 0600 and tightened even when they already existed — `writeFileSync`\n * applies `mode` only on creation, and the default 0644 under the common\n * umask lets any other local account read the key out of a shared build\n * host's workspace.\n */\nfunction writeJson(target: string, data: Record<string, unknown>): void {\n fs.writeFileSync(target, `${JSON.stringify(data, null, 2)}\\n`, {\n encoding: \"utf-8\",\n mode: 0o600,\n });\n try {\n fs.chmodSync(target, 0o600);\n } catch {\n // Windows has no POSIX mode bits; chmod there only toggles read-only.\n // The write above is what matters, and the tests skip the assertion.\n }\n}\n\n/**\n * Ensure `.gitignore` lists the files that now hold credentials.\n *\n * `.kagura.json` and the static-token `.mcp.json` both carry the API key;\n * committing either publishes it.\n */\nfunction protectSecrets(projectDir: string, files: string[]): string[] {\n const target = path.join(projectDir, \".gitignore\");\n const existing = fs.existsSync(target) ? fs.readFileSync(target, \"utf-8\") : \"\";\n const lines = new Set(existing.split(/\\r?\\n/).map((l) => l.trim()));\n const missing = files.filter((f) => !lines.has(f) && !lines.has(`/${f}`));\n if (missing.length === 0) return [];\n const prefix = existing === \"\" || existing.endsWith(\"\\n\") ? \"\" : \"\\n\";\n fs.appendFileSync(\n target,\n `${prefix}\\n# Kagura Memory — these carry credentials\\n${missing.join(\"\\n\")}\\n`,\n \"utf-8\",\n );\n return missing;\n}\n\nconst claude: Command = {\n summary: \"Set up Kagura Memory integration for Claude Code.\",\n spec: {\n flags: [\n API_KEY,\n MCP_URL,\n CONTEXT_ID,\n PROFILE,\n PROJECT_DIR,\n // Accepted so a script written for the Python CLI still runs, but\n // inert: this port never prompts, so it is already what the flag\n // asks for. Said in the help rather than silently ignored — a flag\n // that reads as changing behaviour and does not is worse than one\n // that is rejected.\n {\n name: \"non-interactive\",\n short: \"y\",\n type: \"switch\",\n help: \"Accepted for compatibility; this port never prompts\",\n },\n ],\n },\n run: async (deps, args) => {\n rejectExtraArgs(args);\n const apiKey = args.values[\"api-key\"];\n const profile = args.values.profile;\n\n if (profile !== undefined && apiKey !== undefined) {\n throw new CliUsageError(\n \"--profile (OAuth) and --api-key (static token) are mutually exclusive; pick one.\",\n );\n }\n if (profile !== undefined) {\n // Writing the stdio form would name `kagura-mcp`, a Python console\n // script this package does not install — the config would look right\n // and fail at launch.\n throw new CliError(\n \"the OAuth (--profile) setup writes an .mcp.json that launches the `kagura-mcp` stdio\\n\" +\n \" proxy, which ships with the Python package, not this one.\\n\" +\n \" Use `pip install kagura-memory && kagura setup claude --profile \" +\n `${profile}\\`, or set up the static-token form here with --api-key.`,\n );\n }\n\n const projectDir = path.resolve(args.values[\"project-dir\"] ?? \".\");\n if (!fs.existsSync(projectDir)) {\n throw new CliUsageError(`Invalid value for '--project-dir': ${projectDir} does not exist.`);\n }\n\n // Fall back to whatever is already configured, so re-running with no\n // flags refreshes the files rather than blanking them.\n const { config } = resolveConfig(deps, undefined, false);\n const resolvedKey = apiKey ?? (typeof config.api_key === \"string\" ? config.api_key : \"\");\n const resolvedUrl =\n args.values[\"mcp-url\"] ??\n (typeof config.mcp_url === \"string\" && config.mcp_url\n ? config.mcp_url\n : \"https://memory.kagura-ai.com/mcp\");\n const contextId = args.values[\"context-id\"] ?? config.context_id ?? \"\";\n\n if (!resolvedKey) {\n throw new CliError(\n \"no API key: pass --api-key, or set one in .kagura.json.\\n\" +\n \" For OAuth instead, run: kagura-memory auth login\",\n );\n }\n\n const kaguraPath = path.join(projectDir, \".kagura.json\");\n const kagura = readJsonSafe(kaguraPath);\n kagura.api_key = resolvedKey;\n kagura.mcp_url = resolvedUrl;\n if (contextId) kagura.context_id = contextId;\n writeJson(kaguraPath, kagura);\n\n const mcpPath = path.join(projectDir, \".mcp.json\");\n const mcp = readJsonSafe(mcpPath);\n const servers = (mcp.mcpServers as Record<string, unknown> | undefined) ?? {};\n // The entry is replaced wholesale rather than merged: a stale header\n // from a previous key would keep authenticating as the old identity.\n servers[\"kagura-memory\"] = {\n type: \"url\",\n url: resolvedUrl,\n headers: { Authorization: `Bearer ${resolvedKey}` },\n };\n mcp.mcpServers = servers;\n writeJson(mcpPath, mcp);\n\n const ignored = protectSecrets(projectDir, [\".kagura.json\", \".mcp.json\"]);\n\n deps.write(\n formatJson({\n status: \"success\",\n project_dir: projectDir,\n wrote: [kaguraPath, mcpPath],\n gitignore_added: ignored,\n // Never echo the key itself back.\n mcp_url: resolvedUrl,\n context_id: contextId || null,\n }),\n );\n return 0;\n },\n};\n\nexport const SETUP_GROUP: CommandGroup = {\n summary: \"Set up Kagura integrations for AI coding tools.\",\n commands: { claude },\n};\n","/**\n * `kagura-memory auth …` — the subcommands, with every side effect\n * injected so they can be exercised without a terminal or a network.\n *\n * Deliberately only `auth`. Memory operations stay library-only: the\n * credentials file is the artifact both SDKs share, so converging there is\n * the point, whereas duplicating the whole Python CLI surface would just\n * multiply the parity drift this repo has already spent several PRs\n * fixing.\n *\n * Flag names match `kagura auth …` exactly so documentation and muscle\n * memory transfer.\n */\n\nimport {\n DEFAULT_SCOPE,\n READ_ONLY_SCOPE,\n login,\n type LoginOptions,\n} from \"../auth/login.js\";\nimport { refresh, type RefreshOptions } from \"../auth/refresh.js\";\nimport {\n deleteCredentialsFile,\n deleteProfile,\n isExpired,\n loadCredentialsFile,\n setDefaultProfile,\n type OAuthCredentials,\n} from \"../auth/credentials.js\";\nimport type { DeviceAuthorizationResponse } from \"../auth/deviceFlow.js\";\nimport { excMessage } from \"../errors.js\";\nimport { SDK_VERSION } from \"../version.js\";\nimport {\n isGroup,\n renderGroupHelp,\n renderHelp,\n type Command,\n type CommandDeps,\n type CommandGroup,\n} from \"./command.js\";\nimport {\n CONFIG_GROUP,\n CONTEXTS_ALIAS,\n CONTEXT_GROUP,\n} from \"./commands/context.js\";\nimport { DOCTOR } from \"./commands/doctor.js\";\nimport { FILES_GROUP } from \"./commands/files.js\";\nimport { EDGE_GROUP, SLEEP_GROUP } from \"./commands/graph.js\";\nimport { MEMORY_COMMANDS } from \"./commands/memory.js\";\nimport { RESOURCE_GROUP } from \"./commands/resource.js\";\nimport { SECRET_GROUP } from \"./commands/secret.js\";\nimport { SETUP_GROUP } from \"./commands/setup.js\";\nimport { CliUsageError } from \"./parse.js\";\nimport { parseArgs, type ParseSpec, type ParsedArgs } from \"./parseArgs.js\";\n\n/**\n * Every option the `auth` subcommands accept, pooled.\n *\n * Pooled rather than per-subcommand because the pool is small and entirely\n * unambiguous — no two `auth` subcommands give the same flag different\n * meanings — and because `cmdLogin`/`cmdLogout` already reject the\n * combinations that are individually valid but mutually exclusive.\n */\nconst AUTH_SPEC: ParseSpec = {\n flags: [\n { name: \"profile\", type: \"value\", rejectEmpty: true, help: \"Profile to act on (default: the file's default)\" },\n { name: \"server\", type: \"value\", rejectEmpty: true, metavar: \"URL\", help: \"MCP server URL to authenticate against\" },\n { name: \"scope\", type: \"value\", rejectEmpty: true, help: 'Space-separated scopes, e.g. \"memory:read memory:write\"' },\n { name: \"read-only\", type: \"switch\", help: \"Request memory:read only\" },\n { name: \"no-browser\", type: \"switch\", help: \"Print the code and URL without opening a browser\" },\n { name: \"all\", type: \"switch\", help: \"logout: remove every stored profile\" },\n { name: \"yes\", type: \"switch\", help: \"logout: skip the confirmation prompt\" },\n ],\n};\n\nexport interface CliDeps extends CommandDeps {\n /** Best-effort browser launch; returns false when it could not open. */\n openBrowser: (url: string) => Promise<boolean>;\n login: typeof login;\n refresh: typeof refresh;\n /** Overrides for tests; production passes nothing. */\n credentialsPath?: string;\n}\n\nconst ROOT_SUMMARY = \"Kagura Memory Cloud CLI - AI-driven memory management.\";\n\nconst ROOT_EPILOG = `\nCredentials live in ~/.kagura/credentials.json and are shared with the\nPython CLI, so either tool can create or use a profile. The context id\ncomes from --context-id, or from \"context_id\" in .kagura.json.\n\nScopes:\n memory:read read memories, contexts, files\n memory:write create/update/delete memories, contexts, files\n\nDefault scope is \"${DEFAULT_SCOPE}\"; --read-only requests \"${READ_ONLY_SCOPE}\".\nNarrowing a scope on refresh is silent; widening needs consent, so it\nre-runs the device flow.`;\n\n/** Print the code and URL, then optionally try to open a browser. */\nfunction devicePrompt(deps: CliDeps, openBrowserFlag: boolean) {\n return async (auth: DeviceAuthorizationResponse): Promise<void> => {\n const url = auth.verificationUriComplete || auth.verificationUri;\n // Unconditionally, and before any launch attempt: if the browser opens\n // silently or fails, the operator can still copy the code by eye.\n deps.write(\"\");\n deps.write(` First copy your one-time code: ${auth.userCode}`);\n deps.write(\" Then approve at:\");\n deps.write(` ${url}`);\n deps.write(\"\");\n\n if (!openBrowserFlag) {\n deps.write(\" (--no-browser: not opening a browser; still polling here.)\");\n return;\n }\n if (!(await deps.openBrowser(url))) {\n deps.write(\" (Could not open a browser — use the URL above.)\");\n }\n };\n}\n\n/**\n * A human label for the workspace.\n *\n * `workspace_name` is optional in the token response and parses to `\"\"`\n * when absent, so printing it bare yields \"workspace .\" — fall back to the\n * id, which the response does carry.\n */\nfunction workspaceLabel(creds: OAuthCredentials): string {\n return creds.workspaceName || creds.workspaceId || \"(unknown)\";\n}\n\nfunction describeProfile(name: string, creds: OAuthCredentials, isDefault: boolean): string[] {\n const expired = isExpired(creds);\n const refreshable = Boolean(creds.refreshToken);\n // A profile whose access token has expired is still usable when it can\n // refresh; only one that cannot is genuinely dead.\n const state = !expired ? \"active\" : refreshable ? \"expired (refreshable)\" : \"expired\";\n return [\n `${isDefault ? \"*\" : \" \"} ${name}`,\n ` account: ${creds.userEmail || \"(unknown)\"}`,\n ` workspace: ${workspaceLabel(creds)}`,\n ` server: ${creds.server}`,\n ` scope: ${creds.scope || \"(unknown)\"}`,\n ` expires: ${creds.expiresAt.toISOString()}`,\n ` state: ${state}`,\n ` refreshable: ${refreshable}`,\n ];\n}\n\nasync function cmdLogin(deps: CliDeps, args: ReturnType<typeof parseArgs>): Promise<number> {\n const readOnly = args.flags.has(\"read-only\");\n const scope = args.values.scope;\n if (readOnly && scope !== undefined) {\n deps.writeError(\"--read-only and --scope are mutually exclusive; pick one.\");\n return 2;\n }\n\n const options: LoginOptions = {\n onUserCode: devicePrompt(deps, !args.flags.has(\"no-browser\")),\n };\n if (args.values.profile !== undefined) options.profile = args.values.profile;\n if (args.values.server !== undefined) options.mcpUrl = args.values.server;\n if (readOnly) options.scope = READ_ONLY_SCOPE;\n else if (scope !== undefined) options.scope = scope;\n if (deps.credentialsPath !== undefined) options.credentialsPath = deps.credentialsPath;\n\n const creds = await deps.login(options);\n deps.write(\n `Logged in as ${creds.userEmail || \"(unknown)\"} — workspace ${workspaceLabel(creds)}.`,\n );\n deps.write(`Profile '${args.values.profile ?? \"default\"}' saved. Scope: ${creds.scope}`);\n return 0;\n}\n\nasync function cmdRefresh(deps: CliDeps, args: ReturnType<typeof parseArgs>): Promise<number> {\n const options: RefreshOptions = {\n onUserCode: devicePrompt(deps, !args.flags.has(\"no-browser\")),\n };\n if (args.values.profile !== undefined) options.profile = args.values.profile;\n if (args.values.scope !== undefined) options.scope = args.values.scope;\n if (deps.credentialsPath !== undefined) options.credentialsPath = deps.credentialsPath;\n\n const creds = await deps.refresh(options);\n deps.write(`Refreshed. Expires ${creds.expiresAt.toISOString()}. Scope: ${creds.scope}`);\n return 0;\n}\n\nfunction cmdStatus(deps: CliDeps, args: ReturnType<typeof parseArgs>): number {\n const cf = loadCredentialsFile(deps.credentialsPath);\n const names = Object.keys(cf.profiles);\n if (names.length === 0) {\n deps.write(\"No profiles. Run: kagura-memory auth login\");\n return 0;\n }\n\n const only = args.values.profile;\n if (only !== undefined) {\n const creds = cf.profiles[only];\n if (creds === undefined) {\n deps.writeError(`No profile named '${only}'.`);\n return 1;\n }\n for (const line of describeProfile(only, creds, cf.defaultProfile === only)) {\n deps.write(line);\n }\n return 0;\n }\n\n for (const name of names) {\n for (const line of describeProfile(name, cf.profiles[name]!, cf.defaultProfile === name)) {\n deps.write(line);\n }\n }\n return 0;\n}\n\nasync function cmdUse(deps: CliDeps, args: ReturnType<typeof parseArgs>): Promise<number> {\n const name = args.positionals[0];\n if (name === undefined) {\n deps.writeError(\"Usage: kagura-memory auth use <profile>\");\n return 2;\n }\n // setDefaultProfile rejects an unknown name under the lock, so a typo\n // cannot leave the file pointing at a profile that does not exist.\n await setDefaultProfile(name, deps.credentialsPath);\n deps.write(`Default profile is now '${name}'.`);\n return 0;\n}\n\nasync function cmdLogout(deps: CliDeps, args: ReturnType<typeof parseArgs>): Promise<number> {\n const all = args.flags.has(\"all\");\n const target = args.values.profile;\n if (all && target !== undefined) {\n deps.writeError(\"--all and --profile are mutually exclusive; pick one.\");\n return 2;\n }\n\n const cf = loadCredentialsFile(deps.credentialsPath);\n\n // emptyCredentialsFile() names a default profile even when none are\n // stored, so an untargeted logout would otherwise report \"No profile\n // named 'default'\" and exit 1 on a fresh machine — breaking\n // `logout --yes` in idempotent setup scripts. Nothing to remove is the\n // desired end state, not a failure. An explicitly named profile is\n // still a real mismatch and reported below.\n if (!all && target === undefined && Object.keys(cf.profiles).length === 0) {\n deps.write(\"No profiles stored; nothing to do.\");\n return 0;\n }\n\n const name = target ?? cf.defaultProfile;\n const question = all\n ? \"Remove ALL stored profiles?\"\n : `Remove profile '${name}'?`;\n if (!args.flags.has(\"yes\") && !(await deps.confirm(question))) {\n deps.write(\"Cancelled.\");\n return 1;\n }\n\n if (all) {\n deleteCredentialsFile(deps.credentialsPath);\n deps.write(\"All profiles removed.\");\n return 0;\n }\n // deleteProfile is a no-op on an absent profile; say so rather than\n // reporting a removal that did not happen.\n const existed = cf.profiles[name] !== undefined;\n await deleteProfile(name, deps.credentialsPath);\n deps.write(existed ? `Profile '${name}' removed.` : `No profile named '${name}'.`);\n return existed ? 0 : 1;\n}\n\n/**\n * `kagura auth list` — one line per profile, default marked with `*`.\n *\n * `status` prints the full block; this is the version you can eyeball or\n * pipe into a picker.\n */\nfunction cmdList(deps: CliDeps): number {\n const cf = loadCredentialsFile(deps.credentialsPath);\n const names = Object.keys(cf.profiles).sort();\n if (names.length === 0) {\n deps.write(\"No profiles. Run: kagura-memory auth login\");\n return 0;\n }\n for (const name of names) {\n const creds = cf.profiles[name]!;\n const marker = cf.defaultProfile === name ? \"*\" : \" \";\n const state = !isExpired(creds) ? \"active\" : creds.refreshToken ? \"expired (refreshable)\" : \"expired\";\n deps.write(`${marker} ${name}\\t${creds.userEmail || \"(unknown)\"}\\t${workspaceLabel(creds)}\\t${state}`);\n }\n return 0;\n}\n\n/**\n * `kagura auth token` — the raw access token on stdout, for CI.\n *\n * Refreshes first when the stored token has expired, so a script does not\n * have to distinguish \"no token\" from \"stale token\". The value is printed\n * bare, with no trailing decoration, so `$(… auth token)` is exact.\n */\nasync function cmdToken(deps: CliDeps, args: ReturnType<typeof parseArgs>): Promise<number> {\n const cf = loadCredentialsFile(deps.credentialsPath);\n const name = args.values.profile ?? cf.defaultProfile;\n const creds = cf.profiles[name];\n if (creds === undefined) {\n deps.writeError(`No profile named '${name}'.\\n Run: kagura-memory auth login`);\n return 1;\n }\n if (!isExpired(creds)) {\n deps.write(creds.accessToken);\n return 0;\n }\n if (!creds.refreshToken) {\n deps.writeError(`Profile '${name}' has expired and cannot refresh.\\n Run: kagura-memory auth login`);\n return 1;\n }\n const options: RefreshOptions = {};\n if (args.values.profile !== undefined) options.profile = args.values.profile;\n if (deps.credentialsPath !== undefined) options.credentialsPath = deps.credentialsPath;\n const refreshed = await deps.refresh(options);\n deps.write(refreshed.accessToken);\n return 0;\n}\n\n/** The `auth` subcommands, as registry entries. */\nconst AUTH_GROUP: CommandGroup = {\n summary: \"OAuth2 device-flow authentication for Kagura Memory.\",\n commands: {\n login: {\n summary: \"Authenticate via OAuth2 device flow.\",\n spec: AUTH_SPEC,\n run: (deps, args) => cmdLogin(deps as CliDeps, args),\n },\n refresh: {\n summary: \"Rotate access_token (optionally requesting a new scope).\",\n spec: AUTH_SPEC,\n run: (deps, args) => cmdRefresh(deps as CliDeps, args),\n },\n status: {\n summary: \"Show the current profile, server, scope, expiry, and workspace.\",\n spec: AUTH_SPEC,\n run: async (deps, args) => cmdStatus(deps as CliDeps, args),\n },\n use: {\n summary: \"Set the default profile used when none is selected.\",\n args: \"PROFILE\",\n spec: AUTH_SPEC,\n run: (deps, args) => cmdUse(deps as CliDeps, args),\n },\n logout: {\n summary: \"Delete a stored profile (or all of them).\",\n spec: AUTH_SPEC,\n run: (deps, args) => cmdLogout(deps as CliDeps, args),\n },\n list: {\n summary: \"List every stored profile; the default is marked with `*`.\",\n spec: AUTH_SPEC,\n run: async (deps) => cmdList(deps as CliDeps),\n },\n token: {\n summary: \"Emit the raw access_token to stdout (for CI / scripts).\",\n spec: AUTH_SPEC,\n run: (deps, args) => cmdToken(deps as CliDeps, args),\n },\n },\n};\n\n/** Everything reachable as `kagura-memory <name> …`. */\nexport const ROOT_COMMANDS: Record<string, Command | CommandGroup> = {\n auth: AUTH_GROUP,\n config: CONFIG_GROUP,\n context: CONTEXT_GROUP,\n doctor: DOCTOR,\n contexts: CONTEXTS_ALIAS,\n edge: EDGE_GROUP,\n files: FILES_GROUP,\n resource: RESOURCE_GROUP,\n secret: SECRET_GROUP,\n setup: SETUP_GROUP,\n sleep: SLEEP_GROUP,\n ...MEMORY_COMMANDS,\n};\n\n/**\n * `kagura-memory login` — accepted because v0.7.0 shipped the bin with\n * only `auth`, and both spellings worked. Not listed in the root help;\n * `auth login` is canonical and matches the Python CLI.\n */\nconst BARE_AUTH_ALIASES = new Set(Object.keys(AUTH_GROUP.commands));\n\ninterface Resolved {\n command: Command;\n /** Display path for help and errors, e.g. `kagura-memory auth login`. */\n path: string;\n /** argv with the command tokens removed. */\n rest: string[];\n}\n\n/**\n * Find the command argv names, without a spec.\n *\n * Resolution has to happen before parsing — the parser needs the command's\n * own flag spec to know which tokens are values — so it reads only leading\n * non-flag tokens and walks the registry with them.\n */\nfunction resolve(argv: string[], deps: CliDeps): Resolved | { help: string; code: number } {\n const head = argv[0];\n if (head === undefined || head.startsWith(\"-\")) {\n // No command: `--help` is a request, a bare invocation is a mistake.\n const wantsHelp = head === \"--help\" || head === \"-h\";\n return { help: renderRootHelp(), code: wantsHelp ? 0 : 2 };\n }\n if (head === \"help\") {\n return { help: renderRootHelp(), code: 0 };\n }\n\n const found: Command | CommandGroup | undefined = BARE_AUTH_ALIASES.has(head)\n ? AUTH_GROUP.commands[head]\n : ROOT_COMMANDS[head];\n if (found === undefined) {\n deps.writeError(`Error: No such command '${head}'.`);\n return { help: renderRootHelp(), code: 2 };\n }\n let entry: Command | CommandGroup = found;\n\n // Groups nest — `resource tokens list` is three levels — so walk until a\n // leaf, taking one non-flag token per level.\n const path = BARE_AUTH_ALIASES.has(head) ? [\"auth\", head] : [head];\n let index = 1;\n while (isGroup(entry)) {\n const groupPath = `kagura-memory ${path.join(\" \")}`;\n const next = argv[index];\n if (next === undefined || next.startsWith(\"-\")) {\n const wantsHelp = next === \"--help\" || next === \"-h\";\n return {\n help: renderGroupHelp(groupPath, entry.summary, entry.commands),\n code: wantsHelp ? 0 : 2,\n };\n }\n const child: Command | CommandGroup | undefined = entry.commands[next];\n if (child === undefined) {\n deps.writeError(`Error: No such command '${next}'.`);\n return { help: renderGroupHelp(groupPath, entry.summary, entry.commands), code: 2 };\n }\n entry = child;\n path.push(next);\n index += 1;\n }\n\n return { command: entry, path: `kagura-memory ${path.join(\" \")}`, rest: argv.slice(index) };\n}\n\nfunction renderRootHelp(): string {\n return `${renderGroupHelp(\"kagura-memory\", ROOT_SUMMARY, ROOT_COMMANDS)}\\n${ROOT_EPILOG}`;\n}\n\n/**\n * Run one CLI invocation.\n *\n * @returns the process exit code. Never throws for expected failures —\n * Kagura errors carry their own next-step guidance and are reported with\n * it intact rather than as a stack trace.\n */\nexport async function runCli(argv: string[], deps: CliDeps): Promise<number> {\n if (argv[0] === \"--version\") {\n deps.write(`kagura-memory, version ${SDK_VERSION}`);\n return 0;\n }\n\n const resolved = resolve(argv, deps);\n if (\"help\" in resolved) {\n if (resolved.code === 0) deps.write(resolved.help);\n else deps.writeError(resolved.help);\n return resolved.code;\n }\n\n const { command, path, rest } = resolved;\n const parsed = parseArgs(\n rest,\n command.spec,\n command.passthrough === true ? { stopAtPositional: true } : {},\n );\n\n if (parsed.flags.has(\"help\")) {\n deps.write(renderHelp(path, command));\n return 0;\n }\n\n // Only the flags that declare `rejectEmpty`. Python accepts an empty\n // value everywhere, and three behaviours here depend on that:\n // `--context-id=` falls through to the config via its `or` chain, and\n // `--tags=` / `--details=` treat blank as unset so an unset shell\n // variable is not a hard error. Rejecting every empty value globally\n // contradicted all three — the guard belongs on `--profile` and\n // `--scope`, where \"\" does damage rather than nothing.\n const empty = command.spec.flags\n .filter((flag) => flag.rejectEmpty === true)\n .filter((flag) => {\n const value = parsed.values[flag.name];\n return value !== undefined && value.trim() === \"\";\n })\n .map((flag) => `--${flag.name}`);\n\n if (parsed.unknown.length > 0 || parsed.missingValue.length > 0 || empty.length > 0) {\n for (const flag of parsed.unknown) {\n deps.writeError(`Unknown option: ${flag}`);\n }\n for (const flag of parsed.missingValue) {\n deps.writeError(`Option ${flag} needs a value.`);\n }\n for (const flag of empty) {\n deps.writeError(`Option ${flag} needs a non-empty value.`);\n }\n deps.writeError(renderHelp(path, command));\n return 2;\n }\n\n // The parser lifts the first positional into `command`; commands read\n // their arguments positionally, so put it back.\n const args: ParsedArgs = {\n ...parsed,\n positionals: [\n ...(parsed.command === \"\" ? [] : [parsed.command]),\n ...parsed.positionals,\n // For a passthrough command the remainder was never parsed; it is\n // the child's argv and must arrive byte-for-byte.\n ...parsed.rest,\n ],\n };\n\n try {\n return await command.run(deps, args);\n } catch (e) {\n // Click prefixes both UsageError (exit 2) and ClickException (exit 1)\n // with \"Error: \"; the exit code is what tells a script which it was.\n deps.writeError(`Error: ${excMessage(e)}`);\n return e instanceof CliUsageError ? 2 : 1;\n }\n}\n","/**\n * Shared request contract for the agent bootstrap surfaces.\n *\n * `KaguraClient.getAgentBootstrap` (MCP tool arguments) and\n * `AgentsClient.bootstrap` (REST JSON body) carry the same seven optional\n * keys; this module keeps the two surfaces in lockstep without the REST\n * client importing the MCP module — the analogue of the Python SDK homing\n * `_bootstrap_payload` in models.py so agents_client.py never imports\n * client.py. `agentId` stays transport-specific (MCP argument vs URL\n * path).\n */\n\nimport type { AgentBootstrapComponentName } from \"./models.js\";\n\nexport interface GetAgentBootstrapOptions {\n /** Agent UUID from the registry (required). */\n agentId: string;\n /** Target context UUID. Omit to use the agent's default binding. */\n contextId?: string;\n /**\n * Opaque correlation id (max 128 chars, `[A-Za-z0-9._-]`); echoed in\n * the `correlation` block.\n */\n sessionId?: string;\n /**\n * Recall query (max 1024 chars). Supplying it enables the trusted-only\n * recall component; omit to skip recall — the server never fabricates\n * a query, so the component reports `status=\"skipped\"` even when\n * `include` names it.\n */\n query?: string;\n /** Number of recall results; forwarded to recall's `k` validation. */\n recallK?: number;\n /** Override for the pinned-set cap; clamped server-side to [1, 1000]. */\n pinnedCap?: number;\n /**\n * ISO upper bound for upcoming time memories (the lower bound is\n * always now).\n */\n upcomingUntil?: string;\n /**\n * Component selector — a subset of `\"pinned\"`, `\"recall\"`,\n * `\"upcoming\"`, `\"state\"`, `\"policy\"`. Omit for all components.\n */\n include?: AgentBootstrapComponentName[];\n}\n\n/**\n * Build the omit-when-undefined bootstrap payload shared by both\n * surfaces — the port of the Python SDK's `_bootstrap_payload`.\n * Internal — not part of the public API surface.\n */\nexport function buildBootstrapPayload(\n options: Omit<GetAgentBootstrapOptions, \"agentId\">,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n if (options.contextId !== undefined) {\n payload.context_id = options.contextId;\n }\n if (options.sessionId !== undefined) {\n payload.session_id = options.sessionId;\n }\n if (options.query !== undefined) {\n payload.query = options.query;\n }\n if (options.recallK !== undefined) {\n payload.recall_k = options.recallK;\n }\n if (options.pinnedCap !== undefined) {\n payload.pinned_cap = options.pinnedCap;\n }\n if (options.upcomingUntil !== undefined) {\n payload.upcoming_until = options.upcomingUntil;\n }\n if (options.include !== undefined) {\n payload.include = options.include;\n }\n return payload;\n}\n","/** Low-level client for Kagura Memory Cloud MCP tools (port of client.py). */\n\nimport { buildBootstrapPayload } from \"./agentBootstrap.js\";\nimport type { GetAgentBootstrapOptions } from \"./agentBootstrap.js\";\nimport { resolveAuth } from \"./auth/resolve.js\";\nimport type { AuthProvider } from \"./auth/types.js\";\nimport {\n excMessage,\n KaguraConnectionError,\n KaguraError,\n KaguraNotFoundError,\n KaguraQuotaError,\n} from \"./errors.js\";\nimport { baseUrlFromMcp, SDK_VERSION, throwForKaguraStatus, validateHttpsUrl } from \"./http.js\";\nimport type {\n Agent,\n AgentBinding,\n AgentBootstrapResponse,\n ContextInfo,\n DuplicatesResponse,\n Edge,\n EmbeddingModelsResponse,\n EmbeddingStatus,\n ListTagsResponse,\n MemoryListResponse,\n // Referenced only from JSDoc {@link} on the details/recallNearby options.\n MemoryLocation,\n MemoryStatsResponse,\n RecallNearbyResponse,\n RollbackResult,\n ServerInfo,\n SleepReport,\n SleepReportDetail,\n UsageInfo,\n} from \"./models.js\";\n\n/**\n * Minimum memory-cloud server version this SDK was tested against.\n *\n * The check is opt-in: callers must explicitly invoke\n * {@link KaguraClient.checkServerVersion} to log an advisory warning when\n * the connected server is older. Plain construction and tool calls never\n * throw on version mismatch; older servers may silently ignore unknown\n * parameters.\n */\nexport const MIN_SERVER_VERSION = \"0.17.1\";\n\nconst MIN_SERVER_VERSION_TUPLE = MIN_SERVER_VERSION.split(\".\").slice(0, 3).map(Number);\n\n/** Generic parsed-JSON result of an MCP tool call. */\nexport type ToolResult = Record<string, unknown>;\n\nexport type DeliveryMode = \"always\" | \"on_recall\" | \"on_trigger\";\nexport type SearchMode = \"hybrid\" | \"semantic\" | \"keyword\";\nexport type SourceType = \"file\" | \"url\" | \"vault\" | \"api\" | \"manual\";\n\n/** Agent lifecycle state — `updateAgent`'s fail-closed kill switch. */\nexport type AgentStatus = \"active\" | \"suspended\" | \"retired\";\n/** Binding enforcement ramp: `enforce` denies, `shadow` only logs. */\nexport type AgentEnforcementMode = \"shadow\" | \"enforce\";\n/**\n * Per-binding write gate: `\"deny\"` (server default) or `\"direct\"`.\n * `\"staged\"` is reserved for a later server phase.\n */\nexport type AgentWritePolicy = \"deny\" | \"direct\";\n\nexport interface KaguraClientOptions {\n /** Explicit Kagura API key. When omitted, the resolution chain runs. */\n apiKey?: string;\n /** Explicit MCP URL. When omitted, derived from the credential source. */\n mcpUrl?: string;\n /** Request timeout in milliseconds (default: 30000). */\n timeoutMs?: number;\n /** Named OAuth profile to load (overrides KAGURA_PROFILE and the file default). */\n profile?: string;\n /** Fetch implementation override (for tests; default: globalThis.fetch). */\n fetch?: typeof globalThis.fetch;\n /** Environment source override (for tests; default: process.env). */\n env?: Record<string, string | undefined>;\n /** Home directory override (for tests). */\n home?: string;\n}\n\nexport interface RememberOptions {\n contextId: string;\n /** Memory summary (10-500 chars). */\n summary: string;\n content: string;\n /** Memory type; the server validates against its own vocabulary. */\n type?: string;\n /** Importance score (0.0-1.0). */\n importance?: number;\n tags?: string[];\n /** Origin URI (e.g. `file:///`, `https://`, `vault://`). */\n sourceUri?: string;\n /** Existing memory UUIDs to declare as `declared_link` edges from this memory. */\n linkedMemoryIds?: string[];\n /** Source URIs to resolve into linked memories (unresolved URIs are skipped server-side). */\n linkedSourceUris?: string[];\n /** Origin classification; pairs with sourceUri for downstream filters. */\n sourceType?: SourceType;\n /** Why the memory exists and how to use it (max 2000 chars). */\n contextSummary?: string;\n /**\n * Structured details JSON, stored as-is.\n *\n * A `location: {@link MemoryLocation}` here is what makes the memory\n * reachable from {@link recallNearby}. `lat`/`lon` must be JSON numbers —\n * argument coercion does not recurse into `details`, so string-typed\n * numerics are rejected server-side with HTTP 422.\n */\n details?: Record<string, unknown>;\n /** Open-ended context metadata JSON. */\n context?: Record<string, unknown>;\n /**\n * UUID of an existing memory this one replaces.\n *\n * Creates a supersede edge: the old memory is shadowed out of default\n * recall but stays restorable and reachable via\n * `recall({ includeSuperseded: true })` and {@link explore}. Prefer this\n * over {@link forget} + `remember`, which destroys the history.\n */\n supersedes?: string;\n /**\n * When the memory is surfaced. `\"on_recall\"` (default) leaves it to\n * probabilistic recall; `\"always\"` pins it so every loadPinned call\n * returns it. Only sent when it differs from the server default.\n */\n deliveryMode?: DeliveryMode;\n}\n\nexport interface RecallOptions {\n /** Context ID for single-context search. */\n contextId?: string;\n query: string;\n /** Number of results (default 5). */\n k?: number;\n /** Enable AI reranking for higher quality results. */\n useRerank?: boolean;\n /**\n * Optional filters: `type`, `tags`, `tags_match` (\"any\"/\"all\"),\n * `created_after`/`created_before`, `updated_after`/`updated_before`,\n * `trust_tier` (\"trusted\" excludes external/connector-ingested memories).\n */\n filters?: Record<string, unknown>;\n searchMode?: SearchMode;\n /** Search across multiple contexts (2-20 IDs); contextId not required then. */\n contextIds?: string[];\n /** Include up to 3 graph discovery hints under `explore_hints`. */\n includeExploreHints?: boolean;\n /**\n * Include memories shadowed by a supersedes edge (default false).\n *\n * Superseded versions are demoted out of results by default; `true`\n * returns them annotated with `superseded_by`, which is what makes the\n * history {@link RememberOptions.supersedes} preserves actually\n * readable — audit and \"previous versions of this fact\" views.\n */\n includeSuperseded?: boolean;\n}\n\nexport interface UpdateMemoryOptions {\n contextId: string;\n /** UUID of memory to update in-place (provide exactly one of memoryId/externalId). */\n memoryId?: string;\n /** External resource ID for upsert lookup. */\n externalId?: string;\n summary?: string;\n content?: string;\n type?: string;\n importance?: number;\n tags?: string[];\n contextSummary?: string;\n /**\n * Structured details JSON. **Replaces `details` wholesale** — the server\n * does not deep-merge. Round-trip any keys you want to keep (notably\n * `location`, see {@link MemoryLocation}) or they are silently dropped.\n *\n * Omitted from the request when `undefined`; pass `{}` to clear.\n */\n details?: Record<string, unknown>;\n /** `\"always\"` pins, `\"on_recall\"` unpins; omit to leave unchanged. */\n deliveryMode?: DeliveryMode;\n}\n\nexport interface CreateContextOptions {\n /** Context name (lowercase alphanumeric + hyphen/underscore). */\n name: string;\n displayName?: string;\n description?: string;\n /** LLM-oriented summary (200-500 chars). */\n summary?: string;\n /** LLM-oriented memory usage guidelines. */\n usageGuide?: string;\n /** Resource identifier for external data ingestion. */\n resourceId?: string;\n /** Privacy flag (default: true). */\n isPrivate?: boolean;\n /** Embedding model (immutable after creation); see listEmbeddingModels(). */\n embeddingModel?: string;\n}\n\nexport interface UpdateContextOptions {\n contextId: string;\n displayName?: string;\n description?: string;\n summary?: string;\n usageGuide?: string;\n resourceId?: string;\n /** Public visibility (required for resource tokens). */\n isPublic?: boolean;\n /** Locked contexts cannot be deleted. */\n isLocked?: boolean;\n}\n\nexport interface SetupResourceOptions {\n resourceId: string;\n /** Context name (defaults to resourceId server-side). */\n name?: string;\n summary?: string;\n /** Token description. */\n description?: string;\n /** Token quota (1-10000, default 1000). */\n quotaEventsPerHour?: number;\n}\n\nexport interface ListTagsOptions {\n contextId: string;\n /** Maximum tags to return (1-500, default 50). */\n limit?: number;\n /** Minimum memory count per tag (1-10000, default 1). */\n minCount?: number;\n /** Sort order (default \"count\"). */\n sort?: \"count\" | \"recent\" | \"alpha\";\n /** Case-insensitive prefix filter (max 200 chars). */\n prefix?: string;\n /**\n * Multi-tag AND drill-down: restrict the vocabulary to memories whose\n * tags contain **all** of these values (`tags @> with_tags`), and exclude\n * these values from the returned tags.\n *\n * Combine with `prefix` for server-side faceted browsing — one call per\n * drill-down level, no local index. An empty array is a no-op filter and\n * is not sent.\n */\n withTags?: string[];\n}\n\nexport interface ListMemoriesOptions {\n /** Context UUID; omit for the caller's cross-context view. */\n contextId?: string;\n /** Case-insensitive substring filter on summaries (whitespace-only → no filter). */\n q?: string;\n scope?: \"working\" | \"persistent\";\n type?: string;\n /** Maximum results (1-500, default 50). */\n limit?: number;\n offset?: number;\n /** Time-window overlap lower bound (naive ISO) for type=\"time\" memories. */\n triggerFrom?: string;\n /** Time-window overlap upper bound (naive ISO). */\n triggerUntil?: string;\n /** \"created_at\" (default, newest-first) or \"trigger_from\" (soonest first). */\n orderBy?: \"created_at\" | \"trigger_from\";\n}\n\nexport interface RegisterAgentOptions {\n /** Workspace-unique agent name (max 255 chars). */\n name: string;\n /** Free-text description (max 10000 chars). */\n description?: string;\n /** Framework tag, e.g. `\"claude-code\"`, `\"langgraph\"` (max 100 chars). */\n framework?: string;\n /** Deployment environment, e.g. `\"production\"` (max 100 chars). */\n environment?: string;\n /** Agent build/prompt version (max 100 chars). */\n version?: string;\n}\n\nexport interface UpdateAgentOptions {\n agentId: string;\n /** New workspace-unique name (max 255 chars). */\n name?: string;\n /** New description (max 10000 chars). */\n description?: string;\n /** New framework tag (max 100 chars). */\n framework?: string;\n /** New environment (max 100 chars). */\n environment?: string;\n /** New version (max 100 chars). */\n version?: string;\n /**\n * Lifecycle state — the fail-closed kill switch: `\"suspended\"` /\n * `\"retired\"` agents get every key bound to them rejected at verify\n * time.\n */\n status?: AgentStatus;\n /**\n * Binding enforcement ramp. Setting `\"enforce\"` → `\"shadow\"` is an\n * audited privilege-widening event (bindings stop being enforced and\n * are only logged).\n */\n enforcementMode?: AgentEnforcementMode;\n}\n\n/**\n * The subtractive scope trio shared by {@link BindAgentContextOptions}\n * and {@link UpdateAgentBindingOptions} — the ONE type to extend when\n * memory-cloud #1286 ships the reserved `allowedMemoryTypes` /\n * `allowedSourceTypes` filters (the server accepts only null for them\n * until per-memory enforcement lands, so they are deliberately not\n * declared yet; adding them later is non-breaking).\n */\nexport interface AgentBindingScopeOptions {\n /** Whether the agent may read this context (server default: true). */\n canRead?: boolean;\n /** Write gate (server default: `\"deny\"`). */\n writePolicy?: AgentWritePolicy;\n /** Mark as the agent's bootstrap default binding (max one per agent). */\n isDefault?: boolean;\n}\n\nexport interface BindAgentContextOptions extends AgentBindingScopeOptions {\n agentId: string;\n /** Context to bind (must belong to the agent's workspace). */\n contextId: string;\n}\n\nexport interface UpdateAgentBindingOptions extends AgentBindingScopeOptions {\n agentId: string;\n /** Binding UUID from {@link KaguraClient.listAgentBindings}. */\n bindingId: string;\n}\n\nexport interface UpdateSearchConfigOptions {\n contextId: string;\n /** Semantic search weight (0.0-1.0); weights must sum to 1.0 (±0.01). */\n semanticWeight?: number;\n /** BM25 keyword search weight (0.0-1.0). */\n bm25Weight?: number;\n /** Candidate fetch multiplier (1-10). */\n fetchFactor?: number;\n useRerank?: boolean;\n /** \"voyage\", \"cohere\", or \"ollama\". */\n rerankerProvider?: string;\n rerankerModel?: string;\n}\n\n/**\n * Low-level client for Kagura Memory Cloud MCP tools.\n *\n * All methods may throw KaguraAuthError (authentication failed),\n * KaguraConnectionError (connection failed), or KaguraRateLimitError.\n *\n * MCP tool methods additionally translate the server's structured domain\n * errors (`{\"status\": \"error\", ...}`) into exceptions rather than\n * returning them as data: a missing context/memory/report throws\n * {@link KaguraNotFoundError}, any other domain error throws\n * {@link KaguraError}. Use try/catch rather than inspecting\n * `result.status`.\n *\n * Authentication resolution order when `apiKey` is omitted:\n * 1. `KAGURA_API_KEY` env var (CI / service accounts always win).\n * 2. The OAuth profile from `~/.kagura/credentials.json`, selected by\n * `options.profile` or `KAGURA_PROFILE`, falling back to the file's\n * `default_profile`.\n * 3. `.kagura.json` (cwd or `~/`) plus its own env fallback.\n */\nexport class KaguraClient {\n readonly mcpUrl: string;\n readonly timeoutMs: number;\n\n private readonly baseUrl: string;\n private readonly auth: AuthProvider;\n private readonly fetchImpl: typeof globalThis.fetch;\n private sessionId: string | null = null;\n private requestIdCounter = 1;\n\n constructor(options: KaguraClientOptions = {}) {\n const resolved = resolveAuth({\n apiKey: options.apiKey ?? null,\n mcpUrl: options.mcpUrl ?? null,\n profile: options.profile ?? null,\n env: options.env,\n home: options.home,\n });\n\n const strippedUrl = resolved.mcpUrl.replace(/\\/+$/, \"\");\n validateHttpsUrl(strippedUrl, \"MCP URL\");\n\n this.mcpUrl = strippedUrl;\n this.baseUrl = baseUrlFromMcp(strippedUrl);\n this.timeoutMs = options.timeoutMs ?? 30_000;\n this.fetchImpl = options.fetch ?? globalThis.fetch;\n\n if (resolved.kind === \"static\") {\n // Long-lived API key path: bake the bearer header once.\n const header = `Bearer ${resolved.apiKey}`;\n this.auth = { getAuthHeader: async () => header };\n } else {\n // OAuth path: the provider injects a fresh bearer header per request\n // and coordinates refresh through the shared credentials state.\n this.auth = resolved.oauth;\n }\n }\n\n /** Get next JSON-RPC request ID. */\n private nextRequestId(): number {\n return this.requestIdCounter++;\n }\n\n private async post(\n url: string,\n body: unknown,\n extraHeaders: Record<string, string> = {},\n ): Promise<Response> {\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n accept: \"application/json, text/event-stream\",\n authorization: await this.auth.getAuthHeader(),\n \"user-agent\": `kagura-memory-sdk/${SDK_VERSION}`,\n ...extraHeaders,\n };\n try {\n return await this.fetchImpl(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n } catch (e) {\n throw new KaguraConnectionError(`Connection failed: ${excMessage(e)}`, { cause: e });\n }\n }\n\n /** Initialize the MCP session if not already initialized. */\n private async initializeSession(): Promise<void> {\n if (this.sessionId) {\n return;\n }\n\n const body = {\n jsonrpc: \"2.0\",\n id: this.nextRequestId(),\n method: \"initialize\",\n params: {\n protocolVersion: \"2025-03-26\",\n capabilities: {},\n clientInfo: { name: \"kagura-memory-sdk\", version: SDK_VERSION },\n },\n };\n\n const response = await this.post(this.mcpUrl, body);\n if (!response.ok) {\n throwForKaguraStatus(response.status, response.headers, await this.safeText(response));\n }\n\n const sessionId = response.headers.get(\"mcp-session-id\");\n if (!sessionId) {\n throw new KaguraConnectionError(\"No session ID returned from server\");\n }\n this.sessionId = sessionId;\n }\n\n private async safeText(response: Response): Promise<string> {\n try {\n return await response.text();\n } catch {\n return \"\";\n }\n }\n\n /** Make a JSON-RPC 2.0 request to the MCP server. */\n private async makeJsonRpcRequest(\n method: string,\n params: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n await this.initializeSession();\n\n const body = {\n jsonrpc: \"2.0\",\n id: this.nextRequestId(),\n method,\n params,\n };\n\n const headers: Record<string, string> = this.sessionId\n ? { \"mcp-session-id\": this.sessionId }\n : {};\n const response = await this.post(this.mcpUrl, body, headers);\n const text = await this.safeText(response);\n if (!response.ok) {\n throwForKaguraStatus(response.status, response.headers, text);\n }\n\n let data: Record<string, unknown>;\n try {\n data = text ? (JSON.parse(text) as Record<string, unknown>) : {};\n } catch (e) {\n throw new KaguraConnectionError(`Invalid response format: ${excMessage(e)}`, { cause: e });\n }\n if (data && typeof data === \"object\" && \"error\" in data) {\n const error = data.error as Record<string, unknown> | undefined;\n const message = error && typeof error === \"object\" ? (error.message ?? JSON.stringify(error)) : String(error);\n throw new KaguraConnectionError(`MCP error: ${String(message)}`);\n }\n\n const result = data.result;\n return typeof result === \"object\" && result !== null\n ? (result as Record<string, unknown>)\n : {};\n }\n\n /** GET a REST endpoint and parse the JSON body. */\n private async restGet<T>(path: string, params?: Record<string, unknown>): Promise<T> {\n let url = `${this.baseUrl}${path}`;\n if (params) {\n const query = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n query.set(key, String(value));\n }\n }\n const qs = query.toString();\n if (qs) {\n url += `?${qs}`;\n }\n }\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method: \"GET\",\n headers: {\n authorization: await this.auth.getAuthHeader(),\n \"user-agent\": `kagura-memory-sdk/${SDK_VERSION}`,\n },\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n } catch (e) {\n throw new KaguraConnectionError(`Connection failed: ${excMessage(e)}`, { cause: e });\n }\n\n const text = await this.safeText(response);\n if (!response.ok) {\n throwForKaguraStatus(response.status, response.headers, text);\n }\n try {\n return JSON.parse(text) as T;\n } catch (e) {\n throw new KaguraConnectionError(`Invalid response format: ${excMessage(e)}`, { cause: e });\n }\n }\n\n /**\n * Call an MCP tool via JSON-RPC and parse `content[0].text` as JSON.\n */\n private async callTool(\n toolName: string,\n args: Record<string, unknown>,\n ): Promise<ToolResult> {\n const result = await this.makeJsonRpcRequest(\"tools/call\", {\n name: toolName,\n arguments: args,\n });\n\n const content = result.content;\n if (Array.isArray(content) && content.length > 0) {\n const first = content[0] as Record<string, unknown>;\n const text = typeof first.text === \"string\" ? first.text : \"{}\";\n try {\n return JSON.parse(text) as ToolResult;\n } catch (e) {\n throw new KaguraConnectionError(`Invalid response format: ${excMessage(e)}`, {\n cause: e,\n });\n }\n }\n return {};\n }\n\n /**\n * Call an MCP tool and translate domain errors into exceptions.\n *\n * A server `{\"status\": \"error\", ...}` response throws\n * KaguraNotFoundError / KaguraError instead of being returned as data.\n */\n private async callToolChecked(\n toolName: string,\n args: Record<string, unknown>,\n ): Promise<ToolResult> {\n const result = await this.callTool(toolName, args);\n KaguraClient.raiseForMcpError(result, toolName);\n return result;\n }\n\n /**\n * Call any MCP tool by name — the escape hatch for tools this SDK has no\n * typed wrapper for yet (#28).\n *\n * Everything above is a typed wrapper over a specific tool, and that is\n * still the surface to prefer: wrappers validate arguments locally, map\n * camelCase to the wire's snake_case, and give you a return type. But\n * `callTool` is private, so before this existed one forgotten wrapper left\n * a tool completely unreachable — a caller had to vendor a patched SDK or\n * hand-roll JSON-RPC. `secret_*` was exactly that case.\n *\n * Args are passed through **verbatim**, so they must already be in wire\n * form (`context_id`, not `contextId`), and the result is an untyped\n * `ToolResult`.\n *\n * Domain errors are still translated, so a server `{\"status\": \"error\"}`\n * throws rather than coming back as data — but only error codes the SDK\n * recognizes get a specific class. A code from a tool with no wrapper\n * (`secret_not_found`, say) lands on the generic {@link KaguraError}, so\n * match on the message or add the code to `raiseForMcpError` when you\n * confirm it against the server.\n *\n * Use `getToolDefinitions()` to discover what the connected server offers.\n *\n * @throws Error if `toolName` is empty or whitespace.\n */\n async callRawTool(toolName: string, args: Record<string, unknown> = {}): Promise<ToolResult> {\n if (typeof toolName !== \"string\" || !toolName.trim()) {\n throw new Error(\"toolName must be a non-empty string\");\n }\n return this.callToolChecked(toolName, args);\n }\n\n /**\n * Translate an MCP tool's structured error response to an SDK error.\n *\n * The server's MCP tools return `{\"status\": \"error\", \"error\": <code>,\n * \"message\": <str>, ...}` for domain errors the JSON-RPC transport\n * cannot represent. HTTP-level errors are handled by the request layer.\n */\n private static raiseForMcpError(result: ToolResult, operation: string): void {\n if (result.status !== \"error\") {\n return;\n }\n const code = typeof result.error === \"string\" ? result.error : \"unknown\";\n const message = typeof result.message === \"string\" ? result.message : \"Unknown error\";\n if (\n code === \"report_not_found\" ||\n code === \"context_not_found\" ||\n code === \"memory_not_found\" ||\n code === \"agent_not_found\" ||\n code === \"binding_not_found\"\n ) {\n throw new KaguraNotFoundError(`${operation}: ${message}`);\n }\n throw new KaguraError(`${operation} failed (${code}): ${message}`);\n }\n\n /** Store a memory. Returns the API response with `memory_id`. */\n async remember(options: RememberOptions): Promise<ToolResult> {\n const args: Record<string, unknown> = {\n context_id: options.contextId,\n summary: options.summary,\n content: options.content,\n type: options.type ?? \"note\",\n importance: options.importance ?? 0.5,\n };\n if (options.tags !== undefined) {\n args.tags = options.tags;\n }\n if (options.sourceUri !== undefined) {\n args.source_uri = options.sourceUri;\n }\n if (options.sourceType !== undefined) {\n args.source_type = options.sourceType;\n }\n // Only send a non-default delivery_mode; the server applies\n // server_default='on_recall' so omitting it stays forward-compatible.\n if (options.deliveryMode !== undefined && options.deliveryMode !== \"on_recall\") {\n args.delivery_mode = options.deliveryMode;\n }\n if (options.contextSummary !== undefined) {\n args.context_summary = options.contextSummary;\n }\n if (options.details !== undefined) {\n args.details = options.details;\n }\n if (options.context !== undefined) {\n args.context = options.context;\n }\n if (options.linkedMemoryIds !== undefined) {\n args.linked_memory_ids = options.linkedMemoryIds;\n }\n if (options.linkedSourceUris !== undefined) {\n args.linked_source_uris = options.linkedSourceUris;\n }\n if (options.supersedes !== undefined) {\n args.supersedes = options.supersedes;\n }\n return this.callToolChecked(\"remember\", args);\n }\n\n /**\n * Search memories. Returns the API response with a `results` list.\n *\n * @throws Error if `query` is empty/whitespace; if neither `contextId`\n * nor `contextIds` is provided; if `contextIds` has fewer than 2 or\n * more than 20 IDs; or if `searchMode` is invalid.\n */\n async recall(options: RecallOptions): Promise<ToolResult> {\n const { query, contextId, contextIds, searchMode } = options;\n if (typeof query !== \"string\" || !query.trim()) {\n throw new Error(\"query must be a non-empty string\");\n }\n if (contextIds !== undefined) {\n if (contextIds.length < 2 || contextIds.length > 20) {\n throw new Error(`contextIds must contain 2-20 IDs, got ${contextIds.length}`);\n }\n } else if (contextId === undefined) {\n throw new Error(\"Either contextId or contextIds must be provided\");\n }\n\n const args: Record<string, unknown> = {\n query,\n k: options.k ?? 5,\n };\n if (contextIds !== undefined) {\n args.context_ids = contextIds;\n } else {\n args.context_id = contextId;\n }\n if (options.useRerank) {\n args.use_rerank = true;\n }\n if (options.filters && Object.keys(options.filters).length > 0) {\n args.filters = options.filters;\n }\n if (searchMode) {\n if (searchMode !== \"hybrid\" && searchMode !== \"semantic\" && searchMode !== \"keyword\") {\n throw new Error(`Invalid searchMode: ${JSON.stringify(searchMode)}`);\n }\n args.search_mode = searchMode;\n }\n if (options.includeExploreHints) {\n args.include_explore_hints = true;\n }\n if (options.includeSuperseded) {\n args.include_superseded = true;\n }\n return this.callToolChecked(\"recall\", args);\n }\n\n /**\n * List Time Memories whose scheduled window overlaps a range, soonest\n * first. A deterministic time query over `type=\"time\"` memories — not\n * semantic search, no Hebbian side-effects.\n */\n async recallUpcoming(options: {\n contextId: string;\n /** Lower bound as naive ISO, or the literal \"now\". Omit for no lower bound. */\n from?: string;\n /** Upper bound as naive ISO. Omit for an open-ended future window. */\n until?: string;\n /** Maximum results (default 20, server max 100). */\n k?: number;\n }): Promise<ToolResult> {\n const args: Record<string, unknown> = {\n context_id: options.contextId,\n k: options.k ?? 20,\n };\n if (options.from !== undefined) {\n args.from = options.from;\n }\n if (options.until !== undefined) {\n args.until = options.until;\n }\n return this.callToolChecked(\"recall_upcoming\", args);\n }\n\n /**\n * List memories near a geographic point, nearest first, each carrying\n * `distance_m`. The WHERE axis — a deterministic spatial query over\n * stored `details.location` coordinates, not semantic search (use\n * {@link recall} for topic search). Mirrors {@link recallUpcoming}.\n *\n * Store a location with\n * `remember({ details: { location: { lat, lon, label } } })`; see\n * {@link MemoryLocation}. Any memory type can carry one.\n *\n * Note: {@link updateMemory} replaces `details` wholesale, so resend\n * `location` when updating details or the memory drops off this axis.\n *\n * `radiusM` is clamped server-side to [1, 1_000_000]; it is forwarded\n * unchanged rather than pre-clamped here, so the server stays the single\n * authority on the bound.\n *\n * @throws Error if `lat`/`lon` are not finite numbers in range. The\n * server rejects these with HTTP 422; failing locally turns the common\n * swapped-lat/lon mistake into an immediate, named error.\n */\n async recallNearby(options: {\n contextId: string;\n /** Query latitude (-90..90). */\n lat: number;\n /** Query longitude (-180..180). */\n lon: number;\n /** Search radius in meters (default 1000). */\n radiusM?: number;\n /** Maximum results (default 20; the server clamps to 1-100). */\n k?: number;\n }): Promise<RecallNearbyResponse> {\n const { lat, lon } = options;\n if (!Number.isFinite(lat) || lat < -90 || lat > 90) {\n throw new Error(`lat must be a finite number between -90 and 90, got ${lat}`);\n }\n if (!Number.isFinite(lon) || lon < -180 || lon > 180) {\n throw new Error(`lon must be a finite number between -180 and 180, got ${lon}`);\n }\n const result = await this.callToolChecked(\"recall_nearby\", {\n context_id: options.contextId,\n lat,\n lon,\n radius_m: options.radiusM ?? 1000,\n k: options.k ?? 20,\n });\n return result as unknown as RecallNearbyResponse;\n }\n\n /**\n * Deterministically load a context's pinned (`delivery_mode=\"always\"`)\n * memories — the complete, unranked pinned set on every call.\n *\n * The set is bounded, never silently dropped: when more pinned memories\n * exist than `cap`, the response `truncated` flag is true and\n * `total_available` reports the real count.\n */\n async loadPinned(options: {\n contextId: string;\n /** Override the maximum number returned (1-1000); omit for server default. */\n cap?: number;\n }): Promise<ToolResult> {\n const args: Record<string, unknown> = { context_id: options.contextId };\n if (options.cap !== undefined) {\n args.cap = options.cap;\n }\n return this.callToolChecked(\"load_pinned\", args);\n }\n\n /**\n * Record whether a recalled memory was useful for a query — an\n * append-only usefulness signal, kept in a separate lane from knowledge\n * (never pollutes recall).\n */\n async feedback(options: {\n contextId: string;\n memoryId: string;\n helpful: boolean;\n /** Recall query this feedback is about (max 1024 chars). */\n query?: string;\n /** Free-text note, e.g. why the result was wrong (max 2000 chars). */\n note?: string;\n }): Promise<ToolResult> {\n const args: Record<string, unknown> = {\n context_id: options.contextId,\n memory_id: options.memoryId,\n helpful: options.helpful,\n };\n if (options.query !== undefined) {\n args.query = options.query;\n }\n if (options.note !== undefined) {\n args.note = options.note;\n }\n return this.callToolChecked(\"feedback\", args);\n }\n\n /**\n * Set ephemeral agent run-state at `(contextId, key)` — a TTL-bounded\n * key/value lane kept separate from memories and excluded from recall.\n * Use remember() for durable knowledge.\n */\n async setState(options: {\n contextId: string;\n /** State key (max 255 chars); re-use overwrites. */\n key: string;\n /** Arbitrary JSON value. */\n value: unknown;\n /** TTL in seconds (server clamps to 30 days); omit for no expiry. */\n ttlSeconds?: number;\n }): Promise<ToolResult> {\n const args: Record<string, unknown> = {\n context_id: options.contextId,\n key: options.key,\n value: options.value,\n };\n if (options.ttlSeconds !== undefined) {\n args.ttl_seconds = options.ttlSeconds;\n }\n return this.callToolChecked(\"set_state\", args);\n }\n\n /**\n * Read ephemeral agent run-state. Supply `key` to read one value, omit\n * it to list all live keys for the context.\n */\n async getState(options: { contextId: string; key?: string }): Promise<ToolResult> {\n const args: Record<string, unknown> = { context_id: options.contextId };\n if (options.key !== undefined) {\n args.key = options.key;\n }\n return this.callToolChecked(\"get_state\", args);\n }\n\n // -------------------------------------------------------------------\n // Agent control plane (server v0.49.0+, RFC-0002; issues #1/#2/#3)\n // -------------------------------------------------------------------\n\n /**\n * Unwrap an object envelope (`agent`, `binding`, `report`, …) from a\n * tool result.\n *\n * Match the Python port's `result[\"<key>\"]`: a missing envelope is a\n * contract violation, surfaced loudly rather than as a partial object.\n */\n private static expectEnvelope(\n result: ToolResult,\n key: string,\n operation: string,\n ): Record<string, unknown> {\n const envelope = result[key];\n if (typeof envelope !== \"object\" || envelope === null || Array.isArray(envelope)) {\n throw new KaguraConnectionError(\n `Unexpected ${operation} response: missing '${key}' envelope.`,\n );\n }\n return envelope as Record<string, unknown>;\n }\n\n /**\n * Register an AI agent in the workspace Agent Registry.\n *\n * Calls the `register_agent` MCP tool (server v0.49.0+, RFC-0002 P0-1,\n * memory-cloud #1274) — owner/admin only. An agent is a\n * workspace-scoped registry entry (name unique per workspace) that\n * anchors context bindings, agent-bound credentials,\n * {@link getAgentBootstrap}, and audit correlation — it is a resource,\n * NOT a principal. New agents start with `status=\"active\"` and\n * `enforcement_mode=\"enforce\"`.\n *\n * Requires memory-cloud v0.49.0+ — older servers return an MCP\n * \"tool not found\" error ({@link MIN_SERVER_VERSION} is deliberately\n * not bumped; only the agent control plane needs the newer server).\n *\n * @throws KaguraError on name conflict, agent quota, or insufficient\n * role (owner/admin required).\n */\n async registerAgent(options: RegisterAgentOptions): Promise<Agent> {\n const args: Record<string, unknown> = { name: options.name };\n if (options.description !== undefined) {\n args.description = options.description;\n }\n if (options.framework !== undefined) {\n args.framework = options.framework;\n }\n if (options.environment !== undefined) {\n args.environment = options.environment;\n }\n if (options.version !== undefined) {\n args.version = options.version;\n }\n const result = await this.callToolChecked(\"register_agent\", args);\n return KaguraClient.expectEnvelope(result, \"agent\", \"register_agent\") as unknown as Agent;\n }\n\n /**\n * Fetch one registered agent by id (owner/admin only).\n *\n * @throws KaguraNotFoundError when the agent does not exist. The 404 is\n * uniform (CWE-639) — nonexistent and not-yours are indistinguishable\n * by design, so it does NOT prove the agent is absent.\n */\n async getAgent(agentId: string): Promise<Agent> {\n const result = await this.callToolChecked(\"get_agent\", { agent_id: agentId });\n return KaguraClient.expectEnvelope(result, \"agent\", \"get_agent\") as unknown as Agent;\n }\n\n /** List the workspace's registered agents, newest first (owner/admin only). */\n async listAgents(): Promise<Agent[]> {\n const result = await this.callToolChecked(\"list_agents\", {});\n const agents = result.agents;\n return Array.isArray(agents) ? (agents as unknown as Agent[]) : [];\n }\n\n /**\n * Update a registered agent, including lifecycle transitions\n * (owner/admin only).\n *\n * `status` is the **fail-closed kill switch**: `\"suspended\"` /\n * `\"retired\"` agents cause every key bound to them to be rejected at\n * verify time. Setting `enforcementMode` from `\"enforce\"` to\n * `\"shadow\"` is an audited privilege-widening event.\n *\n * Set-only wrapper: omitted fields are left untouched. The server's\n * null-clears-a-metadata-field semantics is not expressible through\n * this wrapper — clear fields via the web UI or the raw API.\n *\n * @throws Error when no update field is provided (the call would be an\n * empty no-op request).\n */\n async updateAgent(options: UpdateAgentOptions): Promise<Agent> {\n const changes: Record<string, unknown> = {};\n if (options.name !== undefined) {\n changes.name = options.name;\n }\n if (options.description !== undefined) {\n changes.description = options.description;\n }\n if (options.framework !== undefined) {\n changes.framework = options.framework;\n }\n if (options.environment !== undefined) {\n changes.environment = options.environment;\n }\n if (options.version !== undefined) {\n changes.version = options.version;\n }\n if (options.status !== undefined) {\n changes.status = options.status;\n }\n if (options.enforcementMode !== undefined) {\n changes.enforcement_mode = options.enforcementMode;\n }\n if (Object.keys(changes).length === 0) {\n throw new Error(\"updateAgent requires at least one field to update\");\n }\n const result = await this.callToolChecked(\"update_agent\", {\n agent_id: options.agentId,\n ...changes,\n });\n return KaguraClient.expectEnvelope(result, \"agent\", \"update_agent\") as unknown as Agent;\n }\n\n /**\n * Hard-delete an Agent Registry row (owner/admin only). Returns true\n * once the server confirms deletion.\n *\n * Permanent, and cascades every API key bound to the agent\n * (fail-closed). Prefer `updateAgent({status: \"retired\"})` for\n * operational retirement.\n */\n async deleteAgent(agentId: string): Promise<boolean> {\n const result = await this.callToolChecked(\"delete_agent\", { agent_id: agentId });\n return result.deleted === undefined ? true : Boolean(result.deleted);\n }\n\n /**\n * Build the omit-when-undefined binding scope trio shared by\n * {@link bindAgentContext} and {@link updateAgentBinding} — the port of\n * the Python SDK's `_binding_scope_payload`. When memory-cloud #1286\n * ships the reserved filters, extend {@link AgentBindingScopeOptions}\n * and map the new fields here.\n */\n private static bindingScopeArgs(options: AgentBindingScopeOptions): Record<string, unknown> {\n const args: Record<string, unknown> = {};\n if (options.canRead !== undefined) {\n args.can_read = options.canRead;\n }\n if (options.writePolicy !== undefined) {\n args.write_policy = options.writePolicy;\n }\n if (options.isDefault !== undefined) {\n args.is_default = options.isDefault;\n }\n return args;\n }\n\n /**\n * Bind an agent to a context — purely subtractive scoping.\n *\n * Calls the `bind_agent_context` MCP tool (server v0.49.0+, RFC-0002\n * P0-2, memory-cloud #1275) — owner/admin only. The effective\n * permission for an agent-bound request is the existing RBAC decision\n * ∩ binding. Under `enforcement_mode=\"enforce\"`, contexts WITHOUT a\n * binding row are denied for the agent (default-deny); under\n * `\"shadow\"`, violations are only logged.\n *\n * @throws KaguraNotFoundError when the agent or context is not found.\n * @throws KaguraError on duplicate binding or other server-side error.\n */\n async bindAgentContext(options: BindAgentContextOptions): Promise<AgentBinding> {\n const result = await this.callToolChecked(\"bind_agent_context\", {\n agent_id: options.agentId,\n context_id: options.contextId,\n ...KaguraClient.bindingScopeArgs(options),\n });\n return KaguraClient.expectEnvelope(result, \"binding\", \"bind_agent_context\") as unknown as AgentBinding;\n }\n\n /** List an agent's context bindings (owner/admin only). */\n async listAgentBindings(agentId: string): Promise<AgentBinding[]> {\n const result = await this.callToolChecked(\"list_agent_bindings\", { agent_id: agentId });\n const bindings = result.bindings;\n return Array.isArray(bindings) ? (bindings as unknown as AgentBinding[]) : [];\n }\n\n /**\n * Update a binding's scoping fields (owner/admin only).\n *\n * `context_id` is immutable — {@link unbindAgentContext} and re-\n * {@link bindAgentContext} to re-target. Changes are audited with\n * old→new values.\n *\n * @throws Error when no scoping field is provided (the call would be\n * an empty no-op request).\n */\n async updateAgentBinding(options: UpdateAgentBindingOptions): Promise<AgentBinding> {\n const changes = KaguraClient.bindingScopeArgs(options);\n if (Object.keys(changes).length === 0) {\n throw new Error(\n \"updateAgentBinding requires at least one of canRead, writePolicy, or isDefault\",\n );\n }\n const result = await this.callToolChecked(\"update_agent_binding\", {\n agent_id: options.agentId,\n binding_id: options.bindingId,\n ...changes,\n });\n return KaguraClient.expectEnvelope(result, \"binding\", \"update_agent_binding\") as unknown as AgentBinding;\n }\n\n /**\n * Delete a binding — the agent loses that context (owner/admin only).\n * Returns true once the server confirms deletion.\n *\n * Under `enforcement_mode=\"enforce\"` the agent's requests against the\n * unbound context are denied afterwards (uniform `context_not_found`).\n */\n async unbindAgentContext(options: { agentId: string; bindingId: string }): Promise<boolean> {\n const result = await this.callToolChecked(\"unbind_agent_context\", {\n agent_id: options.agentId,\n binding_id: options.bindingId,\n });\n return result.deleted === undefined ? true : Boolean(result.deleted);\n }\n\n /**\n * Rehydrate an agent's cognitive state in one session-start call.\n *\n * Calls the `get_agent_bootstrap` MCP tool (server v0.49.0+, RFC-0002\n * P0-3, memory-cloud #1276). The server composes existing primitives —\n * context guide + pinned memories ({@link loadPinned}) + a trusted-only\n * {@link recall} (only when `query` is supplied) + upcoming time\n * memories ({@link recallUpcoming}) + the agent-state lane\n * ({@link getState}) — with bounds, ordering, and trust filtering\n * inherited from those standalone tools, not re-specified.\n *\n * Components are **fail-soft**: a failing component reports\n * `{\"status\": \"error\", ...}` under `components` while the rest still\n * return, with the top-level `degraded` flag set. Identity and\n * authorization failures are total and throw instead.\n *\n * The REST companion (`POST /api/v1/agents/{agent_id}/bootstrap`) is\n * available via `AgentsClient` for API-key-only callers such as\n * agent-bound member keys.\n *\n * @throws KaguraNotFoundError when the agent or context is not found\n * (uniform 404 — nonexistent and not-yours are indistinguishable by\n * design).\n * @throws KaguraError on invalid arguments or other server-side error.\n */\n async getAgentBootstrap(options: GetAgentBootstrapOptions): Promise<AgentBootstrapResponse> {\n const result = await this.callToolChecked(\"get_agent_bootstrap\", {\n agent_id: options.agentId,\n ...buildBootstrapPayload(options),\n });\n return result as unknown as AgentBootstrapResponse;\n }\n\n /** List available contexts. */\n async listContexts(): Promise<ToolResult> {\n return this.callToolChecked(\"list_contexts\", {});\n }\n\n /**\n * List the tag vocabulary in a context with usage counts and recency.\n *\n * Call before remember() to reuse existing tag spellings, or before\n * recall() with tag filters. Requires memory-cloud server v0.15.4+.\n */\n async listTags(options: ListTagsOptions): Promise<ListTagsResponse> {\n const limit = options.limit ?? 50;\n const minCount = options.minCount ?? 1;\n const prefix = options.prefix ?? \"\";\n if (limit < 1 || limit > 500) {\n throw new Error(`limit must be between 1 and 500, got ${limit}`);\n }\n if (minCount < 1 || minCount > 10_000) {\n throw new Error(`minCount must be between 1 and 10000, got ${minCount}`);\n }\n if (prefix.length > 200) {\n throw new Error(`prefix must be at most 200 characters, got ${prefix.length}`);\n }\n\n const args: Record<string, unknown> = {\n context_id: options.contextId,\n limit,\n min_count: minCount,\n sort: options.sort ?? \"count\",\n };\n if (prefix) {\n args.prefix = prefix;\n }\n // An empty drill-down matches everything (`tags @> '{}'`), so it is\n // equivalent to omitting the key — drop it like an empty prefix.\n if (options.withTags !== undefined && options.withTags.length > 0) {\n args.with_tags = options.withTags;\n }\n const result = await this.callToolChecked(\"list_tags\", args);\n return result as unknown as ListTagsResponse;\n }\n\n /**\n * Call tools/list to get available MCP tool definitions (names,\n * descriptions, parameter schemas).\n */\n async getToolDefinitions(): Promise<Record<string, unknown>[]> {\n const result = await this.makeJsonRpcRequest(\"tools/list\", {});\n const tools = result.tools;\n return Array.isArray(tools) ? (tools as Record<string, unknown>[]) : [];\n }\n\n /** Neural graph traversal from a seed memory. */\n async explore(options: {\n contextId: string;\n memoryId: string;\n /** Maximum traversal depth (1-5, default 2). */\n depth?: number;\n /** Minimum edge weight threshold (default 0.05). */\n minWeight?: number;\n }): Promise<ToolResult> {\n return this.callToolChecked(\"explore\", {\n context_id: options.contextId,\n memory_id: options.memoryId,\n depth: options.depth ?? 2,\n min_weight: options.minWeight ?? 0.05,\n });\n }\n\n /**\n * Get full memory details. Memory data is in `result.memory`.\n */\n async reference(options: { contextId: string; memoryId: string }): Promise<ToolResult> {\n return this.callToolChecked(\"reference\", {\n context_id: options.contextId,\n memory_id: options.memoryId,\n });\n }\n\n /**\n * Update an existing memory in-place (memoryId) or upsert by external\n * ID (externalId — requires summary, content, and type).\n *\n * @throws Error unless exactly one of memoryId/externalId is provided.\n */\n async updateMemory(options: UpdateMemoryOptions): Promise<ToolResult> {\n if (!options.memoryId && !options.externalId) {\n throw new Error(\"Provide exactly one of memoryId or externalId\");\n }\n if (options.memoryId && options.externalId) {\n throw new Error(\"Provide exactly one of memoryId or externalId\");\n }\n\n const args: Record<string, unknown> = { context_id: options.contextId };\n if (options.memoryId !== undefined) {\n args.memory_id = options.memoryId;\n }\n if (options.externalId !== undefined) {\n args.external_id = options.externalId;\n }\n if (options.summary !== undefined) {\n args.summary = options.summary;\n }\n if (options.content !== undefined) {\n args.content = options.content;\n }\n if (options.type !== undefined) {\n args.type = options.type;\n }\n if (options.importance !== undefined) {\n args.importance = options.importance;\n }\n if (options.tags !== undefined) {\n args.tags = options.tags;\n }\n if (options.contextSummary !== undefined) {\n args.context_summary = options.contextSummary;\n }\n if (options.details !== undefined) {\n args.details = options.details;\n }\n if (options.deliveryMode !== undefined) {\n args.delivery_mode = options.deliveryMode;\n }\n return this.callToolChecked(\"update_memory\", args);\n }\n\n /**\n * Soft-delete memories (30-day retention) by specific memoryId or by\n * search query.\n *\n * @throws Error if neither memoryId nor query is provided.\n */\n async forget(options: {\n contextId: string;\n memoryId?: string;\n query?: string;\n /** Number of memories to delete in query mode (default 10). */\n k?: number;\n }): Promise<ToolResult> {\n if (!options.memoryId && !options.query) {\n throw new Error(\"Provide either memoryId or query\");\n }\n const args: Record<string, unknown> = { context_id: options.contextId };\n if (options.memoryId) {\n args.memory_id = options.memoryId;\n }\n if (options.query) {\n args.query = options.query;\n args.k = options.k ?? 10;\n }\n return this.callToolChecked(\"forget\", args);\n }\n\n /**\n * Create a new context in the current workspace.\n *\n * @throws KaguraQuotaError when the workspace context limit is reached.\n */\n async createContext(options: CreateContextOptions): Promise<ToolResult> {\n // Pre-check quota. Match the Python falsy check `not\n // contexts.get(\"can_create\", True)` exactly: `dict.get` substitutes the\n // default ONLY when the key is absent, so a present null/0/\"\"/false\n // (server schema drift, #183) must pass through and be negated as\n // \"cannot create\" — a nullish-coalescing `?? true` would wrongly treat\n // a present `null` as \"can create\".\n const contexts = await this.listContexts();\n const canCreate = \"can_create\" in contexts ? contexts.can_create : true;\n if (!canCreate) {\n // Coerce missing/null count/limit to \"?\" so schema drift never\n // produces \"null/null\" in the message; a real 0 is preserved.\n const count = contexts.count ?? null;\n const limit = contexts.limit ?? null;\n throw new KaguraQuotaError(\n `Context limit reached (${count === null ? \"?\" : String(count)}/` +\n `${limit === null ? \"?\" : String(limit)}). ` +\n \"Delete unused contexts or upgrade your plan.\",\n );\n }\n\n const args: Record<string, unknown> = {\n name: options.name,\n is_private: options.isPrivate ?? true,\n };\n if (options.displayName !== undefined) {\n args.display_name = options.displayName;\n }\n if (options.description !== undefined) {\n args.description = options.description;\n }\n if (options.summary !== undefined) {\n args.summary = options.summary;\n }\n if (options.usageGuide !== undefined) {\n args.usage_guide = options.usageGuide;\n }\n if (options.resourceId !== undefined) {\n args.resource_id = options.resourceId;\n }\n if (options.embeddingModel !== undefined) {\n args.embedding_model = options.embeddingModel;\n }\n return this.callToolChecked(\"create_context\", args);\n }\n\n /** Soft-delete a context and all its memories. */\n async deleteContext(contextId: string): Promise<ToolResult> {\n return this.callToolChecked(\"delete_context\", { context_id: contextId });\n }\n\n /** Update an existing context's settings. */\n async updateContext(options: UpdateContextOptions): Promise<ToolResult> {\n const args: Record<string, unknown> = { context_id: options.contextId };\n if (options.displayName !== undefined) {\n args.display_name = options.displayName;\n }\n if (options.description !== undefined) {\n args.description = options.description;\n }\n if (options.summary !== undefined) {\n args.summary = options.summary;\n }\n if (options.usageGuide !== undefined) {\n args.usage_guide = options.usageGuide;\n }\n if (options.resourceId !== undefined) {\n args.resource_id = options.resourceId;\n }\n if (options.isPublic !== undefined) {\n args.is_public = options.isPublic;\n }\n if (options.isLocked !== undefined) {\n args.is_locked = options.isLocked;\n }\n return this.callToolChecked(\"update_context\", args);\n }\n\n /**\n * Atomically create Context + Resource entity + ingestion token in a\n * single server-side transaction. The returned `token` is plaintext and\n * shown once.\n */\n async setupResource(options: SetupResourceOptions): Promise<ToolResult> {\n const args: Record<string, unknown> = {\n resource_id: options.resourceId,\n quota_events_per_hour: options.quotaEventsPerHour ?? 1000,\n };\n if (options.name !== undefined) {\n args.name = options.name;\n }\n if (options.summary !== undefined) {\n args.summary = options.summary;\n }\n if (options.description !== undefined) {\n args.description = options.description;\n }\n return this.callToolChecked(\"setup_resource\", args);\n }\n\n /**\n * Merge memories from one context into another. Both contexts must use\n * the same embedding model and belong to the same workspace.\n *\n * @throws Error if sourceId and targetId are the same.\n */\n async mergeContexts(options: {\n sourceId: string;\n targetId: string;\n /** Soft-delete the source context after merge. */\n deleteSource?: boolean;\n }): Promise<ToolResult> {\n if (options.sourceId === options.targetId) {\n throw new Error(\"sourceId and targetId must be different\");\n }\n const args: Record<string, unknown> = {\n source_context_id: options.sourceId,\n target_context_id: options.targetId,\n };\n if (options.deleteSource) {\n args.delete_source = true;\n }\n return this.callToolChecked(\"merge_contexts\", args);\n }\n\n /**\n * List neural memory edges connected to a memory (outgoing and\n * incoming, deduplicated).\n *\n * Note: the server applies `limit` to outgoing AND incoming queries\n * independently, so the practical maximum returned is `2 * limit`\n * minus dedup overlap.\n */\n async listEdges(options: {\n contextId: string;\n memoryId: string;\n /** Minimum edge weight (0.0-3.0, default 0.0). */\n minWeight?: number;\n /** Restrict to these edge types; omit for all. */\n edgeTypes?: string[];\n /** Maximum edges per direction; omit for no limit. */\n limit?: number;\n }): Promise<Edge[]> {\n const args: Record<string, unknown> = {\n context_id: options.contextId,\n memory_id: options.memoryId,\n min_weight: options.minWeight ?? 0.0,\n };\n if (options.edgeTypes !== undefined) {\n args.edge_types = options.edgeTypes;\n }\n if (options.limit !== undefined) {\n args.limit = options.limit;\n }\n const result = await this.callToolChecked(\"list_edges\", args);\n const edges = result.edges;\n return Array.isArray(edges) ? (edges as unknown as Edge[]) : [];\n }\n\n /**\n * Create or upsert a neural memory edge from source to target.\n *\n * The server uses `(user_id, source_id, target_id)` as a unique key\n * with max-weight UPSERT semantics — not a pure INSERT.\n *\n * @throws Error if sourceId === targetId (self-loops are rejected).\n */\n async createEdge(options: {\n contextId: string;\n sourceId: string;\n targetId: string;\n /** Edge type label (default \"related_to\"). */\n edgeType?: string;\n /** Edge weight in [0.0, 3.0] (default 0.5). */\n weight?: number;\n /** Edge confidence in [0.0, 1.0] (default 1.0). */\n confidence?: number;\n }): Promise<Edge> {\n if (options.sourceId === options.targetId) {\n throw new Error(\"sourceId and targetId must be different (self-loops are not allowed)\");\n }\n const result = await this.callToolChecked(\"create_edge\", {\n context_id: options.contextId,\n source_id: options.sourceId,\n target_id: options.targetId,\n edge_type: options.edgeType ?? \"related_to\",\n weight: options.weight ?? 0.5,\n confidence: options.confidence ?? 1.0,\n });\n return (result.edge ?? result) as unknown as Edge;\n }\n\n /**\n * Update an existing edge's weight and/or edge type, identified by the\n * `(sourceId, targetId)` pair. Omit a field to leave it unchanged.\n */\n async updateEdge(options: {\n contextId: string;\n sourceId: string;\n targetId: string;\n /** New edge weight in [0.0, 3.0]; omit to keep. */\n weight?: number;\n /** New edge type label; omit to keep. */\n edgeType?: string;\n }): Promise<Edge> {\n const args: Record<string, unknown> = {\n context_id: options.contextId,\n source_id: options.sourceId,\n target_id: options.targetId,\n };\n if (options.weight !== undefined) {\n args.weight = options.weight;\n }\n if (options.edgeType !== undefined) {\n args.edge_type = options.edgeType;\n }\n const result = await this.callToolChecked(\"update_edge\", args);\n return (result.edge ?? result) as unknown as Edge;\n }\n\n /**\n * Delete the edge between sourceId and targetId. Returns true once the\n * server confirms deletion.\n */\n async deleteEdge(options: {\n contextId: string;\n sourceId: string;\n targetId: string;\n }): Promise<boolean> {\n const result = await this.callToolChecked(\"delete_edge\", {\n context_id: options.contextId,\n source_id: options.sourceId,\n target_id: options.targetId,\n });\n // The server confirms a delete with {\"status\": \"success\"} and NO\n // \"deleted\" key; a missing edge raises above. So reaching here means\n // deletion was confirmed — the default true is load-bearing.\n return result.deleted === undefined ? true : Boolean(result.deleted);\n }\n\n /** Get workspace usage and quota limits. */\n async getUsage(): Promise<UsageInfo> {\n const result = await this.callToolChecked(\"get_usage\", {});\n return result as unknown as UsageInfo;\n }\n\n /** Get context information, usage guidelines, and search config. */\n async getContextInfo(options: {\n contextId: string;\n /** Include memory count breakdown (default true). */\n includeDetails?: boolean;\n }): Promise<ContextInfo> {\n const result = await this.callToolChecked(\"get_context_info\", {\n context_id: options.contextId,\n include_details: options.includeDetails ?? true,\n });\n return result as unknown as ContextInfo;\n }\n\n /**\n * Update hybrid search configuration for a context. Weights must sum\n * to 1.0 (±0.01). Requires owner or editor permission.\n */\n async updateSearchConfig(options: UpdateSearchConfigOptions): Promise<ToolResult> {\n const args: Record<string, unknown> = { context_id: options.contextId };\n if (options.semanticWeight !== undefined) {\n args.semantic_weight = options.semanticWeight;\n }\n if (options.bm25Weight !== undefined) {\n args.bm25_weight = options.bm25Weight;\n }\n if (options.fetchFactor !== undefined) {\n args.fetch_factor = options.fetchFactor;\n }\n if (options.useRerank !== undefined) {\n args.use_rerank = options.useRerank;\n }\n if (options.rerankerProvider !== undefined) {\n args.reranker_provider = options.rerankerProvider;\n }\n if (options.rerankerModel !== undefined) {\n args.reranker_model = options.rerankerModel;\n }\n return this.callToolChecked(\"update_search_config\", args);\n }\n\n /** Get server name, version, environment, and feature flags. */\n async getServerInfo(): Promise<ServerInfo> {\n return this.restGet<ServerInfo>(\"/api/v1/system/info\");\n }\n\n /**\n * Check the connected server's version against the SDK's tested\n * minimum. Advisory only — logs a warning, never throws on mismatch.\n */\n async checkServerVersion(): Promise<ServerInfo> {\n const info = await this.getServerInfo();\n const components = info.version.split(\".\").slice(0, 3);\n // Match Python's `int(x)`: a non-integer component (empty string,\n // \"0x1\", \"1e2\") makes the parse fail and we return without warning.\n // Number(\"\") is 0 and Number(\"1e2\") is 100, so guard with a strict\n // integer-digit test rather than relying on NaN.\n if (components.length === 0 || !components.every((c) => /^\\d+$/.test(c))) {\n return info;\n }\n const parts = components.map(Number);\n for (let i = 0; i < MIN_SERVER_VERSION_TUPLE.length; i++) {\n const server = parts[i] ?? 0;\n const min = MIN_SERVER_VERSION_TUPLE[i] ?? 0;\n if (server < min) {\n console.warn(\n `Server version ${info.version} is below the SDK's tested minimum ` +\n `${MIN_SERVER_VERSION}. Some features may not work; older servers ` +\n \"may silently ignore unknown parameters.\",\n );\n break;\n }\n if (server > min) {\n break;\n }\n }\n return info;\n }\n\n /** Get embedding queue status for the workspace. */\n async getEmbeddingStatus(): Promise<EmbeddingStatus> {\n return this.restGet<EmbeddingStatus>(\"/api/v1/workspace/embedding-status\");\n }\n\n /** Get per-memory usage statistics for a context. */\n async getMemoryStats(options: {\n contextId: string;\n /** Sort field (default \"use_count\"). */\n sortBy?: string;\n /** \"asc\" or \"desc\" (default \"desc\"). */\n sortOrder?: \"asc\" | \"desc\";\n /** Maximum results (1-200, default 50). */\n limit?: number;\n offset?: number;\n }): Promise<MemoryStatsResponse> {\n return this.restGet<MemoryStatsResponse>(\n `/api/v1/contexts/${options.contextId}/memory-stats`,\n {\n sort_by: options.sortBy ?? \"use_count\",\n sort_order: options.sortOrder ?? \"desc\",\n limit: options.limit ?? 50,\n offset: options.offset ?? 0,\n },\n );\n }\n\n /** Find duplicate memory pairs in a context. */\n async findDuplicates(options: {\n contextId: string;\n /** Similarity threshold (0.5-1.0, default 0.90). */\n threshold?: number;\n /** Maximum pairs (1-200, default 50). */\n limit?: number;\n }): Promise<DuplicatesResponse> {\n return this.restGet<DuplicatesResponse>(`/api/v1/contexts/${options.contextId}/duplicates`, {\n threshold: options.threshold ?? 0.9,\n limit: options.limit ?? 50,\n });\n }\n\n /**\n * List memories with optional substring, facet, and time-window\n * filters. Without `contextId` this returns the caller's own memories\n * across all contexts. `q` matches summaries only — use recall() for\n * semantic search.\n */\n async listMemories(options: ListMemoriesOptions = {}): Promise<MemoryListResponse> {\n const params: Record<string, unknown> = {\n limit: options.limit ?? 50,\n offset: options.offset ?? 0,\n };\n if (options.contextId !== undefined) {\n params.context_id = options.contextId;\n }\n // Normalize like the server/frontend: strip and drop whitespace-only.\n const qNormalized = (options.q ?? \"\").trim();\n if (qNormalized) {\n params.q = qNormalized;\n }\n if (options.scope !== undefined) {\n params.scope = options.scope;\n }\n if (options.type !== undefined) {\n params.type = options.type;\n }\n if (options.triggerFrom !== undefined) {\n params.trigger_from = options.triggerFrom;\n }\n if (options.triggerUntil !== undefined) {\n params.trigger_until = options.triggerUntil;\n }\n if (options.orderBy !== undefined) {\n params.order_by = options.orderBy;\n }\n return this.restGet<MemoryListResponse>(\"/api/v1/memory/list\", params);\n }\n\n /**\n * List recent Sleep Maintenance runs for a context, newest first.\n */\n async getSleepHistory(options: {\n contextId: string;\n /** Maximum runs (server clamps to 1-50, default 10). */\n limit?: number;\n }): Promise<SleepReport[]> {\n const result = await this.callToolChecked(\"get_sleep_history\", {\n context_id: options.contextId,\n limit: options.limit ?? 10,\n });\n // Match Python's `result[\"reports\"]`: a missing/malformed key is a\n // contract violation, surfaced loudly rather than as an empty success.\n const reports = result.reports;\n if (!Array.isArray(reports)) {\n throw new KaguraConnectionError(\n \"Unexpected get_sleep_history response: missing 'reports' array.\",\n );\n }\n return reports as unknown as SleepReport[];\n }\n\n /**\n * Get a detailed Sleep Maintenance report including the per-action\n * audit log.\n */\n async getSleepReport(options: {\n contextId: string;\n reportId: string;\n }): Promise<SleepReportDetail> {\n const result = await this.callToolChecked(\"get_sleep_report\", {\n context_id: options.contextId,\n report_id: options.reportId,\n });\n // The MCP tool wraps the report fields under a \"report\" key; flatten\n // so SleepReportDetail reads naturally without an extra `.report.`.\n const report = KaguraClient.expectEnvelope(result, \"report\", \"get_sleep_report\");\n return {\n ...report,\n actions: result.actions,\n action_count: result.action_count,\n } as unknown as SleepReportDetail;\n }\n\n /**\n * Reverse the effects of a completed Sleep Maintenance run. The server\n * processes actions in reverse order with per-step commits — a partial\n * failure means SOME actions may have been reversed before the error.\n */\n async rollbackSleepRun(options: {\n contextId: string;\n reportId: string;\n }): Promise<RollbackResult> {\n const result = await this.callToolChecked(\"rollback_sleep_run\", {\n context_id: options.contextId,\n report_id: options.reportId,\n });\n return result as unknown as RollbackResult;\n }\n\n /** List available embedding models with provider info and availability. */\n async listEmbeddingModels(): Promise<EmbeddingModelsResponse> {\n return this.restGet<EmbeddingModelsResponse>(\"/api/v1/system/embedding/models\");\n }\n\n /** Release resources. (fetch has no persistent connection to close; kept for API parity.) */\n async close(): Promise<void> {\n this.sessionId = null;\n }\n}\n","/**\n * REST client for Kagura Memory Cloud file uploads (port of files_client.py).\n *\n * Drives the 3-step file upload flow against memory-cloud:\n * 1. `POST /api/v1/files/reserve` — server returns a presigned PUT URL.\n * 2. `PUT` to R2 with body bytes and the `x-amz-checksum-sha256` header\n * (base64 of the raw sha256 digest), when the presign signed it.\n * 3. `POST /api/v1/files/{file_id}/confirm` — finalize the row.\n *\n * Plus `downloadUrl()`, `delete()` and `list()`. The R2 PUT is sent with a\n * plain fetch and NO Authorization header so the SDK's Bearer credential\n * cannot leak to the object store — the presigned URL carries its own\n * short-lived SigV4 signature.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport { SOURCE_LABEL, type AuthSource } from \"./auth/types.js\";\nimport {\n excMessage,\n KaguraConnectionError,\n KaguraError,\n KaguraIntegrityError,\n} from \"./errors.js\";\nimport { extractDetail, sanitizeServerDetail, SDK_VERSION } from \"./http.js\";\nimport type {\n FileDownloadUrlResponse,\n FileListResponse,\n FileObject,\n FileReserveResponse,\n} from \"./models.js\";\nimport {\n KaguraRestClient,\n type KaguraRestClientOptions,\n type RequestContext,\n type RestResponse,\n} from \"./restBase.js\";\nimport { isUuid } from \"./uuid.js\";\n\n/** A `KaguraConnectionError` carrying the raw non-2xx body for dedup inspection. */\ninterface ErrorWithResponse extends KaguraConnectionError {\n responseStatus?: number;\n responseText?: string;\n}\n\nexport interface FilesClientOptions extends KaguraRestClientOptions {\n /** R2 PUT timeout in ms (default 300000 — 5 min for large files). */\n uploadTimeoutMs?: number;\n}\n\nexport interface UploadOptions {\n /**\n * Target context (workspace) UUID. Mapped to the backend's\n * `workspace_id` field on the wire.\n */\n contextId: string;\n /**\n * File contents. A string is treated as a filesystem path (read fully\n * into memory); a `Uint8Array` is used directly.\n */\n source: string | Uint8Array;\n /** Required when `source` is bytes; defaults to the path basename otherwise. */\n filename?: string;\n /** MIME type; falls back to an extension guess then `application/octet-stream`. */\n contentType?: string;\n /**\n * Optional owning context to bind the file to for access control\n * (server v0.41.0+). Sent as the wire `context_id` field — distinct\n * from `contextId` above, which maps to `workspace_id`.\n */\n bindingContextId?: string;\n}\n\n/** Minimal extension→MIME map (Node has no `mimetypes` module). */\nconst CONTENT_TYPE_BY_EXT: Record<string, string> = {\n \".txt\": \"text/plain\",\n \".md\": \"text/markdown\",\n \".html\": \"text/html\",\n \".htm\": \"text/html\",\n \".json\": \"application/json\",\n \".csv\": \"text/csv\",\n \".pdf\": \"application/pdf\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".svg\": \"image/svg+xml\",\n \".zip\": \"application/zip\",\n \".docx\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n \".xlsx\": \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n \".pptx\": \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n \".epub\": \"application/epub+zip\",\n \".mp3\": \"audio/mpeg\",\n \".mp4\": \"video/mp4\",\n \".wav\": \"audio/wav\",\n};\n\nexport class FilesClient extends KaguraRestClient {\n private readonly uploadTimeoutMs: number;\n\n constructor(options: FilesClientOptions = {}) {\n super(options);\n this.uploadTimeoutMs = options.uploadTimeoutMs ?? 300_000;\n }\n\n // -------------------------------------------------------------------\n // Public API\n // -------------------------------------------------------------------\n\n /**\n * Upload a file to Kagura Memory Cloud, driving reserve → presigned PUT\n * → confirm. Returns the finalized {@link FileObject}.\n *\n * When the file already exists with the same sha256 in the workspace,\n * the server returns 409 and this surfaces the existing FileObject\n * (dedup happy-path) rather than throwing.\n *\n * @throws Error if `source` is bytes and `filename` is not provided.\n * @throws KaguraIntegrityError if R2 rejected the body sha256 binding.\n */\n async upload(options: UploadOptions): Promise<FileObject> {\n validateContextId(options.contextId);\n const { filename, body, sha256Hex, sha256Base64 } = await prepareSource(\n options.source,\n options.filename,\n );\n const sizeBytes = body.byteLength;\n const contentType = resolveContentType(options.contentType, filename);\n\n const reserveBody: Record<string, unknown> = {\n workspace_id: options.contextId,\n filename,\n content_type: contentType,\n size_bytes: sizeBytes,\n sha256: sha256Hex,\n };\n // Only send context_id when a binding was requested — omitting it keeps\n // the upload NULL-context (workspace-scoped, legacy behaviour).\n if (options.bindingContextId !== undefined) {\n reserveBody.context_id = options.bindingContextId;\n }\n\n let reserveResp: RestResponse;\n try {\n reserveResp = await this.request(\"POST\", \"/api/v1/files/reserve\", { json: reserveBody });\n } catch (e) {\n // 409 dedup happy-path: the server reports the existing file in the\n // error body; surface it as a FileObject so callers need not special-\n // case duplicates.\n const existing = extractExistingFile(e);\n if (existing !== null) {\n return existing;\n }\n throw e;\n }\n\n const reserve = this.json(reserveResp) as FileReserveResponse;\n await this.putToObjectStore(reserve.upload_url, body, sha256Base64, contentType);\n\n // workspace_id is required on the confirm query string (memory-cloud\n // v0.41.0); omitting it returns 422 and the upload never finalizes.\n const confirmResp = await this.request(\"POST\", `/api/v1/files/${reserve.file_id}/confirm`, {\n params: { workspace_id: options.contextId },\n json: { sha256: sha256Hex },\n });\n return this.json(confirmResp) as FileObject;\n }\n\n /** Return a short-lived presigned GET URL for `fileId`. */\n async downloadUrl(fileId: string, options: { contextId: string }): Promise<string> {\n validateContextId(options.contextId);\n const response = await this.request(\"GET\", `/api/v1/files/${fileId}/download-url`, {\n params: { workspace_id: options.contextId },\n });\n return (this.json(response) as FileDownloadUrlResponse).download_url;\n }\n\n /** Soft-delete a file by id (server hard-deletes after retention). */\n async delete(fileId: string, options: { contextId: string }): Promise<void> {\n validateContextId(options.contextId);\n await this.request(\"DELETE\", `/api/v1/files/${fileId}`, {\n params: { workspace_id: options.contextId },\n });\n }\n\n /** List uploaded files in a workspace, newest first. */\n async list(options: {\n contextId: string;\n /** Maximum files to return (1-500, default 50). */\n limit?: number;\n /** Forward-compatible pagination cursor (ignored by the current server). */\n cursor?: string;\n }): Promise<FileListResponse> {\n validateContextId(options.contextId);\n const params: Record<string, unknown> = {\n workspace_id: options.contextId,\n limit: options.limit ?? 50,\n };\n if (options.cursor !== undefined) {\n params.cursor = options.cursor;\n }\n const response = await this.request(\"GET\", \"/api/v1/files\", { params });\n const raw = this.json(response);\n // Current server returns a bare `list[FileObject]`; future versions may\n // return `{files, next_cursor}`.\n if (Array.isArray(raw)) {\n return { files: raw as FileObject[], next_cursor: null };\n }\n return raw as FileListResponse;\n }\n\n // -------------------------------------------------------------------\n // R2 PUT (unauthenticated by design)\n // -------------------------------------------------------------------\n\n /**\n * PUT `body` to the presigned R2 URL with checksum binding. Sends\n * `x-amz-checksum-sha256` (base64 of the raw digest) only when the\n * presign signed it; a 400 from the store → {@link KaguraIntegrityError}.\n */\n private async putToObjectStore(\n uploadUrl: string,\n body: Uint8Array,\n sha256Base64: string,\n contentType: string,\n ): Promise<void> {\n const headers: Record<string, string> = {\n \"content-type\": contentType,\n \"user-agent\": `kagura-memory-sdk/${SDK_VERSION}`,\n };\n // Send the checksum header ONLY when the presign signed it: a server with\n // R2 checksum binding OFF presigns without it, and sending it anyway makes\n // the SigV4 signature mismatch → 403 SignatureDoesNotMatch (#226).\n if (presignSignsChecksum(uploadUrl)) {\n headers[\"x-amz-checksum-sha256\"] = sha256Base64;\n }\n\n let response: Response;\n try {\n response = await this.fetchImpl(uploadUrl, {\n method: \"PUT\",\n headers,\n body,\n signal: AbortSignal.timeout(this.uploadTimeoutMs),\n });\n } catch (e) {\n throw new KaguraConnectionError(`Object store PUT failed: ${excMessage(e)}`, { cause: e });\n }\n if (response.status === 400) {\n throw new KaguraIntegrityError(\n \"Object store rejected upload with HTTP 400 — most commonly R2 \" +\n \"BadDigest (body sha256 did not match the presigned PUT binding). \" +\n \"Verify that the SDK is computing sha256 over the exact bytes being PUT.\",\n );\n }\n if (response.status < 200 || response.status >= 300) {\n throw new KaguraConnectionError(`Object store PUT failed: HTTP ${response.status}`);\n }\n }\n\n // -------------------------------------------------------------------\n // Hooks\n // -------------------------------------------------------------------\n\n /**\n * 403 → a workspace-mismatch hint (issue #115): surface the credential\n * source and requested workspace prefix without leaking the api_key.\n */\n protected override error403(response: RestResponse, context: RequestContext): KaguraError {\n return new KaguraConnectionError(\n formatWorkspace403Hint({\n authSource: this.authSource,\n sourceWorkspaceHint: this.workspaceIdHint,\n requestedWorkspace: extractRequestedWorkspace(context.requestJson, context.requestParams),\n serverDetail: extractDetail(response.text),\n }),\n );\n }\n\n /** Stash the raw non-2xx body so the 409 dedup path can recover `existing_file`. */\n protected override genericError(response: RestResponse): KaguraError {\n const err = super.genericError(response) as ErrorWithResponse;\n err.responseStatus = response.status;\n err.responseText = response.text;\n return err;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Module-level helpers\n// ---------------------------------------------------------------------------\n\n/** Truncate a UUID to its 8-char prefix for log-friendly display. */\nfunction shortWorkspace(uuidStr: string | null): string {\n if (!uuidStr) {\n return \"<none>\";\n }\n return `${uuidStr.slice(0, 8)}…`;\n}\n\n/** Recover the `workspace_id` the failing request was targeting. */\nfunction extractRequestedWorkspace(\n json: Record<string, unknown> | undefined,\n params: Record<string, unknown> | undefined,\n): string | null {\n if (json !== undefined) {\n const ws = json.workspace_id;\n if (typeof ws === \"string\") {\n return ws;\n }\n }\n if (params !== undefined) {\n const ws = params.workspace_id;\n if (typeof ws === \"string\") {\n return ws;\n }\n }\n return null;\n}\n\n/** Compose the actionable 403 message for issue #115. */\nfunction formatWorkspace403Hint(args: {\n authSource: AuthSource | null;\n sourceWorkspaceHint: string | null;\n requestedWorkspace: string | null;\n serverDetail: string | null;\n}): string {\n const { authSource, sourceWorkspaceHint, requestedWorkspace, serverDetail } = args;\n if (authSource === null) {\n const safeDetail = sanitizeServerDetail(serverDetail);\n return safeDetail ? `HTTP 403: ${safeDetail}` : \"HTTP 403\";\n }\n const sourceLabel = SOURCE_LABEL[authSource] ?? String(authSource);\n const heading = requestedWorkspace\n ? \"HTTP 403 — workspace not accessible with current credentials.\"\n : \"HTTP 403 — access denied with current credentials.\";\n const lines = [\n heading,\n ` api_key source: ${sourceLabel} (workspace=${shortWorkspace(sourceWorkspaceHint)})`,\n ];\n if (requestedWorkspace) {\n lines.push(` workspace requested: ${shortWorkspace(requestedWorkspace)}`);\n lines.push(\" Hint: contextId may not match the workspace bound to your api_key.\");\n }\n const safeDetail = sanitizeServerDetail(serverDetail);\n if (safeDetail) {\n lines.push(` server detail: ${safeDetail}`);\n }\n return lines.join(\"\\n\");\n}\n\n/** Pull an `existing_file` payload out of a 409 dedup response. */\nfunction extractExistingFile(error: unknown): FileObject | null {\n if (!(error instanceof KaguraConnectionError)) {\n return null;\n }\n const withResponse = error as ErrorWithResponse;\n if (withResponse.responseStatus !== 409 || withResponse.responseText === undefined) {\n return null;\n }\n let body: unknown;\n try {\n body = JSON.parse(withResponse.responseText);\n } catch {\n return null;\n }\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return null;\n }\n const existing = (body as Record<string, unknown>).existing_file;\n if (typeof existing !== \"object\" || existing === null || Array.isArray(existing)) {\n return null;\n }\n return existing as FileObject;\n}\n\n/** Fail fast on a non-UUID `contextId`. */\nfunction validateContextId(contextId: string): void {\n if (!isUuid(contextId)) {\n throw new Error(\n `contextId must be a UUID; got ${JSON.stringify(contextId)}. ` +\n \"Use the OAuth profile's workspace_id, a UUID from `kagura context list`, \" +\n \"or run `kagura auth login` first.\",\n );\n }\n}\n\n/** True if the presigned URL signed the sha256 checksum header. */\nfunction presignSignsChecksum(uploadUrl: string): boolean {\n let signed = \"\";\n try {\n signed = new URL(uploadUrl).searchParams.get(\"X-Amz-SignedHeaders\") ?? \"\";\n } catch {\n return false;\n }\n return signed.toLowerCase().includes(\"x-amz-checksum-sha256\");\n}\n\n/** Pick a content type — explicit > extension guess > octet-stream. */\nfunction resolveContentType(contentType: string | undefined, filename: string): string {\n if (contentType) {\n return contentType;\n }\n const ext = path.extname(filename).toLowerCase();\n return CONTENT_TYPE_BY_EXT[ext] ?? \"application/octet-stream\";\n}\n\n/** Resolve filename, load bytes, compute sha256 (hex + base64 of raw digest). */\nasync function prepareSource(\n source: string | Uint8Array,\n filename: string | undefined,\n): Promise<{ filename: string; body: Uint8Array; sha256Hex: string; sha256Base64: string }> {\n let body: Uint8Array;\n let resolvedFilename: string;\n if (typeof source === \"string\") {\n body = await readFile(source);\n resolvedFilename = filename ?? path.basename(source);\n } else {\n if (!filename) {\n throw new Error(\n \"filename is required when source is bytes (the server requires a non-empty filename).\",\n );\n }\n body = source;\n resolvedFilename = filename;\n }\n const digest = createHash(\"sha256\").update(body).digest();\n return {\n filename: resolvedFilename,\n body,\n sha256Hex: digest.toString(\"hex\"),\n sha256Base64: digest.toString(\"base64\"),\n };\n}\n","/**\n * Auth contracts shared by the credential resolver and the HTTP clients.\n *\n * The Python SDK plugs OAuth refresh in via an httpx.Auth subclass; with\n * fetch there is no request-hook layer, so clients instead ask an\n * `AuthProvider` for a fresh `Authorization` header value before each\n * request.\n */\n\n/** Supplies the `Authorization` header value for each request. */\nexport interface AuthProvider {\n /**\n * Return the current `Authorization` header value (e.g. `Bearer xyz`),\n * refreshing the underlying token first when it is at/near expiry.\n */\n getAuthHeader(): Promise<string>;\n}\n\n/**\n * Which precedence branch produced a static auth result. Pairs an api_key\n * with the workspace it was provisioned for (issue #115).\n */\nexport type StaticSource = \"explicit\" | \"env\" | \"config\";\n\n/** Superset of StaticSource that also covers the OAuth branch. */\nexport type AuthSource = StaticSource | \"oauth\";\n\n/**\n * Human-readable label for each credential source — shared by 403 hint\n * formatting so surfaces never drift.\n */\nexport const SOURCE_LABEL: Record<AuthSource, string> = {\n explicit: \"explicit apiKey argument\",\n env: \"KAGURA_API_KEY env\",\n config: \".kagura.json\",\n oauth: \"OAuth profile (~/.kagura/credentials.json)\",\n};\n\n/** Long-lived API key resolution result. */\nexport interface StaticAuthResult {\n kind: \"static\";\n apiKey: string;\n mcpUrl: string;\n source: StaticSource;\n}\n\n/** OAuth credentials.json resolution result. */\nexport interface OAuthAuthResult {\n kind: \"oauth\";\n oauth: AuthProvider;\n mcpUrl: string;\n /** Workspace bound to this token pair at resolution time. */\n workspaceId: string | null;\n}\n\nexport type ResolvedAuth = StaticAuthResult | OAuthAuthResult;\n","/**\n * Shared construction/auth/lifecycle/error spine for Kagura REST clients\n * (port of _rest_base.py).\n *\n * FilesClient, ResourceClient, SecretClient, and WorkspaceClient would\n * otherwise carry near-verbatim copies of the same scaffolding — and the\n * Python copies had already drifted (403 credential scrubbing and the\n * OAuth-aware 401 hint existed in some clients but not others).\n * {@link KaguraRestClient} owns the spine once; each client keeps only its\n * wire-contract differences via the `error401`/`error403`/`error429`\n * builder hooks.\n *\n * Invariants the base enforces for every client:\n *\n * - credentials are required up front (`apiKey` or an `AuthProvider`) with\n * an actionable error naming the class's factory;\n * - HTTPS-only base URLs (loopback exempt) via `validateHttpsUrl`;\n * - the API key is baked into the `Authorization` header closure exactly\n * once and never stored as an instance field;\n * - every request carries `User-Agent: kagura-memory-sdk/<version>` and an\n * `AbortSignal.timeout` deadline.\n */\n\nimport { resolveAuth } from \"./auth/resolve.js\";\nimport type { AuthProvider, AuthSource, ResolvedAuth } from \"./auth/types.js\";\nimport {\n excMessage,\n KaguraAuthError,\n KaguraConnectionError,\n KaguraError,\n KaguraNotFoundError,\n KaguraQuotaError,\n} from \"./errors.js\";\nimport {\n baseUrlFromMcp,\n extractDetail,\n retryAfterSeconds,\n SDK_VERSION,\n validateHttpsUrl,\n} from \"./http.js\";\n\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\n/** Default REST API origin when no MCP URL or base URL is supplied. */\nexport const DEFAULT_REST_BASE_URL = \"https://memory.kagura-ai.com\";\n\nexport interface KaguraRestClientOptions {\n /**\n * Kagura API key (Bearer token). Required unless `oauth` is supplied.\n * For credential resolution (the auto chain env → `~/.kagura/\n * credentials.json` → `.kagura.json`), use `fromMcpUrl` — a bare\n * constructor deliberately does not read disk state.\n */\n apiKey?: string;\n /** REST API base URL without path (default: {@link DEFAULT_REST_BASE_URL}). */\n baseUrl?: string;\n /** Request timeout in milliseconds (default: 30000). */\n timeoutMs?: number;\n /**\n * Pre-built OAuth provider. `fromMcpUrl` passes one when the resolver\n * picked an OAuth profile; it injects a fresh access token per request.\n */\n oauth?: AuthProvider;\n /**\n * Provenance tag from `resolveAuth`; clients use it to flavor 403\n * hints (issue #115).\n */\n authSource?: AuthSource;\n /**\n * Workspace UUID associated with the credential source — hint display\n * only, never sent on the wire.\n */\n workspaceIdHint?: string | null;\n /** Fetch implementation override (for tests; default: globalThis.fetch). */\n fetch?: typeof globalThis.fetch;\n}\n\nexport interface FromMcpUrlOptions {\n /** Explicit Kagura API key. Skips the resolution chain. */\n apiKey?: string;\n /**\n * Explicit MCP URL. When omitted, the resolved credential source's\n * stored URL is used (default `https://memory.kagura-ai.com/mcp`).\n */\n mcpUrl?: string;\n /** Request timeout in milliseconds (default: 30000). */\n timeoutMs?: number;\n /** Named OAuth profile to load (overrides KAGURA_PROFILE and the file default). */\n profile?: string;\n /** Fetch implementation override (for tests; default: globalThis.fetch). */\n fetch?: typeof globalThis.fetch;\n /** Environment source override (for tests; default: process.env). */\n env?: Record<string, string | undefined>;\n /** Home directory override (for tests). */\n home?: string;\n}\n\n/**\n * Envelope returned by {@link KaguraRestClient.request} for 2xx responses.\n *\n * Beyond the `{status, headers, text}` triple, it carries the request\n * method and path so {@link KaguraRestClient.json} / `expectList` can name\n * the endpoint in shape-mismatch diagnostics (the Python port reads these\n * off `resp.request`; fetch's `Response` has no such back-pointer).\n */\nexport interface RestResponse {\n status: number;\n headers: Headers;\n text: string;\n method: HttpMethod;\n path: string;\n}\n\n/** Request payload context threaded to the 403 hook (subclass hints only). */\nexport interface RequestContext {\n requestJson: Record<string, unknown> | undefined;\n requestParams: Record<string, unknown> | undefined;\n}\n\n/** `typeof`-style name for shape-mismatch diagnostics (`null` → \"null\"). */\nfunction jsonTypeName(value: unknown): string {\n return value === null ? \"null\" : typeof value;\n}\n\n/**\n * Base class for the Kagura REST API clients.\n *\n * Subclasses add their domain methods on top of {@link request} and\n * override the `error*` builder hooks where their contract differs. The\n * default hooks implement the majority behavior:\n *\n * - 401 → {@link KaguraAuthError} with an OAuth-aware recovery hint\n * - 403 → the generic `HTTP 403: <detail>` mapping\n * - 404 → {@link KaguraNotFoundError} (server detail or \"Not found\")\n * - 429 → {@link KaguraQuotaError} with a tolerant `Retry-After`\n * - other statuses → {@link KaguraConnectionError}\n * - transport errors → {@link KaguraConnectionError}\n */\nexport class KaguraRestClient {\n readonly baseUrl: string;\n readonly timeoutMs: number;\n\n /** Supplies the Authorization header for every request (static or OAuth). */\n protected readonly auth: AuthProvider;\n /** Non-null exactly when constructed in OAuth mode (flavors the 401 hint). */\n protected readonly oauth: AuthProvider | null;\n /** Which resolution branch produced the credentials (403 hint flavoring). */\n protected readonly authSource: AuthSource | null;\n /** Workspace bound to the credential source — display only. */\n protected readonly workspaceIdHint: string | null;\n protected readonly fetchImpl: typeof globalThis.fetch;\n\n /**\n * Initialize with a static API key or a pre-built OAuth provider.\n *\n * @throws Error if neither `apiKey` nor `oauth` is given, or the base\n * URL is plain HTTP on a non-loopback host.\n */\n constructor(options: KaguraRestClientOptions = {}) {\n if (options.apiKey === undefined && options.oauth === undefined) {\n const name = new.target.name;\n throw new Error(\n `${name} requires apiKey, or use ${name}.fromMcpUrl(...) to resolve ` +\n \"credentials from environment, OAuth profile, or .kagura.json.\",\n );\n }\n\n const strippedUrl = (options.baseUrl ?? DEFAULT_REST_BASE_URL).replace(/\\/+$/, \"\");\n validateHttpsUrl(strippedUrl, \"Base URL\");\n this.baseUrl = strippedUrl;\n this.timeoutMs = options.timeoutMs ?? 30_000;\n this.fetchImpl = options.fetch ?? globalThis.fetch;\n\n if (options.oauth !== undefined) {\n // OAuth path: the provider injects a fresh access_token per request\n // and coordinates refresh via the shared credentials state.\n this.auth = options.oauth;\n this.oauth = options.oauth;\n } else {\n // Static path: bake the bearer header once, in a closure — the key\n // is never stored as an instance field.\n const header = `Bearer ${options.apiKey}`;\n this.auth = { getAuthHeader: async () => header };\n this.oauth = null;\n }\n this.authSource = options.authSource ?? null;\n this.workspaceIdHint = options.workspaceIdHint ?? null;\n }\n\n // -------------------------------------------------------------------\n // Factories\n // -------------------------------------------------------------------\n\n /**\n * Create a client by resolving credentials from the SDK chain.\n *\n * Precedence: explicit `apiKey` > `KAGURA_API_KEY` env > OAuth profile\n * from `~/.kagura/credentials.json` > `.kagura.json`. The REST\n * `baseUrl` is derived from the resolved MCP URL (strips `/mcp` and any\n * `/mcp/w/{workspaceId}` suffix); a static key bakes the Bearer header\n * once, an OAuth profile installs an auto-refreshing `AuthProvider`.\n *\n * Declared with a polymorphic `this` so every subclass inherits a\n * factory returning its own type: `FilesClient.fromMcpUrl(...)` is a\n * `FilesClient`.\n */\n static fromMcpUrl<T extends typeof KaguraRestClient>(\n this: T,\n options: FromMcpUrlOptions = {},\n ): InstanceType<T> {\n const resolved = resolveAuth({\n apiKey: options.apiKey ?? null,\n mcpUrl: options.mcpUrl ?? null,\n profile: options.profile ?? null,\n env: options.env,\n home: options.home,\n });\n return this.fromResolvedAuth(resolved, {\n timeoutMs: options.timeoutMs,\n fetch: options.fetch,\n });\n }\n\n /**\n * Construct from a pre-resolved auth — internal CLI helper.\n *\n * Shared by {@link fromMcpUrl} (SDK entry) and CLI command runners,\n * which resolve once so apiKey and workspace can be paired from the\n * same credential source (#115).\n *\n * `workspaceIdHint` threads the workspace bound to a static apiKey into\n * the client for 403 hint display. On the OAuth branch the resolver\n * already carries `workspaceId`, so the hint is taken from there and\n * the option is ignored.\n */\n protected static fromResolvedAuth<T extends typeof KaguraRestClient>(\n this: T,\n resolved: ResolvedAuth,\n options: {\n timeoutMs?: number;\n workspaceIdHint?: string | null;\n fetch?: typeof globalThis.fetch;\n } = {},\n ): InstanceType<T> {\n const baseUrl = baseUrlFromMcp(resolved.mcpUrl.replace(/\\/+$/, \"\"));\n const shared: KaguraRestClientOptions = { baseUrl };\n if (options.timeoutMs !== undefined) {\n shared.timeoutMs = options.timeoutMs;\n }\n if (options.fetch !== undefined) {\n shared.fetch = options.fetch;\n }\n if (resolved.kind === \"static\") {\n return new this({\n ...shared,\n apiKey: resolved.apiKey,\n authSource: resolved.source,\n workspaceIdHint: options.workspaceIdHint ?? null,\n }) as InstanceType<T>;\n }\n return new this({\n ...shared,\n oauth: resolved.oauth,\n authSource: \"oauth\",\n workspaceIdHint: resolved.workspaceId,\n }) as InstanceType<T>;\n }\n\n // -------------------------------------------------------------------\n // Lifecycle\n // -------------------------------------------------------------------\n\n /** Release resources. (fetch has no persistent pool to close; kept for API parity.) */\n async close(): Promise<void> {\n // No-op by design; subclasses with real resources override.\n }\n\n // -------------------------------------------------------------------\n // Request spine\n // -------------------------------------------------------------------\n\n /**\n * Make an authenticated request with standard error mapping.\n *\n * Returns the {@link RestResponse} envelope for 2xx; throws the mapped\n * {@link KaguraError} for any other status and wraps transport/abort\n * failures in {@link KaguraConnectionError}.\n */\n protected async request(\n method: HttpMethod,\n path: string,\n opts: {\n json?: Record<string, unknown>;\n params?: Record<string, unknown>;\n extraHeaders?: Record<string, string>;\n } = {},\n ): Promise<RestResponse> {\n let url = `${this.baseUrl}${path}`;\n if (opts.params) {\n const query = new URLSearchParams();\n for (const [key, value] of Object.entries(opts.params)) {\n if (value !== undefined && value !== null) {\n query.set(key, String(value));\n }\n }\n const qs = query.toString();\n if (qs) {\n url += `?${qs}`;\n }\n }\n\n const headers: Record<string, string> = {\n authorization: await this.auth.getAuthHeader(),\n \"user-agent\": `kagura-memory-sdk/${SDK_VERSION}`,\n };\n const init: RequestInit = {\n method,\n headers,\n signal: AbortSignal.timeout(this.timeoutMs),\n };\n if (opts.json !== undefined) {\n headers[\"content-type\"] = \"application/json\";\n init.body = JSON.stringify(opts.json);\n }\n // Extra headers merge last so a caller can override a default —\n // mirrors httpx's per-request header precedence in the Python port.\n Object.assign(headers, opts.extraHeaders);\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, init);\n } catch (e) {\n throw new KaguraConnectionError(`Connection failed: ${excMessage(e)}`, { cause: e });\n }\n\n const envelope: RestResponse = {\n status: response.status,\n headers: response.headers,\n text: await this.safeText(response),\n method,\n path,\n };\n if (response.status < 200 || response.status >= 300) {\n throw this.mapStatusError(envelope, {\n requestJson: opts.json,\n requestParams: opts.params,\n });\n }\n return envelope;\n }\n\n private async safeText(response: Response): Promise<string> {\n try {\n return await response.text();\n } catch {\n return \"\";\n }\n }\n\n /**\n * Build the Kagura error for a non-2xx response.\n *\n * Hooks RETURN the error rather than throwing it so {@link request}\n * owns the single throw site — one uniform chain and a compiler-checked\n * `KaguraError` contract on every hook.\n */\n protected mapStatusError(response: RestResponse, context: RequestContext): KaguraError {\n const status = response.status;\n if (status === 401) {\n return this.error401(response);\n }\n if (status === 403) {\n return this.error403(response, context);\n }\n if (status === 404) {\n return new KaguraNotFoundError(extractDetail(response.text) || \"Not found\");\n }\n if (status === 429) {\n return this.error429(response);\n }\n return this.genericError(response);\n }\n\n // ---- per-status hooks (override where the wire contract differs) ----\n\n /** 401 → auth error with a recovery hint matching the auth mode. */\n protected error401(response: RestResponse): KaguraError {\n const hint =\n this.oauth !== null\n ? \"Re-run `kagura auth login` or inspect ~/.kagura/credentials.json.\"\n : \"Check your API key.\";\n return new KaguraAuthError(`Authentication failed. ${hint}`);\n }\n\n /**\n * 403 → generic mapping by default; clients with a richer story\n * (workspace hints, secret existence-hiding) override this.\n */\n protected error403(response: RestResponse, context: RequestContext): KaguraError {\n return this.genericError(response);\n }\n\n /** 429 → quota error with a tolerant `Retry-After` parse. */\n protected error429(response: RestResponse): KaguraError {\n return new KaguraQuotaError(\n \"Quota exceeded. Try again later.\",\n retryAfterSeconds(response.headers),\n );\n }\n\n /** Any other status → `HTTP <status>: <detail>` connection error. */\n protected genericError(response: RestResponse): KaguraError {\n const detail = extractDetail(response.text);\n const msg = detail ? `HTTP ${response.status}: ${detail}` : `HTTP ${response.status}`;\n return new KaguraConnectionError(msg);\n }\n\n // -------------------------------------------------------------------\n // Response-body helpers\n // -------------------------------------------------------------------\n\n /**\n * Parse a 2xx body as JSON, mapping garbage to a Kagura error.\n *\n * A proxy/CDN can 200 with an HTML maintenance page; that must not\n * surface as a raw `SyntaxError`.\n */\n protected json(response: RestResponse): unknown {\n try {\n return JSON.parse(response.text) as unknown;\n } catch (e) {\n throw new KaguraConnectionError(\n `Server returned a non-JSON body (HTTP ${response.status}) for ` +\n `${response.method} ${response.path}.`,\n { cause: e },\n );\n }\n }\n\n /** Parse a 2xx body that the contract says is a JSON array. */\n protected expectList(response: RestResponse): unknown[] {\n const payload = this.json(response);\n if (!Array.isArray(payload)) {\n throw new KaguraConnectionError(\n `Unexpected response shape for ${response.method} ${response.path}: ` +\n `expected a JSON array, got ${jsonTypeName(payload)}.`,\n );\n }\n return payload;\n }\n}\n","/**\n * Internal UUID parsing/validation — the analogue of Python's `uuid.UUID`.\n *\n * Not part of the public API surface; used by FilesClient (validate-only).\n */\n\nconst CANONICAL_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Parse a UUID in any of the spellings Python's `uuid.UUID` tolerates\n * (canonical, `{braces}`, `urn:uuid:` prefix, dashless 32-hex) and return\n * the canonical lowercase 8-4-4-4-12 form.\n *\n * @throws Error if the input is not a UUID.\n */\nexport function parseUuid(value: string): string {\n if (typeof value !== \"string\") {\n throw new Error(`expected a UUID string, got ${typeof value}`);\n }\n let hex = value.trim().toLowerCase();\n if (hex.startsWith(\"urn:uuid:\")) {\n hex = hex.slice(\"urn:uuid:\".length);\n }\n if (hex.startsWith(\"{\") && hex.endsWith(\"}\")) {\n hex = hex.slice(1, -1);\n }\n hex = hex.replace(/-/g, \"\");\n if (!/^[0-9a-f]{32}$/.test(hex)) {\n throw new Error(`invalid UUID: ${value}`);\n }\n return (\n `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-` +\n `${hex.slice(16, 20)}-${hex.slice(20)}`\n );\n}\n\n/** True when `value` is any parseable UUID spelling. */\nexport function isUuid(value: string): boolean {\n if (CANONICAL_RE.test(value)) {\n return true;\n }\n try {\n parseUuid(value);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * REST API client for Kagura Memory Cloud Resource Tokens (port of\n * resource_client.py).\n *\n * Handles two authentication modes:\n * - Token CRUD: `Authorization: Bearer <api_key>` (set once in constructor)\n * - Event ingestion: `X-Resource-API-Key` (passed per-call, never stored)\n *\n * All methods may throw:\n * - {@link KaguraAuthError}: Authentication failed (401)\n * - {@link KaguraNotFoundError}: Resource not found (404)\n * - {@link KaguraConnectionError}: Connection or HTTP error\n * - {@link KaguraQuotaError}: Quota exceeded (429)\n */\n\nimport type { ResolvedAuth } from \"./auth/types.js\";\nimport { KaguraClient } from \"./client.js\";\nimport { KaguraAuthError, KaguraNotFoundError } from \"./errors.js\";\nimport type {\n IndexerStatusResponse,\n PaginatedResourceTokensResponse,\n ResourceEventBatchResponse,\n ResourceEventResponse,\n ResourceEventsListResponse,\n ResourceImpactResponse,\n ResourceListResponse,\n ResourceSchemaResponse,\n ResourceSetupResponse,\n ResourceTokenCreateResponse,\n ResourceTokenResponse,\n} from \"./models.js\";\nimport { KaguraRestClient } from \"./restBase.js\";\n\n/**\n * Message surfaced when `setupResource` is called on an OAuth-resolved\n * client. Defined at module scope so tests can assert against the stable\n * constant instead of pinning a substring of the rendered output.\n *\n * The hint MUST point at a credential source that outranks OAuth in the\n * resolver chain (`env > OAuth profile > .kagura.json`). Suggesting\n * `.kagura.json` is misleading — it ranks BELOW OAuth and would still\n * be skipped while the OAuth profile is present.\n */\nexport const SETUP_OAUTH_NOT_SUPPORTED_MSG =\n \"setupResource() is not yet available in OAuth mode. \" +\n \"To run it, switch to a credential source that outranks OAuth: \" +\n \"set KAGURA_API_KEY (and KAGURA_MCP_URL too if your api_key is \" +\n \"not for the default cloud server — the env branch uses \" +\n \"KAGURA_MCP_URL or the default URL, not the OAuth profile's \" +\n \"stored mcp_url) and retry, or remove the active OAuth profile \" +\n \"(e.g. `kagura auth logout`, or `kagura auth logout --profile <name>` \" +\n \"for named profiles selected via KAGURA_PROFILE) so .kagura.json \" +\n \"is consulted. The CRUD/ingest endpoints continue to work in \" +\n \"OAuth mode.\";\n\nexport interface CreateTokenOptions {\n /** Resource identifier this token is scoped to. */\n resourceId: string;\n /** Human-readable description. */\n description?: string | null;\n /** Event ingestion quota per hour (1-10000, default 1000). */\n quotaEventsPerHour?: number;\n}\n\nexport interface ListTokensOptions {\n /** Filter by resource ID. */\n resourceId?: string | null;\n /** Number of tokens per page (1-100, default 50). */\n limit?: number;\n /** Starting offset for pagination (default 0). */\n offset?: number;\n}\n\nexport interface UpdateTokenOptions {\n /** Updated description. */\n description?: string | null;\n /** Updated quota (1-10000). */\n quotaEventsPerHour?: number | null;\n}\n\nexport interface ResourceSetupOptions {\n /** Resource identifier for data ingestion. */\n resourceId: string;\n /** Context name (defaults to resourceId server-side). */\n contextName?: string;\n /** Context summary. */\n summary?: string;\n /** Token description. */\n description?: string;\n /** Token quota (1-10000, default 1000). */\n quotaEventsPerHour?: number;\n}\n\n/**\n * A single event to ingest (camelCase input for the wire-model\n * `ResourceEventRequest`). Serialized per-field to the snake_case wire\n * shape; unset/null optional fields are omitted, matching the Python\n * `model_dump(exclude_none=True)` semantics (`eventMetadata` defaults to\n * `{}` and is always sent).\n */\nexport interface ResourceEventInput {\n op: \"upsert\" | \"delete\";\n /** Document ID (1-255 chars). */\n docId: string;\n /** Document version (minimum 1). */\n version?: number | null;\n payload?: Record<string, unknown> | null;\n /** Idempotency key (1-255 chars). */\n idempotencyKey?: string | null;\n eventMetadata?: Record<string, unknown>;\n /** Importance score (0.0-1.0). */\n importance?: number | null;\n}\n\nexport interface ListResourceEventsOptions {\n /** Maximum events per page (1-100, default 50). */\n limit?: number;\n /** Opaque pagination cursor from a prior `next_cursor`. */\n cursor?: string | null;\n /** Filter by operation (`upsert` or `delete`). */\n op?: \"upsert\" | \"delete\" | null;\n /** Filter by document ID. */\n docId?: string | null;\n /** Filter by document version. */\n version?: number | null;\n /**\n * Return only events with `created_at` at or after this time\n * (inclusive). A `Date` is serialized to ISO 8601 UTC; a string is\n * passed through as-is (supply ISO 8601).\n */\n since?: Date | string | null;\n}\n\n/** Serialize one event to the snake_case wire dict (exclude-none semantics). */\nfunction serializeEvent(event: ResourceEventInput): Record<string, unknown> {\n const wire: Record<string, unknown> = {\n op: event.op,\n doc_id: event.docId,\n };\n if (event.version !== undefined && event.version !== null) {\n wire.version = event.version;\n }\n if (event.payload !== undefined && event.payload !== null) {\n wire.payload = event.payload;\n }\n if (event.idempotencyKey !== undefined && event.idempotencyKey !== null) {\n wire.idempotency_key = event.idempotencyKey;\n }\n // Wire-model default is {} (not null), so the field is always present.\n wire.event_metadata = event.eventMetadata ?? {};\n if (event.importance !== undefined && event.importance !== null) {\n wire.importance = event.importance;\n }\n return wire;\n}\n\n/**\n * REST API client for Kagura Memory Cloud Resource Tokens.\n *\n * Extends {@link KaguraRestClient} with the resource-token wire contract;\n * the base's default error hooks already implement this client's mapping\n * (429 → {@link KaguraQuotaError} with `retryAfter`), so no hooks are\n * overridden here.\n */\nexport class ResourceClient extends KaguraRestClient {\n /**\n * Original MCP URL — `null` until {@link fromResolvedAuth} stamps it.\n * {@link setupResource} needs the ORIGINAL MCP URL, which the REST\n * `baseUrl` no longer carries.\n */\n private mcpUrlValue: string | null = null;\n\n /** MCP URL captured by `fromMcpUrl` (null for bare construction). */\n get mcpUrl(): string | null {\n return this.mcpUrlValue;\n }\n\n /**\n * Construct from a pre-resolved auth, stamping the MCP URL.\n *\n * `setupResource()` needs the ORIGINAL MCP URL to build its MCP\n * session — the resolved auth always carries one, whether sourced from\n * the OAuth profile or the priority-4 config.\n */\n protected static override fromResolvedAuth<T extends typeof KaguraRestClient>(\n this: T,\n resolved: ResolvedAuth,\n options: {\n timeoutMs?: number;\n workspaceIdHint?: string | null;\n fetch?: typeof globalThis.fetch;\n } = {},\n ): InstanceType<T> {\n const instance = super.fromResolvedAuth(resolved, options) as InstanceType<T>;\n (instance as unknown as ResourceClient).mcpUrlValue = resolved.mcpUrl.replace(/\\/+$/, \"\");\n return instance;\n }\n\n // -------------------------------------------------------------------\n // Token CRUD (Bearer auth)\n // -------------------------------------------------------------------\n\n /**\n * Create a new resource token.\n *\n * @returns Created token including plaintext token (shown only once).\n */\n async createToken(options: CreateTokenOptions): Promise<ResourceTokenCreateResponse> {\n const body: Record<string, unknown> = { resource_id: options.resourceId };\n if (options.description !== undefined && options.description !== null) {\n body.description = options.description;\n }\n body.quota_events_per_hour = options.quotaEventsPerHour ?? 1000;\n\n const response = await this.request(\"POST\", \"/api/v1/resource-tokens\", { json: body });\n return this.json(response) as unknown as ResourceTokenCreateResponse;\n }\n\n /**\n * List resource tokens with optional filtering.\n *\n * @returns Paginated (`limit`/`offset`) list of resource tokens.\n */\n async listTokens(options: ListTokensOptions = {}): Promise<PaginatedResourceTokensResponse> {\n const params: Record<string, unknown> = {\n limit: options.limit ?? 50,\n offset: options.offset ?? 0,\n };\n if (options.resourceId !== undefined && options.resourceId !== null) {\n params.resource_id = options.resourceId;\n }\n\n const response = await this.request(\"GET\", \"/api/v1/resource-tokens\", { params });\n return this.json(response) as unknown as PaginatedResourceTokensResponse;\n }\n\n /**\n * Update a resource token's metadata. Only fields that are set are\n * sent on the wire.\n *\n * @param tokenId Token database ID.\n * @returns Updated token metadata.\n */\n async updateToken(\n tokenId: number,\n options: UpdateTokenOptions = {},\n ): Promise<ResourceTokenResponse> {\n const body: Record<string, unknown> = {};\n if (options.description !== undefined && options.description !== null) {\n body.description = options.description;\n }\n if (options.quotaEventsPerHour !== undefined && options.quotaEventsPerHour !== null) {\n body.quota_events_per_hour = options.quotaEventsPerHour;\n }\n\n const response = await this.request(\"PATCH\", `/api/v1/resource-tokens/${tokenId}`, {\n json: body,\n });\n return this.json(response) as unknown as ResourceTokenResponse;\n }\n\n /**\n * Revoke (soft-delete) a resource token.\n *\n * @param tokenId Token database ID.\n */\n async revokeToken(tokenId: number): Promise<void> {\n await this.request(\"DELETE\", `/api/v1/resource-tokens/${tokenId}`);\n }\n\n // -------------------------------------------------------------------\n // Setup helper\n // -------------------------------------------------------------------\n\n /**\n * Atomically set up a resource for data ingestion (server v0.14+).\n *\n * Calls the server-side atomic `setup_resource` MCP tool which creates\n * Context + Resource entity + token in a single transaction. On\n * failure, no orphan Context rows are left on the server. Requires the\n * client to be created via `fromMcpUrl()`.\n *\n * @returns ResourceSetupResponse with plaintext token (shown only once).\n * @throws Error if the client was not created via `fromMcpUrl()`, or\n * was constructed via the OAuth resolution path (`setupResource`\n * currently requires a static apiKey — see\n * {@link SETUP_OAUTH_NOT_SUPPORTED_MSG}).\n * @throws KaguraAuthError if the Authorization header is missing or\n * malformed in the static path.\n *\n * Note: Idempotency for repeated calls with the same `resourceId` is\n * not guaranteed; server-side behavior may evolve. Avoid retrying\n * setup for an existing `resourceId` without first verifying state.\n */\n async setupResource(options: ResourceSetupOptions): Promise<ResourceSetupResponse> {\n if (!this.mcpUrlValue) {\n throw new Error(\n \"setupResource() requires MCP URL. Create the client via ResourceClient.fromMcpUrl().\",\n );\n }\n\n if (this.oauth !== null) {\n // `KaguraClient` construction below needs a static apiKey; the\n // OAuth AuthProvider cannot be threaded through yet. Surface the\n // workaround instead of failing with a header-scraping error a\n // few lines down.\n throw new Error(SETUP_OAUTH_NOT_SUPPORTED_MSG);\n }\n\n const auth = await this.auth.getAuthHeader();\n if (!auth.startsWith(\"Bearer \")) {\n throw new KaguraAuthError(\"Authorization header missing or invalid\");\n }\n const apiKey = auth.slice(7);\n\n const mcp = new KaguraClient({\n apiKey,\n mcpUrl: this.mcpUrlValue,\n timeoutMs: this.timeoutMs,\n fetch: this.fetchImpl,\n });\n try {\n const result = await mcp.setupResource({\n resourceId: options.resourceId,\n name: options.contextName,\n summary: options.summary,\n description: options.description,\n quotaEventsPerHour: options.quotaEventsPerHour ?? 1000,\n });\n return result as unknown as ResourceSetupResponse;\n } finally {\n await mcp.close();\n }\n }\n\n // -------------------------------------------------------------------\n // Resource Stats (Bearer auth)\n // -------------------------------------------------------------------\n\n /**\n * Get impact statistics for a resource.\n *\n * @returns Resource impact stats (token_count, memory_count, schema version).\n */\n async getResourceImpact(resourceId: string): Promise<ResourceImpactResponse> {\n const response = await this.request(\"GET\", `/api/v1/resources/${resourceId}/impact`);\n return this.json(response) as unknown as ResourceImpactResponse;\n }\n\n /**\n * List all resources in the caller's workspace (server v0.14+).\n *\n * Returns workspace-scoped resources with aggregated stats\n * (token_count, memory_count, current_schema_version, ...). The\n * endpoint is currently non-paginated; the server caps a workspace at\n * well under 50 resources by design.\n *\n * Workspace owners only — non-owners receive 403.\n */\n async listResources(): Promise<ResourceListResponse> {\n const response = await this.request(\"GET\", \"/api/v1/resources\");\n return this.json(response) as unknown as ResourceListResponse;\n }\n\n /**\n * Get indexer state and recent ingest events for a resource.\n *\n * `state` is `null` when the indexer has never run for this resource —\n * a normal 200 response, distinct from a 404. `recent_events` is\n * server-capped at 5.\n *\n * @throws KaguraNotFoundError Resource slug does not exist in the\n * caller's workspace (404; cross-workspace probe protection).\n */\n async getIndexerStatus(resourceId: string): Promise<IndexerStatusResponse> {\n const response = await this.request(\"GET\", `/api/v1/resources/${resourceId}/indexer-status`);\n return this.json(response) as unknown as IndexerStatusResponse;\n }\n\n /**\n * Get field definitions for a resource.\n *\n * @param schemaVersion Specific schema version to retrieve; omit for\n * the latest version.\n * @returns Resource schema with field definitions, or `null` if no\n * schema is registered for the resource.\n */\n async getResourceSchema(\n resourceId: string,\n schemaVersion?: number | null,\n ): Promise<ResourceSchemaResponse | null> {\n const opts: { params?: Record<string, unknown> } = {};\n if (schemaVersion !== undefined && schemaVersion !== null) {\n opts.params = { schema_version: schemaVersion };\n }\n try {\n const response = await this.request(\"GET\", `/api/v1/resources/${resourceId}/schema`, opts);\n return this.json(response) as unknown as ResourceSchemaResponse;\n } catch (e) {\n if (e instanceof KaguraNotFoundError) {\n return null;\n }\n throw e;\n }\n }\n\n /**\n * List ingested events for a resource (server v0.15+).\n *\n * Mirrors `GET /api/v1/resources/{resource_id}/events`. Results are\n * cursor-paginated: pass the returned `next_cursor` back as `cursor`\n * to fetch the next page (`next_cursor` is `null` on the last page).\n * Note this method uses `limit`/`cursor` pagination, unlike\n * {@link listTokens} which uses `limit`/`offset`.\n *\n * Uses Bearer auth (workspace read), not the `X-Resource-API-Key`\n * ingestion credential. An unknown `resourceId` returns an empty page\n * (`events=[]`, `next_cursor=null`) rather than a 404 — observed\n * against memory-cloud production.\n *\n * @throws KaguraNotFoundError The server returned 404 for this\n * resource (cross-workspace probe protection); applies only if the\n * server does respond with 404.\n */\n async listResourceEvents(\n resourceId: string,\n options: ListResourceEventsOptions = {},\n ): Promise<ResourceEventsListResponse> {\n const params: Record<string, unknown> = { limit: options.limit ?? 50 };\n if (options.cursor !== undefined && options.cursor !== null) {\n params.cursor = options.cursor;\n }\n if (options.op !== undefined && options.op !== null) {\n params.op = options.op;\n }\n if (options.docId !== undefined && options.docId !== null) {\n params.doc_id = options.docId;\n }\n if (options.version !== undefined && options.version !== null) {\n params.version = options.version;\n }\n if (options.since !== undefined && options.since !== null) {\n // A Date always serializes to UTC ISO 8601 (`Z` suffix) — the same\n // \"naive means UTC\" normalization the Python port applies.\n params.since = options.since instanceof Date ? options.since.toISOString() : options.since;\n }\n\n const response = await this.request(\"GET\", `/api/v1/resources/${resourceId}/events`, {\n params,\n });\n return this.json(response) as unknown as ResourceEventsListResponse;\n }\n\n // -------------------------------------------------------------------\n // Event Ingestion (X-Resource-API-Key auth)\n // -------------------------------------------------------------------\n\n /**\n * Ingest a single resource event.\n *\n * @param resourceApiKey Resource API key (`X-Resource-API-Key`\n * header) — sent per-call, never stored on the client.\n * @returns Ingestion result with `event_id`.\n */\n async ingestEvent(\n resourceId: string,\n resourceApiKey: string,\n event: ResourceEventInput,\n ): Promise<ResourceEventResponse> {\n const response = await this.request(\"POST\", `/api/v1/resources/${resourceId}/events`, {\n json: serializeEvent(event),\n extraHeaders: { \"X-Resource-API-Key\": resourceApiKey },\n });\n return this.json(response) as unknown as ResourceEventResponse;\n }\n\n /**\n * Ingest a batch of resource events (1-100; the server validates the\n * bound).\n *\n * @param resourceApiKey Resource API key (`X-Resource-API-Key`\n * header) — sent per-call, never stored on the client.\n * @returns Batch ingestion result with created/failed counts.\n */\n async ingestEvents(\n resourceId: string,\n resourceApiKey: string,\n events: ResourceEventInput[],\n ): Promise<ResourceEventBatchResponse> {\n const response = await this.request(\"POST\", `/api/v1/resources/${resourceId}/events/batch`, {\n json: { events: events.map(serializeEvent) },\n extraHeaders: { \"X-Resource-API-Key\": resourceApiKey },\n });\n return this.json(response) as unknown as ResourceEventBatchResponse;\n }\n}\n","/**\n * REST client for the Kagura zero-knowledge secret store\n * (port of secrets/client.py, #28).\n *\n * Talks to `/api/v1/config/secrets` on memory-cloud (v0.39.0+). This is a\n * pure wire layer: it sends and receives **only armored ciphertext** and\n * public metadata, never holds the age private key (that is\n * {@link KeyManager}'s job), and never sees plaintext. The one exception is\n * {@link SecretClient.putSecretForRecipients}, which encrypts locally before\n * handing the ciphertext to {@link SecretClient.putSecret} — the plaintext\n * still never reaches the wire.\n *\n * Construction mirrors {@link FilesClient} / {@link ResourceClient} /\n * {@link WorkspaceClient} so all four REST clients share one shape;\n * `SecretClient.fromMcpUrl(...)` resolves credentials the same way.\n */\n\nimport { KaguraConnectionError, KaguraError, KaguraSecretError } from \"../errors.js\";\nimport { extractDetail } from \"../http.js\";\nimport type {\n AuditVerifyResponse,\n PubkeyResponse,\n SecretMetaResponse,\n SecretPutResponse,\n SecretValueResponse,\n} from \"../models.js\";\nimport {\n KaguraRestClient,\n type RequestContext,\n type RestResponse,\n} from \"../restBase.js\";\nimport { encrypt, fingerprint } from \"./crypto.js\";\n\nconst BASE = \"/api/v1/config/secrets\";\n\n/**\n * REST client for the secret store's pubkey registry and secret endpoints.\n *\n * Every method may throw {@link KaguraAuthError} (401),\n * {@link KaguraNotFoundError} (404), or {@link KaguraConnectionError} for\n * other HTTP and network failures — including the 400 the server returns\n * when a put's grant set is inconsistent, and the 403 described below.\n */\nexport class SecretClient extends KaguraRestClient {\n // ---- KaguraRestClient hooks -----------------------------------------\n\n /**\n * 403 → an actionable message instead of a bare `HTTP 403`.\n *\n * The server answers 403, not 404, for a secret the caller may not read,\n * so that the response does not reveal whether the secret exists. That\n * means a 403 here has three possible causes and the message has to name\n * all of them rather than guess.\n */\n protected override error403(response: RestResponse, _context: RequestContext): KaguraError {\n const detail = extractDetail(response.text);\n const base =\n \"Access denied (HTTP 403): you may not have a grant on this secret, \" +\n \"it may not exist, or you lack permission for this operation.\";\n return new KaguraConnectionError(detail ? `${base} (${detail})` : base);\n }\n\n /**\n * 429 → the generic `HTTP 429` mapping, not {@link KaguraQuotaError}.\n *\n * Deliberate divergence from the base class, preserved from the Python\n * port: the secret surface has always rendered 429 through the generic\n * branch, and changing it would silently reclassify errors for existing\n * callers on a file both SDKs share.\n */\n protected override error429(response: RestResponse): KaguraError {\n return this.genericError(response);\n }\n\n // -- pubkey registry ---------------------------------------------------\n\n /** Register a public age recipient. Lands in `pending` until an owner approves it. */\n async registerPubkey(pubkey: string, label?: string): Promise<PubkeyResponse> {\n const body: Record<string, unknown> = { pubkey };\n if (label !== undefined) {\n body.label = label;\n }\n const response = await this.request(\"POST\", `${BASE}/pubkeys`, { json: body });\n return this.json(response) as PubkeyResponse;\n }\n\n /** List every pubkey in the workspace (owner/admin view). */\n async listPubkeys(): Promise<PubkeyResponse[]> {\n const response = await this.request(\"GET\", `${BASE}/pubkeys`);\n return this.expectList(response) as PubkeyResponse[];\n }\n\n /** List the caller's own pubkeys. */\n async listMyPubkeys(): Promise<PubkeyResponse[]> {\n const response = await this.request(\"GET\", `${BASE}/pubkeys/me`);\n return this.expectList(response) as PubkeyResponse[];\n }\n\n /** Approve a pending pubkey (owner only; TOFU attestation). */\n async approvePubkey(pubkeyId: string): Promise<PubkeyResponse> {\n const response = await this.request(\"POST\", `${BASE}/pubkeys/${pubkeyId}/approve`);\n return this.json(response) as PubkeyResponse;\n }\n\n /** Revoke a pubkey (owner only). */\n async revokePubkey(pubkeyId: string): Promise<PubkeyResponse> {\n const response = await this.request(\"POST\", `${BASE}/pubkeys/${pubkeyId}/revoke`);\n return this.json(response) as PubkeyResponse;\n }\n\n // -- secrets -----------------------------------------------------------\n\n /**\n * Store a new ciphertext version (low-level).\n *\n * The server enforces `set(recipientsSnapshot) === {fingerprint(pk) for pk\n * in grantPubkeyIds}` and answers 400 on mismatch. Prefer\n * {@link putSecretForRecipients}, which derives both lists from one\n * recipient set so they match by construction.\n */\n async putSecret(options: {\n name: string;\n /** Armored age ciphertext. This client never encrypts for you here. */\n ciphertext: string;\n recipientsSnapshot: string[];\n grantPubkeyIds: string[];\n }): Promise<SecretPutResponse> {\n const response = await this.request(\"POST\", BASE, {\n json: {\n name: options.name,\n ciphertext: options.ciphertext,\n recipients_snapshot: options.recipientsSnapshot,\n grant_pubkey_ids: options.grantPubkeyIds,\n },\n });\n return this.json(response) as SecretPutResponse;\n }\n\n /** List secret metadata. Never includes values. */\n async listSecrets(): Promise<SecretMetaResponse[]> {\n const response = await this.request(\"GET\", BASE);\n return this.expectList(response) as SecretMetaResponse[];\n }\n\n /**\n * Fetch a secret's armored ciphertext.\n *\n * The name travels in the body, not the path, so names containing `/`\n * (e.g. `cloudflare/api-token`) need no escaping here.\n */\n async fetchSecret(name: string, versionNumber?: number): Promise<SecretValueResponse> {\n const body: Record<string, unknown> = { name };\n if (versionNumber !== undefined) {\n body.version_number = versionNumber;\n }\n const response = await this.request(\"POST\", `${BASE}/fetch`, { json: body });\n return this.json(response) as SecretValueResponse;\n }\n\n /**\n * Revoke one recipient's grant on a secret. Flags `rotation_needed`.\n *\n * Revoking does **not** invalidate copies already fetched. To contain a\n * leak: rotate the upstream credential, then re-encrypt to the remaining\n * recipients with {@link putSecretForRecipients}.\n */\n async revokeGrant(name: string, recipientPubkeyId: string): Promise<SecretMetaResponse> {\n const response = await this.request(\"POST\", `${BASE}/revoke-grant`, {\n json: { name, recipient_pubkey_id: recipientPubkeyId },\n });\n return this.json(response) as SecretMetaResponse;\n }\n\n /**\n * Hard-delete a secret and all its versions and grants (owner only).\n *\n * The server appends a `delete` entry to the tamper-evident audit chain\n * *before* removal, so {@link verifyAudit} still passes afterwards.\n *\n * **Cleanup, not a security control.** Removing the stored ciphertext\n * neither un-shares a value a recipient already fetched nor rotates the\n * live upstream credential. To contain a leak, rotate first, then delete.\n *\n * @param name Slash-containing names are addressable: each path segment\n * is percent-encoded individually so the `/` separators stay structural\n * and the server's `{name:path}` converter still routes on them.\n *\n * Dot segments and empty segments are rejected rather than encoded,\n * because percent-encoding does not neutralize them: `.` and `..` are\n * RFC 3986 *unreserved*, so `encodeURIComponent` leaves them untouched\n * and the URL parser in `fetch` then resolves them away. Verified:\n * `deleteSecret(\"cloudflare/../openai\")` would have issued\n * `DELETE /api/v1/config/secrets/openai` — deleting a different secret —\n * and `deleteSecret(\"..\")` would have issued `DELETE /api/v1/config/`.\n * On a destructive, owner-only operation that is not a risk worth\n * carrying for a name shape the server cannot address anyway.\n *\n * The Python SDK has the same hole (`quote(\".\", safe=\"\") === \".\"`) and\n * wants the same guard; this is a divergence in the safe direction until\n * it gets one.\n *\n * @throws KaguraSecretError if `name` is empty or has an empty, `.`, or\n * `..` segment.\n */\n async deleteSecret(name: string): Promise<void> {\n const segments = name.split(\"/\");\n const offending = segments.find((s) => s === \"\" || s === \".\" || s === \"..\");\n if (offending !== undefined) {\n throw new KaguraSecretError(\n `refusing to delete secret ${JSON.stringify(name)}: a name may not be ` +\n \"empty or contain an empty, '.', or '..' path segment. Such a name \" +\n \"would resolve to a different URL than intended and delete the \" +\n \"wrong secret.\",\n );\n }\n const encoded = segments.map((segment) => encodeURIComponent(segment)).join(\"/\");\n await this.request(\"DELETE\", `${BASE}/${encoded}`);\n }\n\n /** Verify the tamper-evident audit chain (owner/admin). */\n async verifyAudit(): Promise<AuditVerifyResponse> {\n const response = await this.request(\"GET\", `${BASE}/audit/verify`);\n return this.json(response) as AuditVerifyResponse;\n }\n\n // -- high-level orchestration ------------------------------------------\n\n /**\n * Encrypt `plaintext` to `recipients` and store it in one call.\n *\n * Enforces the server's grant-consistency invariant client-side, before\n * the network: every recipient must be `active` and must carry a\n * fingerprint matching its own pubkey. `recipients_snapshot` and\n * `grant_pubkey_ids` are then derived 1:1 from the same list, so the two\n * sets agree by construction rather than by the caller's care.\n *\n * The fingerprint check is the one that matters for security: it is what\n * stops the client from encrypting to a pubkey the server has swapped\n * under a fingerprint the caller verified out of band.\n *\n * Requires the optional `age-encryption` package (see\n * {@link ./crypto.js | crypto}); every other method on this client works\n * without it.\n *\n * @throws KaguraSecretError on an empty recipient list, a non-active\n * recipient, or a pubkey/fingerprint mismatch.\n * @throws KaguraCryptoError if `age-encryption` is missing or encryption\n * fails.\n */\n async putSecretForRecipients(options: {\n name: string;\n plaintext: Uint8Array | string;\n recipients: PubkeyResponse[];\n }): Promise<SecretPutResponse> {\n const { name, recipients } = options;\n if (recipients.length === 0) {\n throw new KaguraSecretError(\"at least one recipient is required to put a secret\");\n }\n for (const r of recipients) {\n if (r.status !== \"active\") {\n throw new KaguraSecretError(\n `recipient ${r.pubkey} is not active (status=${JSON.stringify(r.status)}); ` +\n \"grants require an owner-approved (active) pubkey\",\n );\n }\n if (fingerprint(r.pubkey) !== r.fingerprint) {\n throw new KaguraSecretError(\n `pubkey/fingerprint mismatch for recipient ${r.id} — refusing to ` +\n \"encrypt to a pubkey whose advertised fingerprint is inconsistent\",\n );\n }\n }\n\n const plaintext =\n typeof options.plaintext === \"string\"\n ? new TextEncoder().encode(options.plaintext)\n : options.plaintext;\n const ciphertext = await encrypt(\n plaintext,\n recipients.map((r) => r.pubkey),\n );\n return this.putSecret({\n name,\n ciphertext,\n recipientsSnapshot: recipients.map((r) => r.fingerprint),\n grantPubkeyIds: recipients.map((r) => r.id),\n });\n }\n}\n"],"mappings":";;;AAQA,SAAS,SAAAA,cAAa;AACtB,SAAS,aAAAC,kBAAiB;AAC1B,SAAS,gBAAAC,qBAAoB;AAC7B,YAAY,cAAc;;;ACMnB,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;AAGjD,IAAM,sBAAN,cAAkC,YAAY;AAAC;AAG/C,IAAM,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,MAAG;AAAA,MAAS,CAACE,OAAM,WACvBF,SAAQE,UAAS,WAAW,OAAO,IAAI,OAAOC,WAAU,QAAQ,MAAM,KAAK,GAAG;AAAA,IAChF;AAAA,EACF,CAAC;AACL,CAAC;AAED,QAAQ,WAAW;","names":["spawn","constants","readFileSync","fs","path","sleep","stringOr","fs","os","path","platform","resolve","eq","inline","flag","code","path","fs","os","path","fs","path","list","YES","LIMIT","CONTEXT_ID","SUMMARY","IMPORTANCE","optionalFloat","MIN_WEIGHT","fs","DESCRIPTION","LIMIT","IMPORTANCE","fs","PROFILE","list","fs","path","API_KEY","CONTEXT_ID","PROFILE","resolve","path","path","code","createHash","path","jsonTypeName","path","safeDetail","createHash","events","readFileSync","resolve","spawn","code","constants"]}