kagura-memory 0.2.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +392 -162
- package/dist/cli.js +1294 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +426 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +595 -82
- package/dist/index.d.ts +595 -82
- package/dist/index.js +399 -12
- package/dist/index.js.map +1 -1
- package/package.json +66 -63
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/agentBootstrap.ts","../src/config.ts","../src/errors.ts","../src/auth/credentials.ts","../src/auth/deviceFlow.ts","../src/version.ts","../src/http.ts","../src/auth/filelock.ts","../src/auth/resolve.ts","../src/client.ts","../src/restBase.ts","../src/uuid.ts","../src/agentsClient.ts","../src/filesClient.ts","../src/auth/types.ts","../src/resourceClient.ts","../src/workspaceClient.ts"],"sourcesContent":["/** Kagura Memory SDK — memory management for Kagura Memory Cloud. */\n\nexport { KaguraClient, MIN_SERVER_VERSION } from \"./client.js\";\nexport type {\n AgentBindingScopeOptions,\n AgentEnforcementMode,\n AgentStatus,\n AgentWritePolicy,\n BindAgentContextOptions,\n CreateContextOptions,\n DeliveryMode,\n KaguraClientOptions,\n ListMemoriesOptions,\n ListTagsOptions,\n RecallOptions,\n RegisterAgentOptions,\n RememberOptions,\n SearchMode,\n SetupResourceOptions,\n SourceType,\n ToolResult,\n UpdateAgentBindingOptions,\n UpdateAgentOptions,\n UpdateContextOptions,\n UpdateMemoryOptions,\n UpdateSearchConfigOptions,\n} from \"./client.js\";\n\nexport { loadConfig } from \"./config.js\";\nexport type { KaguraConfig, LoadConfigOptions } from \"./config.js\";\n\nexport {\n KaguraAuthDeniedError,\n KaguraAuthError,\n KaguraAuthExpiredError,\n KaguraConnectionError,\n KaguraContextError,\n KaguraError,\n KaguraFetchError,\n KaguraIngestError,\n KaguraIntegrityError,\n KaguraLLMError,\n KaguraNotFoundError,\n KaguraQuotaError,\n KaguraRateLimitError,\n} from \"./errors.js\";\n\nexport { SDK_VERSION } from \"./version.js\";\n\nexport {\n DEFAULT_REST_BASE_URL,\n KaguraRestClient,\n} from \"./restBase.js\";\nexport type {\n FromMcpUrlOptions,\n HttpMethod,\n KaguraRestClientOptions,\n} from \"./restBase.js\";\n\nexport type { GetAgentBootstrapOptions } from \"./agentBootstrap.js\";\nexport { AgentsClient } from \"./agentsClient.js\";\n\nexport { FilesClient } from \"./filesClient.js\";\nexport type { FilesClientOptions, UploadOptions } from \"./filesClient.js\";\n\nexport {\n ResourceClient,\n SETUP_OAUTH_NOT_SUPPORTED_MSG,\n} from \"./resourceClient.js\";\nexport type {\n CreateTokenOptions,\n ListResourceEventsOptions,\n ListTokensOptions,\n ResourceEventInput,\n ResourceSetupOptions,\n UpdateTokenOptions,\n} from \"./resourceClient.js\";\n\nexport {\n VALID_ASSIGNABLE_ROLES,\n VALID_INVITE_EXPIRES,\n WorkspaceClient,\n} from \"./workspaceClient.js\";\nexport type {\n CreateInvitationOptions,\n ListInvitationsOptions,\n} from \"./workspaceClient.js\";\n\nexport { DEFAULT_MCP_URL, resolveAuth } from \"./auth/resolve.js\";\nexport type { ResolveAuthOptions } from \"./auth/resolve.js\";\nexport type {\n AuthProvider,\n AuthSource,\n OAuthAuthResult,\n ResolvedAuth,\n StaticAuthResult,\n StaticSource,\n} from \"./auth/types.js\";\n\nexport * from \"./models.js\";\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","/** 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","/** 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 * 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 { 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(): 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(() => this.refreshLocked(rejectedToken));\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(expectedStaleToken: string | null): 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 if (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);\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 ): Promise<void> {\n const token = await refreshAccessToken(base.server, {\n clientId: base.clientId,\n refreshToken: base.refreshToken,\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 scope: token.scope,\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 * 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.1.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).\nconst LOCALHOST_HTTP_RE = /^http:\\/\\/(?:localhost|127\\.0\\.0\\.1|\\[::1\\])(?::\\d+)?(?:[/?#]|$)/;\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 if (url.startsWith(\"http://\") && !LOCALHOST_HTTP_RE.test(url)) {\n throw new Error(\n `${label} must use HTTPS for security (got: ${url}). ` +\n \"HTTP is only allowed for localhost development.\",\n );\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","/**\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","/** 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 MemoryStatsResponse,\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 /** Structured details JSON, stored as-is. */\n details?: Record<string, unknown>;\n /** Open-ended context metadata JSON. */\n context?: Record<string, unknown>;\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\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 /** `\"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\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 * 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 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 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 * 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 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.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 * 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 client for the agent bootstrap surface (issue #3, server\n * v0.49.0+) — port of the Python SDK's agents_client.py bootstrap call.\n *\n * The `get_agent_bootstrap` MCP tool has a REST companion —\n * `POST /api/v1/agents/{agent_id}/bootstrap` (RFC-0002 P0-3, memory-cloud\n * #1276) — authenticated with `APIKeyOrSessionUser`, so it accepts\n * agent-bound member keys: a deployed agent can rehydrate its cognitive\n * state without opening an MCP session. POST-for-read follows the\n * server's `POST /api/v1/memory/pinned` precedent.\n *\n * Construction, credential resolution, lifecycle, and the base error\n * mapping live in {@link KaguraRestClient}; this module keeps only the\n * bootstrap wire call. The registry/binding CRUD is MCP-only in this SDK\n * (KaguraClient) — provisioning is an operator task that has an MCP\n * session available.\n */\n\nimport { buildBootstrapPayload } from \"./agentBootstrap.js\";\nimport type { GetAgentBootstrapOptions } from \"./agentBootstrap.js\";\nimport type { AgentBootstrapResponse } from \"./models.js\";\nimport { KaguraRestClient } from \"./restBase.js\";\nimport { parseUuid } from \"./uuid.js\";\n\n/**\n * REST API client for agent bootstrap (memory-cloud v0.49.0+).\n *\n * Use this surface when the caller holds an API key but no MCP session —\n * e.g. an agent-bound member key minted for a deployed agent. Against an\n * older server the route 404s.\n *\n * All methods may reject with:\n * - `KaguraAuthError` — authentication failed (401)\n * - `KaguraConnectionError` — invalid arguments (400) or any other\n * HTTP/connection error\n * - `KaguraNotFoundError` — agent or context not found (404). The 404 is\n * uniform (CWE-639) — nonexistent and not-yours are indistinguishable\n * by design, so a 404 does NOT prove the agent is absent.\n * - `KaguraQuotaError` — rate limit exceeded (429)\n */\nexport class AgentsClient extends KaguraRestClient {\n /**\n * Rehydrate an agent's cognitive state at session start.\n *\n * REST companion to `KaguraClient.getAgentBootstrap` — same options,\n * same composed envelope, same fail-soft component semantics (see that\n * method for the full contract).\n */\n async bootstrap(options: GetAgentBootstrapOptions): Promise<AgentBootstrapResponse> {\n let agentId: string;\n try {\n agentId = parseUuid(options.agentId);\n } catch {\n // Normalize instead of interpolating the raw input: a non-UUID\n // would otherwise reach the URL path and surface as a misleading\n // uniform 404 (or worse, a path traversal attempt).\n throw new Error(`agentId must be a UUID, got ${JSON.stringify(options.agentId)}`);\n }\n const resp = await this.request(\"POST\", `/api/v1/agents/${agentId}/bootstrap`, {\n json: buildBootstrapPayload(options),\n });\n return this.json(resp) as AgentBootstrapResponse;\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 * 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 workspace member & invitation management (#225) —\n * port of workspace_client.py.\n *\n * Owner-key operational tooling: memory-cloud v0.42.0 gates every endpoint\n * here at workspace-OWNER role for programmatic principals and rejects\n * OAuth Bearer tokens outright (\"Use a workspace-owner API key\"). The web\n * UI (session auth) keeps its own per-endpoint role semantics — this\n * client only ever sees the programmatic contract.\n *\n * Construction, credential resolution, lifecycle, and the base error\n * mapping live in {@link KaguraRestClient} (#229); this module keeps only\n * the workspace-specific wire contract: the owner-key 403 hint and the\n * detail-carrying 429 quota mapping.\n */\n\nimport { SOURCE_LABEL } from \"./auth/types.js\";\nimport { KaguraConnectionError, KaguraError, KaguraQuotaError } from \"./errors.js\";\nimport { extractDetail, retryAfterSeconds, sanitizeServerDetail } from \"./http.js\";\nimport type { MemberAPIKey, WorkspaceInvitation, WorkspaceMember } from \"./models.js\";\nimport { KaguraRestClient } from \"./restBase.js\";\nimport type { RequestContext, RestResponse } from \"./restBase.js\";\n\nexport const VALID_ASSIGNABLE_ROLES = [\"member\", \"admin\", \"viewer\"] as const;\n// \"owner\" is excluded: the server 422s programmatic role=owner on member\n// add/set-role (memory-cloud#1164 — \"use the ownership transfer flow\") and\n// rejects owner invitations for every principal (memory-cloud#1166).\n\nexport const VALID_INVITE_EXPIRES = [7, 30, 90, 365] as const;\n// Server-side preset list: any other value in the otherwise-valid 1-365\n// range still 400s at the service layer, so fail fast client-side.\n// Omitted = never expires.\n\nconst UNIFORM_403 = \"Insufficient permissions\";\n// The deliberately uniform authorization denial (CWE-639). Every other 403 on\n// this surface carries a purpose-built message (OAuth rejection, deployment\n// kill-switch, plan gate, self-role-change, key/workspace mismatch) that is\n// already actionable and must pass through untouched.\n\nconst UUID_HEX_RE = /^[0-9a-f]{32}$/i;\n\n/**\n * Return the canonical UUID string, rejecting non-UUIDs before the URL.\n *\n * Python's `uuid.UUID` tolerates non-canonical spellings (`{braces}`,\n * `urn:uuid:` prefix, dashless 32-hex, uppercase); interpolating the RAW\n * input would send those to the server and surface as a misleading uniform\n * 404 — normalize instead of just validating.\n */\nfunction normalizeWorkspaceId(workspaceId: string): string {\n const stripped = String(workspaceId)\n .replace(/^urn:/, \"\")\n .replace(/^uuid:/, \"\")\n .replace(/^[{}]+|[{}]+$/g, \"\")\n .replace(/-/g, \"\");\n if (!UUID_HEX_RE.test(stripped)) {\n throw new Error(`workspaceId must be a UUID, got ${JSON.stringify(workspaceId)}`);\n }\n const hex = stripped.toLowerCase();\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/**\n * Strictly require an integer — no float truncation, no string parse.\n *\n * Truncating `7.9` would silently target a DIFFERENT resource id on a\n * destructive endpoint (the TS signature says `number`, which admits\n * floats), so fail loudly instead.\n */\nfunction requireInt(value: number, label: string): number {\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n throw new Error(`${label} must be an integer, got ${JSON.stringify(value)}`);\n }\n return value;\n}\n\n/** Options for {@link WorkspaceClient.createInvitation}. */\nexport interface CreateInvitationOptions {\n /** `member` | `admin` | `viewer` (default: `\"member\"`). */\n role?: string;\n /**\n * Context grant — required (min 1) for member/viewer invitations,\n * ignored for admin. Sent on the wire as `allowed_context_ids`.\n */\n allowedContextIds?: string[];\n /**\n * One of 7/30/90/365 (sent as `expires_in_days`), or omit for a\n * never-expiring invitation.\n */\n expiresInDays?: number;\n}\n\n/** Options for {@link WorkspaceClient.listInvitations}. */\nexport interface ListInvitationsOptions {\n /** Include already-accepted invitations (default: false). */\n includeAccepted?: boolean;\n}\n\n/**\n * REST API client for workspace member / invitation management.\n *\n * Requires the workspace OWNER's API key when called programmatically\n * (memory-cloud v0.42.0+). OAuth profiles are rejected by the server on\n * this surface — resolve a static owner key (`KAGURA_API_KEY` env or\n * `.kagura.json`) instead.\n *\n * All methods may reject with:\n * - `KaguraAuthError` — authentication failed (401)\n * - `KaguraConnectionError` — access denied (403 — non-owner key, OAuth\n * token, or deployment kill-switch; the message says which) or any\n * other HTTP/connection error\n * - `KaguraNotFoundError` — workspace/member/invitation not found (404).\n * Also returned for a workspace-scoped key used against a different\n * workspace (uniform 404, memory-cloud #963) — a 404 here does NOT\n * prove the resource is absent.\n * - `KaguraQuotaError` — member quota or rate limit exceeded (429)\n */\nexport class WorkspaceClient extends KaguraRestClient {\n // -------------------------------------------------------------------\n // Members\n // -------------------------------------------------------------------\n\n /**\n * List workspace members (owner key required).\n *\n * Rows are ordered owner→viewer then by join date and include\n * `user_name`/`user_email` when the member has logged in.\n */\n async listMembers(workspaceId: string): Promise<WorkspaceMember[]> {\n const ws = normalizeWorkspaceId(workspaceId);\n const resp = await this.request(\"GET\", `/api/v1/workspaces/${ws}/members`);\n return this.expectList(resp) as unknown as WorkspaceMember[];\n }\n\n /**\n * Add an already-registered user to the workspace.\n *\n * The server does NOT validate that `userId` exists (v0.42.0) — a typo\n * creates a dangling membership row that lists with null name/email.\n * Prefer {@link createInvitation} for onboarding; use this only with a\n * user_id copied from a trusted source. Duplicate members are rejected\n * with 422.\n */\n async addMember(workspaceId: string, userId: string, role = \"member\"): Promise<WorkspaceMember> {\n const ws = normalizeWorkspaceId(workspaceId);\n this.validateRole(role);\n const resp = await this.request(\"POST\", `/api/v1/workspaces/${ws}/members`, {\n json: { user_id: userId, role },\n });\n return this.json(resp) as unknown as WorkspaceMember;\n }\n\n /** Change a member's role (member/admin/viewer only). */\n async updateMemberRole(\n workspaceId: string,\n userId: string,\n role: string,\n ): Promise<WorkspaceMember> {\n const ws = normalizeWorkspaceId(workspaceId);\n this.validateRole(role);\n const resp = await this.request(\n \"PUT\",\n `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}`,\n { json: { role } },\n );\n return this.json(resp) as unknown as WorkspaceMember;\n }\n\n /** Remove a member from the workspace (server returns 204). */\n async removeMember(workspaceId: string, userId: string): Promise<void> {\n const ws = normalizeWorkspaceId(workspaceId);\n await this.request(\"DELETE\", `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}`);\n }\n\n // -------------------------------------------------------------------\n // Invitations\n // -------------------------------------------------------------------\n\n /**\n * Invite a not-yet-registered user by email.\n *\n * The returned invitation carries `token`/`invitation_url` — the only\n * response that ever exposes them to programmatic callers; treat them\n * as join credentials.\n *\n * @param workspaceId Target workspace UUID.\n * @param email Invitee email (must match their Google account).\n * @param options Role, context grant, and expiry preset.\n */\n async createInvitation(\n workspaceId: string,\n email: string,\n options: CreateInvitationOptions = {},\n ): Promise<WorkspaceInvitation> {\n const ws = normalizeWorkspaceId(workspaceId);\n const role = options.role ?? \"member\";\n this.validateRole(role);\n const { allowedContextIds, expiresInDays } = options;\n if (\n (role === \"member\" || role === \"viewer\") &&\n (allowedContextIds === undefined || allowedContextIds.length === 0)\n ) {\n throw new Error(\n \"allowedContextIds is required (min 1) for member/viewer \" +\n \"invitations — the server rejects them without a context grant.\",\n );\n }\n if (\n expiresInDays !== undefined &&\n !(VALID_INVITE_EXPIRES as readonly number[]).includes(expiresInDays)\n ) {\n throw new Error(\n `expiresInDays must be one of ${VALID_INVITE_EXPIRES.join(\", \")} ` +\n \"or omitted (server-side preset list).\",\n );\n }\n const body: Record<string, unknown> = { email, role };\n if (allowedContextIds !== undefined) {\n body.allowed_context_ids = allowedContextIds;\n }\n if (expiresInDays !== undefined) {\n body.expires_in_days = expiresInDays;\n }\n const resp = await this.request(\"POST\", `/api/v1/workspaces/${ws}/invitations`, {\n json: body,\n });\n return this.json(resp) as unknown as WorkspaceInvitation;\n }\n\n /**\n * List invitations. `token`/`invitation_url` arrive as null for\n * programmatic callers (server-side token hygiene, #1164).\n */\n async listInvitations(\n workspaceId: string,\n options: ListInvitationsOptions = {},\n ): Promise<WorkspaceInvitation[]> {\n const ws = normalizeWorkspaceId(workspaceId);\n const resp = await this.request(\n \"GET\",\n `/api/v1/workspaces/${ws}/invitations`,\n options.includeAccepted ? { params: { include_accepted: \"true\" } } : {},\n );\n return this.expectList(resp) as unknown as WorkspaceInvitation[];\n }\n\n /** Revoke a pending invitation (server returns 200 `{\"success\": true}`). */\n async revokeInvitation(workspaceId: string, invitationId: number): Promise<void> {\n const ws = normalizeWorkspaceId(workspaceId);\n await this.request(\n \"DELETE\",\n `/api/v1/workspaces/${ws}/invitations/${requireInt(invitationId, \"invitationId\")}`,\n );\n }\n\n // -------------------------------------------------------------------\n // Member API keys (#201, memory-cloud#1165)\n // -------------------------------------------------------------------\n\n /**\n * Mint an API key for ANOTHER member (owner key required).\n *\n * Privilege-downgrade provisioning only: the server 403s self-targets\n * (\"An owner key cannot mint keys for itself\") and owner/admin targets\n * — mint for member/viewer service identities. `expiresDays` is\n * required by the server for owner-provisioned mints (never-expiring\n * CI keys are not allowed). The returned `plaintext_key` is shown\n * exactly once — owner-provisioned keys are force-hidden at creation,\n * so no later call returns it.\n */\n async mintMemberKey(\n workspaceId: string,\n userId: string,\n name: string,\n expiresDays: number,\n ): Promise<MemberAPIKey> {\n const ws = normalizeWorkspaceId(workspaceId);\n const days = requireInt(expiresDays, \"expiresDays\");\n if (days < 1 || days > 3650) {\n throw new Error(`expiresDays must be 1-3650, got ${JSON.stringify(days)}`);\n }\n const resp = await this.request(\n \"POST\",\n `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}/credentials/api-keys`,\n { json: { name, expires_days: days } },\n );\n const payload = this.json(resp);\n if (isMintShape(payload)) {\n return payload as unknown as MemberAPIKey;\n }\n // The key already exists server-side and is force-hidden — a shape\n // mismatch must not swallow the ONE chance to see the plaintext.\n const plaintext =\n typeof payload === \"object\" && payload !== null && !Array.isArray(payload)\n ? (payload as Record<string, unknown>).plaintext_key\n : undefined;\n if (typeof plaintext === \"string\" && plaintext) {\n throw new KaguraError(\n \"Server returned an unexpected mint response shape, but the \" +\n `key WAS created. Save the plaintext now: ${plaintext}`,\n );\n }\n throw new KaguraError(\n \"Server returned an unexpected mint response shape; the key may \" +\n \"have been created without displaying its plaintext — check \" +\n \"`kagura auth list-keys` and revoke/re-mint if present.\",\n );\n }\n\n /**\n * List a member's API keys — metadata only.\n *\n * The server wraps the rows in a `MemberCredentialsResponse` envelope\n * (`api_keys` + `target_user_role`) and always nulls `plaintext_key`\n * for programmatic callers.\n */\n async listMemberKeys(workspaceId: string, userId: string): Promise<MemberAPIKey[]> {\n const ws = normalizeWorkspaceId(workspaceId);\n const resp = await this.request(\n \"GET\",\n `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}/credentials`,\n );\n const payload = this.json(resp);\n const rows =\n typeof payload === \"object\" && payload !== null && !Array.isArray(payload)\n ? (payload as Record<string, unknown>).api_keys\n : undefined;\n if (!Array.isArray(rows)) {\n // Guard the FIELD, not just the envelope: api_keys=null would\n // produce garbage rows and api_keys={} is not iterable as rows\n // (Copilot review, PR #228 on the Python port).\n throw new KaguraConnectionError(\n \"Unexpected response shape from the member-credentials endpoint \" +\n \"(expected an object carrying an 'api_keys' array).\",\n );\n }\n return rows as unknown as MemberAPIKey[];\n }\n\n /**\n * Revoke a member's API key.\n *\n * Owner-provisioned revocations are SOFT server-side (`revoked_at`\n * set, row retained for forensics); success is 200 with a status body,\n * and an already-revoked key surfaces as a uniform 404.\n */\n async revokeMemberKey(workspaceId: string, userId: string, keyId: number): Promise<void> {\n const ws = normalizeWorkspaceId(workspaceId);\n await this.request(\n \"DELETE\",\n `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}` +\n `/credentials/api-keys/${requireInt(keyId, \"keyId\")}`,\n );\n }\n\n // -------------------------------------------------------------------\n // Internal helpers\n // -------------------------------------------------------------------\n\n private validateRole(role: string): void {\n if (!(VALID_ASSIGNABLE_ROLES as readonly string[]).includes(role)) {\n throw new Error(\n `role must be one of ${VALID_ASSIGNABLE_ROLES.join(\", \")}, got ` +\n `${JSON.stringify(role)}. Assigning 'owner' is not supported ` +\n \"programmatically — the server directs owner changes to the \" +\n \"ownership transfer flow.\",\n );\n }\n }\n\n /**\n * Build the 403 message, appending the owner-key hint only when useful.\n *\n * v0.42.0 sends purpose-built 403 messages on this surface (OAuth\n * rejection, deployment kill-switch, plan gate, self-role-change,\n * key/workspace mismatch) — those pass through untouched. Only the\n * deliberately uniform denial gets the owner-key hint, because that is\n * the one a non-owner static key actually hits.\n */\n private format403(serverDetail: string): string {\n const safeDetail = sanitizeServerDetail(serverDetail);\n if (safeDetail && safeDetail !== UNIFORM_403) {\n return safeDetail;\n }\n const parts = [\n \"Access denied (HTTP 403): workspace member/invitation/credential \" +\n \"management requires the workspace OWNER's API key when called \" +\n \"programmatically (OAuth tokens are not accepted).\",\n ];\n if (this.authSource !== null) {\n let hint = `credential source: ${SOURCE_LABEL[this.authSource]}`;\n if (this.workspaceIdHint) {\n hint += ` (workspace=${this.workspaceIdHint.slice(0, 8)}…)`;\n }\n parts.push(hint + \" — is this key the workspace owner's?\");\n }\n return parts.join(\" \");\n }\n\n // ---- KaguraRestClient hooks -----------------------------------------\n\n protected override error403(response: RestResponse, _context: RequestContext): KaguraError {\n return new KaguraConnectionError(this.format403(extractDetail(response.text)));\n }\n\n protected override error429(response: RestResponse): KaguraError {\n // Invite-create quota exhaustion (\"Member limit reached ...\") and\n // generic rate limiting both surface as 429 — keep the server\n // message, it names the cause and the fix.\n return new KaguraQuotaError(\n extractDetail(response.text) || \"Quota exceeded. Try again later.\",\n retryAfterSeconds(response.headers),\n );\n }\n}\n\n/**\n * Minimal structural check standing in for pydantic's required-field\n * validation on the mint response — the fields `MemberAPIKey` requires.\n * Everything else is trusted per the SDK's no-runtime-validation policy;\n * this one endpoint gets a guard because a mis-shaped 201 would otherwise\n * silently discard the only copy of the plaintext key.\n */\nfunction isMintShape(payload: unknown): payload is Record<string, unknown> {\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n return false;\n }\n const rec = payload as Record<string, unknown>;\n return (\n typeof rec.id === \"number\" && typeof rec.name === \"string\" && typeof rec.key_prefix === \"string\"\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoDO,SAAS,sBACd,SACyB;AACzB,QAAM,UAAmC,CAAC;AAC1C,MAAI,QAAQ,cAAc,QAAW;AACnC,YAAQ,aAAa,QAAQ;AAAA,EAC/B;AACA,MAAI,QAAQ,cA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AAO,sBAAsB,aAAa,KAAK,UAAU,CAAC;AAC9D,UAAI,KAAK,iBAAiB;AACxB,gBAAQ,eAAe,KAAK,gBAAgB,MAAM,GAAG,CAAC,CAAC;AAAA,MACzD;AACA,YAAM,KAAK,OAAO,4CAAuC;AAAA,IAC3D;AACA,WAAO,MAAM,KAAK,GAAG;AAAA,EACvB;AAAA;AAAA,EAImB,SAAS,UAAwB,UAAuC;AACzF,WAAO,IAAI,sBAAsB,KAAK,UAAU,cAAc,SAAS,IAAI,CAAC,CAAC;AAAA,EAC/E;AAAA,EAEmB,SAAS,UAAqC;AAI/D,WAAO,IAAI;AAAA,MACT,cAAc,SAAS,IAAI,KAAK;AAAA,MAChC,kBAAkB,SAAS,OAAO;AAAA,IACpC;AAAA,EACF;AACF;AASA,SAAS,YAAY,SAAsD;AACzE,MAAI,OAAO,YAAY,YAAY,YAAY,QAAQ,MAAM,QAAQ,OAAO,GAAG;AAC7E,WAAO;AAAA,EACT;AACA,QAAM,MAAM;AACZ,SACE,OAAO,IAAI,OAAO,YAAY,OAAO,IAAI,SAAS,YAAY,OAAO,IAAI,eAAe;AAE5F;","names":["fs","os","path","fs","path","import_promises","sleep","stringOr","stringOr","path","path","import_promises","path","safeDetail"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/agentBootstrap.ts","../src/config.ts","../src/errors.ts","../src/auth/credentials.ts","../src/auth/deviceFlow.ts","../src/version.ts","../src/http.ts","../src/auth/filelock.ts","../src/auth/resolve.ts","../src/client.ts","../src/restBase.ts","../src/uuid.ts","../src/agentsClient.ts","../src/filesClient.ts","../src/auth/types.ts","../src/resourceClient.ts","../src/workspaceClient.ts","../src/auth/login.ts","../src/auth/refresh.ts"],"sourcesContent":["/** Kagura Memory SDK — memory management for Kagura Memory Cloud. */\r\n\r\nexport { KaguraClient, MIN_SERVER_VERSION } from \"./client.js\";\r\nexport type {\r\n AgentBindingScopeOptions,\r\n AgentEnforcementMode,\r\n AgentStatus,\r\n AgentWritePolicy,\r\n BindAgentContextOptions,\r\n CreateContextOptions,\r\n DeliveryMode,\r\n KaguraClientOptions,\r\n ListMemoriesOptions,\r\n ListTagsOptions,\r\n RecallOptions,\r\n RegisterAgentOptions,\r\n RememberOptions,\r\n SearchMode,\r\n SetupResourceOptions,\r\n SourceType,\r\n ToolResult,\r\n UpdateAgentBindingOptions,\r\n UpdateAgentOptions,\r\n UpdateContextOptions,\r\n UpdateMemoryOptions,\r\n UpdateSearchConfigOptions,\r\n} from \"./client.js\";\r\n\r\nexport { loadConfig } from \"./config.js\";\r\nexport type { KaguraConfig, LoadConfigOptions } from \"./config.js\";\r\n\r\nexport {\r\n KaguraAuthDeniedError,\r\n KaguraAuthError,\r\n KaguraAuthExpiredError,\r\n KaguraConnectionError,\r\n KaguraContextError,\r\n KaguraError,\r\n KaguraFetchError,\r\n KaguraIngestError,\r\n KaguraIntegrityError,\r\n KaguraLLMError,\r\n KaguraNotFoundError,\r\n KaguraQuotaError,\r\n KaguraRateLimitError,\r\n} from \"./errors.js\";\r\n\r\nexport { SDK_VERSION } from \"./version.js\";\r\n\r\nexport {\r\n DEFAULT_REST_BASE_URL,\r\n KaguraRestClient,\r\n} from \"./restBase.js\";\r\nexport type {\r\n FromMcpUrlOptions,\r\n HttpMethod,\r\n KaguraRestClientOptions,\r\n} from \"./restBase.js\";\r\n\r\nexport type { GetAgentBootstrapOptions } from \"./agentBootstrap.js\";\r\nexport { AgentsClient } from \"./agentsClient.js\";\r\n\r\nexport { FilesClient } from \"./filesClient.js\";\r\nexport type { FilesClientOptions, UploadOptions } from \"./filesClient.js\";\r\n\r\nexport {\r\n ResourceClient,\r\n SETUP_OAUTH_NOT_SUPPORTED_MSG,\r\n} from \"./resourceClient.js\";\r\nexport type {\r\n CreateTokenOptions,\r\n ListResourceEventsOptions,\r\n ListTokensOptions,\r\n ResourceEventInput,\r\n ResourceSetupOptions,\r\n UpdateTokenOptions,\r\n} from \"./resourceClient.js\";\r\n\r\nexport {\r\n VALID_ASSIGNABLE_ROLES,\r\n VALID_INVITE_EXPIRES,\r\n WorkspaceClient,\r\n} from \"./workspaceClient.js\";\r\nexport type {\r\n CreateInvitationOptions,\r\n ListInvitationsOptions,\r\n} from \"./workspaceClient.js\";\r\n\r\nexport { DEFAULT_MCP_URL, resolveAuth } from \"./auth/resolve.js\";\r\nexport type { ResolveAuthOptions } from \"./auth/resolve.js\";\r\n\r\n// Interactive login (#9) — obtaining credentials, not just reading and\r\n// refreshing them. `login()` is the one-call path; the RFC 8628 primitives\r\n// and the credentials store are exported too so a host app can drive the\r\n// flow itself (e.g. its own polling UI) or manage profiles.\r\nexport { DEFAULT_SCOPE, READ_ONLY_SCOPE, login } from \"./auth/login.js\";\r\nexport type { LoginOptions } from \"./auth/login.js\";\r\n\r\nexport { refresh } from \"./auth/refresh.js\";\r\nexport type { RefreshOptions } from \"./auth/refresh.js\";\r\n\r\nexport {\r\n authorizeDevice,\r\n pollForToken,\r\n refreshAccessToken,\r\n revokeToken,\r\n DEFAULT_CLIENT_ID,\r\n DEVICE_FLOW_GRANT_TYPE,\r\n REFRESH_TOKEN_GRANT_TYPE,\r\n} from \"./auth/deviceFlow.js\";\r\nexport type {\r\n DeviceAuthorizationResponse,\r\n OAuthHttpOptions,\r\n PollForTokenOptions,\r\n RefreshAccessTokenOptions,\r\n TokenResponse,\r\n} from \"./auth/deviceFlow.js\";\r\n\r\nexport {\r\n defaultCredentialsPath,\r\n deleteCredentialsFile,\r\n deleteProfile,\r\n emptyCredentialsFile,\r\n getProfile,\r\n isExpired,\r\n loadCredentialsFile,\r\n removeProfile,\r\n saveCredentialsFile,\r\n setDefaultProfile,\r\n setProfile,\r\n updateProfile,\r\n // Rotation primitives (#16): KaguraOAuth is what actually refreshes and\r\n // persists under the cross-process lock, so a caller holding its own\r\n // provider — a proxy recovering from an upstream 401, say — needs it.\r\n KaguraOAuth,\r\n withRefreshed,\r\n REFRESH_SKEW_SEC,\r\n} from \"./auth/credentials.js\";\r\nexport type {\r\n CredentialsFile,\r\n OAuthCredentials,\r\n SharedCredentialsState,\r\n} from \"./auth/credentials.js\";\r\nexport type {\r\n AuthProvider,\r\n AuthSource,\r\n OAuthAuthResult,\r\n ResolvedAuth,\r\n StaticAuthResult,\r\n StaticSource,\r\n} from \"./auth/types.js\";\r\n\r\nexport * from \"./models.js\";\r\n","/**\r\n * Shared request contract for the agent bootstrap surfaces.\r\n *\r\n * `KaguraClient.getAgentBootstrap` (MCP tool arguments) and\r\n * `AgentsClient.bootstrap` (REST JSON body) carry the same seven optional\r\n * keys; this module keeps the two surfaces in lockstep without the REST\r\n * client importing the MCP module — the analogue of the Python SDK homing\r\n * `_bootstrap_payload` in models.py so agents_client.py never imports\r\n * client.py. `agentId` stays transport-specific (MCP argument vs URL\r\n * path).\r\n */\r\n\r\nimport type { AgentBootstrapComponentName } from \"./models.js\";\r\n\r\nexport interface GetAgentBootstrapOptions {\r\n /** Agent UUID from the registry (required). */\r\n agentId: string;\r\n /** Target context UUID. Omit to use the agent's default binding. */\r\n contextId?: string;\r\n /**\r\n * Opaque correlation id (max 128 chars, `[A-Za-z0-9._-]`); echoed in\r\n * the `correlation` block.\r\n */\r\n sessionId?: string;\r\n /**\r\n * Recall query (max 1024 chars). Supplying it enables the trusted-only\r\n * recall component; omit to skip recall — the server never fabricates\r\n * a query, so the component reports `status=\"skipped\"` even when\r\n * `include` names it.\r\n */\r\n query?: string;\r\n /** Number of recall results; forwarded to recall's `k` validation. */\r\n recallK?: number;\r\n /** Override for the pinned-set cap; clamped server-side to [1, 1000]. */\r\n pinnedCap?: number;\r\n /**\r\n * ISO upper bound for upcoming time memories (the lower bound is\r\n * always now).\r\n */\r\n upcomingUntil?: string;\r\n /**\r\n * Component selector — a subset of `\"pinned\"`, `\"recall\"`,\r\n * `\"upcoming\"`, `\"state\"`, `\"policy\"`. Omit for all components.\r\n */\r\n include?: AgentBootstrapComponentName[];\r\n}\r\n\r\n/**\r\n * Build the omit-when-undefined bootstrap payload shared by both\r\n * surfaces — the port of the Python SDK's `_bootstrap_payload`.\r\n * Internal — not part of the public API surface.\r\n */\r\nexport function buildBootstrapPayload(\r\n options: Omit<GetAgentBootstrapOptions, \"agentId\">,\r\n): Record<string, unknown> {\r\n const payload: Record<string, unknown> = {};\r\n if (options.contextId !== undefined) {\r\n payload.context_id = options.contextId;\r\n }\r\n if (options.sessionId !== undefined) {\r\n payload.session_id = options.sessionId;\r\n }\r\n if (options.query !== undefined) {\r\n payload.query = options.query;\r\n }\r\n if (options.recallK !== undefined) {\r\n payload.recall_k = options.recallK;\r\n }\r\n if (options.pinnedCap !== undefined) {\r\n payload.pinned_cap = options.pinnedCap;\r\n }\r\n if (options.upcomingUntil !== undefined) {\r\n payload.upcoming_until = options.upcomingUntil;\r\n }\r\n if (options.include !== undefined) {\r\n payload.include = options.include;\r\n }\r\n return payload;\r\n}\r\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","/** Custom errors for the Kagura Memory SDK (port of exceptions.py). */\n\n/**\n * Subset of the standard DOM/Node `ErrorOptions`. Declared locally so the\n * published `.d.ts` does not force consumers onto an ES2022 `lib` just to\n * reference our error constructors.\n */\nexport interface KaguraErrorOptions {\n cause?: unknown;\n}\n\n/**\n * Return `String(e)` when non-empty, otherwise the constructor name.\n *\n * Defensive fallback so an unmessaged error still produces a non-empty\n * diagnostic when interpolated into a user-facing error string.\n */\nexport function excMessage(e: unknown): string {\n if (e instanceof Error) {\n return e.message || e.constructor.name;\n }\n const s = String(e);\n return s || (typeof e === \"object\" && e !== null ? e.constructor.name : \"unknown error\");\n}\n\n/** Base error for the Kagura SDK. */\nexport class KaguraError extends Error {\n constructor(message: string, options?: KaguraErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\n/** Authentication failed. */\nexport class KaguraAuthError extends KaguraError {}\n\n/**\n * OAuth refresh token expired or invalid.\n *\n * Raised when an attempted refresh returns `invalid_grant` (or the server\n * otherwise indicates that the stored refresh token can no longer be used).\n * The caller must re-authenticate via `kagura auth login`.\n */\nexport class KaguraAuthExpiredError extends KaguraAuthError {\n readonly expiresAt: Date | null;\n\n constructor(message: string, expiresAt: Date | null = null, options?: KaguraErrorOptions) {\n super(message, options);\n this.expiresAt = expiresAt;\n }\n}\n\n/** User denied authorization at the device-flow consent screen. */\nexport class KaguraAuthDeniedError extends KaguraAuthError {}\n\n/** Connection to Kagura server failed. */\nexport class KaguraConnectionError extends KaguraError {}\n\n/** Requested resource not found (HTTP 404). */\nexport class KaguraNotFoundError extends KaguraError {}\n\n/** Rate limit exceeded. */\nexport class KaguraRateLimitError extends KaguraError {\n readonly retryAfter: number | null;\n\n constructor(message: string, retryAfter: number | null = null, options?: KaguraErrorOptions) {\n super(message, options);\n this.retryAfter = retryAfter;\n }\n}\n\n/** LLM call failed. */\nexport class KaguraLLMError extends KaguraError {}\n\n/** Context not found or invalid. */\nexport class KaguraContextError extends KaguraError {}\n\n/** Resource token quota exceeded (events per hour). */\nexport class KaguraQuotaError extends KaguraError {\n readonly retryAfter: number | null;\n\n constructor(message: string, retryAfter: number | null = null, options?: KaguraErrorOptions) {\n super(message, options);\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * Object store rejected an upload with HTTP 400.\n *\n * Raised for any HTTP 400 response from the object store on a presigned\n * PUT — most commonly R2 `BadDigest` (the body's sha256 did not match the\n * value bound into the presigned PUT URL), but also covers other 400\n * causes such as a malformed presigned URL or a Content-Length mismatch.\n */\nexport class KaguraIntegrityError extends KaguraError {}\n\n/**\n * URL or file fetch failed (SSRF guard, byte cap, redirect loop, etc.).\n *\n * The original URL/path is exposed via the `url` property so callers can\n * present it without re-parsing the message.\n */\nexport class KaguraFetchError extends KaguraError {\n readonly url: string | null;\n\n constructor(message: string, url: string | null = null, options?: KaguraErrorOptions) {\n super(message, options);\n this.url = url;\n }\n}\n\n/** File ingestion orchestration failed for a non-fetch reason. */\nexport class KaguraIngestError extends KaguraError {}\n","/**\r\n * Persistent OAuth credentials for the Kagura SDK (port of\r\n * auth/credentials.py).\r\n *\r\n * This module owns three responsibilities:\r\n *\r\n * 1. The `OAuthCredentials` / `CredentialsFile` shapes and their JSON\r\n * (de)serialization. The on-disk format at `~/.kagura/credentials.json`\r\n * is SHARED with the Python CLI — keys stay snake_case on disk\r\n * (`default_profile`, `profiles`, `access_token`, ...), timestamps are\r\n * Z-suffixed UTC ISO-8601.\r\n * 2. Atomic, mode-0600 read/write of the credentials file with a mode-0700\r\n * parent directory (permissions are best-effort where the platform,\r\n * e.g. Windows/NTFS, does not honor POSIX bits).\r\n * 3. A process-wide cache (`getSharedState`) so concurrent clients pointing\r\n * at the same credentials file share a single in-process mutex, ensuring\r\n * only one `/oauth/token/` refresh fires per cycle even when many client\r\n * instances run side by side.\r\n *\r\n * Multi-process coordination is handled in two layers: the in-process\r\n * `AsyncMutex` coalesces refreshes *within* a process, and the\r\n * cross-process lock in `filelock.ts` (acquired inside the refresh path)\r\n * re-reads the on-disk token after locking and skips the `/oauth/token/`\r\n * round-trip when another process already rotated it.\r\n */\r\n\r\nimport * as crypto from \"node:crypto\";\r\nimport * as fs from \"node:fs\";\r\nimport * as os from \"node:os\";\r\nimport * as path from \"node:path\";\r\n\r\nimport { KaguraAuthExpiredError } from \"../errors.js\";\r\nimport { refreshAccessToken } from \"./deviceFlow.js\";\r\nimport { withFileLock } from \"./filelock.js\";\r\nimport type { AuthProvider } from \"./types.js\";\r\n\r\n/**\r\n * Refresh `accessToken` when within this many seconds of `expiresAt`.\r\n *\r\n * Default of 5 minutes mirrors common OAuth2 client conventions and gives\r\n * enough headroom for a slow refresh round-trip.\r\n */\r\nexport const REFRESH_SKEW_SEC = 300;\r\n\r\nexport const CREDENTIALS_FILE_MODE = 0o600;\r\nexport const CREDENTIALS_DIR_MODE = 0o700;\r\n\r\n/**\r\n * Default location of the credentials file: `~/.kagura/credentials.json`.\r\n * Tests pass an explicit `home`/path instead of touching the real one.\r\n */\r\nexport function defaultCredentialsPath(home?: string): string {\r\n return path.join(home ?? os.homedir(), \".kagura\", \"credentials.json\");\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Data shapes\r\n// ---------------------------------------------------------------------------\r\n\r\n/** A single profile's OAuth2 credentials (camelCase in memory, snake_case on disk). */\r\nexport interface OAuthCredentials {\r\n server: string;\r\n mcpUrl: string;\r\n clientId: string;\r\n accessToken: string;\r\n refreshToken: string;\r\n tokenType: string;\r\n expiresAt: Date;\r\n scope: string;\r\n workspaceId: string;\r\n workspaceName: string;\r\n userEmail: string;\r\n issuedAt: Date;\r\n}\r\n\r\n/** True when `accessToken` is past `expiresAt - skewSeconds`. */\r\nexport function isExpired(creds: OAuthCredentials, skewSeconds = 0): boolean {\r\n return Date.now() >= creds.expiresAt.getTime() - skewSeconds * 1000;\r\n}\r\n\r\n/**\r\n * Return a copy of `creds` with the rotated token fields applied.\r\n *\r\n * `refreshToken` is rotated when the server returns a new one (RFC 6749\r\n * §10.4 recommended) — pass `null`/omit to preserve the stored one.\r\n * `scope` is updated when the server narrows or widens the grant.\r\n */\r\nexport function withRefreshed(\r\n creds: OAuthCredentials,\r\n fields: {\r\n accessToken: string;\r\n refreshToken?: string | null;\r\n expiresAt: Date;\r\n scope?: string | null;\r\n },\r\n): OAuthCredentials {\r\n return {\r\n ...creds,\r\n accessToken: fields.accessToken,\r\n refreshToken: fields.refreshToken ?? creds.refreshToken,\r\n expiresAt: fields.expiresAt,\r\n scope: fields.scope ?? creds.scope,\r\n };\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Datetime helpers (Z-suffixed UTC ISO-8601 for human readability)\r\n// ---------------------------------------------------------------------------\r\n\r\n/** Serialize a Date as `YYYY-MM-DDTHH:MM:SSZ` (UTC, seconds precision). */\r\nexport function isoUtc(date: Date): string {\r\n return `${date.toISOString().slice(0, 19)}Z`;\r\n}\r\n\r\n/**\r\n * Parse ISO-8601, accepting `...Z`, `...+00:00`, and naive suffixes.\r\n *\r\n * Normalizes a missing timezone to UTC so a user-edited / legacy\r\n * credentials file with naive timestamps doesn't get parsed as local time\r\n * (JavaScript's `Date` parses a bare `YYYY-MM-DDTHH:MM:SS` as local).\r\n */\r\nexport function parseIso(s: string): Date {\r\n const normalized = /(?:Z|[+-]\\d{2}:?\\d{2})$/.test(s) ? s : `${s}Z`;\r\n const date = new Date(normalized);\r\n if (Number.isNaN(date.getTime())) {\r\n throw new Error(`invalid ISO-8601 timestamp: ${s}`);\r\n }\r\n return date;\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// JSON (de)serialization — snake_case on disk, shared with the Python CLI\r\n// ---------------------------------------------------------------------------\r\n\r\nexport function credentialsToDict(creds: OAuthCredentials): Record<string, unknown> {\r\n return {\r\n server: creds.server,\r\n mcp_url: creds.mcpUrl,\r\n client_id: creds.clientId,\r\n access_token: creds.accessToken,\r\n refresh_token: creds.refreshToken,\r\n token_type: creds.tokenType,\r\n expires_at: isoUtc(creds.expiresAt),\r\n scope: creds.scope,\r\n workspace_id: creds.workspaceId,\r\n workspace_name: creds.workspaceName,\r\n user_email: creds.userEmail,\r\n issued_at: isoUtc(creds.issuedAt),\r\n };\r\n}\r\n\r\nfunction requireString(d: Record<string, unknown>, key: string): string {\r\n const value = d[key];\r\n if (typeof value !== \"string\") {\r\n throw new Error(`credentials profile missing required field '${key}'`);\r\n }\r\n return value;\r\n}\r\n\r\nfunction stringOr(value: unknown, fallback: string): string {\r\n return typeof value === \"string\" ? value : fallback;\r\n}\r\n\r\n/** @throws Error when required fields are missing or timestamps invalid. */\r\nexport function credentialsFromDict(d: Record<string, unknown>): OAuthCredentials {\r\n const issuedAtRaw = d.issued_at;\r\n return {\r\n server: requireString(d, \"server\"),\r\n mcpUrl: requireString(d, \"mcp_url\"),\r\n clientId: requireString(d, \"client_id\"),\r\n accessToken: requireString(d, \"access_token\"),\r\n refreshToken: requireString(d, \"refresh_token\"),\r\n tokenType: stringOr(d.token_type, \"Bearer\"),\r\n expiresAt: parseIso(requireString(d, \"expires_at\")),\r\n scope: stringOr(d.scope, \"\"),\r\n workspaceId: stringOr(d.workspace_id, \"\"),\r\n workspaceName: stringOr(d.workspace_name, \"\"),\r\n userEmail: stringOr(d.user_email, \"\"),\r\n issuedAt: typeof issuedAtRaw === \"string\" && issuedAtRaw ? parseIso(issuedAtRaw) : new Date(),\r\n };\r\n}\r\n\r\n/** Top-level wrapper for `~/.kagura/credentials.json`. */\r\nexport interface CredentialsFile {\r\n version: number;\r\n defaultProfile: string;\r\n profiles: Record<string, OAuthCredentials>;\r\n}\r\n\r\nexport function emptyCredentialsFile(): CredentialsFile {\r\n return { version: 1, defaultProfile: \"default\", profiles: {} };\r\n}\r\n\r\n/** Return the named profile, or the default, or `null` if missing. */\r\nexport function getProfile(\r\n cf: CredentialsFile,\r\n name?: string | null,\r\n): OAuthCredentials | null {\r\n const key = name || cf.defaultProfile;\r\n return cf.profiles[key] ?? null;\r\n}\r\n\r\n/** Insert or replace a profile. The first profile becomes default. */\r\nexport function setProfile(cf: CredentialsFile, name: string, creds: OAuthCredentials): void {\r\n cf.profiles[name] = creds;\r\n if (!(cf.defaultProfile in cf.profiles)) {\r\n cf.defaultProfile = name;\r\n }\r\n}\r\n\r\n/** Remove a profile in memory if present; repoints a deleted default. */\r\nexport function removeProfile(cf: CredentialsFile, name: string): void {\r\n delete cf.profiles[name];\r\n const next = Object.keys(cf.profiles)[0];\r\n if (cf.defaultProfile === name && next !== undefined) {\r\n cf.defaultProfile = next;\r\n }\r\n}\r\n\r\nexport function credentialsFileToDict(cf: CredentialsFile): Record<string, unknown> {\r\n const profiles: Record<string, unknown> = {};\r\n for (const [name, creds] of Object.entries(cf.profiles)) {\r\n profiles[name] = credentialsToDict(creds);\r\n }\r\n return {\r\n version: cf.version,\r\n default_profile: cf.defaultProfile,\r\n profiles,\r\n };\r\n}\r\n\r\n/** @throws Error when any profile is malformed (caller treats file as empty). */\r\nexport function credentialsFileFromDict(d: Record<string, unknown>): CredentialsFile {\r\n const profilesRaw = d.profiles;\r\n const profiles: Record<string, OAuthCredentials> = {};\r\n if (typeof profilesRaw === \"object\" && profilesRaw !== null && !Array.isArray(profilesRaw)) {\r\n for (const [name, p] of Object.entries(profilesRaw)) {\r\n if (typeof p !== \"object\" || p === null || Array.isArray(p)) {\r\n throw new Error(`credentials profile '${name}' is not an object`);\r\n }\r\n profiles[name] = credentialsFromDict(p as Record<string, unknown>);\r\n }\r\n }\r\n return {\r\n version: typeof d.version === \"number\" ? d.version : 1,\r\n defaultProfile: stringOr(d.default_profile, \"default\"),\r\n profiles,\r\n };\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Filesystem IO\r\n// ---------------------------------------------------------------------------\r\n\r\n/** Force the directory to mode 0700 (best-effort; no-op where unsupported). */\r\nfunction enforceDirPerms(directory: string): void {\r\n try {\r\n const mode = fs.statSync(directory).mode & 0o777;\r\n if (mode !== CREDENTIALS_DIR_MODE) {\r\n fs.chmodSync(directory, CREDENTIALS_DIR_MODE);\r\n }\r\n } catch {\r\n // Best-effort: a directory we can't chmod is the user's problem, not\r\n // ours to abort over. Reads/writes will fail downstream with a clearer\r\n // error if perms genuinely block access.\r\n }\r\n}\r\n\r\n/** Force the credentials file to mode 0600 (defense in depth, best-effort). */\r\nfunction enforceFilePerms(filePath: string): void {\r\n try {\r\n const mode = fs.statSync(filePath).mode & 0o777;\r\n if (mode !== CREDENTIALS_FILE_MODE) {\r\n fs.chmodSync(filePath, CREDENTIALS_FILE_MODE);\r\n }\r\n } catch {\r\n // Best-effort — see enforceDirPerms.\r\n }\r\n}\r\n\r\n/**\r\n * Write `data` to `filePath` atomically.\r\n *\r\n * Steps: exclusive-create temp file in the same directory → write JSON →\r\n * fsync → chmod → rename over the target. A kill between any two steps\r\n * either leaves the original file untouched or replaces it cleanly.\r\n */\r\nfunction atomicWriteJson(\r\n filePath: string,\r\n data: unknown,\r\n mode: number = CREDENTIALS_FILE_MODE,\r\n): void {\r\n const dir = path.dirname(filePath);\r\n fs.mkdirSync(dir, { recursive: true });\r\n enforceDirPerms(dir);\r\n\r\n const tmp = path.join(\r\n dir,\r\n `.${path.basename(filePath)}.${crypto.randomBytes(6).toString(\"hex\")}.tmp`,\r\n );\r\n let fd: number | null = null;\r\n try {\r\n fd = fs.openSync(tmp, \"wx\", 0o600);\r\n fs.writeSync(fd, `${JSON.stringify(data, null, 2)}\\n`);\r\n fs.fsyncSync(fd);\r\n fs.closeSync(fd);\r\n fd = null;\r\n fs.chmodSync(tmp, mode);\r\n fs.renameSync(tmp, filePath);\r\n // fsync the parent directory so the rename itself is durable on crash /\r\n // power-loss. Best-effort: Windows and some filesystems don't support\r\n // fsync on a directory descriptor; the atomic rename already happened,\r\n // so the worst case is losing the most recent write, never file\r\n // integrity.\r\n try {\r\n const dirFd = fs.openSync(dir, \"r\");\r\n try {\r\n fs.fsyncSync(dirFd);\r\n } finally {\r\n fs.closeSync(dirFd);\r\n }\r\n } catch {\r\n // See comment above.\r\n }\r\n } catch (e) {\r\n if (fd !== null) {\r\n try {\r\n fs.closeSync(fd);\r\n } catch {\r\n // fd already closed / invalid — nothing more to release.\r\n }\r\n }\r\n fs.rmSync(tmp, { force: true });\r\n throw e;\r\n }\r\n}\r\n\r\nfunction resolvePath(p?: string): string {\r\n return p ?? defaultCredentialsPath();\r\n}\r\n\r\n/**\r\n * Read and parse the credentials file.\r\n *\r\n * Returns an empty `CredentialsFile` when the file is missing, unreadable,\r\n * or malformed — the caller can distinguish \"no profile\" via\r\n * `getProfile(cf) === null`. On a present file, parent directory and file\r\n * permissions are coerced to 0700/0600 (best-effort).\r\n */\r\nexport function loadCredentialsFile(credentialsPath?: string): CredentialsFile {\r\n const p = resolvePath(credentialsPath);\r\n if (!fs.existsSync(p)) {\r\n return emptyCredentialsFile();\r\n }\r\n\r\n enforceDirPerms(path.dirname(p));\r\n enforceFilePerms(p);\r\n\r\n let data: unknown;\r\n try {\r\n data = JSON.parse(fs.readFileSync(p, \"utf-8\"));\r\n } catch {\r\n return emptyCredentialsFile();\r\n }\r\n if (typeof data !== \"object\" || data === null || Array.isArray(data)) {\r\n return emptyCredentialsFile();\r\n }\r\n try {\r\n return credentialsFileFromDict(data as Record<string, unknown>);\r\n } catch {\r\n // Corrupt or partial file — treat as empty rather than crashing.\r\n return emptyCredentialsFile();\r\n }\r\n}\r\n\r\n/** Atomically persist a `CredentialsFile` to disk. */\r\nexport function saveCredentialsFile(cf: CredentialsFile, credentialsPath?: string): void {\r\n atomicWriteJson(resolvePath(credentialsPath), credentialsFileToDict(cf), CREDENTIALS_FILE_MODE);\r\n}\r\n\r\n/**\r\n * Load, mutate one profile, and atomically save back.\r\n *\r\n * The read-modify-write is wrapped in the cross-process lock from\r\n * `filelock.ts` so concurrent writers in *different* processes cannot lose\r\n * an update. The lock is on a sibling `credentials.json.lock`, not the\r\n * file itself, so it never races the atomic rename in\r\n * `saveCredentialsFile`.\r\n */\r\nexport async function updateProfile(\r\n profileName: string,\r\n creds: OAuthCredentials,\r\n credentialsPath?: string,\r\n): Promise<void> {\r\n const p = resolvePath(credentialsPath);\r\n await withFileLock(p, () => {\r\n const cf = loadCredentialsFile(p);\r\n setProfile(cf, profileName, creds);\r\n saveCredentialsFile(cf, p);\r\n });\r\n}\r\n\r\n/**\r\n * Set `default_profile` to an existing profile (backs `kagura auth use`).\r\n *\r\n * Unlike `setProfile`'s implicit first-wins promotion, this is a\r\n * *deliberate* default selection, wrapped in the same cross-process lock as\r\n * `updateProfile` so a concurrent refresh/login cannot clobber it.\r\n *\r\n * @throws Error if `profileName` is not an existing profile — selecting a\r\n * non-existent default would silently break resolution. (Python raises\r\n * `KeyError` here; a plain `Error` is the TS equivalent.)\r\n */\r\nexport async function setDefaultProfile(\r\n profileName: string,\r\n credentialsPath?: string,\r\n): Promise<void> {\r\n const p = resolvePath(credentialsPath);\r\n await withFileLock(p, () => {\r\n const cf = loadCredentialsFile(p);\r\n if (!(profileName in cf.profiles)) {\r\n throw new Error(`profile '${profileName}' not found in credentials file`);\r\n }\r\n cf.defaultProfile = profileName;\r\n saveCredentialsFile(cf, p);\r\n });\r\n}\r\n\r\n/**\r\n * Remove a profile and save. No-op if the profile is absent.\r\n *\r\n * The read-modify-write is wrapped in the cross-process lock so a logout\r\n * (delete) racing a concurrent token refresh (update) in a sibling process\r\n * cannot clobber a freshly written token. The absent-profile early return\r\n * runs *inside* the lock so the membership check and the save observe one\r\n * consistent snapshot (no TOCTOU).\r\n */\r\nexport async function deleteProfile(\r\n profileName: string,\r\n credentialsPath?: string,\r\n): Promise<void> {\r\n const p = resolvePath(credentialsPath);\r\n await withFileLock(p, () => {\r\n const cf = loadCredentialsFile(p);\r\n if (!(profileName in cf.profiles)) {\r\n return;\r\n }\r\n removeProfile(cf, profileName);\r\n saveCredentialsFile(cf, p);\r\n });\r\n}\r\n\r\n/**\r\n * Remove the entire credentials file (`kagura auth logout --all`).\r\n *\r\n * Missing file is treated as success — logout is idempotent.\r\n */\r\nexport function deleteCredentialsFile(credentialsPath?: string): void {\r\n fs.rmSync(resolvePath(credentialsPath), { force: true });\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Shared state cache (in-process single-flight)\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Minimal promise-chaining mutex — the `asyncio.Lock` equivalent.\r\n *\r\n * `runExclusive` calls are serialized in arrival order; a rejection inside\r\n * one critical section does not poison the chain for later callers.\r\n */\r\nexport class AsyncMutex {\r\n private tail: Promise<unknown> = Promise.resolve();\r\n\r\n runExclusive<T>(fn: () => T | Promise<T>): Promise<T> {\r\n const run = this.tail.then(() => fn());\r\n this.tail = run.catch(() => undefined);\r\n return run;\r\n }\r\n}\r\n\r\n/**\r\n * Mutable per-(path, profile) state shared across clients.\r\n *\r\n * The `mutex` is shared across **all profiles in the same file** — not\r\n * per-(path, profile) — so two profiles refreshing concurrently can't both\r\n * read-modify-write the file and clobber each other's update.\r\n */\r\nexport interface SharedCredentialsState {\r\n credentials: OAuthCredentials;\r\n profileName: string;\r\n /** Resolved absolute path of the credentials file. */\r\n path: string;\r\n mutex: AsyncMutex;\r\n}\r\n\r\nconst stateCache = new Map<string, SharedCredentialsState>();\r\n// One mutex per credentials file path, shared across profiles in the same\r\n// file so concurrent refreshes serialize at the file level.\r\nconst fileMutexes = new Map<string, AsyncMutex>();\r\n\r\nfunction getFileMutex(p: string): AsyncMutex {\r\n let mutex = fileMutexes.get(p);\r\n if (mutex === undefined) {\r\n mutex = new AsyncMutex();\r\n fileMutexes.set(p, mutex);\r\n }\r\n return mutex;\r\n}\r\n\r\n/**\r\n * Return the shared state for `(path, profile)`, loading lazily.\r\n *\r\n * Returns `null` if the credentials file is missing or has no matching\r\n * profile — the caller falls back to other credential sources (static API\r\n * key, `.kagura.json`, etc.) in that case.\r\n *\r\n * Concurrent clients that resolve to the same `(path, profile)` pair get\r\n * the same state object, which means they share a single mutex and any\r\n * refresh fired by one of them benefits all of them.\r\n */\r\nexport function getSharedState(\r\n credentialsPath?: string,\r\n profile?: string | null,\r\n): SharedCredentialsState | null {\r\n // Normalize the path once so the cache key and the persisted state path\r\n // stay consistent — a relative path could otherwise cause the cache\r\n // lookup and the refresh-time write to target different files.\r\n const p = path.resolve(resolvePath(credentialsPath));\r\n const cf = loadCredentialsFile(p);\r\n const creds = getProfile(cf, profile);\r\n if (creds === null) {\r\n return null;\r\n }\r\n\r\n const profileName = profile || cf.defaultProfile;\r\n // JSON-encode the pair so a path containing spaces can never collide\r\n // with another (path, profile) combination.\r\n const key = JSON.stringify([p, profileName]);\r\n let cached = stateCache.get(key);\r\n if (cached === undefined) {\r\n cached = {\r\n credentials: creds,\r\n profileName,\r\n path: p,\r\n mutex: getFileMutex(p),\r\n };\r\n stateCache.set(key, cached);\r\n } else {\r\n // Refresh in-memory creds from disk so a recent CLI login is visible\r\n // to clients already constructed in this process.\r\n cached.credentials = creds;\r\n }\r\n return cached;\r\n}\r\n\r\n/** Clear the module-level cache. Tests call this between cases. */\r\nexport function resetStateCache(): void {\r\n stateCache.clear();\r\n fileMutexes.clear();\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// KaguraOAuth — AuthProvider with single-flight refresh\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * `AuthProvider` that supplies the current access token as a Bearer header.\r\n *\r\n * Holds a reference to a shared `SharedCredentialsState`, so concurrent\r\n * client instances pointing at the same credentials file all coalesce\r\n * refresh calls through a single in-process mutex. When the access token\r\n * is within `REFRESH_SKEW_SEC` of expiry the mutex is acquired, the\r\n * refresh runs once, and every other in-flight `getAuthHeader` call waits\r\n * and then sees the rotated token.\r\n *\r\n * (The Python SDK expresses this as an `httpx.Auth` subclass; with `fetch`\r\n * there is no request-hook layer, so clients ask for a fresh header value\r\n * before each request instead.)\r\n */\r\nexport class KaguraOAuth implements AuthProvider {\r\n private readonly state: SharedCredentialsState;\r\n private readonly fetchImpl: typeof globalThis.fetch | undefined;\r\n\r\n constructor(\r\n state: SharedCredentialsState,\r\n options: { fetch?: typeof globalThis.fetch } = {},\r\n ) {\r\n this.state = state;\r\n this.fetchImpl = options.fetch;\r\n }\r\n\r\n /**\r\n * Return `Bearer <access_token>`, refreshing first when the token is\r\n * within the skew window.\r\n */\r\n async getAuthHeader(): Promise<string> {\r\n await this.maybeRefresh();\r\n return `Bearer ${this.state.credentials.accessToken}`;\r\n }\r\n\r\n /**\r\n * Refresh the access token if it's within the skew window.\r\n *\r\n * The mutex is held across the entire read-check-refresh-persist\r\n * sequence so a second caller waiting on it will find the token already\r\n * rotated when it acquires.\r\n */\r\n private async maybeRefresh(): Promise<void> {\r\n await this.state.mutex.runExclusive(async () => {\r\n if (!isExpired(this.state.credentials, REFRESH_SKEW_SEC)) {\r\n return;\r\n }\r\n await this.refreshLocked(null);\r\n });\r\n }\r\n\r\n /**\r\n * Unconditionally refresh the access token, ignoring the skew window.\r\n *\r\n * Used on an upstream 401: the token was rejected server-side (rotated /\r\n * revoked out-of-band) even though it is not yet within the skew window.\r\n * The same in-process mutex serializes this with skew-driven refreshes.\r\n * Cross-process dedup is handled in `refreshLocked` via the\r\n * rejected-token identity check.\r\n */\r\n async forceRefresh(options: { scope?: string } = {}): Promise<void> {\r\n // Capture the rejected token BEFORE the in-process mutex: if a peer\r\n // already rotated it while we waited, we must still compare against\r\n // the token that actually got the 401, otherwise the rotated token\r\n // would compare equal to disk and force a redundant refresh.\r\n const rejectedToken = this.state.credentials.accessToken;\r\n await this.state.mutex.runExclusive(() =>\r\n this.refreshLocked(rejectedToken, options.scope),\r\n );\r\n }\r\n\r\n /**\r\n * Refresh `/oauth/token/` once across all processes. Caller holds the\r\n * in-process mutex.\r\n *\r\n * After acquiring the cross-process file lock, re-read the credentials\r\n * from disk and **skip the network call when another process already\r\n * rotated the token** — \"skip\" means \"adopt the on-disk result\", never\r\n * \"leave the stale in-memory token in place\".\r\n *\r\n * `expectedStaleToken` governs the \"already rotated?\" predicate:\r\n * `null` (skew path) → skip when the on-disk token is no longer within\r\n * the skew window. A token string (401 path) → skip only when the\r\n * on-disk token *differs* from the rejected one (a 401 is independent of\r\n * `expiresAt`).\r\n */\r\n private async refreshLocked(\r\n expectedStaleToken: string | null,\r\n scope?: string,\r\n ): Promise<void> {\r\n const credPath = this.state.path;\r\n const profileName = this.state.profileName;\r\n await withFileLock(credPath, async () => {\r\n const disk = getProfile(loadCredentialsFile(credPath), profileName);\r\n // A scope change must never adopt a peer's rotation: that token was\r\n // issued for the *old* scope, so treating it as \"already done\" would\r\n // silently drop the change the caller asked for.\r\n if (scope === undefined && disk !== null && this.alreadyRotated(disk, expectedStaleToken)) {\r\n this.state.credentials = disk;\r\n return;\r\n }\r\n const base = disk ?? this.state.credentials;\r\n await this.networkRefreshAndSave(base, credPath, profileName, scope);\r\n });\r\n }\r\n\r\n /** Whether `disk` shows another process already produced a usable token. */\r\n private alreadyRotated(disk: OAuthCredentials, expectedStaleToken: string | null): boolean {\r\n if (expectedStaleToken === null) {\r\n // Skew path: a token outside the skew window is fresh enough.\r\n return !isExpired(disk, REFRESH_SKEW_SEC);\r\n }\r\n // 401 path: a different token means someone rotated; an identical token\r\n // means the rejected token is still current and we must refresh.\r\n return disk.accessToken !== expectedStaleToken;\r\n }\r\n\r\n /** Hit `/oauth/token/` from `base` and persist. Caller holds both locks. */\r\n private async networkRefreshAndSave(\r\n base: OAuthCredentials,\r\n credPath: string,\r\n profileName: string,\r\n scope?: string,\r\n ): Promise<void> {\r\n // A profile stored without a refresh token cannot be refreshed. Going\r\n // to the network first only earns an `invalid_grant`, whose message\r\n // (\"refresh token is no longer valid\") describes a token that never\r\n // existed — the actual cause is that the grant never carried offline\r\n // access. Fail here instead, naming that.\r\n if (!base.refreshToken) {\r\n throw new KaguraAuthExpiredError(\r\n \"This profile was stored without a refresh token, so it cannot be \" +\r\n \"refreshed — log in again to get one.\\n\" +\r\n \" Run: kagura auth login (or `npx kagura-memory auth login`)\",\r\n base.expiresAt,\r\n );\r\n }\r\n\r\n const token = await refreshAccessToken(base.server, {\r\n clientId: base.clientId,\r\n refreshToken: base.refreshToken,\r\n ...(scope !== undefined ? { scope } : {}),\r\n ...(this.fetchImpl ? { fetch: this.fetchImpl } : {}),\r\n });\r\n // Pass `null` when the server omits `refresh_token` so the stored token\r\n // is preserved: `TokenResponse.refreshToken` defaults to \"\" when\r\n // absent, and overwriting a valid stored token with an empty one would\r\n // break every subsequent refresh.\r\n this.state.credentials = withRefreshed(base, {\r\n accessToken: token.accessToken,\r\n refreshToken: token.refreshToken || null,\r\n expiresAt: token.expiresAt,\r\n // `||` not `??`: TokenResponse.scope defaults to \"\" when the server\r\n // omits it, and withRefreshed's `?? creds.scope` only catches\r\n // null/undefined — so an omitted scope used to blank the stored one.\r\n scope: token.scope || null,\r\n });\r\n // We already hold the cross-process lock; write directly rather than\r\n // via updateProfile (which would re-acquire the same lock and\r\n // deadlock). Re-load → set → save still preserves every other profile\r\n // in the file.\r\n const cf = loadCredentialsFile(credPath);\r\n setProfile(cf, profileName, this.state.credentials);\r\n saveCredentialsFile(cf, credPath);\r\n }\r\n}\r\n","/**\n * OAuth2 RFC 8628 device authorization grant — stateless async helpers\n * (port of auth/device_flow.py).\n *\n * Pure-function API: every entry point takes the server base URL plus the\n * relevant parameters and returns a plain object. No CLI, no terminal IO,\n * no global state.\n *\n * The Python SDK constructs a dedicated unauthenticated `httpx.AsyncClient`\n * so the SDK's `Authorization: Bearer` header cannot leak into `/oauth/*`\n * requests (device-flow uses `client_id` body-parameter authentication, RFC\n * 8628 §3.1 `token_endpoint_auth_method='none'`). With `fetch` there is no\n * client object; the same isolation holds because each request here sets\n * its own headers and never an `Authorization` header. The `fetch`\n * implementation is injectable on every function so tests can stub HTTP.\n */\n\nimport { setTimeout as sleepMs } from \"node:timers/promises\";\n\nimport {\n KaguraAuthDeniedError,\n KaguraAuthError,\n KaguraAuthExpiredError,\n KaguraConnectionError,\n excMessage,\n} from \"../errors.js\";\nimport { extractDetail } from \"../http.js\";\nimport { SDK_VERSION } from \"../version.js\";\n\n// OAuth2 endpoint paths under {server}.\n// The path prefix is /api/v1/oauth/ (NOT /oauth2/) per memory-cloud's\n// actual mount point; the token endpoint requires the trailing slash.\nconst PATH_DEVICE_AUTHORIZE = \"/api/v1/oauth/device/authorize\";\nconst PATH_TOKEN = \"/api/v1/oauth/token/\";\nconst PATH_REVOKE = \"/api/v1/oauth/revoke\";\n\n// RFC 8628 §3.5 — \"slow_down\" requires the client to add 5 seconds.\nconst SLOW_DOWN_INCREMENT_SEC = 5;\n\n/** The pre-registered public client ID seeded by memory-cloud #624. */\nexport const DEFAULT_CLIENT_ID = \"kagura-cli\";\n\nexport const DEVICE_FLOW_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:device_code\";\nexport const REFRESH_TOKEN_GRANT_TYPE = \"refresh_token\";\n\n/** RFC 8628 §3.2 device authorization response. */\nexport interface DeviceAuthorizationResponse {\n deviceCode: string;\n userCode: string;\n verificationUri: string;\n verificationUriComplete: string;\n expiresIn: number;\n /** Polling interval in seconds. */\n interval: number;\n /** = now + expiresIn. */\n expiresAt: Date;\n}\n\n/**\n * RFC 8628 §3.5 / RFC 6749 §5.1 successful token response.\n *\n * `expiresAt` is computed once at receipt time so a paused or suspended\n * laptop never sees a negative TTL after wake.\n */\nexport interface TokenResponse {\n accessToken: string;\n refreshToken: string;\n tokenType: string;\n expiresAt: Date;\n scope: string;\n userEmail: string;\n workspaceId: string;\n workspaceName: string;\n}\n\n/** Common HTTP knobs: injectable `fetch` so tests can stub the transport. */\nexport interface OAuthHttpOptions {\n fetch?: typeof globalThis.fetch;\n}\n\nfunction userAgent(): string {\n return `kagura-memory-sdk/${SDK_VERSION}`;\n}\n\nfunction tokenUrl(server: string): string {\n return `${server.replace(/\\/+$/, \"\")}${PATH_TOKEN}`;\n}\n\n/** Coerce an unknown JSON value to a whole number, or `null`. */\nfunction toInt(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return Math.trunc(value);\n }\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const n = Number(value);\n return Number.isFinite(n) ? Math.trunc(n) : null;\n }\n return null;\n}\n\nfunction stringOr(value: unknown, fallback: string): string {\n return typeof value === \"string\" ? value : fallback;\n}\n\n/**\n * Parse a 200 response body as a JSON object.\n *\n * Converts malformed / non-object success bodies into a `KaguraAuthError`\n * with HTTP status + truncated body, so a server that wedges and returns\n * HTML / a JSON array / a scalar doesn't surface as an unhelpful\n * `SyntaxError`.\n */\nfunction safeJsonObject(\n bodyText: string,\n status: number,\n endpoint: string,\n): Record<string, unknown> {\n let body: unknown;\n try {\n body = JSON.parse(bodyText);\n } catch (e) {\n const detail = bodyText.slice(0, 200);\n throw new KaguraAuthError(\n `${endpoint} returned HTTP ${status} but body is not JSON: ${excMessage(e)}. ` +\n `Body: ${detail}`,\n { cause: e },\n );\n }\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n throw new KaguraAuthError(\n `${endpoint} returned HTTP ${status} but body is not a JSON object ` +\n `(got ${Array.isArray(body) ? \"array\" : typeof body})`,\n );\n }\n return body as Record<string, unknown>;\n}\n\n/** Parse a response body as a JSON object, or `{}` if unparseable. */\nfunction safeJson(bodyText: string): Record<string, unknown> {\n let body: unknown;\n try {\n body = JSON.parse(bodyText);\n } catch {\n return {};\n }\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return {};\n }\n return body as Record<string, unknown>;\n}\n\n/**\n * Build a `TokenResponse` from a 200 `/oauth/token/` body.\n *\n * `expiresAt` is computed from `expires_in` at receipt time so laptop sleep\n * / clock skew won't yield a negative TTL after wake. Missing or invalid\n * required fields surface as `KaguraAuthError`.\n */\nfunction tokenResponseFromBody(bodyText: string, status: number): TokenResponse {\n const body = safeJsonObject(bodyText, status, \"Token endpoint\");\n const accessToken = body.access_token;\n const expiresIn = toInt(body.expires_in ?? 0);\n if (typeof accessToken !== \"string\" || expiresIn === null) {\n throw new KaguraAuthError(\n `Token endpoint returned HTTP ${status} but body is missing required fields. ` +\n `Body keys: ${Object.keys(body).sort().join(\", \")}`,\n );\n }\n return {\n accessToken,\n refreshToken: stringOr(body.refresh_token, \"\"),\n tokenType: stringOr(body.token_type, \"Bearer\"),\n expiresAt: new Date(Date.now() + expiresIn * 1000),\n scope: stringOr(body.scope, \"\"),\n userEmail: stringOr(body.user_email, \"\"),\n workspaceId: stringOr(body.workspace_id, \"\"),\n workspaceName: stringOr(body.workspace_name, \"\"),\n };\n}\n\n/**\n * POST `{server}/api/v1/oauth/device/authorize` and parse the response.\n *\n * memory-cloud's device/authorize accepts JSON, unlike the /oauth/token/ +\n * /oauth/revoke endpoints which take application/x-www-form-urlencoded.\n */\nexport async function authorizeDevice(\n server: string,\n options: OAuthHttpOptions & { clientId?: string; scope?: string } = {},\n): Promise<DeviceAuthorizationResponse> {\n const clientId = options.clientId ?? DEFAULT_CLIENT_ID;\n const scope = options.scope ?? \"memory:read\";\n const doFetch = options.fetch ?? globalThis.fetch;\n const url = `${server.replace(/\\/+$/, \"\")}${PATH_DEVICE_AUTHORIZE}`;\n\n let response: Response;\n let text: string;\n try {\n response = await doFetch(url, {\n method: \"POST\",\n headers: {\n \"User-Agent\": userAgent(),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ client_id: clientId, scope }),\n });\n text = await response.text();\n } catch (e) {\n throw new KaguraConnectionError(`Could not reach ${url}: ${excMessage(e)}`, { cause: e });\n }\n\n if (!response.ok) {\n const detail = extractDetail(text) || text;\n throw new KaguraAuthError(\n `Device authorization failed (HTTP ${response.status}): ${detail}\\n` +\n ` Verify the server URL and that '${clientId}' is registered.`,\n );\n }\n\n const body = safeJsonObject(text, response.status, \"Device authorization\");\n const deviceCode = body.device_code;\n const userCode = body.user_code;\n const verificationUri = body.verification_uri;\n const expiresIn = toInt(body.expires_in);\n if (\n typeof deviceCode !== \"string\" ||\n typeof userCode !== \"string\" ||\n typeof verificationUri !== \"string\" ||\n expiresIn === null\n ) {\n throw new KaguraAuthError(\n \"Device authorization returned HTTP 200 but body is missing required fields. \" +\n `Body keys: ${Object.keys(body).sort().join(\", \")}`,\n );\n }\n return {\n deviceCode,\n userCode,\n verificationUri,\n verificationUriComplete: stringOr(body.verification_uri_complete, verificationUri),\n expiresIn,\n interval: toInt(body.interval) ?? 5,\n expiresAt: new Date(Date.now() + expiresIn * 1000),\n };\n}\n\nexport interface PollForTokenOptions extends OAuthHttpOptions {\n clientId: string;\n deviceCode: string;\n /** RFC 8628 polling interval in seconds. */\n interval: number;\n expiresAt: Date;\n /**\n * Injectable sleep (milliseconds) so tests can supply a no-op or\n * counter-based stub without waiting real seconds.\n */\n sleep?: (ms: number) => Promise<void>;\n}\n\n/**\n * Poll `{server}/api/v1/oauth/token/` until the user approves or denies.\n *\n * The first poll fires immediately (no initial sleep) so a fast approval\n * never waits a whole interval; sleeps only happen between retries after\n * `authorization_pending` / `slow_down`.\n *\n * @throws KaguraAuthDeniedError user clicked \"Deny\" at the consent screen\n * (server returns `access_denied`).\n * @throws KaguraAuthExpiredError the `device_code` lifetime elapsed without\n * approval (server returns `expired_token`, or `expiresAt` passed locally).\n * @throws KaguraAuthError any other OAuth error or unexpected response.\n * @throws KaguraConnectionError network failure during polling.\n */\nexport async function pollForToken(\n server: string,\n options: PollForTokenOptions,\n): Promise<TokenResponse> {\n const doFetch = options.fetch ?? globalThis.fetch;\n const sleep = options.sleep ?? (async (ms: number): Promise<void> => void (await sleepMs(ms)));\n const url = tokenUrl(server);\n\n let currentInterval = options.interval;\n let firstPoll = true;\n\n for (;;) {\n if (Date.now() >= options.expiresAt.getTime()) {\n throw new KaguraAuthExpiredError(\n \"Device code expired before user approval. Run: kagura auth login\",\n options.expiresAt,\n );\n }\n\n // Skip the initial sleep so an immediate approval (or a fast\n // server-side error) doesn't wait one whole interval.\n if (firstPoll) {\n firstPoll = false;\n } else {\n await sleep(currentInterval * 1000);\n }\n\n let response: Response;\n let text: string;\n try {\n response = await doFetch(url, {\n method: \"POST\",\n headers: { \"User-Agent\": userAgent() },\n body: new URLSearchParams({\n grant_type: DEVICE_FLOW_GRANT_TYPE,\n device_code: options.deviceCode,\n client_id: options.clientId,\n }),\n });\n text = await response.text();\n } catch (e) {\n throw new KaguraConnectionError(\n `Lost connection while waiting for approval: ${excMessage(e)}\\n` +\n ` The login session may still be valid; re-run: kagura auth login`,\n { cause: e },\n );\n }\n\n if (response.status === 200) {\n return tokenResponseFromBody(text, response.status);\n }\n\n // RFC 8628 §3.5 — errors come as HTTP 4xx with JSON `error` field.\n const body = safeJson(text);\n const error = stringOr(body.error, \"\");\n\n if (error === \"authorization_pending\") {\n continue;\n }\n if (error === \"slow_down\") {\n currentInterval += SLOW_DOWN_INCREMENT_SEC;\n continue;\n }\n if (error === \"access_denied\") {\n throw new KaguraAuthDeniedError(\n \"Authorization denied at the consent screen.\\n\" +\n \" Re-run: kagura auth login\\n\" +\n \" To use a different workspace, log in with that account \" +\n \"in your browser first.\",\n );\n }\n if (error === \"expired_token\") {\n throw new KaguraAuthExpiredError(\n \"Device code expired before user approval. Run: kagura auth login\",\n options.expiresAt,\n );\n }\n\n // Unknown error — surface the HTTP status + raw response so the\n // operator can debug non-OAuth failures (HTML 5xx, proxy errors,\n // non-JSON bodies that make `error` come back empty).\n const description = stringOr(body.error_description, \"\");\n if (error || description) {\n throw new KaguraAuthError(\n `Token endpoint returned unexpected error '${error}': ${description}`,\n );\n }\n const detail = extractDetail(text) || text.slice(0, 200);\n throw new KaguraAuthError(\n `Token endpoint returned HTTP ${response.status} with no OAuth error code. ` +\n `Body: ${detail}`,\n );\n }\n}\n\nexport interface RefreshAccessTokenOptions extends OAuthHttpOptions {\n clientId: string;\n refreshToken: string;\n scope?: string | null;\n}\n\n/**\n * POST `{server}/api/v1/oauth/token/` with `grant_type=refresh_token`.\n *\n * When `scope` is supplied, the server may reject the call with\n * `insufficient_scope` / `invalid_scope` if the grant doesn't cover it.\n *\n * @throws KaguraAuthExpiredError refresh token is invalid or expired\n * (server returns `invalid_grant`).\n * @throws KaguraAuthError any other OAuth error.\n * @throws KaguraConnectionError network failure.\n */\nexport async function refreshAccessToken(\n server: string,\n options: RefreshAccessTokenOptions,\n): Promise<TokenResponse> {\n const doFetch = options.fetch ?? globalThis.fetch;\n const url = tokenUrl(server);\n const form = new URLSearchParams({\n grant_type: REFRESH_TOKEN_GRANT_TYPE,\n refresh_token: options.refreshToken,\n client_id: options.clientId,\n });\n if (options.scope !== undefined && options.scope !== null) {\n form.set(\"scope\", options.scope);\n }\n\n let response: Response;\n let text: string;\n try {\n response = await doFetch(url, {\n method: \"POST\",\n headers: { \"User-Agent\": userAgent() },\n body: form,\n });\n text = await response.text();\n } catch (e) {\n throw new KaguraConnectionError(`Could not reach ${url}: ${excMessage(e)}`, { cause: e });\n }\n\n if (response.status === 200) {\n return tokenResponseFromBody(text, response.status);\n }\n\n const body = safeJson(text);\n const error = stringOr(body.error, \"\");\n\n if (error === \"invalid_grant\") {\n throw new KaguraAuthExpiredError(\n \"Your login expired (refresh token is no longer valid).\\n\" +\n \" Run: kagura auth login\\n\" +\n \" Your server and workspace selection are preserved.\",\n );\n }\n\n const description = stringOr(body.error_description, \"\");\n if (error) {\n throw new KaguraAuthError(\n `Refresh failed: ${error}${description ? ` — ${description}` : \"\"}`,\n );\n }\n // Non-OAuth failure (HTML 5xx, network proxy returning text/plain, etc.).\n const detail = extractDetail(text) || text.slice(0, 200);\n throw new KaguraAuthError(\n `Refresh failed: HTTP ${response.status} with no OAuth error code. Body: ${detail}`,\n );\n}\n\n/**\n * POST `{server}/api/v1/oauth/revoke`. Best-effort — never throws.\n *\n * Returns `true` on success, `false` on any failure. The caller\n * (`kagura auth logout`) deletes the local profile regardless of the\n * return value, on the principle that local logout must succeed even when\n * the server is unreachable.\n */\nexport async function revokeToken(\n server: string,\n options: OAuthHttpOptions & { token: string; clientId?: string },\n): Promise<boolean> {\n const doFetch = options.fetch ?? globalThis.fetch;\n const url = `${server.replace(/\\/+$/, \"\")}${PATH_REVOKE}`;\n try {\n const response = await doFetch(url, {\n method: \"POST\",\n headers: { \"User-Agent\": userAgent() },\n body: new URLSearchParams({\n token: options.token,\n client_id: options.clientId ?? DEFAULT_CLIENT_ID,\n }),\n });\n return response.status === 200 || response.status === 204;\n } catch {\n return false;\n }\n}\n","/**\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.5.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","/**\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","/**\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","/** Low-level client for Kagura Memory Cloud MCP tools (port of client.py). */\r\n\r\nimport { buildBootstrapPayload } from \"./agentBootstrap.js\";\r\nimport type { GetAgentBootstrapOptions } from \"./agentBootstrap.js\";\r\nimport { resolveAuth } from \"./auth/resolve.js\";\r\nimport type { AuthProvider } from \"./auth/types.js\";\r\nimport {\r\n excMessage,\r\n KaguraConnectionError,\r\n KaguraError,\r\n KaguraNotFoundError,\r\n KaguraQuotaError,\r\n} from \"./errors.js\";\r\nimport { baseUrlFromMcp, SDK_VERSION, throwForKaguraStatus, validateHttpsUrl } from \"./http.js\";\r\nimport type {\r\n Agent,\r\n AgentBinding,\r\n AgentBootstrapResponse,\r\n ContextInfo,\r\n DuplicatesResponse,\r\n Edge,\r\n EmbeddingModelsResponse,\r\n EmbeddingStatus,\r\n ListTagsResponse,\r\n MemoryListResponse,\r\n // Referenced only from JSDoc {@link} on the details/recallNearby options.\r\n MemoryLocation,\r\n MemoryStatsResponse,\r\n RecallNearbyResponse,\r\n RollbackResult,\r\n ServerInfo,\r\n SleepReport,\r\n SleepReportDetail,\r\n UsageInfo,\r\n} from \"./models.js\";\r\n\r\n/**\r\n * Minimum memory-cloud server version this SDK was tested against.\r\n *\r\n * The check is opt-in: callers must explicitly invoke\r\n * {@link KaguraClient.checkServerVersion} to log an advisory warning when\r\n * the connected server is older. Plain construction and tool calls never\r\n * throw on version mismatch; older servers may silently ignore unknown\r\n * parameters.\r\n */\r\nexport const MIN_SERVER_VERSION = \"0.17.1\";\r\n\r\nconst MIN_SERVER_VERSION_TUPLE = MIN_SERVER_VERSION.split(\".\").slice(0, 3).map(Number);\r\n\r\n/** Generic parsed-JSON result of an MCP tool call. */\r\nexport type ToolResult = Record<string, unknown>;\r\n\r\nexport type DeliveryMode = \"always\" | \"on_recall\" | \"on_trigger\";\r\nexport type SearchMode = \"hybrid\" | \"semantic\" | \"keyword\";\r\nexport type SourceType = \"file\" | \"url\" | \"vault\" | \"api\" | \"manual\";\r\n\r\n/** Agent lifecycle state — `updateAgent`'s fail-closed kill switch. */\r\nexport type AgentStatus = \"active\" | \"suspended\" | \"retired\";\r\n/** Binding enforcement ramp: `enforce` denies, `shadow` only logs. */\r\nexport type AgentEnforcementMode = \"shadow\" | \"enforce\";\r\n/**\r\n * Per-binding write gate: `\"deny\"` (server default) or `\"direct\"`.\r\n * `\"staged\"` is reserved for a later server phase.\r\n */\r\nexport type AgentWritePolicy = \"deny\" | \"direct\";\r\n\r\nexport interface KaguraClientOptions {\r\n /** Explicit Kagura API key. When omitted, the resolution chain runs. */\r\n apiKey?: string;\r\n /** Explicit MCP URL. When omitted, derived from the credential source. */\r\n mcpUrl?: string;\r\n /** Request timeout in milliseconds (default: 30000). */\r\n timeoutMs?: number;\r\n /** Named OAuth profile to load (overrides KAGURA_PROFILE and the file default). */\r\n profile?: string;\r\n /** Fetch implementation override (for tests; default: globalThis.fetch). */\r\n fetch?: typeof globalThis.fetch;\r\n /** Environment source override (for tests; default: process.env). */\r\n env?: Record<string, string | undefined>;\r\n /** Home directory override (for tests). */\r\n home?: string;\r\n}\r\n\r\nexport interface RememberOptions {\r\n contextId: string;\r\n /** Memory summary (10-500 chars). */\r\n summary: string;\r\n content: string;\r\n /** Memory type; the server validates against its own vocabulary. */\r\n type?: string;\r\n /** Importance score (0.0-1.0). */\r\n importance?: number;\r\n tags?: string[];\r\n /** Origin URI (e.g. `file:///`, `https://`, `vault://`). */\r\n sourceUri?: string;\r\n /** Existing memory UUIDs to declare as `declared_link` edges from this memory. */\r\n linkedMemoryIds?: string[];\r\n /** Source URIs to resolve into linked memories (unresolved URIs are skipped server-side). */\r\n linkedSourceUris?: string[];\r\n /** Origin classification; pairs with sourceUri for downstream filters. */\r\n sourceType?: SourceType;\r\n /** Why the memory exists and how to use it (max 2000 chars). */\r\n contextSummary?: string;\r\n /**\r\n * Structured details JSON, stored as-is.\r\n *\r\n * A `location: {@link MemoryLocation}` here is what makes the memory\r\n * reachable from {@link recallNearby}. `lat`/`lon` must be JSON numbers —\r\n * argument coercion does not recurse into `details`, so string-typed\r\n * numerics are rejected server-side with HTTP 422.\r\n */\r\n details?: Record<string, unknown>;\r\n /** Open-ended context metadata JSON. */\r\n context?: Record<string, unknown>;\r\n /**\r\n * UUID of an existing memory this one replaces.\r\n *\r\n * Creates a supersede edge: the old memory is shadowed out of default\r\n * recall but stays restorable and reachable via\r\n * `recall({ includeSuperseded: true })` and {@link explore}. Prefer this\r\n * over {@link forget} + `remember`, which destroys the history.\r\n */\r\n supersedes?: string;\r\n /**\r\n * When the memory is surfaced. `\"on_recall\"` (default) leaves it to\r\n * probabilistic recall; `\"always\"` pins it so every loadPinned call\r\n * returns it. Only sent when it differs from the server default.\r\n */\r\n deliveryMode?: DeliveryMode;\r\n}\r\n\r\nexport interface RecallOptions {\r\n /** Context ID for single-context search. */\r\n contextId?: string;\r\n query: string;\r\n /** Number of results (default 5). */\r\n k?: number;\r\n /** Enable AI reranking for higher quality results. */\r\n useRerank?: boolean;\r\n /**\r\n * Optional filters: `type`, `tags`, `tags_match` (\"any\"/\"all\"),\r\n * `created_after`/`created_before`, `updated_after`/`updated_before`,\r\n * `trust_tier` (\"trusted\" excludes external/connector-ingested memories).\r\n */\r\n filters?: Record<string, unknown>;\r\n searchMode?: SearchMode;\r\n /** Search across multiple contexts (2-20 IDs); contextId not required then. */\r\n contextIds?: string[];\r\n /** Include up to 3 graph discovery hints under `explore_hints`. */\r\n includeExploreHints?: boolean;\r\n}\r\n\r\nexport interface UpdateMemoryOptions {\r\n contextId: string;\r\n /** UUID of memory to update in-place (provide exactly one of memoryId/externalId). */\r\n memoryId?: string;\r\n /** External resource ID for upsert lookup. */\r\n externalId?: string;\r\n summary?: string;\r\n content?: string;\r\n type?: string;\r\n importance?: number;\r\n tags?: string[];\r\n contextSummary?: string;\r\n /**\r\n * Structured details JSON. **Replaces `details` wholesale** — the server\r\n * does not deep-merge. Round-trip any keys you want to keep (notably\r\n * `location`, see {@link MemoryLocation}) or they are silently dropped.\r\n *\r\n * Omitted from the request when `undefined`; pass `{}` to clear.\r\n */\r\n details?: Record<string, unknown>;\r\n /** `\"always\"` pins, `\"on_recall\"` unpins; omit to leave unchanged. */\r\n deliveryMode?: DeliveryMode;\r\n}\r\n\r\nexport interface CreateContextOptions {\r\n /** Context name (lowercase alphanumeric + hyphen/underscore). */\r\n name: string;\r\n displayName?: string;\r\n description?: string;\r\n /** LLM-oriented summary (200-500 chars). */\r\n summary?: string;\r\n /** LLM-oriented memory usage guidelines. */\r\n usageGuide?: string;\r\n /** Resource identifier for external data ingestion. */\r\n resourceId?: string;\r\n /** Privacy flag (default: true). */\r\n isPrivate?: boolean;\r\n /** Embedding model (immutable after creation); see listEmbeddingModels(). */\r\n embeddingModel?: string;\r\n}\r\n\r\nexport interface UpdateContextOptions {\r\n contextId: string;\r\n displayName?: string;\r\n description?: string;\r\n summary?: string;\r\n usageGuide?: string;\r\n resourceId?: string;\r\n /** Public visibility (required for resource tokens). */\r\n isPublic?: boolean;\r\n /** Locked contexts cannot be deleted. */\r\n isLocked?: boolean;\r\n}\r\n\r\nexport interface SetupResourceOptions {\r\n resourceId: string;\r\n /** Context name (defaults to resourceId server-side). */\r\n name?: string;\r\n summary?: string;\r\n /** Token description. */\r\n description?: string;\r\n /** Token quota (1-10000, default 1000). */\r\n quotaEventsPerHour?: number;\r\n}\r\n\r\nexport interface ListTagsOptions {\r\n contextId: string;\r\n /** Maximum tags to return (1-500, default 50). */\r\n limit?: number;\r\n /** Minimum memory count per tag (1-10000, default 1). */\r\n minCount?: number;\r\n /** Sort order (default \"count\"). */\r\n sort?: \"count\" | \"recent\" | \"alpha\";\r\n /** Case-insensitive prefix filter (max 200 chars). */\r\n prefix?: string;\r\n /**\r\n * Multi-tag AND drill-down: restrict the vocabulary to memories whose\r\n * tags contain **all** of these values (`tags @> with_tags`), and exclude\r\n * these values from the returned tags.\r\n *\r\n * Combine with `prefix` for server-side faceted browsing — one call per\r\n * drill-down level, no local index. An empty array is a no-op filter and\r\n * is not sent.\r\n */\r\n withTags?: string[];\r\n}\r\n\r\nexport interface ListMemoriesOptions {\r\n /** Context UUID; omit for the caller's cross-context view. */\r\n contextId?: string;\r\n /** Case-insensitive substring filter on summaries (whitespace-only → no filter). */\r\n q?: string;\r\n scope?: \"working\" | \"persistent\";\r\n type?: string;\r\n /** Maximum results (1-500, default 50). */\r\n limit?: number;\r\n offset?: number;\r\n /** Time-window overlap lower bound (naive ISO) for type=\"time\" memories. */\r\n triggerFrom?: string;\r\n /** Time-window overlap upper bound (naive ISO). */\r\n triggerUntil?: string;\r\n /** \"created_at\" (default, newest-first) or \"trigger_from\" (soonest first). */\r\n orderBy?: \"created_at\" | \"trigger_from\";\r\n}\r\n\r\nexport interface RegisterAgentOptions {\r\n /** Workspace-unique agent name (max 255 chars). */\r\n name: string;\r\n /** Free-text description (max 10000 chars). */\r\n description?: string;\r\n /** Framework tag, e.g. `\"claude-code\"`, `\"langgraph\"` (max 100 chars). */\r\n framework?: string;\r\n /** Deployment environment, e.g. `\"production\"` (max 100 chars). */\r\n environment?: string;\r\n /** Agent build/prompt version (max 100 chars). */\r\n version?: string;\r\n}\r\n\r\nexport interface UpdateAgentOptions {\r\n agentId: string;\r\n /** New workspace-unique name (max 255 chars). */\r\n name?: string;\r\n /** New description (max 10000 chars). */\r\n description?: string;\r\n /** New framework tag (max 100 chars). */\r\n framework?: string;\r\n /** New environment (max 100 chars). */\r\n environment?: string;\r\n /** New version (max 100 chars). */\r\n version?: string;\r\n /**\r\n * Lifecycle state — the fail-closed kill switch: `\"suspended\"` /\r\n * `\"retired\"` agents get every key bound to them rejected at verify\r\n * time.\r\n */\r\n status?: AgentStatus;\r\n /**\r\n * Binding enforcement ramp. Setting `\"enforce\"` → `\"shadow\"` is an\r\n * audited privilege-widening event (bindings stop being enforced and\r\n * are only logged).\r\n */\r\n enforcementMode?: AgentEnforcementMode;\r\n}\r\n\r\n/**\r\n * The subtractive scope trio shared by {@link BindAgentContextOptions}\r\n * and {@link UpdateAgentBindingOptions} — the ONE type to extend when\r\n * memory-cloud #1286 ships the reserved `allowedMemoryTypes` /\r\n * `allowedSourceTypes` filters (the server accepts only null for them\r\n * until per-memory enforcement lands, so they are deliberately not\r\n * declared yet; adding them later is non-breaking).\r\n */\r\nexport interface AgentBindingScopeOptions {\r\n /** Whether the agent may read this context (server default: true). */\r\n canRead?: boolean;\r\n /** Write gate (server default: `\"deny\"`). */\r\n writePolicy?: AgentWritePolicy;\r\n /** Mark as the agent's bootstrap default binding (max one per agent). */\r\n isDefault?: boolean;\r\n}\r\n\r\nexport interface BindAgentContextOptions extends AgentBindingScopeOptions {\r\n agentId: string;\r\n /** Context to bind (must belong to the agent's workspace). */\r\n contextId: string;\r\n}\r\n\r\nexport interface UpdateAgentBindingOptions extends AgentBindingScopeOptions {\r\n agentId: string;\r\n /** Binding UUID from {@link KaguraClient.listAgentBindings}. */\r\n bindingId: string;\r\n}\r\n\r\nexport interface UpdateSearchConfigOptions {\r\n contextId: string;\r\n /** Semantic search weight (0.0-1.0); weights must sum to 1.0 (±0.01). */\r\n semanticWeight?: number;\r\n /** BM25 keyword search weight (0.0-1.0). */\r\n bm25Weight?: number;\r\n /** Candidate fetch multiplier (1-10). */\r\n fetchFactor?: number;\r\n useRerank?: boolean;\r\n /** \"voyage\", \"cohere\", or \"ollama\". */\r\n rerankerProvider?: string;\r\n rerankerModel?: string;\r\n}\r\n\r\n/**\r\n * Low-level client for Kagura Memory Cloud MCP tools.\r\n *\r\n * All methods may throw KaguraAuthError (authentication failed),\r\n * KaguraConnectionError (connection failed), or KaguraRateLimitError.\r\n *\r\n * MCP tool methods additionally translate the server's structured domain\r\n * errors (`{\"status\": \"error\", ...}`) into exceptions rather than\r\n * returning them as data: a missing context/memory/report throws\r\n * {@link KaguraNotFoundError}, any other domain error throws\r\n * {@link KaguraError}. Use try/catch rather than inspecting\r\n * `result.status`.\r\n *\r\n * Authentication resolution order when `apiKey` is omitted:\r\n * 1. `KAGURA_API_KEY` env var (CI / service accounts always win).\r\n * 2. The OAuth profile from `~/.kagura/credentials.json`, selected by\r\n * `options.profile` or `KAGURA_PROFILE`, falling back to the file's\r\n * `default_profile`.\r\n * 3. `.kagura.json` (cwd or `~/`) plus its own env fallback.\r\n */\r\nexport class KaguraClient {\r\n readonly mcpUrl: string;\r\n readonly timeoutMs: number;\r\n\r\n private readonly baseUrl: string;\r\n private readonly auth: AuthProvider;\r\n private readonly fetchImpl: typeof globalThis.fetch;\r\n private sessionId: string | null = null;\r\n private requestIdCounter = 1;\r\n\r\n constructor(options: KaguraClientOptions = {}) {\r\n const resolved = resolveAuth({\r\n apiKey: options.apiKey ?? null,\r\n mcpUrl: options.mcpUrl ?? null,\r\n profile: options.profile ?? null,\r\n env: options.env,\r\n home: options.home,\r\n });\r\n\r\n const strippedUrl = resolved.mcpUrl.replace(/\\/+$/, \"\");\r\n validateHttpsUrl(strippedUrl, \"MCP URL\");\r\n\r\n this.mcpUrl = strippedUrl;\r\n this.baseUrl = baseUrlFromMcp(strippedUrl);\r\n this.timeoutMs = options.timeoutMs ?? 30_000;\r\n this.fetchImpl = options.fetch ?? globalThis.fetch;\r\n\r\n if (resolved.kind === \"static\") {\r\n // Long-lived API key path: bake the bearer header once.\r\n const header = `Bearer ${resolved.apiKey}`;\r\n this.auth = { getAuthHeader: async () => header };\r\n } else {\r\n // OAuth path: the provider injects a fresh bearer header per request\r\n // and coordinates refresh through the shared credentials state.\r\n this.auth = resolved.oauth;\r\n }\r\n }\r\n\r\n /** Get next JSON-RPC request ID. */\r\n private nextRequestId(): number {\r\n return this.requestIdCounter++;\r\n }\r\n\r\n private async post(\r\n url: string,\r\n body: unknown,\r\n extraHeaders: Record<string, string> = {},\r\n ): Promise<Response> {\r\n const headers: Record<string, string> = {\r\n \"content-type\": \"application/json\",\r\n accept: \"application/json, text/event-stream\",\r\n authorization: await this.auth.getAuthHeader(),\r\n \"user-agent\": `kagura-memory-sdk/${SDK_VERSION}`,\r\n ...extraHeaders,\r\n };\r\n try {\r\n return await this.fetchImpl(url, {\r\n method: \"POST\",\r\n headers,\r\n body: JSON.stringify(body),\r\n signal: AbortSignal.timeout(this.timeoutMs),\r\n });\r\n } catch (e) {\r\n throw new KaguraConnectionError(`Connection failed: ${excMessage(e)}`, { cause: e });\r\n }\r\n }\r\n\r\n /** Initialize the MCP session if not already initialized. */\r\n private async initializeSession(): Promise<void> {\r\n if (this.sessionId) {\r\n return;\r\n }\r\n\r\n const body = {\r\n jsonrpc: \"2.0\",\r\n id: this.nextRequestId(),\r\n method: \"initialize\",\r\n params: {\r\n protocolVersion: \"2025-03-26\",\r\n capabilities: {},\r\n clientInfo: { name: \"kagura-memory-sdk\", version: SDK_VERSION },\r\n },\r\n };\r\n\r\n const response = await this.post(this.mcpUrl, body);\r\n if (!response.ok) {\r\n throwForKaguraStatus(response.status, response.headers, await this.safeText(response));\r\n }\r\n\r\n const sessionId = response.headers.get(\"mcp-session-id\");\r\n if (!sessionId) {\r\n throw new KaguraConnectionError(\"No session ID returned from server\");\r\n }\r\n this.sessionId = sessionId;\r\n }\r\n\r\n private async safeText(response: Response): Promise<string> {\r\n try {\r\n return await response.text();\r\n } catch {\r\n return \"\";\r\n }\r\n }\r\n\r\n /** Make a JSON-RPC 2.0 request to the MCP server. */\r\n private async makeJsonRpcRequest(\r\n method: string,\r\n params: Record<string, unknown>,\r\n ): Promise<Record<string, unknown>> {\r\n await this.initializeSession();\r\n\r\n const body = {\r\n jsonrpc: \"2.0\",\r\n id: this.nextRequestId(),\r\n method,\r\n params,\r\n };\r\n\r\n const headers: Record<string, string> = this.sessionId\r\n ? { \"mcp-session-id\": this.sessionId }\r\n : {};\r\n const response = await this.post(this.mcpUrl, body, headers);\r\n const text = await this.safeText(response);\r\n if (!response.ok) {\r\n throwForKaguraStatus(response.status, response.headers, text);\r\n }\r\n\r\n let data: Record<string, unknown>;\r\n try {\r\n data = text ? (JSON.parse(text) as Record<string, unknown>) : {};\r\n } catch (e) {\r\n throw new KaguraConnectionError(`Invalid response format: ${excMessage(e)}`, { cause: e });\r\n }\r\n if (data && typeof data === \"object\" && \"error\" in data) {\r\n const error = data.error as Record<string, unknown> | undefined;\r\n const message = error && typeof error === \"object\" ? (error.message ?? JSON.stringify(error)) : String(error);\r\n throw new KaguraConnectionError(`MCP error: ${String(message)}`);\r\n }\r\n\r\n const result = data.result;\r\n return typeof result === \"object\" && result !== null\r\n ? (result as Record<string, unknown>)\r\n : {};\r\n }\r\n\r\n /** GET a REST endpoint and parse the JSON body. */\r\n private async restGet<T>(path: string, params?: Record<string, unknown>): Promise<T> {\r\n let url = `${this.baseUrl}${path}`;\r\n if (params) {\r\n const query = new URLSearchParams();\r\n for (const [key, value] of Object.entries(params)) {\r\n if (value !== undefined && value !== null) {\r\n query.set(key, String(value));\r\n }\r\n }\r\n const qs = query.toString();\r\n if (qs) {\r\n url += `?${qs}`;\r\n }\r\n }\r\n\r\n let response: Response;\r\n try {\r\n response = await this.fetchImpl(url, {\r\n method: \"GET\",\r\n headers: {\r\n authorization: await this.auth.getAuthHeader(),\r\n \"user-agent\": `kagura-memory-sdk/${SDK_VERSION}`,\r\n },\r\n signal: AbortSignal.timeout(this.timeoutMs),\r\n });\r\n } catch (e) {\r\n throw new KaguraConnectionError(`Connection failed: ${excMessage(e)}`, { cause: e });\r\n }\r\n\r\n const text = await this.safeText(response);\r\n if (!response.ok) {\r\n throwForKaguraStatus(response.status, response.headers, text);\r\n }\r\n try {\r\n return JSON.parse(text) as T;\r\n } catch (e) {\r\n throw new KaguraConnectionError(`Invalid response format: ${excMessage(e)}`, { cause: e });\r\n }\r\n }\r\n\r\n /**\r\n * Call an MCP tool via JSON-RPC and parse `content[0].text` as JSON.\r\n */\r\n private async callTool(\r\n toolName: string,\r\n args: Record<string, unknown>,\r\n ): Promise<ToolResult> {\r\n const result = await this.makeJsonRpcRequest(\"tools/call\", {\r\n name: toolName,\r\n arguments: args,\r\n });\r\n\r\n const content = result.content;\r\n if (Array.isArray(content) && content.length > 0) {\r\n const first = content[0] as Record<string, unknown>;\r\n const text = typeof first.text === \"string\" ? first.text : \"{}\";\r\n try {\r\n return JSON.parse(text) as ToolResult;\r\n } catch (e) {\r\n throw new KaguraConnectionError(`Invalid response format: ${excMessage(e)}`, {\r\n cause: e,\r\n });\r\n }\r\n }\r\n return {};\r\n }\r\n\r\n /**\r\n * Call an MCP tool and translate domain errors into exceptions.\r\n *\r\n * A server `{\"status\": \"error\", ...}` response throws\r\n * KaguraNotFoundError / KaguraError instead of being returned as data.\r\n */\r\n private async callToolChecked(\r\n toolName: string,\r\n args: Record<string, unknown>,\r\n ): Promise<ToolResult> {\r\n const result = await this.callTool(toolName, args);\r\n KaguraClient.raiseForMcpError(result, toolName);\r\n return result;\r\n }\r\n\r\n /**\r\n * Translate an MCP tool's structured error response to an SDK error.\r\n *\r\n * The server's MCP tools return `{\"status\": \"error\", \"error\": <code>,\r\n * \"message\": <str>, ...}` for domain errors the JSON-RPC transport\r\n * cannot represent. HTTP-level errors are handled by the request layer.\r\n */\r\n private static raiseForMcpError(result: ToolResult, operation: string): void {\r\n if (result.status !== \"error\") {\r\n return;\r\n }\r\n const code = typeof result.error === \"string\" ? result.error : \"unknown\";\r\n const message = typeof result.message === \"string\" ? result.message : \"Unknown error\";\r\n if (\r\n code === \"report_not_found\" ||\r\n code === \"context_not_found\" ||\r\n code === \"memory_not_found\" ||\r\n code === \"agent_not_found\" ||\r\n code === \"binding_not_found\"\r\n ) {\r\n throw new KaguraNotFoundError(`${operation}: ${message}`);\r\n }\r\n throw new KaguraError(`${operation} failed (${code}): ${message}`);\r\n }\r\n\r\n /** Store a memory. Returns the API response with `memory_id`. */\r\n async remember(options: RememberOptions): Promise<ToolResult> {\r\n const args: Record<string, unknown> = {\r\n context_id: options.contextId,\r\n summary: options.summary,\r\n content: options.content,\r\n type: options.type ?? \"note\",\r\n importance: options.importance ?? 0.5,\r\n };\r\n if (options.tags !== undefined) {\r\n args.tags = options.tags;\r\n }\r\n if (options.sourceUri !== undefined) {\r\n args.source_uri = options.sourceUri;\r\n }\r\n if (options.sourceType !== undefined) {\r\n args.source_type = options.sourceType;\r\n }\r\n // Only send a non-default delivery_mode; the server applies\r\n // server_default='on_recall' so omitting it stays forward-compatible.\r\n if (options.deliveryMode !== undefined && options.deliveryMode !== \"on_recall\") {\r\n args.delivery_mode = options.deliveryMode;\r\n }\r\n if (options.contextSummary !== undefined) {\r\n args.context_summary = options.contextSummary;\r\n }\r\n if (options.details !== undefined) {\r\n args.details = options.details;\r\n }\r\n if (options.context !== undefined) {\r\n args.context = options.context;\r\n }\r\n if (options.linkedMemoryIds !== undefined) {\r\n args.linked_memory_ids = options.linkedMemoryIds;\r\n }\r\n if (options.linkedSourceUris !== undefined) {\r\n args.linked_source_uris = options.linkedSourceUris;\r\n }\r\n if (options.supersedes !== undefined) {\r\n args.supersedes = options.supersedes;\r\n }\r\n return this.callToolChecked(\"remember\", args);\r\n }\r\n\r\n /**\r\n * Search memories. Returns the API response with a `results` list.\r\n *\r\n * @throws Error if `query` is empty/whitespace; if neither `contextId`\r\n * nor `contextIds` is provided; if `contextIds` has fewer than 2 or\r\n * more than 20 IDs; or if `searchMode` is invalid.\r\n */\r\n async recall(options: RecallOptions): Promise<ToolResult> {\r\n const { query, contextId, contextIds, searchMode } = options;\r\n if (typeof query !== \"string\" || !query.trim()) {\r\n throw new Error(\"query must be a non-empty string\");\r\n }\r\n if (contextIds !== undefined) {\r\n if (contextIds.length < 2 || contextIds.length > 20) {\r\n throw new Error(`contextIds must contain 2-20 IDs, got ${contextIds.length}`);\r\n }\r\n } else if (contextId === undefined) {\r\n throw new Error(\"Either contextId or contextIds must be provided\");\r\n }\r\n\r\n const args: Record<string, unknown> = {\r\n query,\r\n k: options.k ?? 5,\r\n };\r\n if (contextIds !== undefined) {\r\n args.context_ids = contextIds;\r\n } else {\r\n args.context_id = contextId;\r\n }\r\n if (options.useRerank) {\r\n args.use_rerank = true;\r\n }\r\n if (options.filters && Object.keys(options.filters).length > 0) {\r\n args.filters = options.filters;\r\n }\r\n if (searchMode) {\r\n if (searchMode !== \"hybrid\" && searchMode !== \"semantic\" && searchMode !== \"keyword\") {\r\n throw new Error(`Invalid searchMode: ${JSON.stringify(searchMode)}`);\r\n }\r\n args.search_mode = searchMode;\r\n }\r\n if (options.includeExploreHints) {\r\n args.include_explore_hints = true;\r\n }\r\n return this.callToolChecked(\"recall\", args);\r\n }\r\n\r\n /**\r\n * List Time Memories whose scheduled window overlaps a range, soonest\r\n * first. A deterministic time query over `type=\"time\"` memories — not\r\n * semantic search, no Hebbian side-effects.\r\n */\r\n async recallUpcoming(options: {\r\n contextId: string;\r\n /** Lower bound as naive ISO, or the literal \"now\". Omit for no lower bound. */\r\n from?: string;\r\n /** Upper bound as naive ISO. Omit for an open-ended future window. */\r\n until?: string;\r\n /** Maximum results (default 20, server max 100). */\r\n k?: number;\r\n }): Promise<ToolResult> {\r\n const args: Record<string, unknown> = {\r\n context_id: options.contextId,\r\n k: options.k ?? 20,\r\n };\r\n if (options.from !== undefined) {\r\n args.from = options.from;\r\n }\r\n if (options.until !== undefined) {\r\n args.until = options.until;\r\n }\r\n return this.callToolChecked(\"recall_upcoming\", args);\r\n }\r\n\r\n /**\r\n * List memories near a geographic point, nearest first, each carrying\r\n * `distance_m`. The WHERE axis — a deterministic spatial query over\r\n * stored `details.location` coordinates, not semantic search (use\r\n * {@link recall} for topic search). Mirrors {@link recallUpcoming}.\r\n *\r\n * Store a location with\r\n * `remember({ details: { location: { lat, lon, label } } })`; see\r\n * {@link MemoryLocation}. Any memory type can carry one.\r\n *\r\n * Note: {@link updateMemory} replaces `details` wholesale, so resend\r\n * `location` when updating details or the memory drops off this axis.\r\n *\r\n * `radiusM` is clamped server-side to [1, 1_000_000]; it is forwarded\r\n * unchanged rather than pre-clamped here, so the server stays the single\r\n * authority on the bound.\r\n *\r\n * @throws Error if `lat`/`lon` are not finite numbers in range. The\r\n * server rejects these with HTTP 422; failing locally turns the common\r\n * swapped-lat/lon mistake into an immediate, named error.\r\n */\r\n async recallNearby(options: {\r\n contextId: string;\r\n /** Query latitude (-90..90). */\r\n lat: number;\r\n /** Query longitude (-180..180). */\r\n lon: number;\r\n /** Search radius in meters (default 1000). */\r\n radiusM?: number;\r\n /** Maximum results (default 20; the server clamps to 1-100). */\r\n k?: number;\r\n }): Promise<RecallNearbyResponse> {\r\n const { lat, lon } = options;\r\n if (!Number.isFinite(lat) || lat < -90 || lat > 90) {\r\n throw new Error(`lat must be a finite number between -90 and 90, got ${lat}`);\r\n }\r\n if (!Number.isFinite(lon) || lon < -180 || lon > 180) {\r\n throw new Error(`lon must be a finite number between -180 and 180, got ${lon}`);\r\n }\r\n const result = await this.callToolChecked(\"recall_nearby\", {\r\n context_id: options.contextId,\r\n lat,\r\n lon,\r\n radius_m: options.radiusM ?? 1000,\r\n k: options.k ?? 20,\r\n });\r\n return result as unknown as RecallNearbyResponse;\r\n }\r\n\r\n /**\r\n * Deterministically load a context's pinned (`delivery_mode=\"always\"`)\r\n * memories — the complete, unranked pinned set on every call.\r\n *\r\n * The set is bounded, never silently dropped: when more pinned memories\r\n * exist than `cap`, the response `truncated` flag is true and\r\n * `total_available` reports the real count.\r\n */\r\n async loadPinned(options: {\r\n contextId: string;\r\n /** Override the maximum number returned (1-1000); omit for server default. */\r\n cap?: number;\r\n }): Promise<ToolResult> {\r\n const args: Record<string, unknown> = { context_id: options.contextId };\r\n if (options.cap !== undefined) {\r\n args.cap = options.cap;\r\n }\r\n return this.callToolChecked(\"load_pinned\", args);\r\n }\r\n\r\n /**\r\n * Record whether a recalled memory was useful for a query — an\r\n * append-only usefulness signal, kept in a separate lane from knowledge\r\n * (never pollutes recall).\r\n */\r\n async feedback(options: {\r\n contextId: string;\r\n memoryId: string;\r\n helpful: boolean;\r\n /** Recall query this feedback is about (max 1024 chars). */\r\n query?: string;\r\n /** Free-text note, e.g. why the result was wrong (max 2000 chars). */\r\n note?: string;\r\n }): Promise<ToolResult> {\r\n const args: Record<string, unknown> = {\r\n context_id: options.contextId,\r\n memory_id: options.memoryId,\r\n helpful: options.helpful,\r\n };\r\n if (options.query !== undefined) {\r\n args.query = options.query;\r\n }\r\n if (options.note !== undefined) {\r\n args.note = options.note;\r\n }\r\n return this.callToolChecked(\"feedback\", args);\r\n }\r\n\r\n /**\r\n * Set ephemeral agent run-state at `(contextId, key)` — a TTL-bounded\r\n * key/value lane kept separate from memories and excluded from recall.\r\n * Use remember() for durable knowledge.\r\n */\r\n async setState(options: {\r\n contextId: string;\r\n /** State key (max 255 chars); re-use overwrites. */\r\n key: string;\r\n /** Arbitrary JSON value. */\r\n value: unknown;\r\n /** TTL in seconds (server clamps to 30 days); omit for no expiry. */\r\n ttlSeconds?: number;\r\n }): Promise<ToolResult> {\r\n const args: Record<string, unknown> = {\r\n context_id: options.contextId,\r\n key: options.key,\r\n value: options.value,\r\n };\r\n if (options.ttlSeconds !== undefined) {\r\n args.ttl_seconds = options.ttlSeconds;\r\n }\r\n return this.callToolChecked(\"set_state\", args);\r\n }\r\n\r\n /**\r\n * Read ephemeral agent run-state. Supply `key` to read one value, omit\r\n * it to list all live keys for the context.\r\n */\r\n async getState(options: { contextId: string; key?: string }): Promise<ToolResult> {\r\n const args: Record<string, unknown> = { context_id: options.contextId };\r\n if (options.key !== undefined) {\r\n args.key = options.key;\r\n }\r\n return this.callToolChecked(\"get_state\", args);\r\n }\r\n\r\n // -------------------------------------------------------------------\r\n // Agent control plane (server v0.49.0+, RFC-0002; issues #1/#2/#3)\r\n // -------------------------------------------------------------------\r\n\r\n /**\r\n * Unwrap an object envelope (`agent`, `binding`, `report`, …) from a\r\n * tool result.\r\n *\r\n * Match the Python port's `result[\"<key>\"]`: a missing envelope is a\r\n * contract violation, surfaced loudly rather than as a partial object.\r\n */\r\n private static expectEnvelope(\r\n result: ToolResult,\r\n key: string,\r\n operation: string,\r\n ): Record<string, unknown> {\r\n const envelope = result[key];\r\n if (typeof envelope !== \"object\" || envelope === null || Array.isArray(envelope)) {\r\n throw new KaguraConnectionError(\r\n `Unexpected ${operation} response: missing '${key}' envelope.`,\r\n );\r\n }\r\n return envelope as Record<string, unknown>;\r\n }\r\n\r\n /**\r\n * Register an AI agent in the workspace Agent Registry.\r\n *\r\n * Calls the `register_agent` MCP tool (server v0.49.0+, RFC-0002 P0-1,\r\n * memory-cloud #1274) — owner/admin only. An agent is a\r\n * workspace-scoped registry entry (name unique per workspace) that\r\n * anchors context bindings, agent-bound credentials,\r\n * {@link getAgentBootstrap}, and audit correlation — it is a resource,\r\n * NOT a principal. New agents start with `status=\"active\"` and\r\n * `enforcement_mode=\"enforce\"`.\r\n *\r\n * Requires memory-cloud v0.49.0+ — older servers return an MCP\r\n * \"tool not found\" error ({@link MIN_SERVER_VERSION} is deliberately\r\n * not bumped; only the agent control plane needs the newer server).\r\n *\r\n * @throws KaguraError on name conflict, agent quota, or insufficient\r\n * role (owner/admin required).\r\n */\r\n async registerAgent(options: RegisterAgentOptions): Promise<Agent> {\r\n const args: Record<string, unknown> = { name: options.name };\r\n if (options.description !== undefined) {\r\n args.description = options.description;\r\n }\r\n if (options.framework !== undefined) {\r\n args.framework = options.framework;\r\n }\r\n if (options.environment !== undefined) {\r\n args.environment = options.environment;\r\n }\r\n if (options.version !== undefined) {\r\n args.version = options.version;\r\n }\r\n const result = await this.callToolChecked(\"register_agent\", args);\r\n return KaguraClient.expectEnvelope(result, \"agent\", \"register_agent\") as unknown as Agent;\r\n }\r\n\r\n /**\r\n * Fetch one registered agent by id (owner/admin only).\r\n *\r\n * @throws KaguraNotFoundError when the agent does not exist. The 404 is\r\n * uniform (CWE-639) — nonexistent and not-yours are indistinguishable\r\n * by design, so it does NOT prove the agent is absent.\r\n */\r\n async getAgent(agentId: string): Promise<Agent> {\r\n const result = await this.callToolChecked(\"get_agent\", { agent_id: agentId });\r\n return KaguraClient.expectEnvelope(result, \"agent\", \"get_agent\") as unknown as Agent;\r\n }\r\n\r\n /** List the workspace's registered agents, newest first (owner/admin only). */\r\n async listAgents(): Promise<Agent[]> {\r\n const result = await this.callToolChecked(\"list_agents\", {});\r\n const agents = result.agents;\r\n return Array.isArray(agents) ? (agents as unknown as Agent[]) : [];\r\n }\r\n\r\n /**\r\n * Update a registered agent, including lifecycle transitions\r\n * (owner/admin only).\r\n *\r\n * `status` is the **fail-closed kill switch**: `\"suspended\"` /\r\n * `\"retired\"` agents cause every key bound to them to be rejected at\r\n * verify time. Setting `enforcementMode` from `\"enforce\"` to\r\n * `\"shadow\"` is an audited privilege-widening event.\r\n *\r\n * Set-only wrapper: omitted fields are left untouched. The server's\r\n * null-clears-a-metadata-field semantics is not expressible through\r\n * this wrapper — clear fields via the web UI or the raw API.\r\n *\r\n * @throws Error when no update field is provided (the call would be an\r\n * empty no-op request).\r\n */\r\n async updateAgent(options: UpdateAgentOptions): Promise<Agent> {\r\n const changes: Record<string, unknown> = {};\r\n if (options.name !== undefined) {\r\n changes.name = options.name;\r\n }\r\n if (options.description !== undefined) {\r\n changes.description = options.description;\r\n }\r\n if (options.framework !== undefined) {\r\n changes.framework = options.framework;\r\n }\r\n if (options.environment !== undefined) {\r\n changes.environment = options.environment;\r\n }\r\n if (options.version !== undefined) {\r\n changes.version = options.version;\r\n }\r\n if (options.status !== undefined) {\r\n changes.status = options.status;\r\n }\r\n if (options.enforcementMode !== undefined) {\r\n changes.enforcement_mode = options.enforcementMode;\r\n }\r\n if (Object.keys(changes).length === 0) {\r\n throw new Error(\"updateAgent requires at least one field to update\");\r\n }\r\n const result = await this.callToolChecked(\"update_agent\", {\r\n agent_id: options.agentId,\r\n ...changes,\r\n });\r\n return KaguraClient.expectEnvelope(result, \"agent\", \"update_agent\") as unknown as Agent;\r\n }\r\n\r\n /**\r\n * Hard-delete an Agent Registry row (owner/admin only). Returns true\r\n * once the server confirms deletion.\r\n *\r\n * Permanent, and cascades every API key bound to the agent\r\n * (fail-closed). Prefer `updateAgent({status: \"retired\"})` for\r\n * operational retirement.\r\n */\r\n async deleteAgent(agentId: string): Promise<boolean> {\r\n const result = await this.callToolChecked(\"delete_agent\", { agent_id: agentId });\r\n return result.deleted === undefined ? true : Boolean(result.deleted);\r\n }\r\n\r\n /**\r\n * Build the omit-when-undefined binding scope trio shared by\r\n * {@link bindAgentContext} and {@link updateAgentBinding} — the port of\r\n * the Python SDK's `_binding_scope_payload`. When memory-cloud #1286\r\n * ships the reserved filters, extend {@link AgentBindingScopeOptions}\r\n * and map the new fields here.\r\n */\r\n private static bindingScopeArgs(options: AgentBindingScopeOptions): Record<string, unknown> {\r\n const args: Record<string, unknown> = {};\r\n if (options.canRead !== undefined) {\r\n args.can_read = options.canRead;\r\n }\r\n if (options.writePolicy !== undefined) {\r\n args.write_policy = options.writePolicy;\r\n }\r\n if (options.isDefault !== undefined) {\r\n args.is_default = options.isDefault;\r\n }\r\n return args;\r\n }\r\n\r\n /**\r\n * Bind an agent to a context — purely subtractive scoping.\r\n *\r\n * Calls the `bind_agent_context` MCP tool (server v0.49.0+, RFC-0002\r\n * P0-2, memory-cloud #1275) — owner/admin only. The effective\r\n * permission for an agent-bound request is the existing RBAC decision\r\n * ∩ binding. Under `enforcement_mode=\"enforce\"`, contexts WITHOUT a\r\n * binding row are denied for the agent (default-deny); under\r\n * `\"shadow\"`, violations are only logged.\r\n *\r\n * @throws KaguraNotFoundError when the agent or context is not found.\r\n * @throws KaguraError on duplicate binding or other server-side error.\r\n */\r\n async bindAgentContext(options: BindAgentContextOptions): Promise<AgentBinding> {\r\n const result = await this.callToolChecked(\"bind_agent_context\", {\r\n agent_id: options.agentId,\r\n context_id: options.contextId,\r\n ...KaguraClient.bindingScopeArgs(options),\r\n });\r\n return KaguraClient.expectEnvelope(result, \"binding\", \"bind_agent_context\") as unknown as AgentBinding;\r\n }\r\n\r\n /** List an agent's context bindings (owner/admin only). */\r\n async listAgentBindings(agentId: string): Promise<AgentBinding[]> {\r\n const result = await this.callToolChecked(\"list_agent_bindings\", { agent_id: agentId });\r\n const bindings = result.bindings;\r\n return Array.isArray(bindings) ? (bindings as unknown as AgentBinding[]) : [];\r\n }\r\n\r\n /**\r\n * Update a binding's scoping fields (owner/admin only).\r\n *\r\n * `context_id` is immutable — {@link unbindAgentContext} and re-\r\n * {@link bindAgentContext} to re-target. Changes are audited with\r\n * old→new values.\r\n *\r\n * @throws Error when no scoping field is provided (the call would be\r\n * an empty no-op request).\r\n */\r\n async updateAgentBinding(options: UpdateAgentBindingOptions): Promise<AgentBinding> {\r\n const changes = KaguraClient.bindingScopeArgs(options);\r\n if (Object.keys(changes).length === 0) {\r\n throw new Error(\r\n \"updateAgentBinding requires at least one of canRead, writePolicy, or isDefault\",\r\n );\r\n }\r\n const result = await this.callToolChecked(\"update_agent_binding\", {\r\n agent_id: options.agentId,\r\n binding_id: options.bindingId,\r\n ...changes,\r\n });\r\n return KaguraClient.expectEnvelope(result, \"binding\", \"update_agent_binding\") as unknown as AgentBinding;\r\n }\r\n\r\n /**\r\n * Delete a binding — the agent loses that context (owner/admin only).\r\n * Returns true once the server confirms deletion.\r\n *\r\n * Under `enforcement_mode=\"enforce\"` the agent's requests against the\r\n * unbound context are denied afterwards (uniform `context_not_found`).\r\n */\r\n async unbindAgentContext(options: { agentId: string; bindingId: string }): Promise<boolean> {\r\n const result = await this.callToolChecked(\"unbind_agent_context\", {\r\n agent_id: options.agentId,\r\n binding_id: options.bindingId,\r\n });\r\n return result.deleted === undefined ? true : Boolean(result.deleted);\r\n }\r\n\r\n /**\r\n * Rehydrate an agent's cognitive state in one session-start call.\r\n *\r\n * Calls the `get_agent_bootstrap` MCP tool (server v0.49.0+, RFC-0002\r\n * P0-3, memory-cloud #1276). The server composes existing primitives —\r\n * context guide + pinned memories ({@link loadPinned}) + a trusted-only\r\n * {@link recall} (only when `query` is supplied) + upcoming time\r\n * memories ({@link recallUpcoming}) + the agent-state lane\r\n * ({@link getState}) — with bounds, ordering, and trust filtering\r\n * inherited from those standalone tools, not re-specified.\r\n *\r\n * Components are **fail-soft**: a failing component reports\r\n * `{\"status\": \"error\", ...}` under `components` while the rest still\r\n * return, with the top-level `degraded` flag set. Identity and\r\n * authorization failures are total and throw instead.\r\n *\r\n * The REST companion (`POST /api/v1/agents/{agent_id}/bootstrap`) is\r\n * available via `AgentsClient` for API-key-only callers such as\r\n * agent-bound member keys.\r\n *\r\n * @throws KaguraNotFoundError when the agent or context is not found\r\n * (uniform 404 — nonexistent and not-yours are indistinguishable by\r\n * design).\r\n * @throws KaguraError on invalid arguments or other server-side error.\r\n */\r\n async getAgentBootstrap(options: GetAgentBootstrapOptions): Promise<AgentBootstrapResponse> {\r\n const result = await this.callToolChecked(\"get_agent_bootstrap\", {\r\n agent_id: options.agentId,\r\n ...buildBootstrapPayload(options),\r\n });\r\n return result as unknown as AgentBootstrapResponse;\r\n }\r\n\r\n /** List available contexts. */\r\n async listContexts(): Promise<ToolResult> {\r\n return this.callToolChecked(\"list_contexts\", {});\r\n }\r\n\r\n /**\r\n * List the tag vocabulary in a context with usage counts and recency.\r\n *\r\n * Call before remember() to reuse existing tag spellings, or before\r\n * recall() with tag filters. Requires memory-cloud server v0.15.4+.\r\n */\r\n async listTags(options: ListTagsOptions): Promise<ListTagsResponse> {\r\n const limit = options.limit ?? 50;\r\n const minCount = options.minCount ?? 1;\r\n const prefix = options.prefix ?? \"\";\r\n if (limit < 1 || limit > 500) {\r\n throw new Error(`limit must be between 1 and 500, got ${limit}`);\r\n }\r\n if (minCount < 1 || minCount > 10_000) {\r\n throw new Error(`minCount must be between 1 and 10000, got ${minCount}`);\r\n }\r\n if (prefix.length > 200) {\r\n throw new Error(`prefix must be at most 200 characters, got ${prefix.length}`);\r\n }\r\n\r\n const args: Record<string, unknown> = {\r\n context_id: options.contextId,\r\n limit,\r\n min_count: minCount,\r\n sort: options.sort ?? \"count\",\r\n };\r\n if (prefix) {\r\n args.prefix = prefix;\r\n }\r\n // An empty drill-down matches everything (`tags @> '{}'`), so it is\r\n // equivalent to omitting the key — drop it like an empty prefix.\r\n if (options.withTags !== undefined && options.withTags.length > 0) {\r\n args.with_tags = options.withTags;\r\n }\r\n const result = await this.callToolChecked(\"list_tags\", args);\r\n return result as unknown as ListTagsResponse;\r\n }\r\n\r\n /**\r\n * Call tools/list to get available MCP tool definitions (names,\r\n * descriptions, parameter schemas).\r\n */\r\n async getToolDefinitions(): Promise<Record<string, unknown>[]> {\r\n const result = await this.makeJsonRpcRequest(\"tools/list\", {});\r\n const tools = result.tools;\r\n return Array.isArray(tools) ? (tools as Record<string, unknown>[]) : [];\r\n }\r\n\r\n /** Neural graph traversal from a seed memory. */\r\n async explore(options: {\r\n contextId: string;\r\n memoryId: string;\r\n /** Maximum traversal depth (1-5, default 2). */\r\n depth?: number;\r\n /** Minimum edge weight threshold (default 0.05). */\r\n minWeight?: number;\r\n }): Promise<ToolResult> {\r\n return this.callToolChecked(\"explore\", {\r\n context_id: options.contextId,\r\n memory_id: options.memoryId,\r\n depth: options.depth ?? 2,\r\n min_weight: options.minWeight ?? 0.05,\r\n });\r\n }\r\n\r\n /**\r\n * Get full memory details. Memory data is in `result.memory`.\r\n */\r\n async reference(options: { contextId: string; memoryId: string }): Promise<ToolResult> {\r\n return this.callToolChecked(\"reference\", {\r\n context_id: options.contextId,\r\n memory_id: options.memoryId,\r\n });\r\n }\r\n\r\n /**\r\n * Update an existing memory in-place (memoryId) or upsert by external\r\n * ID (externalId — requires summary, content, and type).\r\n *\r\n * @throws Error unless exactly one of memoryId/externalId is provided.\r\n */\r\n async updateMemory(options: UpdateMemoryOptions): Promise<ToolResult> {\r\n if (!options.memoryId && !options.externalId) {\r\n throw new Error(\"Provide exactly one of memoryId or externalId\");\r\n }\r\n if (options.memoryId && options.externalId) {\r\n throw new Error(\"Provide exactly one of memoryId or externalId\");\r\n }\r\n\r\n const args: Record<string, unknown> = { context_id: options.contextId };\r\n if (options.memoryId !== undefined) {\r\n args.memory_id = options.memoryId;\r\n }\r\n if (options.externalId !== undefined) {\r\n args.external_id = options.externalId;\r\n }\r\n if (options.summary !== undefined) {\r\n args.summary = options.summary;\r\n }\r\n if (options.content !== undefined) {\r\n args.content = options.content;\r\n }\r\n if (options.type !== undefined) {\r\n args.type = options.type;\r\n }\r\n if (options.importance !== undefined) {\r\n args.importance = options.importance;\r\n }\r\n if (options.tags !== undefined) {\r\n args.tags = options.tags;\r\n }\r\n if (options.contextSummary !== undefined) {\r\n args.context_summary = options.contextSummary;\r\n }\r\n if (options.details !== undefined) {\r\n args.details = options.details;\r\n }\r\n if (options.deliveryMode !== undefined) {\r\n args.delivery_mode = options.deliveryMode;\r\n }\r\n return this.callToolChecked(\"update_memory\", args);\r\n }\r\n\r\n /**\r\n * Soft-delete memories (30-day retention) by specific memoryId or by\r\n * search query.\r\n *\r\n * @throws Error if neither memoryId nor query is provided.\r\n */\r\n async forget(options: {\r\n contextId: string;\r\n memoryId?: string;\r\n query?: string;\r\n /** Number of memories to delete in query mode (default 10). */\r\n k?: number;\r\n }): Promise<ToolResult> {\r\n if (!options.memoryId && !options.query) {\r\n throw new Error(\"Provide either memoryId or query\");\r\n }\r\n const args: Record<string, unknown> = { context_id: options.contextId };\r\n if (options.memoryId) {\r\n args.memory_id = options.memoryId;\r\n }\r\n if (options.query) {\r\n args.query = options.query;\r\n args.k = options.k ?? 10;\r\n }\r\n return this.callToolChecked(\"forget\", args);\r\n }\r\n\r\n /**\r\n * Create a new context in the current workspace.\r\n *\r\n * @throws KaguraQuotaError when the workspace context limit is reached.\r\n */\r\n async createContext(options: CreateContextOptions): Promise<ToolResult> {\r\n // Pre-check quota. Match the Python falsy check `not\r\n // contexts.get(\"can_create\", True)` exactly: `dict.get` substitutes the\r\n // default ONLY when the key is absent, so a present null/0/\"\"/false\r\n // (server schema drift, #183) must pass through and be negated as\r\n // \"cannot create\" — a nullish-coalescing `?? true` would wrongly treat\r\n // a present `null` as \"can create\".\r\n const contexts = await this.listContexts();\r\n const canCreate = \"can_create\" in contexts ? contexts.can_create : true;\r\n if (!canCreate) {\r\n // Coerce missing/null count/limit to \"?\" so schema drift never\r\n // produces \"null/null\" in the message; a real 0 is preserved.\r\n const count = contexts.count ?? null;\r\n const limit = contexts.limit ?? null;\r\n throw new KaguraQuotaError(\r\n `Context limit reached (${count === null ? \"?\" : String(count)}/` +\r\n `${limit === null ? \"?\" : String(limit)}). ` +\r\n \"Delete unused contexts or upgrade your plan.\",\r\n );\r\n }\r\n\r\n const args: Record<string, unknown> = {\r\n name: options.name,\r\n is_private: options.isPrivate ?? true,\r\n };\r\n if (options.displayName !== undefined) {\r\n args.display_name = options.displayName;\r\n }\r\n if (options.description !== undefined) {\r\n args.description = options.description;\r\n }\r\n if (options.summary !== undefined) {\r\n args.summary = options.summary;\r\n }\r\n if (options.usageGuide !== undefined) {\r\n args.usage_guide = options.usageGuide;\r\n }\r\n if (options.resourceId !== undefined) {\r\n args.resource_id = options.resourceId;\r\n }\r\n if (options.embeddingModel !== undefined) {\r\n args.embedding_model = options.embeddingModel;\r\n }\r\n return this.callToolChecked(\"create_context\", args);\r\n }\r\n\r\n /** Soft-delete a context and all its memories. */\r\n async deleteContext(contextId: string): Promise<ToolResult> {\r\n return this.callToolChecked(\"delete_context\", { context_id: contextId });\r\n }\r\n\r\n /** Update an existing context's settings. */\r\n async updateContext(options: UpdateContextOptions): Promise<ToolResult> {\r\n const args: Record<string, unknown> = { context_id: options.contextId };\r\n if (options.displayName !== undefined) {\r\n args.display_name = options.displayName;\r\n }\r\n if (options.description !== undefined) {\r\n args.description = options.description;\r\n }\r\n if (options.summary !== undefined) {\r\n args.summary = options.summary;\r\n }\r\n if (options.usageGuide !== undefined) {\r\n args.usage_guide = options.usageGuide;\r\n }\r\n if (options.resourceId !== undefined) {\r\n args.resource_id = options.resourceId;\r\n }\r\n if (options.isPublic !== undefined) {\r\n args.is_public = options.isPublic;\r\n }\r\n if (options.isLocked !== undefined) {\r\n args.is_locked = options.isLocked;\r\n }\r\n return this.callToolChecked(\"update_context\", args);\r\n }\r\n\r\n /**\r\n * Atomically create Context + Resource entity + ingestion token in a\r\n * single server-side transaction. The returned `token` is plaintext and\r\n * shown once.\r\n */\r\n async setupResource(options: SetupResourceOptions): Promise<ToolResult> {\r\n const args: Record<string, unknown> = {\r\n resource_id: options.resourceId,\r\n quota_events_per_hour: options.quotaEventsPerHour ?? 1000,\r\n };\r\n if (options.name !== undefined) {\r\n args.name = options.name;\r\n }\r\n if (options.summary !== undefined) {\r\n args.summary = options.summary;\r\n }\r\n if (options.description !== undefined) {\r\n args.description = options.description;\r\n }\r\n return this.callToolChecked(\"setup_resource\", args);\r\n }\r\n\r\n /**\r\n * Merge memories from one context into another. Both contexts must use\r\n * the same embedding model and belong to the same workspace.\r\n *\r\n * @throws Error if sourceId and targetId are the same.\r\n */\r\n async mergeContexts(options: {\r\n sourceId: string;\r\n targetId: string;\r\n /** Soft-delete the source context after merge. */\r\n deleteSource?: boolean;\r\n }): Promise<ToolResult> {\r\n if (options.sourceId === options.targetId) {\r\n throw new Error(\"sourceId and targetId must be different\");\r\n }\r\n const args: Record<string, unknown> = {\r\n source_context_id: options.sourceId,\r\n target_context_id: options.targetId,\r\n };\r\n if (options.deleteSource) {\r\n args.delete_source = true;\r\n }\r\n return this.callToolChecked(\"merge_contexts\", args);\r\n }\r\n\r\n /**\r\n * List neural memory edges connected to a memory (outgoing and\r\n * incoming, deduplicated).\r\n *\r\n * Note: the server applies `limit` to outgoing AND incoming queries\r\n * independently, so the practical maximum returned is `2 * limit`\r\n * minus dedup overlap.\r\n */\r\n async listEdges(options: {\r\n contextId: string;\r\n memoryId: string;\r\n /** Minimum edge weight (0.0-3.0, default 0.0). */\r\n minWeight?: number;\r\n /** Restrict to these edge types; omit for all. */\r\n edgeTypes?: string[];\r\n /** Maximum edges per direction; omit for no limit. */\r\n limit?: number;\r\n }): Promise<Edge[]> {\r\n const args: Record<string, unknown> = {\r\n context_id: options.contextId,\r\n memory_id: options.memoryId,\r\n min_weight: options.minWeight ?? 0.0,\r\n };\r\n if (options.edgeTypes !== undefined) {\r\n args.edge_types = options.edgeTypes;\r\n }\r\n if (options.limit !== undefined) {\r\n args.limit = options.limit;\r\n }\r\n const result = await this.callToolChecked(\"list_edges\", args);\r\n const edges = result.edges;\r\n return Array.isArray(edges) ? (edges as unknown as Edge[]) : [];\r\n }\r\n\r\n /**\r\n * Create or upsert a neural memory edge from source to target.\r\n *\r\n * The server uses `(user_id, source_id, target_id)` as a unique key\r\n * with max-weight UPSERT semantics — not a pure INSERT.\r\n *\r\n * @throws Error if sourceId === targetId (self-loops are rejected).\r\n */\r\n async createEdge(options: {\r\n contextId: string;\r\n sourceId: string;\r\n targetId: string;\r\n /** Edge type label (default \"related_to\"). */\r\n edgeType?: string;\r\n /** Edge weight in [0.0, 3.0] (default 0.5). */\r\n weight?: number;\r\n /** Edge confidence in [0.0, 1.0] (default 1.0). */\r\n confidence?: number;\r\n }): Promise<Edge> {\r\n if (options.sourceId === options.targetId) {\r\n throw new Error(\"sourceId and targetId must be different (self-loops are not allowed)\");\r\n }\r\n const result = await this.callToolChecked(\"create_edge\", {\r\n context_id: options.contextId,\r\n source_id: options.sourceId,\r\n target_id: options.targetId,\r\n edge_type: options.edgeType ?? \"related_to\",\r\n weight: options.weight ?? 0.5,\r\n confidence: options.confidence ?? 1.0,\r\n });\r\n return (result.edge ?? result) as unknown as Edge;\r\n }\r\n\r\n /**\r\n * Update an existing edge's weight and/or edge type, identified by the\r\n * `(sourceId, targetId)` pair. Omit a field to leave it unchanged.\r\n */\r\n async updateEdge(options: {\r\n contextId: string;\r\n sourceId: string;\r\n targetId: string;\r\n /** New edge weight in [0.0, 3.0]; omit to keep. */\r\n weight?: number;\r\n /** New edge type label; omit to keep. */\r\n edgeType?: string;\r\n }): Promise<Edge> {\r\n const args: Record<string, unknown> = {\r\n context_id: options.contextId,\r\n source_id: options.sourceId,\r\n target_id: options.targetId,\r\n };\r\n if (options.weight !== undefined) {\r\n args.weight = options.weight;\r\n }\r\n if (options.edgeType !== undefined) {\r\n args.edge_type = options.edgeType;\r\n }\r\n const result = await this.callToolChecked(\"update_edge\", args);\r\n return (result.edge ?? result) as unknown as Edge;\r\n }\r\n\r\n /**\r\n * Delete the edge between sourceId and targetId. Returns true once the\r\n * server confirms deletion.\r\n */\r\n async deleteEdge(options: {\r\n contextId: string;\r\n sourceId: string;\r\n targetId: string;\r\n }): Promise<boolean> {\r\n const result = await this.callToolChecked(\"delete_edge\", {\r\n context_id: options.contextId,\r\n source_id: options.sourceId,\r\n target_id: options.targetId,\r\n });\r\n // The server confirms a delete with {\"status\": \"success\"} and NO\r\n // \"deleted\" key; a missing edge raises above. So reaching here means\r\n // deletion was confirmed — the default true is load-bearing.\r\n return result.deleted === undefined ? true : Boolean(result.deleted);\r\n }\r\n\r\n /** Get workspace usage and quota limits. */\r\n async getUsage(): Promise<UsageInfo> {\r\n const result = await this.callToolChecked(\"get_usage\", {});\r\n return result as unknown as UsageInfo;\r\n }\r\n\r\n /** Get context information, usage guidelines, and search config. */\r\n async getContextInfo(options: {\r\n contextId: string;\r\n /** Include memory count breakdown (default true). */\r\n includeDetails?: boolean;\r\n }): Promise<ContextInfo> {\r\n const result = await this.callToolChecked(\"get_context_info\", {\r\n context_id: options.contextId,\r\n include_details: options.includeDetails ?? true,\r\n });\r\n return result as unknown as ContextInfo;\r\n }\r\n\r\n /**\r\n * Update hybrid search configuration for a context. Weights must sum\r\n * to 1.0 (±0.01). Requires owner or editor permission.\r\n */\r\n async updateSearchConfig(options: UpdateSearchConfigOptions): Promise<ToolResult> {\r\n const args: Record<string, unknown> = { context_id: options.contextId };\r\n if (options.semanticWeight !== undefined) {\r\n args.semantic_weight = options.semanticWeight;\r\n }\r\n if (options.bm25Weight !== undefined) {\r\n args.bm25_weight = options.bm25Weight;\r\n }\r\n if (options.fetchFactor !== undefined) {\r\n args.fetch_factor = options.fetchFactor;\r\n }\r\n if (options.useRerank !== undefined) {\r\n args.use_rerank = options.useRerank;\r\n }\r\n if (options.rerankerProvider !== undefined) {\r\n args.reranker_provider = options.rerankerProvider;\r\n }\r\n if (options.rerankerModel !== undefined) {\r\n args.reranker_model = options.rerankerModel;\r\n }\r\n return this.callToolChecked(\"update_search_config\", args);\r\n }\r\n\r\n /** Get server name, version, environment, and feature flags. */\r\n async getServerInfo(): Promise<ServerInfo> {\r\n return this.restGet<ServerInfo>(\"/api/v1/system/info\");\r\n }\r\n\r\n /**\r\n * Check the connected server's version against the SDK's tested\r\n * minimum. Advisory only — logs a warning, never throws on mismatch.\r\n */\r\n async checkServerVersion(): Promise<ServerInfo> {\r\n const info = await this.getServerInfo();\r\n const components = info.version.split(\".\").slice(0, 3);\r\n // Match Python's `int(x)`: a non-integer component (empty string,\r\n // \"0x1\", \"1e2\") makes the parse fail and we return without warning.\r\n // Number(\"\") is 0 and Number(\"1e2\") is 100, so guard with a strict\r\n // integer-digit test rather than relying on NaN.\r\n if (components.length === 0 || !components.every((c) => /^\\d+$/.test(c))) {\r\n return info;\r\n }\r\n const parts = components.map(Number);\r\n for (let i = 0; i < MIN_SERVER_VERSION_TUPLE.length; i++) {\r\n const server = parts[i] ?? 0;\r\n const min = MIN_SERVER_VERSION_TUPLE[i] ?? 0;\r\n if (server < min) {\r\n console.warn(\r\n `Server version ${info.version} is below the SDK's tested minimum ` +\r\n `${MIN_SERVER_VERSION}. Some features may not work; older servers ` +\r\n \"may silently ignore unknown parameters.\",\r\n );\r\n break;\r\n }\r\n if (server > min) {\r\n break;\r\n }\r\n }\r\n return info;\r\n }\r\n\r\n /** Get embedding queue status for the workspace. */\r\n async getEmbeddingStatus(): Promise<EmbeddingStatus> {\r\n return this.restGet<EmbeddingStatus>(\"/api/v1/workspace/embedding-status\");\r\n }\r\n\r\n /** Get per-memory usage statistics for a context. */\r\n async getMemoryStats(options: {\r\n contextId: string;\r\n /** Sort field (default \"use_count\"). */\r\n sortBy?: string;\r\n /** \"asc\" or \"desc\" (default \"desc\"). */\r\n sortOrder?: \"asc\" | \"desc\";\r\n /** Maximum results (1-200, default 50). */\r\n limit?: number;\r\n offset?: number;\r\n }): Promise<MemoryStatsResponse> {\r\n return this.restGet<MemoryStatsResponse>(\r\n `/api/v1/contexts/${options.contextId}/memory-stats`,\r\n {\r\n sort_by: options.sortBy ?? \"use_count\",\r\n sort_order: options.sortOrder ?? \"desc\",\r\n limit: options.limit ?? 50,\r\n offset: options.offset ?? 0,\r\n },\r\n );\r\n }\r\n\r\n /** Find duplicate memory pairs in a context. */\r\n async findDuplicates(options: {\r\n contextId: string;\r\n /** Similarity threshold (0.5-1.0, default 0.90). */\r\n threshold?: number;\r\n /** Maximum pairs (1-200, default 50). */\r\n limit?: number;\r\n }): Promise<DuplicatesResponse> {\r\n return this.restGet<DuplicatesResponse>(`/api/v1/contexts/${options.contextId}/duplicates`, {\r\n threshold: options.threshold ?? 0.9,\r\n limit: options.limit ?? 50,\r\n });\r\n }\r\n\r\n /**\r\n * List memories with optional substring, facet, and time-window\r\n * filters. Without `contextId` this returns the caller's own memories\r\n * across all contexts. `q` matches summaries only — use recall() for\r\n * semantic search.\r\n */\r\n async listMemories(options: ListMemoriesOptions = {}): Promise<MemoryListResponse> {\r\n const params: Record<string, unknown> = {\r\n limit: options.limit ?? 50,\r\n offset: options.offset ?? 0,\r\n };\r\n if (options.contextId !== undefined) {\r\n params.context_id = options.contextId;\r\n }\r\n // Normalize like the server/frontend: strip and drop whitespace-only.\r\n const qNormalized = (options.q ?? \"\").trim();\r\n if (qNormalized) {\r\n params.q = qNormalized;\r\n }\r\n if (options.scope !== undefined) {\r\n params.scope = options.scope;\r\n }\r\n if (options.type !== undefined) {\r\n params.type = options.type;\r\n }\r\n if (options.triggerFrom !== undefined) {\r\n params.trigger_from = options.triggerFrom;\r\n }\r\n if (options.triggerUntil !== undefined) {\r\n params.trigger_until = options.triggerUntil;\r\n }\r\n if (options.orderBy !== undefined) {\r\n params.order_by = options.orderBy;\r\n }\r\n return this.restGet<MemoryListResponse>(\"/api/v1/memory/list\", params);\r\n }\r\n\r\n /**\r\n * List recent Sleep Maintenance runs for a context, newest first.\r\n */\r\n async getSleepHistory(options: {\r\n contextId: string;\r\n /** Maximum runs (server clamps to 1-50, default 10). */\r\n limit?: number;\r\n }): Promise<SleepReport[]> {\r\n const result = await this.callToolChecked(\"get_sleep_history\", {\r\n context_id: options.contextId,\r\n limit: options.limit ?? 10,\r\n });\r\n // Match Python's `result[\"reports\"]`: a missing/malformed key is a\r\n // contract violation, surfaced loudly rather than as an empty success.\r\n const reports = result.reports;\r\n if (!Array.isArray(reports)) {\r\n throw new KaguraConnectionError(\r\n \"Unexpected get_sleep_history response: missing 'reports' array.\",\r\n );\r\n }\r\n return reports as unknown as SleepReport[];\r\n }\r\n\r\n /**\r\n * Get a detailed Sleep Maintenance report including the per-action\r\n * audit log.\r\n */\r\n async getSleepReport(options: {\r\n contextId: string;\r\n reportId: string;\r\n }): Promise<SleepReportDetail> {\r\n const result = await this.callToolChecked(\"get_sleep_report\", {\r\n context_id: options.contextId,\r\n report_id: options.reportId,\r\n });\r\n // The MCP tool wraps the report fields under a \"report\" key; flatten\r\n // so SleepReportDetail reads naturally without an extra `.report.`.\r\n const report = KaguraClient.expectEnvelope(result, \"report\", \"get_sleep_report\");\r\n return {\r\n ...report,\r\n actions: result.actions,\r\n action_count: result.action_count,\r\n } as unknown as SleepReportDetail;\r\n }\r\n\r\n /**\r\n * Reverse the effects of a completed Sleep Maintenance run. The server\r\n * processes actions in reverse order with per-step commits — a partial\r\n * failure means SOME actions may have been reversed before the error.\r\n */\r\n async rollbackSleepRun(options: {\r\n contextId: string;\r\n reportId: string;\r\n }): Promise<RollbackResult> {\r\n const result = await this.callToolChecked(\"rollback_sleep_run\", {\r\n context_id: options.contextId,\r\n report_id: options.reportId,\r\n });\r\n return result as unknown as RollbackResult;\r\n }\r\n\r\n /** List available embedding models with provider info and availability. */\r\n async listEmbeddingModels(): Promise<EmbeddingModelsResponse> {\r\n return this.restGet<EmbeddingModelsResponse>(\"/api/v1/system/embedding/models\");\r\n }\r\n\r\n /** Release resources. (fetch has no persistent connection to close; kept for API parity.) */\r\n async close(): Promise<void> {\r\n this.sessionId = null;\r\n }\r\n}\r\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","/**\r\n * REST client for the agent bootstrap surface (issue #3, server\r\n * v0.49.0+) — port of the Python SDK's agents_client.py bootstrap call.\r\n *\r\n * The `get_agent_bootstrap` MCP tool has a REST companion —\r\n * `POST /api/v1/agents/{agent_id}/bootstrap` (RFC-0002 P0-3, memory-cloud\r\n * #1276) — authenticated with `APIKeyOrSessionUser`, so it accepts\r\n * agent-bound member keys: a deployed agent can rehydrate its cognitive\r\n * state without opening an MCP session. POST-for-read follows the\r\n * server's `POST /api/v1/memory/pinned` precedent.\r\n *\r\n * Construction, credential resolution, lifecycle, and the base error\r\n * mapping live in {@link KaguraRestClient}; this module keeps only the\r\n * bootstrap wire call. The registry/binding CRUD is MCP-only in this SDK\r\n * (KaguraClient) — provisioning is an operator task that has an MCP\r\n * session available.\r\n */\r\n\r\nimport { buildBootstrapPayload } from \"./agentBootstrap.js\";\r\nimport type { GetAgentBootstrapOptions } from \"./agentBootstrap.js\";\r\nimport type { AgentBootstrapResponse } from \"./models.js\";\r\nimport { KaguraRestClient } from \"./restBase.js\";\r\nimport { parseUuid } from \"./uuid.js\";\r\n\r\n/**\r\n * REST API client for agent bootstrap (memory-cloud v0.49.0+).\r\n *\r\n * Use this surface when the caller holds an API key but no MCP session —\r\n * e.g. an agent-bound member key minted for a deployed agent. Against an\r\n * older server the route 404s.\r\n *\r\n * All methods may reject with:\r\n * - `KaguraAuthError` — authentication failed (401)\r\n * - `KaguraConnectionError` — invalid arguments (400) or any other\r\n * HTTP/connection error\r\n * - `KaguraNotFoundError` — agent or context not found (404). The 404 is\r\n * uniform (CWE-639) — nonexistent and not-yours are indistinguishable\r\n * by design, so a 404 does NOT prove the agent is absent.\r\n * - `KaguraQuotaError` — rate limit exceeded (429)\r\n */\r\nexport class AgentsClient extends KaguraRestClient {\r\n /**\r\n * Rehydrate an agent's cognitive state at session start.\r\n *\r\n * REST companion to `KaguraClient.getAgentBootstrap` — same options,\r\n * same composed envelope, same fail-soft component semantics (see that\r\n * method for the full contract).\r\n */\r\n async bootstrap(options: GetAgentBootstrapOptions): Promise<AgentBootstrapResponse> {\r\n let agentId: string;\r\n try {\r\n agentId = parseUuid(options.agentId);\r\n } catch {\r\n // Normalize instead of interpolating the raw input: a non-UUID\r\n // would otherwise reach the URL path and surface as a misleading\r\n // uniform 404 (or worse, a path traversal attempt).\r\n throw new Error(`agentId must be a UUID, got ${JSON.stringify(options.agentId)}`);\r\n }\r\n const resp = await this.request(\"POST\", `/api/v1/agents/${agentId}/bootstrap`, {\r\n json: buildBootstrapPayload(options),\r\n });\r\n return this.json(resp) as AgentBootstrapResponse;\r\n }\r\n}\r\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 * 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 workspace member & invitation management (#225) —\n * port of workspace_client.py.\n *\n * Owner-key operational tooling: memory-cloud v0.42.0 gates every endpoint\n * here at workspace-OWNER role for programmatic principals and rejects\n * OAuth Bearer tokens outright (\"Use a workspace-owner API key\"). The web\n * UI (session auth) keeps its own per-endpoint role semantics — this\n * client only ever sees the programmatic contract.\n *\n * Construction, credential resolution, lifecycle, and the base error\n * mapping live in {@link KaguraRestClient} (#229); this module keeps only\n * the workspace-specific wire contract: the owner-key 403 hint and the\n * detail-carrying 429 quota mapping.\n */\n\nimport { SOURCE_LABEL } from \"./auth/types.js\";\nimport { KaguraConnectionError, KaguraError, KaguraQuotaError } from \"./errors.js\";\nimport { extractDetail, retryAfterSeconds, sanitizeServerDetail } from \"./http.js\";\nimport type { MemberAPIKey, WorkspaceInvitation, WorkspaceMember } from \"./models.js\";\nimport { KaguraRestClient } from \"./restBase.js\";\nimport type { RequestContext, RestResponse } from \"./restBase.js\";\n\nexport const VALID_ASSIGNABLE_ROLES = [\"member\", \"admin\", \"viewer\"] as const;\n// \"owner\" is excluded: the server 422s programmatic role=owner on member\n// add/set-role (memory-cloud#1164 — \"use the ownership transfer flow\") and\n// rejects owner invitations for every principal (memory-cloud#1166).\n\nexport const VALID_INVITE_EXPIRES = [7, 30, 90, 365] as const;\n// Server-side preset list: any other value in the otherwise-valid 1-365\n// range still 400s at the service layer, so fail fast client-side.\n// Omitted = never expires.\n\nconst UNIFORM_403 = \"Insufficient permissions\";\n// The deliberately uniform authorization denial (CWE-639). Every other 403 on\n// this surface carries a purpose-built message (OAuth rejection, deployment\n// kill-switch, plan gate, self-role-change, key/workspace mismatch) that is\n// already actionable and must pass through untouched.\n\nconst UUID_HEX_RE = /^[0-9a-f]{32}$/i;\n\n/**\n * Return the canonical UUID string, rejecting non-UUIDs before the URL.\n *\n * Python's `uuid.UUID` tolerates non-canonical spellings (`{braces}`,\n * `urn:uuid:` prefix, dashless 32-hex, uppercase); interpolating the RAW\n * input would send those to the server and surface as a misleading uniform\n * 404 — normalize instead of just validating.\n */\nfunction normalizeWorkspaceId(workspaceId: string): string {\n const stripped = String(workspaceId)\n .replace(/^urn:/, \"\")\n .replace(/^uuid:/, \"\")\n .replace(/^[{}]+|[{}]+$/g, \"\")\n .replace(/-/g, \"\");\n if (!UUID_HEX_RE.test(stripped)) {\n throw new Error(`workspaceId must be a UUID, got ${JSON.stringify(workspaceId)}`);\n }\n const hex = stripped.toLowerCase();\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/**\n * Strictly require an integer — no float truncation, no string parse.\n *\n * Truncating `7.9` would silently target a DIFFERENT resource id on a\n * destructive endpoint (the TS signature says `number`, which admits\n * floats), so fail loudly instead.\n */\nfunction requireInt(value: number, label: string): number {\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n throw new Error(`${label} must be an integer, got ${JSON.stringify(value)}`);\n }\n return value;\n}\n\n/** Options for {@link WorkspaceClient.createInvitation}. */\nexport interface CreateInvitationOptions {\n /** `member` | `admin` | `viewer` (default: `\"member\"`). */\n role?: string;\n /**\n * Context grant — required (min 1) for member/viewer invitations,\n * ignored for admin. Sent on the wire as `allowed_context_ids`.\n */\n allowedContextIds?: string[];\n /**\n * One of 7/30/90/365 (sent as `expires_in_days`), or omit for a\n * never-expiring invitation.\n */\n expiresInDays?: number;\n}\n\n/** Options for {@link WorkspaceClient.listInvitations}. */\nexport interface ListInvitationsOptions {\n /** Include already-accepted invitations (default: false). */\n includeAccepted?: boolean;\n}\n\n/**\n * REST API client for workspace member / invitation management.\n *\n * Requires the workspace OWNER's API key when called programmatically\n * (memory-cloud v0.42.0+). OAuth profiles are rejected by the server on\n * this surface — resolve a static owner key (`KAGURA_API_KEY` env or\n * `.kagura.json`) instead.\n *\n * All methods may reject with:\n * - `KaguraAuthError` — authentication failed (401)\n * - `KaguraConnectionError` — access denied (403 — non-owner key, OAuth\n * token, or deployment kill-switch; the message says which) or any\n * other HTTP/connection error\n * - `KaguraNotFoundError` — workspace/member/invitation not found (404).\n * Also returned for a workspace-scoped key used against a different\n * workspace (uniform 404, memory-cloud #963) — a 404 here does NOT\n * prove the resource is absent.\n * - `KaguraQuotaError` — member quota or rate limit exceeded (429)\n */\nexport class WorkspaceClient extends KaguraRestClient {\n // -------------------------------------------------------------------\n // Members\n // -------------------------------------------------------------------\n\n /**\n * List workspace members (owner key required).\n *\n * Rows are ordered owner→viewer then by join date and include\n * `user_name`/`user_email` when the member has logged in.\n */\n async listMembers(workspaceId: string): Promise<WorkspaceMember[]> {\n const ws = normalizeWorkspaceId(workspaceId);\n const resp = await this.request(\"GET\", `/api/v1/workspaces/${ws}/members`);\n return this.expectList(resp) as unknown as WorkspaceMember[];\n }\n\n /**\n * Add an already-registered user to the workspace.\n *\n * The server does NOT validate that `userId` exists (v0.42.0) — a typo\n * creates a dangling membership row that lists with null name/email.\n * Prefer {@link createInvitation} for onboarding; use this only with a\n * user_id copied from a trusted source. Duplicate members are rejected\n * with 422.\n */\n async addMember(workspaceId: string, userId: string, role = \"member\"): Promise<WorkspaceMember> {\n const ws = normalizeWorkspaceId(workspaceId);\n this.validateRole(role);\n const resp = await this.request(\"POST\", `/api/v1/workspaces/${ws}/members`, {\n json: { user_id: userId, role },\n });\n return this.json(resp) as unknown as WorkspaceMember;\n }\n\n /** Change a member's role (member/admin/viewer only). */\n async updateMemberRole(\n workspaceId: string,\n userId: string,\n role: string,\n ): Promise<WorkspaceMember> {\n const ws = normalizeWorkspaceId(workspaceId);\n this.validateRole(role);\n const resp = await this.request(\n \"PUT\",\n `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}`,\n { json: { role } },\n );\n return this.json(resp) as unknown as WorkspaceMember;\n }\n\n /** Remove a member from the workspace (server returns 204). */\n async removeMember(workspaceId: string, userId: string): Promise<void> {\n const ws = normalizeWorkspaceId(workspaceId);\n await this.request(\"DELETE\", `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}`);\n }\n\n // -------------------------------------------------------------------\n // Invitations\n // -------------------------------------------------------------------\n\n /**\n * Invite a not-yet-registered user by email.\n *\n * The returned invitation carries `token`/`invitation_url` — the only\n * response that ever exposes them to programmatic callers; treat them\n * as join credentials.\n *\n * @param workspaceId Target workspace UUID.\n * @param email Invitee email (must match their Google account).\n * @param options Role, context grant, and expiry preset.\n */\n async createInvitation(\n workspaceId: string,\n email: string,\n options: CreateInvitationOptions = {},\n ): Promise<WorkspaceInvitation> {\n const ws = normalizeWorkspaceId(workspaceId);\n const role = options.role ?? \"member\";\n this.validateRole(role);\n const { allowedContextIds, expiresInDays } = options;\n if (\n (role === \"member\" || role === \"viewer\") &&\n (allowedContextIds === undefined || allowedContextIds.length === 0)\n ) {\n throw new Error(\n \"allowedContextIds is required (min 1) for member/viewer \" +\n \"invitations — the server rejects them without a context grant.\",\n );\n }\n if (\n expiresInDays !== undefined &&\n !(VALID_INVITE_EXPIRES as readonly number[]).includes(expiresInDays)\n ) {\n throw new Error(\n `expiresInDays must be one of ${VALID_INVITE_EXPIRES.join(\", \")} ` +\n \"or omitted (server-side preset list).\",\n );\n }\n const body: Record<string, unknown> = { email, role };\n if (allowedContextIds !== undefined) {\n body.allowed_context_ids = allowedContextIds;\n }\n if (expiresInDays !== undefined) {\n body.expires_in_days = expiresInDays;\n }\n const resp = await this.request(\"POST\", `/api/v1/workspaces/${ws}/invitations`, {\n json: body,\n });\n return this.json(resp) as unknown as WorkspaceInvitation;\n }\n\n /**\n * List invitations. `token`/`invitation_url` arrive as null for\n * programmatic callers (server-side token hygiene, #1164).\n */\n async listInvitations(\n workspaceId: string,\n options: ListInvitationsOptions = {},\n ): Promise<WorkspaceInvitation[]> {\n const ws = normalizeWorkspaceId(workspaceId);\n const resp = await this.request(\n \"GET\",\n `/api/v1/workspaces/${ws}/invitations`,\n options.includeAccepted ? { params: { include_accepted: \"true\" } } : {},\n );\n return this.expectList(resp) as unknown as WorkspaceInvitation[];\n }\n\n /** Revoke a pending invitation (server returns 200 `{\"success\": true}`). */\n async revokeInvitation(workspaceId: string, invitationId: number): Promise<void> {\n const ws = normalizeWorkspaceId(workspaceId);\n await this.request(\n \"DELETE\",\n `/api/v1/workspaces/${ws}/invitations/${requireInt(invitationId, \"invitationId\")}`,\n );\n }\n\n // -------------------------------------------------------------------\n // Member API keys (#201, memory-cloud#1165)\n // -------------------------------------------------------------------\n\n /**\n * Mint an API key for ANOTHER member (owner key required).\n *\n * Privilege-downgrade provisioning only: the server 403s self-targets\n * (\"An owner key cannot mint keys for itself\") and owner/admin targets\n * — mint for member/viewer service identities. `expiresDays` is\n * required by the server for owner-provisioned mints (never-expiring\n * CI keys are not allowed). The returned `plaintext_key` is shown\n * exactly once — owner-provisioned keys are force-hidden at creation,\n * so no later call returns it.\n */\n async mintMemberKey(\n workspaceId: string,\n userId: string,\n name: string,\n expiresDays: number,\n ): Promise<MemberAPIKey> {\n const ws = normalizeWorkspaceId(workspaceId);\n const days = requireInt(expiresDays, \"expiresDays\");\n if (days < 1 || days > 3650) {\n throw new Error(`expiresDays must be 1-3650, got ${JSON.stringify(days)}`);\n }\n const resp = await this.request(\n \"POST\",\n `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}/credentials/api-keys`,\n { json: { name, expires_days: days } },\n );\n const payload = this.json(resp);\n if (isMintShape(payload)) {\n return payload as unknown as MemberAPIKey;\n }\n // The key already exists server-side and is force-hidden — a shape\n // mismatch must not swallow the ONE chance to see the plaintext.\n const plaintext =\n typeof payload === \"object\" && payload !== null && !Array.isArray(payload)\n ? (payload as Record<string, unknown>).plaintext_key\n : undefined;\n if (typeof plaintext === \"string\" && plaintext) {\n throw new KaguraError(\n \"Server returned an unexpected mint response shape, but the \" +\n `key WAS created. Save the plaintext now: ${plaintext}`,\n );\n }\n throw new KaguraError(\n \"Server returned an unexpected mint response shape; the key may \" +\n \"have been created without displaying its plaintext — check \" +\n \"`kagura auth list-keys` and revoke/re-mint if present.\",\n );\n }\n\n /**\n * List a member's API keys — metadata only.\n *\n * The server wraps the rows in a `MemberCredentialsResponse` envelope\n * (`api_keys` + `target_user_role`) and always nulls `plaintext_key`\n * for programmatic callers.\n */\n async listMemberKeys(workspaceId: string, userId: string): Promise<MemberAPIKey[]> {\n const ws = normalizeWorkspaceId(workspaceId);\n const resp = await this.request(\n \"GET\",\n `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}/credentials`,\n );\n const payload = this.json(resp);\n const rows =\n typeof payload === \"object\" && payload !== null && !Array.isArray(payload)\n ? (payload as Record<string, unknown>).api_keys\n : undefined;\n if (!Array.isArray(rows)) {\n // Guard the FIELD, not just the envelope: api_keys=null would\n // produce garbage rows and api_keys={} is not iterable as rows\n // (Copilot review, PR #228 on the Python port).\n throw new KaguraConnectionError(\n \"Unexpected response shape from the member-credentials endpoint \" +\n \"(expected an object carrying an 'api_keys' array).\",\n );\n }\n return rows as unknown as MemberAPIKey[];\n }\n\n /**\n * Revoke a member's API key.\n *\n * Owner-provisioned revocations are SOFT server-side (`revoked_at`\n * set, row retained for forensics); success is 200 with a status body,\n * and an already-revoked key surfaces as a uniform 404.\n */\n async revokeMemberKey(workspaceId: string, userId: string, keyId: number): Promise<void> {\n const ws = normalizeWorkspaceId(workspaceId);\n await this.request(\n \"DELETE\",\n `/api/v1/workspaces/${ws}/members/${encodeURIComponent(userId)}` +\n `/credentials/api-keys/${requireInt(keyId, \"keyId\")}`,\n );\n }\n\n // -------------------------------------------------------------------\n // Internal helpers\n // -------------------------------------------------------------------\n\n private validateRole(role: string): void {\n if (!(VALID_ASSIGNABLE_ROLES as readonly string[]).includes(role)) {\n throw new Error(\n `role must be one of ${VALID_ASSIGNABLE_ROLES.join(\", \")}, got ` +\n `${JSON.stringify(role)}. Assigning 'owner' is not supported ` +\n \"programmatically — the server directs owner changes to the \" +\n \"ownership transfer flow.\",\n );\n }\n }\n\n /**\n * Build the 403 message, appending the owner-key hint only when useful.\n *\n * v0.42.0 sends purpose-built 403 messages on this surface (OAuth\n * rejection, deployment kill-switch, plan gate, self-role-change,\n * key/workspace mismatch) — those pass through untouched. Only the\n * deliberately uniform denial gets the owner-key hint, because that is\n * the one a non-owner static key actually hits.\n */\n private format403(serverDetail: string): string {\n const safeDetail = sanitizeServerDetail(serverDetail);\n if (safeDetail && safeDetail !== UNIFORM_403) {\n return safeDetail;\n }\n const parts = [\n \"Access denied (HTTP 403): workspace member/invitation/credential \" +\n \"management requires the workspace OWNER's API key when called \" +\n \"programmatically (OAuth tokens are not accepted).\",\n ];\n if (this.authSource !== null) {\n let hint = `credential source: ${SOURCE_LABEL[this.authSource]}`;\n if (this.workspaceIdHint) {\n hint += ` (workspace=${this.workspaceIdHint.slice(0, 8)}…)`;\n }\n parts.push(hint + \" — is this key the workspace owner's?\");\n }\n return parts.join(\" \");\n }\n\n // ---- KaguraRestClient hooks -----------------------------------------\n\n protected override error403(response: RestResponse, _context: RequestContext): KaguraError {\n return new KaguraConnectionError(this.format403(extractDetail(response.text)));\n }\n\n protected override error429(response: RestResponse): KaguraError {\n // Invite-create quota exhaustion (\"Member limit reached ...\") and\n // generic rate limiting both surface as 429 — keep the server\n // message, it names the cause and the fix.\n return new KaguraQuotaError(\n extractDetail(response.text) || \"Quota exceeded. Try again later.\",\n retryAfterSeconds(response.headers),\n );\n }\n}\n\n/**\n * Minimal structural check standing in for pydantic's required-field\n * validation on the mint response — the fields `MemberAPIKey` requires.\n * Everything else is trusted per the SDK's no-runtime-validation policy;\n * this one endpoint gets a guard because a mis-shaped 201 would otherwise\n * silently discard the only copy of the plaintext key.\n */\nfunction isMintShape(payload: unknown): payload is Record<string, unknown> {\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n return false;\n }\n const rec = payload as Record<string, unknown>;\n return (\n typeof rec.id === \"number\" && typeof rec.name === \"string\" && typeof rec.key_prefix === \"string\"\n );\n}\n","/**\r\n * Interactive OAuth login — the one step the SDK could not do on its own.\r\n *\r\n * `deviceFlow.ts` provides the stateless RFC 8628 primitives and\r\n * `credentials.ts` the Python-CLI-compatible store; this module is the thin\r\n * orchestrator that joins them: authorize → hand the user code to the host\r\n * app → poll → persist. It is what lets a TypeScript-only consumer (an\r\n * Electron app, a CLI of its own) obtain credentials instead of requiring\r\n * the user to install and run the Python `kagura auth login` first.\r\n *\r\n * Deliberately still no terminal IO and no browser launching: `onUserCode`\r\n * hands the code and verification URI back to the caller, which owns how it\r\n * is displayed. The only side effect is the credentials file write.\r\n */\r\n\r\nimport { baseUrlFromMcp, validateHttpsUrl } from \"../http.js\";\r\nimport type { OAuthCredentials } from \"./credentials.js\";\r\nimport { setDefaultProfile, updateProfile } from \"./credentials.js\";\r\nimport { authorizeDevice, pollForToken, DEFAULT_CLIENT_ID } from \"./deviceFlow.js\";\r\nimport type { DeviceAuthorizationResponse } from \"./deviceFlow.js\";\r\nimport { DEFAULT_MCP_URL } from \"./resolve.js\";\r\n\r\n/**\r\n * Scope requested when `login()` is called without one.\r\n *\r\n * Read **and** write, matching the Python CLI's `kagura auth login`\r\n * default. The credentials file is shared between both SDKs, so a profile\r\n * must not end up with different authority depending on which one wrote\r\n * it. Opt down with `scope: READ_ONLY_SCOPE` — the CLI's `--read-only`.\r\n */\r\nexport const DEFAULT_SCOPE = \"memory:read memory:write\";\r\n\r\n/** Read-only scope; the Python CLI's `--read-only`. */\r\nexport const READ_ONLY_SCOPE = \"memory:read\";\r\n\r\nexport interface LoginOptions {\r\n /**\r\n * MCP endpoint to log into. The OAuth endpoints are derived from it, and\r\n * both URLs are stored on the profile so the pair can never drift apart.\r\n *\r\n * Resolution mirrors the Python CLI's `--server` chain: this option,\r\n * then `KAGURA_MCP_URL`, then {@link DEFAULT_MCP_URL}. Plain HTTP is\r\n * rejected for non-loopback hosts — the flow carries a bearer token.\r\n */\r\n mcpUrl?: string;\r\n /** Environment source override (for tests; default: `process.env`). */\r\n env?: Record<string, string | undefined>;\r\n /** OAuth client ID (default {@link DEFAULT_CLIENT_ID}). */\r\n clientId?: string;\r\n /**\r\n * Requested scope. Defaults to {@link DEFAULT_SCOPE} (read + write), the\r\n * same default as the Python CLI's `kagura auth login`. Pass\r\n * {@link READ_ONLY_SCOPE} for the CLI's `--read-only` behaviour.\r\n */\r\n scope?: string;\r\n /** Profile name to store under (default `\"default\"`). */\r\n profile?: string;\r\n /** Credentials file path (default `~/.kagura/credentials.json`). */\r\n credentialsPath?: string;\r\n /**\r\n * Make this profile the default even when others already exist.\r\n *\r\n * Off by default: the first profile ever written is promoted\r\n * automatically, so adding a second one leaves the user's existing\r\n * default alone unless they ask for the switch.\r\n */\r\n setAsDefault?: boolean;\r\n /**\r\n * Called once with the device-authorization response before polling\r\n * starts — display `userCode` and `verificationUri` (or open\r\n * `verificationUriComplete`) here.\r\n *\r\n * Awaited, and a throw aborts the login before any polling or disk\r\n * write, so a host app that cannot show the code fails fast.\r\n */\r\n onUserCode?: (auth: DeviceAuthorizationResponse) => void | Promise<void>;\r\n /** Injectable fetch (tests / custom agents). */\r\n fetch?: typeof globalThis.fetch;\r\n /** Injectable sleep in milliseconds, used between polls. */\r\n sleep?: (ms: number) => Promise<void>;\r\n}\r\n\r\n/**\r\n * Run the full device-authorization login and persist the result.\r\n *\r\n * @returns the credentials that were written.\r\n * @throws KaguraAuthDeniedError the user denied at the consent screen.\r\n * @throws KaguraAuthExpiredError the device code expired before approval.\r\n * @throws KaguraAuthError propagated from the device-flow primitives on a\r\n * protocol/response failure.\r\n * @throws KaguraConnectionError the server was unreachable.\r\n *\r\n * Nothing is written unless the token exchange succeeds, so a failed login\r\n * never disturbs an existing profile. A response with no `refresh_token`\r\n * warns and still persists (matching the Python CLI); check the returned\r\n * `refreshToken` if the caller needs to react.\r\n */\r\nexport async function login(options: LoginOptions = {}): Promise<OAuthCredentials> {\r\n const env = options.env ?? process.env;\r\n // Explicit arg > KAGURA_MCP_URL > public default, matching the Python\r\n // CLI. Without the env step a self-hosted user with KAGURA_MCP_URL set\r\n // would be silently logged in to the public cloud instead.\r\n const mcpUrl = options.mcpUrl?.trim() || env.KAGURA_MCP_URL?.trim() || DEFAULT_MCP_URL;\r\n // The device flow carries a bearer token back over this connection, so\r\n // the destination is validated before any request goes out.\r\n validateHttpsUrl(mcpUrl, \"MCP URL\");\r\n const server = baseUrlFromMcp(mcpUrl);\r\n const clientId = options.clientId ?? DEFAULT_CLIENT_ID;\r\n const profile = options.profile ?? \"default\";\r\n\r\n const authorization = await authorizeDevice(server, {\r\n clientId,\r\n scope: options.scope ?? DEFAULT_SCOPE,\r\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\r\n });\r\n\r\n await options.onUserCode?.(authorization);\r\n\r\n const token = await pollForToken(server, {\r\n clientId,\r\n deviceCode: authorization.deviceCode,\r\n interval: authorization.interval,\r\n expiresAt: authorization.expiresAt,\r\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\r\n ...(options.sleep !== undefined ? { sleep: options.sleep } : {}),\r\n });\r\n\r\n // A response with no refresh_token yields a profile that cannot\r\n // auto-refresh. Python treats that as a legitimate degraded state — it\r\n // writes the profile and reports `refreshable: false` from\r\n // `kagura auth status` — so this SDK must not reject a state the other\r\n // one considers valid on the file they share. Warn instead: the caller\r\n // can also branch on the returned `refreshToken`.\r\n if (!token.refreshToken) {\r\n console.warn(\r\n \"Logged in, but the token response carried no refresh_token: this \" +\r\n \"profile cannot auto-refresh and will need another login when the \" +\r\n `access token expires. Verify the '${clientId}' client is allowed ` +\r\n `offline access on ${server}.`,\r\n );\r\n }\r\n\r\n const credentials: OAuthCredentials = {\r\n server,\r\n mcpUrl,\r\n clientId,\r\n accessToken: token.accessToken,\r\n refreshToken: token.refreshToken,\r\n tokenType: token.tokenType,\r\n expiresAt: token.expiresAt,\r\n scope: token.scope,\r\n workspaceId: token.workspaceId,\r\n workspaceName: token.workspaceName,\r\n userEmail: token.userEmail,\r\n issuedAt: new Date(),\r\n };\r\n\r\n await updateProfile(profile, credentials, options.credentialsPath);\r\n if (options.setAsDefault) {\r\n await setDefaultProfile(profile, options.credentialsPath);\r\n }\r\n return credentials;\r\n}\r\n","/**\r\n * Explicit credential refresh — the `kagura auth refresh` counterpart.\r\n *\r\n * Auto-refresh already happens inside {@link KaguraOAuth} as tokens near\r\n * expiry, so this is for the cases that skew-driven rotation cannot cover:\r\n * a token revoked out-of-band (rejected server-side while still outside\r\n * the skew window), a deliberate scope change, or a pre-flight refresh\r\n * before a long batch.\r\n *\r\n * Like `login()`, this owns no terminal IO — the device-flow fallback\r\n * hands the user code back through `onUserCode`.\r\n */\r\n\r\nimport { KaguraAuthError } from \"../errors.js\";\r\nimport type { OAuthCredentials } from \"./credentials.js\";\r\nimport {\r\n KaguraOAuth,\r\n getSharedState,\r\n loadCredentialsFile,\r\n updateProfile,\r\n} from \"./credentials.js\";\r\nimport { authorizeDevice, pollForToken } from \"./deviceFlow.js\";\r\nimport type { DeviceAuthorizationResponse } from \"./deviceFlow.js\";\r\n\r\nexport interface RefreshOptions {\r\n /** Profile to refresh (default: the file's default profile). */\r\n profile?: string;\r\n /** Credentials file path (default `~/.kagura/credentials.json`). */\r\n credentialsPath?: string;\r\n /**\r\n * Request a different scope.\r\n *\r\n * Narrowing goes through the refresh grant silently. Widening needs\r\n * fresh consent, so a server rejection triggers a full device flow —\r\n * see {@link RefreshOptions.onUserCode}.\r\n */\r\n scope?: string;\r\n /**\r\n * Called with the device-authorization response when a scope widening\r\n * forces re-consent. Required in practice for that path: without it the\r\n * user is never shown the code, and polling times out.\r\n */\r\n onUserCode?: (auth: DeviceAuthorizationResponse) => void | Promise<void>;\r\n /** Injectable fetch (tests / custom agents). */\r\n fetch?: typeof globalThis.fetch;\r\n /** Injectable sleep in milliseconds, used between device-flow polls. */\r\n sleep?: (ms: number) => Promise<void>;\r\n}\r\n\r\n/** Whether an auth failure is the server refusing a wider grant. */\r\nfunction isScopeRejection(error: unknown): boolean {\r\n if (!(error instanceof KaguraAuthError)) {\r\n return false;\r\n }\r\n const message = error.message.toLowerCase();\r\n return message.includes(\"insufficient_scope\") || message.includes(\"invalid_scope\");\r\n}\r\n\r\n/**\r\n * Refresh a stored profile's access token and persist the result.\r\n *\r\n * @returns the credentials that were written.\r\n * @throws Error if the named profile does not exist.\r\n * @throws KaguraAuthExpiredError the refresh token is no longer valid —\r\n * the stored profile is left untouched so it can still be inspected.\r\n * @throws KaguraAuthError other protocol/response failures.\r\n * @throws KaguraConnectionError the server was unreachable.\r\n */\r\nexport async function refresh(options: RefreshOptions = {}): Promise<OAuthCredentials> {\r\n const cf = loadCredentialsFile(options.credentialsPath);\r\n const target = options.profile || cf.defaultProfile;\r\n const stored = cf.profiles[target];\r\n if (stored === undefined) {\r\n throw new Error(`No profile named '${target}'. Run a login first.`);\r\n }\r\n\r\n const httpOptions = options.fetch !== undefined ? { fetch: options.fetch } : {};\r\n\r\n // Delegate to KaguraOAuth rather than driving refreshAccessToken here:\r\n // it holds the cross-process file lock across the whole\r\n // read-check-refresh-persist sequence, so a peer that rotated while we\r\n // waited is adopted instead of racing us into an `invalid_grant` on a\r\n // token that is already stale on disk.\r\n const state = getSharedState(options.credentialsPath, target);\r\n if (state === null) {\r\n throw new Error(`No profile named '${target}'. Run a login first.`);\r\n }\r\n const provider = new KaguraOAuth(state, httpOptions);\r\n\r\n try {\r\n await provider.forceRefresh(options.scope !== undefined ? { scope: options.scope } : {});\r\n return state.credentials;\r\n } catch (e) {\r\n // A rejection only means \"widen\" when the caller actually asked for a\r\n // different scope; otherwise re-consent would be the wrong response\r\n // to what is simply a failed refresh.\r\n if (options.scope === undefined || !isScopeRejection(e)) {\r\n throw e;\r\n }\r\n // Runs outside the lock — forceRefresh released it on the way out, and\r\n // updateProfile below re-acquires it, so there is no deadlock.\r\n const next = await consentToWiderScope(state.credentials, options.scope, options, httpOptions);\r\n await updateProfile(target, next, options.credentialsPath);\r\n state.credentials = next;\r\n return next;\r\n }\r\n}\r\n\r\n/**\r\n * Re-run the device flow to collect consent for a wider grant.\r\n *\r\n * Mirrors the Python CLI's fallback: narrowing succeeds through the\r\n * refresh grant, widening needs the user to approve again. Diverging here\r\n * would make `--scope` widening behave differently between the two SDKs\r\n * on the credentials file they share.\r\n */\r\nasync function consentToWiderScope(\r\n stored: OAuthCredentials,\r\n scope: string,\r\n options: RefreshOptions,\r\n httpOptions: { fetch?: typeof globalThis.fetch },\r\n): Promise<OAuthCredentials> {\r\n // Without a way to show the code, polling would just run until the\r\n // device code expires. Fail now, while the cause is still legible.\r\n if (options.onUserCode === undefined) {\r\n throw new KaguraAuthError(\r\n `Widening the scope to '${scope}' needs fresh consent, which requires ` +\r\n \"showing the user a device code — pass onUserCode to refresh(). \" +\r\n \"Narrowing a scope does not need consent and works without it.\",\r\n );\r\n }\r\n\r\n const authorization = await authorizeDevice(stored.server, {\r\n clientId: stored.clientId,\r\n scope,\r\n ...httpOptions,\r\n });\r\n\r\n await options.onUserCode(authorization);\r\n\r\n const token = await pollForToken(stored.server, {\r\n clientId: stored.clientId,\r\n deviceCode: authorization.deviceCode,\r\n interval: authorization.interval,\r\n expiresAt: authorization.expiresAt,\r\n ...httpOptions,\r\n ...(options.sleep !== undefined ? { sleep: options.sleep } : {}),\r\n });\r\n\r\n // A fresh grant carries its own identity fields; fall back to the\r\n // stored ones only where the response is silent.\r\n return {\r\n ...stored,\r\n accessToken: token.accessToken,\r\n refreshToken: token.refreshToken || stored.refreshToken,\r\n tokenType: token.tokenType,\r\n expiresAt: token.expiresAt,\r\n scope: token.scope || scope,\r\n workspaceId: token.workspaceId || stored.workspaceId,\r\n workspaceName: token.workspaceName || stored.workspaceName,\r\n userEmail: token.userEmail || stored.userEmail,\r\n issuedAt: new Date(),\r\n };\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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KAAK;AAAA,EACrB;AACF;","names":["fs","os","path","sleep","sleepMs","fs","path","import_promises","sleep","stringOr","path","path","import_promises","path","safeDetail"]}
|