memorysync-sdk 1.7.0 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/connections.ts","../src/control-plane.ts"],"sourcesContent":["/**\r\n * MemorySync SDK — JavaScript / TypeScript client.\r\n *\r\n * Wraps the public REST surface of MemorySync. Every method here maps 1:1\r\n * to a route that exists in the backend; field names mirror the on-the-wire\r\n * JSON exactly (snake_case is preserved on payloads, camelCase is exposed\r\n * on the public TypeScript API).\r\n */\r\n\r\n// ───────────────────────────────────────────────────────────────────────\r\n// Types\r\n// ───────────────────────────────────────────────────────────────────────\r\n\r\nexport interface MemorySyncConfig {\r\n apiKey: string;\r\n baseUrl: string;\r\n projectId?: string;\r\n endUserId?: string;\r\n timeoutMs?: number;\r\n fetch?: typeof fetch;\r\n}\r\n\r\nexport interface AddRequest {\r\n text: string;\r\n source?: string;\r\n tags?: string[];\r\n importance?: number;\r\n sessionId?: string;\r\n metadata?: Record<string, unknown>;\r\n endUserId?: string;\r\n}\r\n\r\nexport interface MemoryRecord {\r\n id: number;\r\n text: string;\r\n summary?: string | null;\r\n tags?: string[] | null;\r\n source?: string | null;\r\n eventType?: string | null;\r\n importance?: number | null;\r\n metadata?: Record<string, unknown> | null;\r\n isSummary: boolean;\r\n createdAt: string;\r\n updatedAt?: string | null;\r\n score?: number | null;\r\n}\r\n\r\nexport interface AddSkippedResponse {\r\n status: \"skipped\";\r\n reason: string;\r\n memoryIds: number[];\r\n candidatesExtracted: number;\r\n candidatesStored: number;\r\n}\r\n\r\nexport type AddResponse = MemoryRecord | AddSkippedResponse;\r\n\r\nexport interface BulkAddItem {\r\n text: string;\r\n source?: string;\r\n eventType?: string;\r\n tags?: string[];\r\n metadata?: Record<string, unknown>;\r\n importance?: number;\r\n endUserId?: string;\r\n}\r\n\r\nexport interface BulkAddItemResult {\r\n index: number;\r\n status: \"created\" | \"skipped\" | \"rejected\";\r\n memoryIds: number[];\r\n reason: string | null;\r\n}\r\n\r\nexport interface BulkAddResponse {\r\n total: number;\r\n created: number;\r\n skipped: number;\r\n rejected: number;\r\n results: BulkAddItemResult[];\r\n}\r\n\r\nexport interface QueryFilters {\r\n memoryType?: string;\r\n source?: string;\r\n tags?: string[];\r\n since?: string;\r\n until?: string;\r\n includeSummaries?: boolean;\r\n tier?: \"hot\" | \"warm\" | \"cold\";\r\n}\r\n\r\nexport interface QueryRequest {\r\n query: string;\r\n k?: number;\r\n filters?: QueryFilters;\r\n sessionId?: string;\r\n traversalDepth?: number;\r\n}\r\n\r\nexport interface QueryResponse {\r\n memories: MemoryRecord[];\r\n context?: string | null;\r\n latencyMs?: number | null;\r\n sessionId?: string | null;\r\n queryIntent?: string | null;\r\n}\r\n\r\nexport interface UpdateRequest {\r\n tags?: string[];\r\n importance?: number;\r\n metadata?: Record<string, unknown>;\r\n source?: string;\r\n eventType?: string;\r\n}\r\n\r\nexport interface SummarizeRequest {\r\n memoryIds: number[];\r\n lossless?: boolean;\r\n}\r\n\r\nexport interface ComposeRequest {\r\n promptTemplate: string;\r\n recallK?: number;\r\n maxTokens?: number;\r\n}\r\n\r\nexport interface ComposeResponse {\r\n composedPrompt: string;\r\n memoriesUsed: number;\r\n tokenCount: number;\r\n truncated: boolean;\r\n}\r\n\r\nexport type RelationshipType =\r\n | \"similar\"\r\n | \"derived_from\"\r\n | \"continuation\"\r\n | \"contradiction\"\r\n | \"summary_of\"\r\n | \"detail_of\"\r\n | \"caused_by\"\r\n | \"references\"\r\n | \"supports\"\r\n | \"extends\";\r\n\r\nexport interface RelationCreateRequest {\r\n toMemoryId: number;\r\n relationshipType: RelationshipType;\r\n confidence?: number;\r\n metadata?: Record<string, unknown>;\r\n}\r\n\r\nexport interface RelationRecord {\r\n id: number;\r\n fromMemoryId: number;\r\n toMemoryId: number;\r\n relationshipType: RelationshipType;\r\n confidence: number;\r\n metadata?: Record<string, unknown> | null;\r\n createdAt: string;\r\n}\r\n\r\nexport interface ExportResponse {\r\n userId: number;\r\n memories: Array<Record<string, unknown>>;\r\n generatedAt: string;\r\n}\r\n\r\n// ───────────────────────────────────────────────────────────────────────\r\n// Errors\r\n// ───────────────────────────────────────────────────────────────────────\r\n\r\nimport {\r\n AuthError,\r\n ErrorOptions,\r\n MemorySyncError,\r\n NotFoundError,\r\n RateLimitError,\r\n ServerError,\r\n ValidationError,\r\n} from \"./errors\";\r\n\r\nexport {\r\n AuthError,\r\n MemorySyncError,\r\n NotFoundError,\r\n RateLimitError,\r\n ServerError,\r\n ValidationError,\r\n} from \"./errors\";\r\n\r\ntype ErrorOpts = ErrorOptions;\r\n\r\n// ───────────────────────────────────────────────────────────────────────\r\n// Internals\r\n// ───────────────────────────────────────────────────────────────────────\r\n\r\nconst SDK_VERSION = \"1.7.0\";\r\n\r\n// ── Phase 1 feature types ────────────────────────────────────────────\r\n\r\n/** One edit inside a {@link MemorySyncClient.batchUpdate} call. */\r\nexport interface BatchUpdateItem {\r\n memoryId: number;\r\n tags?: string[];\r\n importance?: number;\r\n metadata?: Record<string, unknown>;\r\n source?: string;\r\n eventType?: string;\r\n}\r\n\r\nexport interface BatchUpdateItemResult {\r\n index: number;\r\n memoryId: number;\r\n status: \"updated\" | \"not_found\";\r\n changedFields: string[];\r\n}\r\n\r\n/**\r\n * Result of a batch update.\r\n *\r\n * The server answers `207 Multi-Status`: a batch may legitimately name a memory\r\n * the caller cannot see, and the caller needs to know which one rather than\r\n * losing the whole request. `notFound` is an ordinary outcome, not an error.\r\n */\r\nexport interface BatchUpdateResponse {\r\n total: number;\r\n updated: number;\r\n notFound: number;\r\n results: BatchUpdateItemResult[];\r\n}\r\n\r\n/**\r\n * Criteria for a filter-based delete.\r\n *\r\n * At least one field must be set — an all-empty filter would mean \"delete\r\n * everything I own\", which has to be an explicit `purgeUser()` call instead.\r\n * `tags` matches memories carrying **all** the listed tags, not any of them.\r\n */\r\nexport interface ForgetFilters {\r\n source?: string;\r\n eventType?: string;\r\n tags?: string[];\r\n tier?: string;\r\n before?: string;\r\n after?: string;\r\n}\r\n\r\nexport interface ForgetRequest {\r\n memoryIds?: number[];\r\n filters?: ForgetFilters;\r\n /** Return the ids that *would* be deleted without deleting anything. */\r\n dryRun?: boolean;\r\n reason?: string;\r\n}\r\n\r\nexport type RevisionEvent =\r\n | \"created\"\r\n | \"updated\"\r\n | \"superseded\"\r\n | \"soft_deleted\"\r\n | \"restored\"\r\n | \"archived\"\r\n | \"purged\";\r\n\r\n/**\r\n * One recorded change to a memory.\r\n *\r\n * Revision 0 is the creation entry, synthesised by the server. `actor` is `null`\r\n * for changes made by background workers, which have no request behind them —\r\n * that is expected rather than missing data.\r\n */\r\nexport interface RevisionEntry {\r\n revision: number;\r\n event: RevisionEvent;\r\n changedFields: string[];\r\n diff: Record<string, { old?: unknown; new?: unknown }>;\r\n actor: string | null;\r\n createdAt: string;\r\n}\r\n\r\nexport interface HistoryResponse {\r\n memoryId: number;\r\n total: number;\r\n revisions: RevisionEntry[];\r\n /**\r\n * The fields changes are recorded for. Worth reading: only user-meaningful\r\n * fields are tracked, so without this you cannot tell \"nothing changed\" from\r\n * \"that change is not recorded\".\r\n */\r\n trackedFields: string[];\r\n}\r\n\r\nexport type FeedbackSignal = \"positive\" | \"negative\" | \"retrieved\" | \"ignored\";\r\n\r\nexport interface FeedbackTrend {\r\n momentum: string;\r\n consistency: number;\r\n trendMultiplier: number;\r\n recentCount: number;\r\n}\r\n\r\nexport interface FeedbackSummary {\r\n totalSignals: number;\r\n signalCounts: Record<string, number>;\r\n trend: FeedbackTrend;\r\n}\r\n\r\nexport interface FeedbackResponse {\r\n memoryId: number;\r\n signal: FeedbackSignal;\r\n importanceBefore: number;\r\n importanceAfter: number;\r\n /** Delta actually applied. `0` when ranking influence is off, or when the change was clamped at the bounds. */\r\n adjustment: number;\r\n /** Whether this signal was allowed to change ranking. Reported, not assumed. */\r\n influencedRanking: boolean;\r\n summary: FeedbackSummary;\r\n}\r\n\r\n/**\r\n * The memory vocabulary in effect for an organization.\r\n *\r\n * The built-in types are a floor: they always apply and cannot be removed,\r\n * because dropping a type would leave memories already filed under it invisible\r\n * to any typed retrieval. Only `custom*` entries are removable.\r\n */\r\nexport interface Ontology {\r\n contentTypes: string[];\r\n relationTypes: string[];\r\n builtinContentTypes: string[];\r\n builtinRelationTypes: string[];\r\n customContentTypes: string[];\r\n customRelationTypes: string[];\r\n maxCustomTypes: number;\r\n}\r\n\r\nexport interface OntologyUpdateRequest {\r\n contentTypes?: string[];\r\n relationTypes?: string[];\r\n}\r\n\r\nexport interface UploadRequest {\r\n /** File contents. A `Blob`/`File` in browsers and Node 18+, or a `Uint8Array`. */\r\n file: Blob | Uint8Array;\r\n /** Required: the server picks its parser from the extension. */\r\n filename: string;\r\n contentType?: string;\r\n source?: string;\r\n metadata?: Record<string, unknown>;\r\n endUserId?: string;\r\n}\r\n\r\nimport {\r\n ConnectionsNamespace,\r\n IntegrationsNamespace,\r\n ObjectsNamespace,\r\n ProvidersNamespace,\r\n SyncJobsNamespace,\r\n type RequestFn,\r\n} from \"./connections\";\r\n\r\nfunction camelToSnakeKey(key: string): string {\r\n return key.replace(/([A-Z])/g, \"_$1\").toLowerCase();\r\n}\r\n\r\nfunction camelToSnakeShallow(obj: Record<string, unknown> | undefined | null): Record<string, unknown> | undefined {\r\n if (!obj) return undefined;\r\n const out: Record<string, unknown> = {};\r\n for (const [k, v] of Object.entries(obj)) {\r\n if (v === undefined) continue;\r\n out[camelToSnakeKey(k)] = v;\r\n }\r\n return out;\r\n}\r\n\r\nfunction snakeToCamelMemory(m: Record<string, unknown>): MemoryRecord {\r\n return {\r\n id: m.id as number,\r\n text: (m.text as string) ?? \"\",\r\n summary: (m.summary as string | null) ?? null,\r\n tags: (m.tags as string[] | null) ?? null,\r\n source: (m.source as string | null) ?? null,\r\n eventType: (m.event_type as string | null) ?? null,\r\n importance: (m.importance as number | null) ?? null,\r\n metadata: (m.metadata as Record<string, unknown> | null) ?? null,\r\n isSummary: Boolean(m.is_summary),\r\n createdAt: m.created_at as string,\r\n updatedAt: (m.updated_at as string | null) ?? null,\r\n score: (m.score as number | null) ?? null,\r\n };\r\n}\r\n\r\n/**\r\n * Render a query string, omitting anything the caller did not set.\r\n *\r\n * `undefined` and `null` are dropped rather than serialised: sending `depth=`\r\n * makes the server parse an empty string, which is a different request from not\r\n * asking for a depth at all.\r\n */\r\nfunction buildQuery(params?: Record<string, unknown>): string {\r\n if (!params) return \"\";\r\n const search = new URLSearchParams();\r\n for (const [key, value] of Object.entries(params)) {\r\n if (value === undefined || value === null) continue;\r\n if (Array.isArray(value)) {\r\n for (const item of value) {\r\n if (item !== undefined && item !== null) search.append(key, String(item));\r\n }\r\n } else {\r\n search.append(key, String(value));\r\n }\r\n }\r\n const qs = search.toString();\r\n return qs ? `?${qs}` : \"\";\r\n}\r\n\r\nfunction safeJson(text: string): unknown {\r\n try {\r\n return JSON.parse(text);\r\n } catch {\r\n return text;\r\n }\r\n}\r\n\r\nfunction extractDetail(body: unknown): string | undefined {\r\n if (!body || typeof body !== \"object\") return undefined;\r\n const b = body as Record<string, unknown>;\r\n if (typeof b.detail === \"string\") return b.detail;\r\n if (b.error && typeof b.error === \"object\") {\r\n const e = b.error as Record<string, unknown>;\r\n if (typeof e.message === \"string\") return e.message;\r\n }\r\n if (Array.isArray(b.detail) && b.detail.length > 0) {\r\n const first = b.detail[0] as Record<string, unknown>;\r\n if (typeof first.msg === \"string\") return first.msg;\r\n }\r\n return undefined;\r\n}\r\n\r\nfunction extractRetryAfter(body: unknown): number {\r\n if (!body || typeof body !== \"object\") return 0;\r\n const b = body as Record<string, unknown>;\r\n if (typeof b.retry_after === \"number\") return b.retry_after;\r\n if (b.error && typeof b.error === \"object\") {\r\n const e = b.error as Record<string, unknown>;\r\n if (typeof e.retry_after === \"number\") return e.retry_after;\r\n }\r\n return 0;\r\n}\r\n\r\n// ───────────────────────────────────────────────────────────────────────\r\n// Client\r\n// ───────────────────────────────────────────────────────────────────────\r\n\r\nexport class MemorySyncClient {\r\n private readonly apiKey: string;\r\n private readonly baseUrl: string;\r\n private readonly projectId?: string;\r\n private readonly endUserId?: string;\r\n private readonly timeoutMs: number;\r\n private readonly fetchImpl: typeof fetch;\r\n\r\n /** Connections to external sources, with provider sub-namespaces. */\r\n readonly connections: ConnectionsNamespace;\r\n /** Individual objects a connector ingested. */\r\n readonly objects: ObjectsNamespace;\r\n /** Connectors this deployment supports. */\r\n readonly providers: ProvidersNamespace;\r\n /** Individual sync runs. */\r\n readonly syncJobs: SyncJobsNamespace;\r\n /** The legacy `/api/v1/integrations` surface, including the web crawler. */\r\n readonly integrations: IntegrationsNamespace;\r\n\r\n constructor(config: MemorySyncConfig) {\r\n if (!config.apiKey?.trim()) throw new Error(\"apiKey is required\");\r\n if (!config.baseUrl?.trim()) throw new Error(\"baseUrl is required\");\r\n this.apiKey = config.apiKey;\r\n this.baseUrl = config.baseUrl.replace(/\\/$/, \"\");\r\n this.projectId = config.projectId;\r\n this.endUserId = config.endUserId;\r\n this.timeoutMs = config.timeoutMs ?? 30_000;\r\n const f = config.fetch ?? (typeof fetch !== \"undefined\" ? fetch : undefined);\r\n if (!f) {\r\n throw new Error(\"No fetch implementation available. Pass `fetch` in config or use Node 18+.\");\r\n }\r\n this.fetchImpl = f;\r\n\r\n // Bound so the namespaces carry no transport of their own and inherit every\r\n // header, timeout and error mapping this client applies.\r\n const request: RequestFn = (method, path, options) =>\r\n this.request(method, path, options ?? {});\r\n this.connections = new ConnectionsNamespace(request);\r\n this.objects = new ObjectsNamespace(request);\r\n this.providers = new ProvidersNamespace(request);\r\n this.syncJobs = new SyncJobsNamespace(request);\r\n this.integrations = new IntegrationsNamespace(request);\r\n }\r\n\r\n private headers(extra: Record<string, string> = {}): Record<string, string> {\r\n const h: Record<string, string> = {\r\n \"X-API-Key\": this.apiKey,\r\n \"Content-Type\": \"application/json\",\r\n \"Accept\": \"application/json\",\r\n \"User-Agent\": `memorysync-sdk-js/${SDK_VERSION}`,\r\n ...extra,\r\n };\r\n if (this.projectId) h[\"X-Project-ID\"] = this.projectId;\r\n if (this.endUserId) h[\"X-End-User-ID\"] = this.endUserId;\r\n return h;\r\n }\r\n\r\n private async request<T>(\r\n method: string,\r\n path: string,\r\n options: {\r\n body?: unknown;\r\n query?: Record<string, unknown>;\r\n form?: FormData;\r\n endUserOverride?: string;\r\n } = {},\r\n ): Promise<T> {\r\n const url = `${this.baseUrl}${path}${buildQuery(options.query)}`;\r\n const controller = new AbortController();\r\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\r\n try {\r\n const headers = this.headers(\r\n options.endUserOverride ? { \"X-End-User-ID\": options.endUserOverride } : {},\r\n );\r\n if (options.form) {\r\n // fetch sets multipart/form-data together with the boundary. Sending our\r\n // own Content-Type produces a body the server cannot parse, and the\r\n // symptom is misleading: every form field comes back \"field required\".\r\n delete headers[\"Content-Type\"];\r\n }\r\n const res = await this.fetchImpl(url, {\r\n method,\r\n headers,\r\n body: options.form\r\n ? options.form\r\n : options.body !== undefined\r\n ? JSON.stringify(options.body)\r\n : undefined,\r\n signal: controller.signal,\r\n });\r\n const requestId = res.headers.get(\"X-Request-ID\") ?? undefined;\r\n\r\n if (res.status === 204) return undefined as unknown as T;\r\n\r\n const text = await res.text();\r\n const parsed: unknown = text ? safeJson(text) : null;\r\n\r\n if (!res.ok) this.throwForStatus(res.status, parsed, requestId);\r\n return parsed as T;\r\n } catch (e) {\r\n if (e instanceof MemorySyncError) throw e;\r\n if (e instanceof Error && e.name === \"AbortError\") {\r\n throw new MemorySyncError(`Request timed out after ${this.timeoutMs}ms`);\r\n }\r\n throw new MemorySyncError(`Network error: ${(e as Error).message}`);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n\r\n private throwForStatus(status: number, body: unknown, requestId?: string): never {\r\n const detail = extractDetail(body);\r\n const opts: ErrorOpts = { statusCode: status, response: body, requestId };\r\n if (status === 401) throw new AuthError(detail || \"Unauthenticated\", opts);\r\n if (status === 403) throw new AuthError(detail || \"Forbidden\", opts);\r\n if (status === 404) throw new NotFoundError(detail || \"Not found\", opts);\r\n if (status === 400 || status === 409 || status === 422) {\r\n throw new ValidationError(detail || \"Validation error\", opts);\r\n }\r\n if (status === 429) {\r\n const retryAfter = extractRetryAfter(body);\r\n throw new RateLimitError(detail || \"Rate limited\", retryAfter, opts);\r\n }\r\n if (status >= 500) throw new ServerError(detail || `Server error (${status})`, opts);\r\n throw new MemorySyncError(detail || `Unexpected status ${status}`, opts);\r\n }\r\n\r\n // ── Memory ─────────────────────────────────────────────────────────\r\n\r\n async add(req: AddRequest): Promise<AddResponse> {\r\n const body: Record<string, unknown> = { text: req.text };\r\n if (req.source !== undefined) body.source = req.source;\r\n if (req.tags !== undefined) body.tags = req.tags;\r\n if (req.importance !== undefined) body.importance = req.importance;\r\n if (req.sessionId !== undefined) body.session_id = req.sessionId;\r\n if (req.metadata !== undefined) body.metadata = req.metadata;\r\n if (req.endUserId !== undefined) body.end_user_id = req.endUserId;\r\n\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/add\", {\r\n body,\r\n endUserOverride: req.endUserId,\r\n });\r\n if (raw && raw.status === \"skipped\") {\r\n return {\r\n status: \"skipped\",\r\n reason: (raw.reason as string) ?? \"no_high_value_content\",\r\n memoryIds: (raw.memory_ids as number[]) ?? [],\r\n candidatesExtracted: (raw.candidates_extracted as number) ?? 0,\r\n candidatesStored: (raw.candidates_stored as number) ?? 0,\r\n };\r\n }\r\n return snakeToCamelMemory(raw);\r\n }\r\n\r\n async bulkAdd(items: BulkAddItem[], opts: { deduplicate?: boolean } = {}): Promise<BulkAddResponse> {\r\n if (items.length === 0) throw new ValidationError(\"items must contain at least one entry\");\r\n if (items.length > 50) throw new ValidationError(\"items may contain at most 50 entries per request\");\r\n const body = {\r\n items: items.map((i) => {\r\n const o: Record<string, unknown> = { text: i.text };\r\n if (i.source !== undefined) o.source = i.source;\r\n if (i.eventType !== undefined) o.event_type = i.eventType;\r\n if (i.tags !== undefined) o.tags = i.tags;\r\n if (i.metadata !== undefined) o.metadata = i.metadata;\r\n if (i.importance !== undefined) o.importance = i.importance;\r\n if (i.endUserId !== undefined) o.end_user_id = i.endUserId;\r\n return o;\r\n }),\r\n deduplicate: opts.deduplicate ?? true,\r\n };\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/bulk-add\", { body });\r\n return {\r\n total: raw.total as number,\r\n created: raw.created as number,\r\n skipped: raw.skipped as number,\r\n rejected: raw.rejected as number,\r\n results: ((raw.results as Array<Record<string, unknown>>) ?? []).map((r) => ({\r\n index: r.index as number,\r\n status: r.status as BulkAddItemResult[\"status\"],\r\n memoryIds: (r.memory_ids as number[]) ?? [],\r\n reason: (r.reason as string | null) ?? null,\r\n })),\r\n };\r\n }\r\n\r\n async query(req: QueryRequest): Promise<QueryResponse> {\r\n const body: Record<string, unknown> = { query: req.query };\r\n if (req.k !== undefined) body.k = req.k;\r\n if (req.sessionId !== undefined) body.session_id = req.sessionId;\r\n if (req.traversalDepth !== undefined) body.traversal_depth = req.traversalDepth;\r\n if (req.filters) body.filters = camelToSnakeShallow(req.filters as Record<string, unknown>);\r\n\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/query\", { body });\r\n return {\r\n memories: ((raw.memories as Array<Record<string, unknown>>) ?? []).map(snakeToCamelMemory),\r\n context: (raw.context as string | null) ?? null,\r\n latencyMs: (raw.latency_ms as number | null) ?? null,\r\n sessionId: (raw.session_id as string | null) ?? null,\r\n queryIntent: (raw.query_intent as string | null) ?? null,\r\n };\r\n }\r\n\r\n async get(memoryId: number): Promise<MemoryRecord> {\r\n if (!Number.isInteger(memoryId) || memoryId <= 0) {\r\n throw new ValidationError(\"memoryId must be a positive integer\");\r\n }\r\n const raw = await this.request<Record<string, unknown>>(\"GET\", `/memory/${memoryId}`);\r\n return snakeToCamelMemory(raw);\r\n }\r\n\r\n async update(memoryId: number, req: UpdateRequest): Promise<MemoryRecord> {\r\n if (!Number.isInteger(memoryId) || memoryId <= 0) {\r\n throw new ValidationError(\"memoryId must be a positive integer\");\r\n }\r\n const body: Record<string, unknown> = {};\r\n if (req.tags !== undefined) body.tags = req.tags;\r\n if (req.importance !== undefined) body.importance = req.importance;\r\n if (req.metadata !== undefined) body.metadata = req.metadata;\r\n if (req.source !== undefined) body.source = req.source;\r\n if (req.eventType !== undefined) body.event_type = req.eventType;\r\n if (Object.keys(body).length === 0) {\r\n throw new ValidationError(\"update() requires at least one editable field\");\r\n }\r\n const raw = await this.request<Record<string, unknown>>(\"PATCH\", `/memory/${memoryId}`, { body });\r\n return snakeToCamelMemory(raw);\r\n }\r\n\r\n /**\r\n * Delete memories, either by id or by filter. Returns the deleted ids.\r\n *\r\n * Accepts the legacy positional form `forget([1,2], \"reason\")` as well as\r\n * `forget({ filters, dryRun })`. The positional form is kept because it ships\r\n * in 1.1.x and removing it would break installed callers for no benefit.\r\n *\r\n * Exactly one selector. Passing both is rejected rather than resolved by a\r\n * precedence rule, because getting that wrong on a delete cannot be undone.\r\n * Deletion is scoped to the calling end user, so a filter never reaches\r\n * another end user's memories — including the organisation's connector history.\r\n */\r\n async forget(request: ForgetRequest): Promise<number[]>;\r\n async forget(memoryIds: number[], reason?: string): Promise<number[]>;\r\n async forget(\r\n arg: ForgetRequest | number[],\r\n legacyReason?: string,\r\n ): Promise<number[]> {\r\n const req: ForgetRequest = Array.isArray(arg)\r\n ? { memoryIds: arg, reason: legacyReason }\r\n : arg;\r\n\r\n const hasIds = req.memoryIds !== undefined;\r\n const hasFilters = req.filters !== undefined;\r\n if (hasIds && hasFilters) {\r\n throw new ValidationError(\"Provide either memoryIds or filters, not both\");\r\n }\r\n if (!hasIds && !hasFilters) {\r\n throw new ValidationError(\"Provide either memoryIds or filters\");\r\n }\r\n\r\n const body: Record<string, unknown> = {};\r\n if (hasIds) {\r\n if (!Array.isArray(req.memoryIds) || req.memoryIds.length === 0) {\r\n throw new ValidationError(\"memoryIds must be a non-empty array\");\r\n }\r\n body.memory_ids = req.memoryIds;\r\n } else {\r\n const f = req.filters!;\r\n const filters: Record<string, unknown> = {};\r\n if (f.source !== undefined) filters.source = f.source;\r\n if (f.eventType !== undefined) filters.event_type = f.eventType;\r\n if (f.tags !== undefined) filters.tags = f.tags;\r\n if (f.tier !== undefined) filters.tier = f.tier;\r\n if (f.before !== undefined) filters.before = f.before;\r\n if (f.after !== undefined) filters.after = f.after;\r\n if (Object.keys(filters).length === 0) {\r\n throw new ValidationError(\r\n \"filters must set at least one criterion; use purgeUser() to remove everything for an end user\",\r\n );\r\n }\r\n body.filters = filters;\r\n if (req.dryRun) body.dry_run = true;\r\n }\r\n if (req.reason !== undefined) body.reason = req.reason;\r\n return await this.request<number[]>(\"DELETE\", \"/memory/forget\", { body });\r\n }\r\n\r\n /**\r\n * Delete every memory belonging to the calling end user.\r\n *\r\n * Separate from {@link forget} on purpose: this reads like what it does, so a\r\n * whole-namespace delete can never be the accidental result of an empty filter.\r\n */\r\n async purgeUser(): Promise<Record<string, unknown>> {\r\n return (await this.request<Record<string, unknown>>(\"DELETE\", \"/memory/user/purge\")) ?? {};\r\n }\r\n\r\n async summarize(req: SummarizeRequest): Promise<MemoryRecord> {\r\n if (!req.memoryIds || req.memoryIds.length === 0) {\r\n throw new ValidationError(\"summarize() requires memoryIds\");\r\n }\r\n const body: Record<string, unknown> = { memory_ids: req.memoryIds };\r\n if (req.lossless !== undefined) body.lossless = req.lossless;\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/summarize\", { body });\r\n return snakeToCamelMemory(raw);\r\n }\r\n\r\n async compose(req: ComposeRequest): Promise<ComposeResponse> {\r\n const body: Record<string, unknown> = { prompt_template: req.promptTemplate };\r\n if (req.recallK !== undefined) body.recall_k = req.recallK;\r\n if (req.maxTokens !== undefined) body.max_tokens = req.maxTokens;\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/compose\", { body });\r\n return {\r\n composedPrompt: (raw.composed_prompt as string) ?? \"\",\r\n memoriesUsed: (raw.memories_used as number) ?? 0,\r\n tokenCount: (raw.token_count as number) ?? 0,\r\n truncated: Boolean(raw.truncated),\r\n };\r\n }\r\n\r\n async exportAll(): Promise<ExportResponse> {\r\n const raw = await this.request<Record<string, unknown>>(\"GET\", \"/memory/export\");\r\n return {\r\n userId: raw.user_id as number,\r\n memories: (raw.memories as Array<Record<string, unknown>>) ?? [],\r\n generatedAt: raw.generated_at as string,\r\n };\r\n }\r\n\r\n async createRelation(fromMemoryId: number, req: RelationCreateRequest): Promise<RelationRecord> {\r\n if (!Number.isInteger(fromMemoryId) || fromMemoryId <= 0) {\r\n throw new ValidationError(\"fromMemoryId must be a positive integer\");\r\n }\r\n if (fromMemoryId === req.toMemoryId) {\r\n throw new ValidationError(\"fromMemoryId must differ from toMemoryId (no self-loops)\");\r\n }\r\n const body: Record<string, unknown> = {\r\n to_memory_id: req.toMemoryId,\r\n relationship_type: req.relationshipType,\r\n };\r\n if (req.confidence !== undefined) body.confidence = req.confidence;\r\n if (req.metadata !== undefined) body.metadata = req.metadata;\r\n const raw = await this.request<Record<string, unknown>>(\r\n \"POST\",\r\n `/memory/${fromMemoryId}/relations`,\r\n { body },\r\n );\r\n return {\r\n id: raw.id as number,\r\n fromMemoryId: raw.from_memory_id as number,\r\n toMemoryId: raw.to_memory_id as number,\r\n relationshipType: raw.relationship_type as RelationshipType,\r\n confidence: raw.confidence as number,\r\n metadata: (raw.metadata as Record<string, unknown> | null) ?? null,\r\n createdAt: raw.created_at as string,\r\n };\r\n }\r\n\r\n // ── Files ──────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Ingest a document and store the memories extracted from its text.\r\n *\r\n * Accepts the formats the connectors accept — PDF, DOCX, PPTX, XLSX, CSV,\r\n * text, Markdown, HTML, source code, and images/audio/video where\r\n * transcription is configured.\r\n *\r\n * Billed as an add, one unit per memory created. Resolves to the first stored\r\n * memory, or an {@link AddSkippedResponse} when the file yielded nothing worth\r\n * keeping — a blank scan, a sheet of empty cells, or content the extractor\r\n * judges trivial are all normal outcomes rather than errors.\r\n */\r\n async upload(req: UploadRequest): Promise<AddResponse> {\r\n if (!req.filename?.trim()) {\r\n throw new ValidationError(\"filename is required so the server can pick a parser\");\r\n }\r\n const form = new FormData();\r\n const blob =\r\n req.file instanceof Uint8Array\r\n ? new Blob([req.file as unknown as BlobPart], {\r\n type: req.contentType ?? \"application/octet-stream\",\r\n })\r\n : req.file;\r\n form.append(\"file\", blob, req.filename);\r\n if (req.source !== undefined) form.append(\"source\", req.source);\r\n if (req.metadata !== undefined) form.append(\"metadata\", JSON.stringify(req.metadata));\r\n if (req.endUserId !== undefined) form.append(\"end_user_id\", req.endUserId);\r\n\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/upload\", {\r\n form,\r\n endUserOverride: req.endUserId,\r\n });\r\n if (raw && raw.status === \"skipped\") {\r\n return {\r\n status: \"skipped\",\r\n reason: (raw.reason as string) ?? \"no_extractable_text\",\r\n memoryIds: (raw.memory_ids as number[]) ?? [],\r\n candidatesExtracted: (raw.candidates_extracted as number) ?? 0,\r\n candidatesStored: (raw.candidates_stored as number) ?? 0,\r\n };\r\n }\r\n return snakeToCamelMemory(raw);\r\n }\r\n\r\n // ── Bulk edit ──────────────────────────────────────────────────────\r\n\r\n /**\r\n * Apply many metadata edits in one request.\r\n *\r\n * Editable: `tags`, `importance`, `metadata`, `source`, `eventType`. A memory's\r\n * text, embeddings, owner, environment and project are not editable.\r\n *\r\n * Applied in one transaction, so the batch either lands or it does not — but an\r\n * id the caller cannot see is reported per item rather than failing the request.\r\n */\r\n async batchUpdate(items: BatchUpdateItem[]): Promise<BatchUpdateResponse> {\r\n if (!Array.isArray(items) || items.length === 0) {\r\n throw new ValidationError(\"items must contain at least one entry\");\r\n }\r\n if (items.length > 100) {\r\n throw new ValidationError(\"items may contain at most 100 entries per request\");\r\n }\r\n const seen = new Map<number, number>();\r\n const payload = items.map((item, index) => {\r\n if (!Number.isInteger(item.memoryId) || item.memoryId <= 0) {\r\n throw new ValidationError(`items[${index}].memoryId must be a positive integer`);\r\n }\r\n const o: Record<string, unknown> = { memory_id: item.memoryId };\r\n if (item.tags !== undefined) o.tags = item.tags;\r\n if (item.importance !== undefined) o.importance = item.importance;\r\n if (item.metadata !== undefined) o.metadata = item.metadata;\r\n if (item.source !== undefined) o.source = item.source;\r\n if (item.eventType !== undefined) o.event_type = item.eventType;\r\n if (Object.keys(o).length === 1) {\r\n throw new ValidationError(\r\n `items[${index}] (memoryId ${item.memoryId}): at least one updatable field must be provided`,\r\n );\r\n }\r\n const previous = seen.get(item.memoryId);\r\n if (previous !== undefined) {\r\n // Two edits to one memory have no defined order, so the outcome would\r\n // depend on array position.\r\n throw new ValidationError(\r\n `items must not contain the same memoryId twice: ${item.memoryId} appears at index ${previous} and ${index}`,\r\n );\r\n }\r\n seen.set(item.memoryId, index);\r\n return o;\r\n });\r\n\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/batch-update\", {\r\n body: { items: payload },\r\n });\r\n return {\r\n total: (raw?.total as number) ?? 0,\r\n updated: (raw?.updated as number) ?? 0,\r\n notFound: (raw?.not_found as number) ?? 0,\r\n results: ((raw?.results as Array<Record<string, unknown>>) ?? []).map((r) => ({\r\n index: r.index as number,\r\n memoryId: r.memory_id as number,\r\n status: r.status as \"updated\" | \"not_found\",\r\n changedFields: (r.changed_fields as string[]) ?? [],\r\n })),\r\n };\r\n }\r\n\r\n // ── History and feedback ───────────────────────────────────────────\r\n\r\n /**\r\n * Recorded changes to one memory, oldest first.\r\n *\r\n * Entry 0 is the creation. Later entries carry the old and new value per field.\r\n * Entries written by background workers have `actor: null`. Only\r\n * user-meaningful fields are tracked; the watched list comes back in\r\n * `trackedFields`.\r\n */\r\n async history(\r\n memoryId: number,\r\n opts: { limit?: number; offset?: number } = {},\r\n ): Promise<HistoryResponse> {\r\n if (!Number.isInteger(memoryId) || memoryId <= 0) {\r\n throw new ValidationError(\"memoryId must be a positive integer\");\r\n }\r\n const raw = await this.request<Record<string, unknown>>(\r\n \"GET\",\r\n `/memory/${memoryId}/history`,\r\n { query: { limit: opts.limit ?? 100, offset: opts.offset ?? 0 } },\r\n );\r\n return {\r\n memoryId: (raw?.memory_id as number) ?? memoryId,\r\n total: (raw?.total as number) ?? 0,\r\n revisions: ((raw?.revisions as Array<Record<string, unknown>>) ?? []).map((r) => ({\r\n revision: r.revision as number,\r\n event: r.event as RevisionEvent,\r\n changedFields: (r.changed_fields as string[]) ?? [],\r\n diff: (r.diff as Record<string, { old?: unknown; new?: unknown }>) ?? {},\r\n actor: (r.actor as string | null) ?? null,\r\n createdAt: r.created_at as string,\r\n })),\r\n trackedFields: (raw?.tracked_fields as string[]) ?? [],\r\n };\r\n }\r\n\r\n /**\r\n * Tell MemorySync whether a memory was useful.\r\n *\r\n * By default this moves the memory's `importance`, a weighted retrieval-ranking\r\n * factor, so a memory marked useful surfaces more readily and one marked wrong\r\n * surfaces less. The size of the move is adaptive: consistent signals amplify\r\n * it, mixed signals damp it. Importance is clamped to [0.05, 1.0], so no run of\r\n * negative feedback can make a memory permanently unreachable. Not billed.\r\n */\r\n async feedback(\r\n memoryId: number,\r\n signal: FeedbackSignal,\r\n opts: { comment?: string } = {},\r\n ): Promise<FeedbackResponse> {\r\n if (!Number.isInteger(memoryId) || memoryId <= 0) {\r\n throw new ValidationError(\"memoryId must be a positive integer\");\r\n }\r\n const valid: FeedbackSignal[] = [\"positive\", \"negative\", \"retrieved\", \"ignored\"];\r\n if (!valid.includes(signal)) {\r\n throw new ValidationError(`signal must be one of ${valid.join(\", \")}; got ${String(signal)}`);\r\n }\r\n const body: Record<string, unknown> = { signal };\r\n if (opts.comment !== undefined) body.comment = opts.comment;\r\n const raw = await this.request<Record<string, unknown>>(\r\n \"POST\",\r\n `/memory/${memoryId}/feedback`,\r\n { body },\r\n );\r\n const summary = (raw?.summary as Record<string, unknown>) ?? {};\r\n const trend = (summary.trend as Record<string, unknown>) ?? {};\r\n return {\r\n memoryId: (raw?.memory_id as number) ?? memoryId,\r\n signal: (raw?.signal as FeedbackSignal) ?? signal,\r\n importanceBefore: (raw?.importance_before as number) ?? 0,\r\n importanceAfter: (raw?.importance_after as number) ?? 0,\r\n adjustment: (raw?.adjustment as number) ?? 0,\r\n influencedRanking: Boolean(raw?.influenced_ranking),\r\n summary: {\r\n totalSignals: (summary.total_signals as number) ?? 0,\r\n signalCounts: (summary.signal_counts as Record<string, number>) ?? {},\r\n trend: {\r\n momentum: (trend.momentum as string) ?? \"neutral\",\r\n consistency: (trend.consistency as number) ?? 0,\r\n trendMultiplier: (trend.trend_multiplier as number) ?? 1,\r\n recentCount: (trend.recent_count as number) ?? 0,\r\n },\r\n },\r\n };\r\n }\r\n\r\n // ── Ontology ───────────────────────────────────────────────────────\r\n\r\n /** The memory vocabulary in effect for this organization. */\r\n async getOntology(): Promise<Ontology> {\r\n const raw = await this.request<Record<string, unknown>>(\"GET\", \"/memory/ontology\");\r\n return toOntology(raw);\r\n }\r\n\r\n /**\r\n * Replace this organization's *additions* to the vocabulary.\r\n *\r\n * The two vocabularies are independent: omit one and it is left untouched, so\r\n * adding a content type cannot wipe your relation types. Pass an empty array to\r\n * clear a vocabulary's custom entries. The built-in types always remain.\r\n */\r\n async updateOntology(req: OntologyUpdateRequest): Promise<Ontology> {\r\n if (req.contentTypes === undefined && req.relationTypes === undefined) {\r\n throw new ValidationError(\r\n \"provide contentTypes, relationTypes, or both; an empty request would silently do nothing\",\r\n );\r\n }\r\n const body: Record<string, unknown> = {};\r\n if (req.contentTypes !== undefined) body.content_types = req.contentTypes;\r\n if (req.relationTypes !== undefined) body.relation_types = req.relationTypes;\r\n const raw = await this.request<Record<string, unknown>>(\"PUT\", \"/memory/ontology\", { body });\r\n return toOntology(raw);\r\n }\r\n\r\n // ── Retrieval variants ─────────────────────────────────────────────\r\n\r\n /**\r\n * Alias of {@link query} against `/memory/retrieve`.\r\n *\r\n * Both paths are live, and integrators arriving from other platforms reach for\r\n * `retrieve`. Identical semantics.\r\n */\r\n async retrieve(req: QueryRequest): Promise<QueryResponse> {\r\n const body: Record<string, unknown> = { query: req.query };\r\n if (req.k !== undefined) body.k = req.k;\r\n if (req.filters !== undefined) body.filters = camelToSnakeShallow(req.filters as Record<string, unknown>);\r\n if (req.sessionId !== undefined) body.session_id = req.sessionId;\r\n if (req.traversalDepth !== undefined) body.traversal_depth = req.traversalDepth;\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/retrieve\", { body });\r\n return {\r\n memories: ((raw.memories as Array<Record<string, unknown>>) ?? []).map(snakeToCamelMemory),\r\n context: (raw.context as string | null) ?? null,\r\n latencyMs: (raw.latency_ms as number | null) ?? null,\r\n sessionId: (raw.session_id as string | null) ?? null,\r\n queryIntent: (raw.query_intent as string | null) ?? null,\r\n };\r\n }\r\n\r\n /**\r\n * Route a question to the best knowledge source and answer from it.\r\n *\r\n * Returns the raw payload: the response carries routing diagnostics whose shape\r\n * is richer and more volatile than an SDK should freeze into an interface.\r\n */\r\n async searchRouted(\r\n query: string,\r\n opts: { k?: number; route?: string; includeReasoning?: boolean } = {},\r\n ): Promise<Record<string, unknown>> {\r\n const body: Record<string, unknown> = { query };\r\n if (opts.k !== undefined) body.k = opts.k;\r\n if (opts.route !== undefined) body.route = opts.route;\r\n if (opts.includeReasoning !== undefined) body.include_reasoning = opts.includeReasoning;\r\n return (\r\n (await this.request<Record<string, unknown>>(\"POST\", \"/memory/search/routed\", { body })) ?? {}\r\n );\r\n }\r\n\r\n /** Compose an answer across several memories, with citations. */\r\n async synthesize(\r\n opts: { query?: string; memoryIds?: number[]; maxMemories?: number } = {},\r\n ): Promise<Record<string, unknown>> {\r\n const body: Record<string, unknown> = {};\r\n if (opts.query !== undefined) body.query = opts.query;\r\n if (opts.memoryIds !== undefined) body.memory_ids = opts.memoryIds;\r\n if (opts.maxMemories !== undefined) body.max_memories = opts.maxMemories;\r\n return (\r\n (await this.request<Record<string, unknown>>(\"POST\", \"/memory/synthesize\", { body })) ?? {}\r\n );\r\n }\r\n\r\n /** Re-embed this end user's memories. Returns immediately (`202`). */\r\n async refresh(): Promise<Record<string, unknown>> {\r\n return (await this.request<Record<string, unknown>>(\"POST\", \"/memory/refresh\")) ?? {};\r\n }\r\n\r\n // ── Intelligence and graph ─────────────────────────────────────────\r\n\r\n /** Nodes and typed edges for this end user's memory graph. */\r\n async graph(\r\n opts: { limit?: number; memoryId?: number; depth?: number } = {},\r\n ): Promise<Record<string, unknown>> {\r\n return (\r\n (await this.request<Record<string, unknown>>(\"GET\", \"/memory/graph\", {\r\n query: { limit: opts.limit, memory_id: opts.memoryId, depth: opts.depth },\r\n })) ?? {}\r\n );\r\n }\r\n\r\n /** Semantic clusters over this end user's memories. */\r\n async clusters(opts: { limit?: number } = {}): Promise<Record<string, unknown>> {\r\n return (\r\n (await this.request<Record<string, unknown>>(\"GET\", \"/memory/clusters\", {\r\n query: { limit: opts.limit },\r\n })) ?? {}\r\n );\r\n }\r\n\r\n /** Contradictions and open decisions detected across memories. */\r\n async decisions(opts: { limit?: number } = {}): Promise<Record<string, unknown>> {\r\n return (\r\n (await this.request<Record<string, unknown>>(\"GET\", \"/memory/decisions\", {\r\n query: { limit: opts.limit },\r\n })) ?? {}\r\n );\r\n }\r\n\r\n /** Record which side of a contradiction wins. */\r\n async resolveDecision(\r\n opts: {\r\n decisionId?: string;\r\n winningMemoryId?: number;\r\n resolution?: string;\r\n note?: string;\r\n } = {},\r\n ): Promise<Record<string, unknown>> {\r\n const body: Record<string, unknown> = {};\r\n if (opts.decisionId !== undefined) body.decision_id = opts.decisionId;\r\n if (opts.winningMemoryId !== undefined) body.winning_memory_id = opts.winningMemoryId;\r\n if (opts.resolution !== undefined) body.resolution = opts.resolution;\r\n if (opts.note !== undefined) body.note = opts.note;\r\n return (\r\n (await this.request<Record<string, unknown>>(\"POST\", \"/memory/decision/resolve\", { body })) ??\r\n {}\r\n );\r\n }\r\n\r\n /**\r\n * The intelligence report: themes, entities, patterns, dual-horizon view.\r\n *\r\n * `scope` is explicit by design server-side — nothing is inferred, so if you do\r\n * not ask for a scope you do not get it.\r\n */\r\n async intelligence(\r\n opts: { limit?: number; scope?: string; projectId?: string } = {},\r\n ): Promise<Record<string, unknown>> {\r\n return (\r\n (await this.request<Record<string, unknown>>(\"GET\", \"/memory/intelligence\", {\r\n query: { limit: opts.limit, scope: opts.scope, project_id: opts.projectId },\r\n })) ?? {}\r\n );\r\n }\r\n\r\n /** Counts and coverage for the knowledge base. */\r\n async knowledgeStats(): Promise<Record<string, unknown>> {\r\n return (await this.request<Record<string, unknown>>(\"GET\", \"/memory/knowledge/stats\")) ?? {};\r\n }\r\n\r\n // ── v1 data plane ──────────────────────────────────────────────────\r\n\r\n /** Add a conversation turn and extract memories from it. */\r\n async addTurn(req: {\r\n tenantId: string;\r\n userId: string;\r\n messages: Array<Record<string, unknown>>;\r\n sessionId?: string;\r\n metadata?: Record<string, unknown>;\r\n }): Promise<Record<string, unknown>> {\r\n const body: Record<string, unknown> = {\r\n tenant_id: req.tenantId,\r\n user_id: req.userId,\r\n messages: req.messages,\r\n };\r\n if (req.sessionId !== undefined) body.session_id = req.sessionId;\r\n if (req.metadata !== undefined) body.metadata = req.metadata;\r\n return (\r\n (await this.request<Record<string, unknown>>(\"POST\", \"/v1/memory/add_turn\", { body })) ?? {}\r\n );\r\n }\r\n\r\n /**\r\n * Build a prompt-ready context block for an LLM call.\r\n *\r\n * `types` narrows the result to those content types. Names outside the\r\n * organization's vocabulary are dropped rather than rejected, so a stale client\r\n * gets a narrower answer instead of an error.\r\n */\r\n async recall(req: {\r\n tenantId: string;\r\n userId: string;\r\n prompt: string;\r\n k?: number;\r\n types?: string[];\r\n }): Promise<Record<string, unknown>> {\r\n const body: Record<string, unknown> = {\r\n tenant_id: req.tenantId,\r\n user_id: req.userId,\r\n prompt: req.prompt,\r\n };\r\n if (req.k !== undefined) body.k = req.k;\r\n if (req.types !== undefined) body.types = req.types;\r\n return (\r\n (await this.request<Record<string, unknown>>(\"POST\", \"/v1/memory/recall\", { body })) ?? {}\r\n );\r\n }\r\n\r\n /** Async ingestion status for one memory. */\r\n async status(memoryId: number): Promise<Record<string, unknown>> {\r\n if (!Number.isInteger(memoryId) || memoryId <= 0) {\r\n throw new ValidationError(\"memoryId must be a positive integer\");\r\n }\r\n return (\r\n (await this.request<Record<string, unknown>>(\"GET\", `/v1/memory/status/${memoryId}`)) ?? {}\r\n );\r\n }\r\n\r\n /** Page through a specific end user's memories. */\r\n async listMemories(req: {\r\n tenantId: string;\r\n userId: string;\r\n limit?: number;\r\n offset?: number;\r\n }): Promise<Record<string, unknown>> {\r\n return (\r\n (await this.request<Record<string, unknown>>(\r\n \"GET\",\r\n `/v1/memory/${encodeURIComponent(req.tenantId)}/${encodeURIComponent(req.userId)}/list`,\r\n { query: { limit: req.limit, offset: req.offset } },\r\n )) ?? {}\r\n );\r\n }\r\n}\r\n\r\nfunction toOntology(raw: Record<string, unknown> | null | undefined): Ontology {\r\n return {\r\n contentTypes: (raw?.content_types as string[]) ?? [],\r\n relationTypes: (raw?.relation_types as string[]) ?? [],\r\n builtinContentTypes: (raw?.builtin_content_types as string[]) ?? [],\r\n builtinRelationTypes: (raw?.builtin_relation_types as string[]) ?? [],\r\n customContentTypes: (raw?.custom_content_types as string[]) ?? [],\r\n customRelationTypes: (raw?.custom_relation_types as string[]) ?? [],\r\n maxCustomTypes: (raw?.max_custom_types as number) ?? 32,\r\n };\r\n}\r\n\r\nexport * from \"./control-plane\";\r\nexport {\r\n ConnectionOAuthNamespace,\r\n ConnectionsNamespace,\r\n GoogleDriveNamespace,\r\n GranolaNamespace,\r\n IntegrationsNamespace,\r\n ObjectsNamespace,\r\n ProvidersNamespace,\r\n S3Namespace,\r\n SlackNamespace,\r\n SyncJobsNamespace,\r\n WebCrawlerNamespace,\r\n} from \"./connections\";\r\n","export interface ErrorOptions {\r\n statusCode?: number;\r\n response?: unknown;\r\n requestId?: string;\r\n}\r\n\r\nexport class MemorySyncError extends Error {\r\n readonly statusCode?: number;\r\n readonly response?: unknown;\r\n readonly requestId?: string;\r\n\r\n constructor(message: string, options: ErrorOptions = {}) {\r\n super(message);\r\n this.name = \"MemorySyncError\";\r\n this.statusCode = options.statusCode;\r\n this.response = options.response;\r\n this.requestId = options.requestId;\r\n }\r\n}\r\n\r\nexport class AuthError extends MemorySyncError {\r\n constructor(message: string, options?: ErrorOptions) {\r\n super(message, options);\r\n this.name = \"AuthError\";\r\n }\r\n}\r\n\r\nexport class ValidationError extends MemorySyncError {\r\n constructor(message: string, options?: ErrorOptions) {\r\n super(message, options);\r\n this.name = \"ValidationError\";\r\n }\r\n}\r\n\r\nexport class NotFoundError extends MemorySyncError {\r\n constructor(message: string, options?: ErrorOptions) {\r\n super(message, options);\r\n this.name = \"NotFoundError\";\r\n }\r\n}\r\nexport class RateLimitError extends MemorySyncError {\r\n readonly retryAfterSeconds: number;\r\n\r\n constructor(message: string, retryAfterSeconds: number, options?: ErrorOptions) {\r\n super(message, options);\r\n this.name = \"RateLimitError\";\r\n this.retryAfterSeconds = retryAfterSeconds;\r\n }\r\n}\r\n\r\nexport class ServerError extends MemorySyncError {\r\n constructor(message: string, options?: ErrorOptions) {\r\n super(message, options);\r\n this.name = \"ServerError\";\r\n }\r\n}\r\n","/**\r\n * Connector namespaces — `client.connections`, `client.objects` and friends.\r\n *\r\n * Covers the connector API: creating and managing connections to Slack, Google\r\n * Drive, S3 and Granola, driving syncs, and inspecting the objects a sync\r\n * produced. Shaped after `client.connections.*` in comparable SDKs so the layout\r\n * is familiar.\r\n *\r\n * ## Why these return raw payloads\r\n *\r\n * Connector responses are large, provider-shaped and still moving — a Slack\r\n * channel listing looks nothing like an S3 prefix listing, and both carry\r\n * provider fields that change when the provider changes. Freezing them into\r\n * interfaces would mean an SDK release every time a provider adds a field, and\r\n * callers unable to see the new field until then. Typed models are reserved for\r\n * the small, stable, first-party shapes (memories, history, feedback, ontology).\r\n */\r\n\r\nconst V2 = \"/api/v2/integrations\";\r\nconst V1 = \"/api/v1/integrations\";\r\n\r\n/** The client's request function, injected so namespaces carry no transport. */\r\nexport type RequestFn = <T>(\r\n method: string,\r\n path: string,\r\n options?: { body?: unknown; query?: Record<string, unknown> },\r\n) => Promise<T>;\r\n\r\ntype Json = Record<string, unknown>;\r\n\r\n/**\r\n * Percent-encode one path segment.\r\n *\r\n * Connection, object and resource ids come from providers, not from us. A Slack\r\n * channel id is tame but a Drive resource id or an S3 prefix is not, and an\r\n * unencoded `/` in one of them would silently change which route is called.\r\n */\r\nfunction seg(value: string | number): string {\r\n return encodeURIComponent(String(value));\r\n}\r\n\r\n/**\r\n * Normalize one selection entry into the object the API expects.\r\n *\r\n * Two of the approval endpoints take a list of objects rather than a list of\r\n * ids — Slack channels carry an optional name and type, S3 prefixes carry an\r\n * optional bucket and label. Callers almost always have just the id, so both\r\n * forms are accepted and widened to the object form here, rather than making\r\n * every caller write `{ id: channelId }` and making the simple case ugly.\r\n */\r\nfunction asItem(value: string | Json, key: string): Json {\r\n return typeof value === \"string\" ? { [key]: value } : value;\r\n}\r\n\r\nclass Namespace {\r\n protected readonly req: RequestFn;\r\n constructor(request: RequestFn) {\r\n this.req = request;\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────\r\n// Provider-specific namespaces\r\n// ─────────────────────────────────────────────────────────────────────\r\n\r\n/** Slack connection settings. */\r\nexport class SlackNamespace extends Namespace {\r\n /**\r\n * Channels the app can see and could be added.\r\n *\r\n * Private channels appear only where the deployment allows them *and* a human\r\n * has invited the app, so this never widens what someone already granted.\r\n */\r\n availableChannels(connectionId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/slack/available-channels`, { query });\r\n }\r\n\r\n /** Channels currently selected for syncing. */\r\n channels(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/slack/channels`);\r\n }\r\n\r\n /**\r\n * Select channels for syncing.\r\n *\r\n * Accepts bare channel ids, which is the common case, or objects carrying the\r\n * name and type across so the server does not have to look them up again:\r\n *\r\n * ```ts\r\n * await client.connections.slack.addChannels(\"c1\", [\"C0123\", \"C0456\"]);\r\n * await client.connections.slack.addChannels(\"c1\", [\r\n * { id: \"C0123\", name: \"support\", is_private: false },\r\n * ]);\r\n * ```\r\n */\r\n addChannels(connectionId: string, channels: Array<string | Json>): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/slack/channels`, {\r\n body: { channels: channels.map((c) => asItem(c, \"id\")) },\r\n });\r\n }\r\n\r\n /** Stop syncing one channel. */\r\n removeChannel(connectionId: string, channelId: string): Promise<Json> {\r\n return this.req(\r\n \"DELETE\",\r\n `${V2}/connections/${seg(connectionId)}/slack/channels/${seg(channelId)}`,\r\n );\r\n }\r\n\r\n /**\r\n * Channels this connection will never sync.\r\n *\r\n * The deployment-wide floor cannot be removed here; a tenant may only add to it.\r\n */\r\n exclusionPolicy(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/slack/exclusion-policy`);\r\n }\r\n\r\n /** Replace this connection's additions to the exclusion policy. */\r\n setExclusionPolicy(connectionId: string, policy: Json): Promise<Json> {\r\n return this.req(\"PUT\", `${V2}/connections/${seg(connectionId)}/slack/exclusion-policy`, {\r\n body: policy,\r\n });\r\n }\r\n\r\n /** Slack users seen on this connection and who they map to. */\r\n identities(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/slack/identities`);\r\n }\r\n\r\n /** Map a Slack user to a MemorySync end user. */\r\n linkIdentity(connectionId: string, body: Json): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/slack/identities/link`, { body });\r\n }\r\n\r\n /** Re-read the Slack member list and refresh the identity table. */\r\n syncIdentities(connectionId: string): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/slack/identities/sync`);\r\n }\r\n}\r\n\r\n/** Google Drive connection settings. */\r\nexport class GoogleDriveNamespace extends Namespace {\r\n /** Config for rendering Google's own file picker in your UI. */\r\n pickerConfig(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/gdrive/picker-config`);\r\n }\r\n\r\n /** Files and folders selected for syncing. */\r\n resources(connectionId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/gdrive/resources`, { query });\r\n }\r\n\r\n /** Select files or folders for syncing. */\r\n addResources(connectionId: string, body: Json): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/gdrive/resources`, { body });\r\n }\r\n\r\n /** Stop syncing one file or folder. */\r\n removeResource(connectionId: string, resourceId: string): Promise<Json> {\r\n return this.req(\r\n \"DELETE\",\r\n `${V2}/connections/${seg(connectionId)}/gdrive/resources/${seg(resourceId)}`,\r\n );\r\n }\r\n}\r\n\r\n/** S3 connection settings. */\r\nexport class S3Namespace extends Namespace {\r\n /** Prefixes visible in the bucket that could be added. */\r\n availablePrefixes(connectionId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/s3/available-prefixes`, { query });\r\n }\r\n\r\n /** Prefixes currently selected for syncing. */\r\n prefixes(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/s3/prefixes`);\r\n }\r\n\r\n /**\r\n * Select prefixes for syncing.\r\n *\r\n * Accepts bare prefixes, or objects carrying `bucket` and `label`:\r\n *\r\n * ```ts\r\n * await client.connections.s3.addPrefixes(\"c1\", [\"handbook/\", \"policies/\"]);\r\n * await client.connections.s3.addPrefixes(\"c1\", [\r\n * { prefix: \"handbook/\", label: \"Handbook\" },\r\n * ]);\r\n * ```\r\n *\r\n * An empty string means the bucket root. The bucket defaults to the one the\r\n * connection's credentials were validated against, and the API rejects any\r\n * other bucket rather than indexing one nobody proved access to.\r\n */\r\n addPrefixes(connectionId: string, prefixes: Array<string | Json>): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/s3/prefixes`, {\r\n body: { prefixes: prefixes.map((p) => asItem(p, \"prefix\")) },\r\n });\r\n }\r\n\r\n /**\r\n * Revoke one prefix approval, optionally purging what it produced.\r\n *\r\n * The prefix travels as a query parameter, not in the body and not as a path\r\n * segment: prefixes contain slashes, which a path segment cannot carry\r\n * unambiguously, and this endpoint reads no body at all.\r\n *\r\n * Pass `purge: true` to also delete the memories already derived from the\r\n * prefix. The default leaves them in place, so revoking an approval does not\r\n * silently destroy knowledge.\r\n */\r\n removePrefix(\r\n connectionId: string,\r\n prefix = \"\",\r\n options: { bucket?: string; purge?: boolean } = {},\r\n ): Promise<Json> {\r\n const query: Record<string, unknown> = { prefix, purge: options.purge ?? false };\r\n if (options.bucket !== undefined) query.bucket = options.bucket;\r\n return this.req(\"DELETE\", `${V2}/connections/${seg(connectionId)}/s3/prefixes`, { query });\r\n }\r\n\r\n /** Keys and patterns this connection will never sync. */\r\n exclusionPolicy(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/s3/exclusion-policy`);\r\n }\r\n\r\n /** Replace this connection's additions to the exclusion policy. */\r\n setExclusionPolicy(connectionId: string, policy: Json): Promise<Json> {\r\n return this.req(\"PUT\", `${V2}/connections/${seg(connectionId)}/s3/exclusion-policy`, {\r\n body: policy,\r\n });\r\n }\r\n\r\n /** Effective S3 settings, including the per-object size ceiling. */\r\n settings(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/s3/settings`);\r\n }\r\n}\r\n\r\n/** Granola connection settings. */\r\nexport class GranolaNamespace extends Namespace {\r\n /** Folders that could be added. */\r\n availableFolders(connectionId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/granola/available-folders`, { query });\r\n }\r\n\r\n /** Folders currently selected for syncing. */\r\n folders(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/granola/folders`);\r\n }\r\n\r\n /** Select folders for syncing. */\r\n addFolders(connectionId: string, body: Json): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/granola/folders`, { body });\r\n }\r\n\r\n /** Stop syncing one folder. */\r\n removeFolder(connectionId: string, folderId: string): Promise<Json> {\r\n return this.req(\r\n \"DELETE\",\r\n `${V2}/connections/${seg(connectionId)}/granola/folders/${seg(folderId)}`,\r\n );\r\n }\r\n\r\n /** Folders and meetings this connection will never sync. */\r\n exclusionPolicy(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/granola/exclusion-policy`);\r\n }\r\n\r\n /** Replace this connection's additions to the exclusion policy. */\r\n setExclusionPolicy(connectionId: string, policy: Json): Promise<Json> {\r\n return this.req(\"PUT\", `${V2}/connections/${seg(connectionId)}/granola/exclusion-policy`, {\r\n body: policy,\r\n });\r\n }\r\n\r\n /** Meeting participants seen on this connection and who they map to. */\r\n identities(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/granola/identities`);\r\n }\r\n\r\n /** Map a participant to a MemorySync end user. */\r\n linkIdentity(connectionId: string, body: Json): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/granola/identities/link`, { body });\r\n }\r\n\r\n /**\r\n * Re-run identity matching for this connection.\r\n *\r\n * Takes no arguments: the route reads no body and re-matches the whole roster.\r\n * `body` is kept optional only so a forward-compatible field can be passed\r\n * once the route grows one.\r\n */\r\n relinkIdentity(connectionId: string, body: Json = {}): Promise<Json> {\r\n const hasFields = Object.keys(body).length > 0;\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/granola/identities/relink`, {\r\n body: hasFields ? body : undefined,\r\n });\r\n }\r\n\r\n /** Effective Granola settings for this connection. */\r\n settings(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/granola/settings`);\r\n }\r\n\r\n /** Update Granola settings for this connection. */\r\n setSettings(connectionId: string, settings: Json): Promise<Json> {\r\n return this.req(\"PUT\", `${V2}/connections/${seg(connectionId)}/granola/settings`, {\r\n body: settings,\r\n });\r\n }\r\n}\r\n\r\n/** Starting an OAuth connection. */\r\nexport class ConnectionOAuthNamespace extends Namespace {\r\n /**\r\n * Begin an OAuth connection and get the URL to send the user to.\r\n *\r\n * The user completes consent in a browser and the provider calls the platform\r\n * back — not your backend. Poll {@link status} to find out how it went.\r\n */\r\n initiate(provider: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/oauth/initiate`, {\r\n body: { provider_id: provider, ...body },\r\n });\r\n }\r\n\r\n /** Where an in-flight OAuth connection got to. */\r\n status(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/oauth/status`, { query });\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────\r\n// Connections\r\n// ─────────────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * Connections to external sources.\r\n *\r\n * Provider-specific settings live in sub-namespaces: `connections.slack`,\r\n * `connections.gdrive`, `connections.s3`, `connections.granola`.\r\n */\r\nexport class ConnectionsNamespace extends Namespace {\r\n readonly slack: SlackNamespace;\r\n readonly gdrive: GoogleDriveNamespace;\r\n readonly s3: S3Namespace;\r\n readonly granola: GranolaNamespace;\r\n readonly oauth: ConnectionOAuthNamespace;\r\n\r\n constructor(request: RequestFn) {\r\n super(request);\r\n this.slack = new SlackNamespace(request);\r\n this.gdrive = new GoogleDriveNamespace(request);\r\n this.s3 = new S3Namespace(request);\r\n this.granola = new GranolaNamespace(request);\r\n this.oauth = new ConnectionOAuthNamespace(request);\r\n }\r\n\r\n /** Every connection in this organization. */\r\n list(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections`, { query });\r\n }\r\n\r\n /** One connection, including its status and last sync. */\r\n get(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}`);\r\n }\r\n\r\n /** Connect a provider that authenticates with an API key or bot token. */\r\n /**\r\n * Connect a provider that authenticates with an API key or bot token.\r\n *\r\n * The wire field is `provider_id`; the argument is named `provider` because\r\n * that is what the rest of this namespace calls it.\r\n */\r\n createWithApiKey(provider: string, apiKey: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/api-key`, {\r\n body: { provider_id: provider, api_key: apiKey, ...body },\r\n });\r\n }\r\n\r\n /** Connect a provider that needs a credential bundle, such as S3 keys. */\r\n createWithCredentials(provider: string, credentials: Json, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/credentials`, {\r\n body: { provider_id: provider, credentials, ...body },\r\n });\r\n }\r\n\r\n /** Change a connection's name, schedule or settings. */\r\n update(connectionId: string, body: Json): Promise<Json> {\r\n return this.req(\"PATCH\", `${V2}/connections/${seg(connectionId)}`, { body });\r\n }\r\n\r\n /**\r\n * Remove a connection.\r\n *\r\n * Stops future syncing. Memories already extracted are left in place — use\r\n * {@link purge} for those, so disconnecting never silently deletes knowledge\r\n * someone still depends on.\r\n */\r\n delete(connectionId: string): Promise<Json> {\r\n return this.req(\"DELETE\", `${V2}/connections/${seg(connectionId)}`);\r\n }\r\n\r\n /** Re-authorise a connection whose credentials expired or were revoked. */\r\n reconnect(connectionId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/reconnect`, { body });\r\n }\r\n\r\n /**\r\n * Delete the memories this connection produced.\r\n *\r\n * Separate from {@link delete} on purpose: removing a connection and removing\r\n * what it taught you are different decisions.\r\n */\r\n purge(connectionId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/purge`, { body });\r\n }\r\n\r\n /** Current and recent sync state for a connection. */\r\n syncStatus(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/sync`);\r\n }\r\n\r\n /** Start a sync now instead of waiting for the schedule. */\r\n triggerSync(connectionId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/sync`, { body });\r\n }\r\n\r\n /** Objects a connection has ingested — files, messages, meetings. */\r\n objects(connectionId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/objects`, { query });\r\n }\r\n\r\n /** Object listing with richer filtering and paging than {@link objects}. */\r\n objectsV2(connectionId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/objects/v2`, { query });\r\n }\r\n\r\n /** Apply one action to many objects — pause, resume, re-extract. */\r\n bulkObjectAction(connectionId: string, body: Json): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/objects/bulk`, { body });\r\n }\r\n\r\n /** Connector totals: connections, objects synced, memories produced. */\r\n stats(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/stats`, { query });\r\n }\r\n\r\n /** Audit trail of connector activity. */\r\n auditLogs(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/audit-logs`, { query });\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────\r\n// Objects\r\n// ─────────────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * A single synced object: a Drive file, a Slack message batch, an S3 key, a\r\n * meeting transcript.\r\n */\r\nexport class ObjectsNamespace extends Namespace {\r\n /** Metadata and sync state for one object. */\r\n get(objectId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/objects/${seg(objectId)}`);\r\n }\r\n\r\n /** What extraction made of this object. */\r\n analysis(objectId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/objects/${seg(objectId)}/analysis`);\r\n }\r\n\r\n /** Every action taken on this object. */\r\n audit(objectId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/objects/${seg(objectId)}/audit`, { query });\r\n }\r\n\r\n /** Versions of this object seen across syncs. */\r\n history(objectId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/objects/${seg(objectId)}/history`, { query });\r\n }\r\n\r\n /** Which memories this object produced, and whether extraction finished. */\r\n memoryStatus(objectId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/objects/${seg(objectId)}/memory-status`);\r\n }\r\n\r\n /** Row and column statistics for spreadsheet-shaped objects. */\r\n structuredStats(objectId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/objects/${seg(objectId)}/structured-stats`);\r\n }\r\n\r\n /** Score this object for extraction worthiness without extracting. */\r\n evaluate(objectId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/objects/${seg(objectId)}/evaluate`, { body });\r\n }\r\n\r\n /** Stop re-syncing this object, leaving its memories in place. */\r\n pause(objectId: string): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/objects/${seg(objectId)}/pause`);\r\n }\r\n\r\n /** Resume syncing a paused object. */\r\n resume(objectId: string): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/objects/${seg(objectId)}/resume`);\r\n }\r\n\r\n /**\r\n * Run extraction again over content already fetched.\r\n *\r\n * Counts against the plan's add allowance, exactly like the first extraction,\r\n * because it creates memories the same way.\r\n */\r\n reextract(objectId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/objects/${seg(objectId)}/reextract`, { body });\r\n }\r\n\r\n /** Fetch this object from the provider again, then extract. */\r\n resync(objectId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/objects/${seg(objectId)}/resync`, { body });\r\n }\r\n\r\n /** Remove the memories this object produced, keeping the object record. */\r\n deleteMemories(objectId: string, query?: Json): Promise<Json> {\r\n return this.req(\"DELETE\", `${V2}/objects/${seg(objectId)}/memories`, { query });\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────\r\n// Providers and sync jobs\r\n// ─────────────────────────────────────────────────────────────────────\r\n\r\n/** Connectors this deployment supports. */\r\nexport class ProvidersNamespace extends Namespace {\r\n /** Every available provider and what it needs to connect. */\r\n list(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/providers`, { query });\r\n }\r\n\r\n /** One provider's capabilities, scopes and settings schema. */\r\n get(providerId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/providers/${seg(providerId)}`);\r\n }\r\n}\r\n\r\n/** Individual sync runs. */\r\nexport class SyncJobsNamespace extends Namespace {\r\n /** Progress and outcome of one sync run. */\r\n get(jobId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/sync-jobs/${seg(jobId)}`);\r\n }\r\n\r\n /** Stop a running sync. Objects already ingested are kept. */\r\n cancel(jobId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/sync-jobs/${seg(jobId)}/cancel`, { body });\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────\r\n// Web crawler\r\n// ─────────────────────────────────────────────────────────────────────\r\n\r\n/** Turn websites into memories. */\r\nexport class WebCrawlerNamespace extends Namespace {\r\n /** Check a URL is reachable and crawlable before committing to a job. */\r\n validate(url: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V1}/web-crawler/validate`, { body: { url, ...body } });\r\n }\r\n\r\n /**\r\n * Start a crawl. Returns a job to poll.\r\n *\r\n * Crawling only fetches and stores page content. Nothing becomes a memory until\r\n * you call {@link importJob}, so a large crawl cannot quietly consume your add\r\n * allowance.\r\n */\r\n crawl(url: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V1}/web-crawler/crawl`, { body: { url, ...body } });\r\n }\r\n\r\n /** Crawl jobs for this organization. */\r\n jobs(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/web-crawler/jobs`, { query });\r\n }\r\n\r\n /** One crawl job's status and progress. */\r\n job(jobId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/web-crawler/jobs/${seg(jobId)}`);\r\n }\r\n\r\n /** Stop a running crawl. Pages already fetched are kept. */\r\n cancelJob(jobId: string): Promise<Json> {\r\n return this.req(\"POST\", `${V1}/web-crawler/jobs/${seg(jobId)}/cancel`);\r\n }\r\n\r\n /** Delete a crawl job and its fetched pages. */\r\n deleteJob(jobId: string): Promise<Json> {\r\n return this.req(\"DELETE\", `${V1}/web-crawler/jobs/${seg(jobId)}`);\r\n }\r\n\r\n /** Pages a crawl fetched, before any import. */\r\n jobContent(jobId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/web-crawler/jobs/${seg(jobId)}/content`, { query });\r\n }\r\n\r\n /** Page counts, byte totals and error breakdown for a crawl. */\r\n jobStatistics(jobId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/web-crawler/jobs/${seg(jobId)}/statistics`);\r\n }\r\n\r\n /**\r\n * Turn a completed crawl's pages into memories.\r\n *\r\n * This is the step that creates memories, so this is the step that is billed —\r\n * one unit per memory created, like every other ingestion path.\r\n */\r\n importJob(jobId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V1}/web-crawler/jobs/${seg(jobId)}/import`, { body });\r\n }\r\n\r\n /** Crawls running right now. */\r\n active(): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/web-crawler/active`);\r\n }\r\n\r\n /** Crawler limits in force: depth, page ceiling, rate, timeouts. */\r\n config(): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/web-crawler/config`);\r\n }\r\n}\r\n\r\n/**\r\n * The `/api/v1/integrations` surface.\r\n *\r\n * Kept because the catalog and the web crawler live here and have no v2\r\n * equivalent. For connection lifecycle use `client.connections`, which is the\r\n * current API — `connected()` and `stats()` here are older, thinner views of the\r\n * same data.\r\n */\r\nexport class IntegrationsNamespace extends Namespace {\r\n readonly webCrawler: WebCrawlerNamespace;\r\n\r\n constructor(request: RequestFn) {\r\n super(request);\r\n this.webCrawler = new WebCrawlerNamespace(request);\r\n }\r\n\r\n /** Every integration this deployment offers, for building a picker UI. */\r\n catalog(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/catalog`, { query });\r\n }\r\n\r\n /** Integrations currently connected. Older view of `connections.list()`. */\r\n connected(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/connected`, { query });\r\n }\r\n\r\n /** Legacy integration counters. Prefer `connections.stats()`. */\r\n stats(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/stats`, { query });\r\n }\r\n\r\n /** Update a legacy integration record. */\r\n update(integrationId: string, body: Json): Promise<Json> {\r\n return this.req(\"PATCH\", `${V1}/${seg(integrationId)}`, { body });\r\n }\r\n\r\n /** Delete a legacy integration record. */\r\n delete(integrationId: string): Promise<Json> {\r\n return this.req(\"DELETE\", `${V1}/${seg(integrationId)}`);\r\n }\r\n}\r\n","import {\r\n AuthError,\r\n ErrorOptions,\r\n MemorySyncError,\r\n NotFoundError,\r\n RateLimitError,\r\n ServerError,\r\n ValidationError,\r\n} from \"./errors\";\r\n\r\n// Kept in step with package.json and with index.ts: this is the version the\r\n// control-plane client reports in its User-Agent, and it sat at 1.1.1 through two\r\n// releases while the data-plane client moved on.\r\nconst SDK_VERSION = \"1.7.0\";\r\n\r\nexport interface ControlPlaneConfig {\r\n baseUrl: string;\r\n accessToken?: string;\r\n projectId?: string;\r\n timeoutMs?: number;\r\n fetch?: typeof fetch;\r\n}\r\n\r\nexport interface ControlPlaneRequestOptions {\r\n projectId?: string;\r\n}\r\n\r\nexport interface SignupRequest {\r\n email: string;\r\n password: string;\r\n organizationName: string;\r\n fullName?: string;\r\n}\r\n\r\nexport interface SignupResponse {\r\n message: string;\r\n email: string;\r\n requiresVerification: boolean;\r\n}\r\n\r\nexport interface LoginRequest {\r\n email: string;\r\n password: string;\r\n}\r\n\r\nexport interface TokenPair {\r\n accessToken: string;\r\n refreshToken: string;\r\n tokenType: string;\r\n}\r\n\r\nexport interface RefreshRequest {\r\n refreshToken: string;\r\n}\r\n\r\nexport interface CurrentUserResponse {\r\n userId: string;\r\n role: string | null;\r\n org: string | number | null;\r\n sid: number | null;\r\n oauthScopes?: string[];\r\n oauthAppId?: string | null;\r\n}\r\n\r\nexport interface LoginResponse {\r\n tokens: TokenPair;\r\n session: {\r\n userId: number;\r\n organizationId: number;\r\n role: string;\r\n };\r\n mfaRequired: boolean;\r\n mfaSetupRequired: boolean;\r\n}\r\n\r\nexport type ApiKeyTestStatus = \"active\" | \"revoked\" | \"expired\" | string;\r\nexport interface BulkRevokeApiKeysRequest {\r\n keyIds: number[];\r\n}\r\n\r\nexport interface BulkRevokeApiKeyResult {\r\n keyId: number;\r\n status: \"revoked\" | \"already_revoked\" | \"not_found\" | \"forbidden\";\r\n}\r\n\r\nexport interface BulkRevokeApiKeysResponse {\r\n revoked: number;\r\n alreadyRevoked: number;\r\n notFound: number;\r\n results: BulkRevokeApiKeyResult[];\r\n}\r\n\r\nexport interface ApiKeyTestResponse {\r\n keyId: number;\r\n valid: boolean;\r\n status: ApiKeyTestStatus;\r\n environment: string;\r\n rateLimitTier: string;\r\n scopes: string[];\r\n projectId: string | null;\r\n lastUsedAt: string | null;\r\n expiresAt: string | null;\r\n expired: boolean;\r\n serverTime: string;\r\n}\r\n\r\nexport interface PlanLimits {\r\n addRequests: number | null;\r\n retrievalRequests: number | null;\r\n}\r\n\r\nexport interface Plan {\r\n id: string;\r\n name: string;\r\n priceCents?: number | null;\r\n priceLabel: string;\r\n description?: string;\r\n limits: PlanLimits;\r\n features?: string[];\r\n ctaLabel?: string;\r\n isEnterprise?: boolean;\r\n}\r\n\r\nexport interface CurrentPlanResponse {\r\n plan: Plan;\r\n status: string;\r\n billingPeriodStart: string | null;\r\n billingPeriodEnd: string | null;\r\n nextResetAt?: string | null;\r\n planLimitAdd?: number | null;\r\n planLimitRetrieval?: number | null;\r\n paymentFailed: boolean;\r\n paymentStatus?: string;\r\n scheduledPlanId: string | null;\r\n cancelAtPeriodEnd: boolean;\r\n}\r\nexport interface Session {\r\n id: number;\r\n isCurrent: boolean;\r\n sessionType: string;\r\n sessionName: string;\r\n userAgent: string;\r\n ip: string;\r\n location: string | null;\r\n geo: Record<string, unknown> | null;\r\n createdAt: string;\r\n lastActivityAt: string;\r\n expiresAt: string;\r\n}\r\n\r\nexport interface SessionListResponse {\r\n sessions: Session[];\r\n currentSessionId: number | null;\r\n}\r\n\r\nexport interface IntegrationQuery {\r\n category?: string;\r\n}\r\n\r\nexport interface Integration {\r\n id: string;\r\n name: string;\r\n description: string;\r\n category: string;\r\n features: string[];\r\n authType: string;\r\n isConfigured: boolean;\r\n isConnected: boolean;\r\n comingSoon: boolean;\r\n}\r\n\r\nexport interface CreateOrganizationRequest {\r\n name: string;\r\n domain?: string;\r\n}\r\n\r\nexport interface OrganizationMembership {\r\n userId: number;\r\n organizationId: number;\r\n role: string;\r\n}\r\n\r\nexport interface Project {\r\n id: string;\r\n name: string;\r\n tenantId: string;\r\n isDefault: boolean;\r\n memoryCount: number;\r\n archivedAt: string | null;\r\n createdAt: string;\r\n updatedAt: string;\r\n}\r\n\r\nexport interface CreateProjectRequest {\r\n name: string;\r\n}\r\n\r\nexport interface RenameProjectRequest {\r\n name: string;\r\n}\r\n\r\nexport interface WebhookRetryConfig {\r\n enabled?: boolean;\r\n maxRetries?: number;\r\n initialDelaySeconds?: number;\r\n maxDelaySeconds?: number;\r\n backoffMultiplier?: number;\r\n retryStatusCodes?: string[];\r\n}\r\n\r\nexport interface WebhookSignatureConfig {\r\n algorithm?: \"hmac-sha256\" | \"hmac-sha512\";\r\n headerName?: string;\r\n timestampHeader?: string;\r\n toleranceSeconds?: number;\r\n}\r\n\r\nexport interface CreateWebhookRequest {\r\n name: string;\r\n url: string;\r\n events: string[];\r\n description?: string;\r\n retryConfig?: WebhookRetryConfig;\r\n signatureConfig?: WebhookSignatureConfig;\r\n projectId?: string;\r\n}\r\n\r\nexport interface UpdateWebhookRequest {\r\n name?: string;\r\n url?: string;\r\n description?: string;\r\n events?: string[];\r\n retryConfig?: WebhookRetryConfig;\r\n signatureConfig?: WebhookSignatureConfig;\r\n}\r\n\r\nexport interface Webhook {\r\n id: number;\r\n name: string;\r\n url: string;\r\n description: string | null;\r\n secretPrefix: string;\r\n events: string[];\r\n enabled: boolean;\r\n signatureAlgorithm: string;\r\n signatureHeader?: string;\r\n timestampHeader?: string;\r\n signatureTolerance?: number;\r\n retryEnabled?: boolean;\r\n maxRetries?: number;\r\n initialDelaySeconds?: number;\r\n maxDelaySeconds?: number;\r\n backoffMultiplier?: number;\r\n retryStatusCodes?: string[];\r\n totalDeliveries?: number;\r\n successfulDeliveries?: number;\r\n failedDeliveries?: number;\r\n consecutiveFailures?: number;\r\n successRate?: number;\r\n lastTriggeredAt?: string | null;\r\n lastSuccessAt?: string | null;\r\n lastFailureAt?: string | null;\r\n lastError?: string | null;\r\n lastStatusCode?: number | null;\r\n createdAt?: string;\r\n updatedAt?: string;\r\n createdByName?: string | null;\r\n projectId: string | null;\r\n}\r\n\r\nexport interface CreatedWebhook extends Webhook {\r\n secret: string;\r\n}\r\n\r\nexport interface WebhookListResponse {\r\n endpoints: Webhook[];\r\n totalEndpoints: number;\r\n activeEndpoints: number;\r\n totalDeliveries: number;\r\n avgSuccessRate: number;\r\n failingEndpoints: number;\r\n}\r\n\r\nexport interface TestWebhookRequest {\r\n eventType?: string;\r\n}\r\n\r\nexport interface TestWebhookResponse {\r\n deliveryId: number;\r\n eventId: string;\r\n eventType: string;\r\n endpointId: number;\r\n status: string;\r\n payload: Record<string, unknown>;\r\n message: string;\r\n}\r\n\r\nexport interface ReplayWebhookDeliveriesRequest {\r\n sinceMinutes?: number;\r\n statuses?: string[];\r\n limit?: number;\r\n}\r\n\r\nexport interface ReplayWebhookDeliveriesResponse {\r\n endpointId: number;\r\n eligible: number;\r\n replayed: number;\r\n skipped: number;\r\n deliveryIds: number[];\r\n}\r\n\r\nexport interface WebhookDeliveryQuery {\r\n page?: number;\r\n pageSize?: number;\r\n status?: string;\r\n}\r\nexport interface WebhookDelivery {\r\n id: number;\r\n endpointId: number;\r\n eventType: string;\r\n eventId: string;\r\n status: string;\r\n payload?: Record<string, unknown>;\r\n payloadHash: string;\r\n signature?: string | null;\r\n statusCode: number | null;\r\n responseBody?: string | null;\r\n errorMessage?: string | null;\r\n latencyMs: number | null;\r\n attemptNumber: number;\r\n maxAttempts: number;\r\n nextRetryAt?: string | null;\r\n createdAt: string;\r\n completedAt: string | null;\r\n}\r\n\r\nexport interface WebhookDeliveryListResponse {\r\n deliveries: WebhookDelivery[];\r\n total: number;\r\n page: number;\r\n pageSize: number;\r\n}\r\n\r\nexport interface WebhookEventTypesResponse {\r\n eventTypes: string[];\r\n categories: Record<string, string[]>;\r\n}\r\n\r\nexport interface WebhookHealth {\r\n activeWebhooks: number;\r\n totalWebhooks: number;\r\n totalDeliveriesAllTime: number;\r\n totalDeliveries24h: number;\r\n successRate7d: number;\r\n failingEndpoints: number;\r\n pendingRetries: number;\r\n deadLetterCount: number;\r\n}\r\n\r\nexport interface RecentWebhookDeliveryQuery extends WebhookDeliveryQuery {\r\n endpointId?: number;\r\n}\r\n\r\nexport type ExportFormat = \"csv\" | \"jsonl\";\r\nexport type ExportScope = \"filtered\" | \"all\" | \"date_range\";\r\nexport type ExportJobStatus =\r\n | \"queued\"\r\n | \"processing\"\r\n | \"generating\"\r\n | \"completed\"\r\n | \"failed\"\r\n | \"cancelled\"\r\n | \"expired\";\r\n\r\nexport interface ExportFilters {\r\n q?: string | null;\r\n userId?: string | null;\r\n isSummary?: boolean | null;\r\n tier?: string | null;\r\n source?: string | null;\r\n timeRange?: string | null;\r\n dateFrom?: string | null;\r\n dateTo?: string | null;\r\n includeSoftDeleted?: boolean;\r\n}\r\n\r\nexport interface CreateExportRequest {\r\n format?: ExportFormat;\r\n scope?: ExportScope;\r\n filters?: ExportFilters | null;\r\n}\r\n\r\nexport interface ExportJob {\r\n id: string;\r\n projectId: string | null;\r\n environment: string;\r\n format: ExportFormat;\r\n scope: ExportScope;\r\n filters: ExportFilters;\r\n status: ExportJobStatus;\r\n errorMessage: string | null;\r\n retryCount: number;\r\n totalRows: number | null;\r\n processedRows: number;\r\n progressPercentage: number;\r\n fileSizeBytes: number | null;\r\n sha256Hash: string | null;\r\n downloadCount: number;\r\n createdAt: string | null;\r\n startedAt: string | null;\r\n completedAt: string | null;\r\n expiresAt: string | null;\r\n downloadUrl: string | null;\r\n}\r\n\r\nexport interface CreateExportResponse {\r\n job: ExportJob;\r\n estimatedTotal: number | null;\r\n}\r\n\r\nexport interface ExportListQuery {\r\n limit?: number;\r\n}\r\n\r\nexport interface ExportJobListResponse {\r\n jobs: ExportJob[];\r\n total: number;\r\n}\r\n\r\nexport interface ExportDownloadUrl {\r\n downloadUrl: string;\r\n expiresAt: string | null;\r\n fileSizeBytes: number | null;\r\n filename: string;\r\n}\r\n\r\ntype QueryValue = string | number | boolean | null | undefined;\r\ntype WireObject = Record<string, unknown>;\r\n\r\nfunction safeJson(text: string): unknown {\r\n try {\r\n return JSON.parse(text);\r\n } catch {\r\n return text;\r\n }\r\n}\r\n\r\nfunction extractDetail(body: unknown): string | undefined {\r\n if (!body || typeof body !== \"object\") return undefined;\r\n const value = body as Record<string, unknown>;\r\n if (typeof value.detail === \"string\") return value.detail;\r\n if (value.error && typeof value.error === \"object\") {\r\n const error = value.error as Record<string, unknown>;\r\n if (typeof error.message === \"string\") return error.message;\r\n }\r\n if (Array.isArray(value.detail) && value.detail.length > 0) {\r\n const first = value.detail[0];\r\n if (first && typeof first === \"object\" && typeof (first as Record<string, unknown>).msg === \"string\") {\r\n return (first as Record<string, unknown>).msg as string;\r\n }\r\n }\r\n return undefined;\r\n}\r\nfunction extractBodyRetryAfter(body: unknown): number {\r\n if (!body || typeof body !== \"object\") return 0;\r\n const value = body as Record<string, unknown>;\r\n if (typeof value.retry_after === \"number\") return value.retry_after;\r\n if (value.error && typeof value.error === \"object\") {\r\n const retryAfter = (value.error as Record<string, unknown>).retry_after;\r\n if (typeof retryAfter === \"number\") return retryAfter;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction parseRetryAfter(value: string | null): number | undefined {\r\n if (!value) return undefined;\r\n const seconds = Number(value);\r\n if (Number.isFinite(seconds) && seconds >= 0) return seconds;\r\n const date = Date.parse(value);\r\n if (Number.isNaN(date)) return undefined;\r\n return Math.max(0, Math.ceil((date - Date.now()) / 1000));\r\n}\r\n\r\nfunction snakeToCamel(key: string): string {\r\n return key.replace(/_([a-z0-9])/g, (_, character: string) => character.toUpperCase());\r\n}\r\n\r\nconst OPAQUE_RESPONSE_KEYS = new Set([\"payload\", \"metadata\", \"geo\", \"configuration\"]);\r\n\r\nfunction normalizeResponse(value: unknown): unknown {\r\n if (Array.isArray(value)) return value.map(normalizeResponse);\r\n if (!value || typeof value !== \"object\") return value;\r\n const normalized: Record<string, unknown> = {};\r\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\r\n const camelKey = snakeToCamel(key);\r\n normalized[camelKey] = OPAQUE_RESPONSE_KEYS.has(camelKey) ? item : normalizeResponse(item);\r\n }\r\n return normalized;\r\n}\r\n\r\nfunction queryString(values: Record<string, QueryValue>): string {\r\n const params = new URLSearchParams();\r\n for (const [key, value] of Object.entries(values)) {\r\n if (value !== undefined && value !== null) params.set(key, String(value));\r\n }\r\n const encoded = params.toString();\r\n return encoded ? `?${encoded}` : \"\";\r\n}\r\n\r\nfunction positiveId(value: number, name: string): void {\r\n if (!Number.isInteger(value) || value <= 0) {\r\n throw new ValidationError(`${name} must be a positive integer`);\r\n }\r\n}\r\n\r\nfunction nonEmpty(value: string, name: string): void {\r\n if (typeof value !== \"string\" || !value.trim()) throw new ValidationError(`${name} must not be empty`);\r\n}\r\n\r\nfunction boundedInteger(value: number, name: string, minimum: number, maximum: number): void {\r\n if (!Number.isInteger(value) || value < minimum || value > maximum) {\r\n throw new ValidationError(`${name} must be an integer between ${minimum} and ${maximum}`);\r\n }\r\n}\r\n\r\nfunction nonNegativeInteger(value: number, name: string): void {\r\n if (!Number.isInteger(value) || value < 0) {\r\n throw new ValidationError(`${name} must be a non-negative integer`);\r\n }\r\n}\r\n\r\nfunction nonEmptyStrings(values: string[], name: string): void {\r\n if (!Array.isArray(values) || values.length === 0 ||\r\n values.some((value) => typeof value !== \"string\" || !value.trim())) {\r\n throw new ValidationError(`${name} must contain at least one non-empty string`);\r\n }\r\n}\r\n\r\nfunction projectName(value: string): void {\r\n nonEmpty(value, \"name\");\r\n if (value.length > 200) throw new ValidationError(\"name may contain at most 200 characters\");\r\n}\r\n\r\nfunction pathId(value: string, name: string, minimum = 1, maximum?: number): string {\r\n nonEmpty(value, name);\r\n const trimmed = value.trim();\r\n if (trimmed.length < minimum || (maximum !== undefined && trimmed.length > maximum)) {\r\n const range = maximum === undefined ? `at least ${minimum}` : `between ${minimum} and ${maximum}`;\r\n throw new ValidationError(`${name} must contain ${range} characters`);\r\n }\r\n return encodeURIComponent(trimmed);\r\n}\r\n\r\nfunction validateWebhookRetryConfig(config: WebhookRetryConfig): void {\r\n if (config.maxRetries !== undefined) boundedInteger(config.maxRetries, \"maxRetries\", 1, 10);\r\n if (config.initialDelaySeconds !== undefined) boundedInteger(config.initialDelaySeconds, \"initialDelaySeconds\", 1, 60);\r\n if (config.maxDelaySeconds !== undefined) boundedInteger(config.maxDelaySeconds, \"maxDelaySeconds\", 60, 86_400);\r\n if (config.backoffMultiplier !== undefined &&\r\n (!Number.isFinite(config.backoffMultiplier) || config.backoffMultiplier < 1 || config.backoffMultiplier > 5)) {\r\n throw new ValidationError(\"backoffMultiplier must be between 1 and 5\");\r\n }\r\n if (config.retryStatusCodes !== undefined &&\r\n (!Array.isArray(config.retryStatusCodes) || config.retryStatusCodes.length === 0 ||\r\n config.retryStatusCodes.some((value) => typeof value !== \"string\" || value.trim().length === 0))) {\r\n throw new ValidationError(\"retryStatusCodes must contain at least one non-empty string\");\r\n }\r\n}\r\n\r\nfunction validateWebhookSignatureConfig(config: WebhookSignatureConfig): void {\r\n if (config.algorithm !== undefined && config.algorithm !== \"hmac-sha256\" && config.algorithm !== \"hmac-sha512\") {\r\n throw new ValidationError(\"algorithm must be 'hmac-sha256' or 'hmac-sha512'\");\r\n }\r\n for (const [name, value] of [[\"headerName\", config.headerName], [\"timestampHeader\", config.timestampHeader]] as const) {\r\n if (value !== undefined && value.trim().length === 0) {\r\n throw new ValidationError(`${name} must be a non-empty string`);\r\n }\r\n if (value !== undefined && value.length > 64) {\r\n throw new ValidationError(`${name} may contain at most 64 characters`);\r\n }\r\n }\r\n if (config.toleranceSeconds !== undefined) boundedInteger(config.toleranceSeconds, \"toleranceSeconds\", 60, 3_600);\r\n}\r\n\r\nfunction webhookRetryConfig(config: WebhookRetryConfig): WireObject {\r\n validateWebhookRetryConfig(config);\r\n const wire: WireObject = {};\r\n if (config.enabled !== undefined) wire.enabled = config.enabled;\r\n if (config.maxRetries !== undefined) wire.max_retries = config.maxRetries;\r\n if (config.initialDelaySeconds !== undefined) wire.initial_delay_seconds = config.initialDelaySeconds;\r\n if (config.maxDelaySeconds !== undefined) wire.max_delay_seconds = config.maxDelaySeconds;\r\n if (config.backoffMultiplier !== undefined) wire.backoff_multiplier = config.backoffMultiplier;\r\n if (config.retryStatusCodes !== undefined) wire.retry_status_codes = config.retryStatusCodes;\r\n return wire;\r\n}\r\n\r\nfunction webhookSignatureConfig(config: WebhookSignatureConfig): WireObject {\r\n validateWebhookSignatureConfig(config);\r\n const wire: WireObject = {};\r\n if (config.algorithm !== undefined) wire.algorithm = config.algorithm;\r\n if (config.headerName !== undefined) wire.header_name = config.headerName;\r\n if (config.timestampHeader !== undefined) wire.timestamp_header = config.timestampHeader;\r\n if (config.toleranceSeconds !== undefined) wire.tolerance_seconds = config.toleranceSeconds;\r\n return wire;\r\n}\r\n\r\nfunction exportFilters(filters: ExportFilters): WireObject {\r\n const wire: WireObject = {};\r\n if (filters.q !== undefined) wire.q = filters.q;\r\n if (filters.userId !== undefined) wire.user_id = filters.userId;\r\n if (filters.isSummary !== undefined) wire.is_summary = filters.isSummary;\r\n if (filters.tier !== undefined) wire.tier = filters.tier;\r\n if (filters.source !== undefined) wire.source = filters.source;\r\n if (filters.timeRange !== undefined) wire.time_range = filters.timeRange;\r\n if (filters.dateFrom !== undefined) wire.date_from = filters.dateFrom;\r\n if (filters.dateTo !== undefined) wire.date_to = filters.dateTo;\r\n if (filters.includeSoftDeleted !== undefined) wire.include_soft_deleted = filters.includeSoftDeleted;\r\n return wire;\r\n}\r\n\r\nfunction validateWebhook(name: string, url: string, events: string[]): void {\r\n nonEmpty(name, \"name\");\r\n if (name.length > 128) throw new ValidationError(\"name may contain at most 128 characters\");\r\n nonEmptyStrings(events, \"events\");\r\n validateWebhookUrl(url);\r\n}\r\n\r\nfunction validateWebhookUrl(url: string): void {\r\n nonEmpty(url, \"url\");\r\n let parsed: URL;\r\n try {\r\n parsed = new URL(url);\r\n } catch {\r\n throw new ValidationError(\"url must be a valid HTTP or HTTPS URL\");\r\n }\r\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\r\n throw new ValidationError(\"url must be a valid HTTP or HTTPS URL\");\r\n }\r\n if (parsed.username || parsed.password) throw new ValidationError(\"url must not contain credentials\");\r\n}\r\n\r\ninterface RequestOptions extends ControlPlaneRequestOptions {\r\n body?: unknown;\r\n auth?: boolean;\r\n project?: boolean;\r\n}\r\n\r\nexport class ControlPlaneClient {\r\n private readonly baseUrl: string;\r\n private readonly accessToken?: string;\r\n private readonly projectId?: string;\r\n private readonly timeoutMs: number;\r\n private readonly fetchImpl: typeof fetch;\r\n constructor(config: ControlPlaneConfig) {\r\n if (!config.baseUrl?.trim()) throw new ValidationError(\"baseUrl is required\");\r\n let parsed: URL;\r\n try {\r\n parsed = new URL(config.baseUrl);\r\n } catch {\r\n throw new ValidationError(\"baseUrl must be an absolute HTTP or HTTPS URL\");\r\n }\r\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\r\n throw new ValidationError(\"baseUrl must be an absolute HTTP or HTTPS URL\");\r\n }\r\n if (config.accessToken !== undefined && !config.accessToken.trim()) {\r\n throw new ValidationError(\"accessToken must not be empty when provided\");\r\n }\r\n if (config.projectId !== undefined && !config.projectId.trim()) {\r\n throw new ValidationError(\"projectId must not be empty when provided\");\r\n }\r\n if (config.timeoutMs !== undefined && (!Number.isFinite(config.timeoutMs) || config.timeoutMs <= 0)) {\r\n throw new ValidationError(\"timeoutMs must be greater than zero\");\r\n }\r\n this.baseUrl = config.baseUrl.replace(/\\/+$/, \"\");\r\n this.accessToken = config.accessToken?.trim();\r\n this.projectId = config.projectId?.trim();\r\n this.timeoutMs = config.timeoutMs ?? 30_000;\r\n const implementation = config.fetch ?? (typeof fetch !== \"undefined\" ? fetch : undefined);\r\n if (!implementation) {\r\n throw new Error(\"No fetch implementation available. Pass `fetch` in config or use Node 18+.\");\r\n }\r\n this.fetchImpl = implementation;\r\n }\r\n\r\n private async request<T>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\r\n const requiresAuth = options.auth !== false;\r\n if (requiresAuth && !this.accessToken) {\r\n throw new AuthError(\"accessToken is required for this operation\");\r\n }\r\n if (options.projectId !== undefined && !options.projectId.trim()) {\r\n throw new ValidationError(\"projectId override must not be empty\");\r\n }\r\n const headers: Record<string, string> = {\r\n Accept: \"application/json\",\r\n \"User-Agent\": `memorysync-sdk-js/${SDK_VERSION}`,\r\n };\r\n if (requiresAuth) headers.Authorization = `Bearer ${this.accessToken}`;\r\n const selectedProject = options.project === false\r\n ? undefined\r\n : options.projectId?.trim() ?? this.projectId;\r\n if (selectedProject) headers[\"X-Project-ID\"] = selectedProject;\r\n if (options.body !== undefined) headers[\"Content-Type\"] = \"application/json\";\r\n\r\n const controller = new AbortController();\r\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\r\n try {\r\n const response = await this.fetchImpl(`${this.baseUrl}${path}`, {\r\n method,\r\n headers,\r\n body: options.body === undefined ? undefined : JSON.stringify(options.body),\r\n signal: controller.signal,\r\n });\r\n const requestId = response.headers.get(\"X-Request-ID\") ?? undefined;\r\n if (response.status === 204) return undefined as T;\r\n const text = await response.text();\r\n const parsedBody = text ? safeJson(text) : null;\r\n if (!response.ok) {\r\n this.throwForStatus(response.status, parsedBody, requestId, response.headers.get(\"Retry-After\"));\r\n }\r\n return normalizeResponse(parsedBody) as T;\r\n } catch (error) {\r\n if (error instanceof MemorySyncError) throw error;\r\n if (error instanceof Error && error.name === \"AbortError\") {\r\n throw new MemorySyncError(`Request timed out after ${this.timeoutMs}ms`);\r\n }\r\n const message = error instanceof Error ? error.message : String(error);\r\n throw new MemorySyncError(`Network error: ${message}`);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n private throwForStatus(\r\n status: number,\r\n body: unknown,\r\n requestId: string | undefined,\r\n retryAfterHeader: string | null,\r\n ): never {\r\n const detail = extractDetail(body);\r\n const options: ErrorOptions = { statusCode: status, response: body, requestId };\r\n if (status === 401) throw new AuthError(detail || \"Unauthenticated\", options);\r\n if (status === 403) throw new AuthError(detail || \"Forbidden\", options);\r\n if (status === 404) throw new NotFoundError(detail || \"Not found\", options);\r\n if (status === 400 || status === 409 || status === 422) {\r\n throw new ValidationError(detail || \"Validation error\", options);\r\n }\r\n if (status === 429) {\r\n const retryAfter = parseRetryAfter(retryAfterHeader) ?? extractBodyRetryAfter(body);\r\n throw new RateLimitError(detail || \"Rate limited\", retryAfter, options);\r\n }\r\n if (status >= 500) throw new ServerError(detail || `Server error (${status})`, options);\r\n throw new MemorySyncError(detail || `Unexpected status ${status}`, options);\r\n }\r\n\r\n async bulkRevokeApiKeys(\r\n request: BulkRevokeApiKeysRequest,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<BulkRevokeApiKeysResponse> {\r\n if (!Array.isArray(request.keyIds) || request.keyIds.length < 1 || request.keyIds.length > 100) {\r\n throw new ValidationError(\"keyIds must contain between 1 and 100 entries\");\r\n }\r\n request.keyIds.forEach((id) => positiveId(id, \"keyIds entry\"));\r\n return this.request(\"POST\", \"/org/api-keys/bulk-revoke\", {\r\n ...options,\r\n body: { key_ids: request.keyIds },\r\n });\r\n }\r\n\r\n async testApiKey(keyId: number, options: ControlPlaneRequestOptions = {}): Promise<ApiKeyTestResponse> {\r\n positiveId(keyId, \"keyId\");\r\n return this.request(\"POST\", `/org/api-keys/${keyId}/test`, options);\r\n }\r\n\r\n async signup(request: SignupRequest): Promise<SignupResponse> {\r\n nonEmpty(request.email, \"email\");\r\n if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(request.email)) {\r\n throw new ValidationError(\"email must be a valid email address\");\r\n }\r\n nonEmpty(request.password, \"password\");\r\n if (request.password.length < 8) {\r\n throw new ValidationError(\"password must contain at least 8 characters\");\r\n }\r\n nonEmpty(request.organizationName, \"organizationName\");\r\n const organizationLength = request.organizationName.trim().length;\r\n if (organizationLength < 2 || organizationLength > 100) {\r\n throw new ValidationError(\"organizationName must contain between 2 and 100 characters\");\r\n }\r\n return this.request(\"POST\", \"/auth/signup\", {\r\n auth: false,\r\n project: false,\r\n body: {\r\n email: request.email,\r\n password: request.password,\r\n organization_name: request.organizationName,\r\n ...(request.fullName === undefined ? {} : { full_name: request.fullName }),\r\n },\r\n });\r\n }\r\n\r\n async login(request: LoginRequest, options: ControlPlaneRequestOptions = {}): Promise<LoginResponse> {\r\n nonEmpty(request.email, \"email\");\r\n nonEmpty(request.password, \"password\");\r\n if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(request.email)) {\r\n throw new ValidationError(\"email must be a valid email address\");\r\n }\r\n return this.request(\"POST\", \"/auth/login\", {\r\n ...options,\r\n auth: false,\r\n project: false,\r\n body: { email: request.email, password: request.password },\r\n });\r\n }\r\n\r\n async refresh(request: RefreshRequest): Promise<TokenPair> {\r\n nonEmpty(request.refreshToken, \"refreshToken\");\r\n return this.request(\"POST\", \"/auth/refresh\", {\r\n auth: false,\r\n project: false,\r\n body: { refresh_token: request.refreshToken },\r\n });\r\n }\r\n\r\n async logout(request: RefreshRequest): Promise<void> {\r\n nonEmpty(request.refreshToken, \"refreshToken\");\r\n return this.request(\"POST\", \"/auth/logout\", {\r\n auth: false,\r\n project: false,\r\n body: { refresh_token: request.refreshToken },\r\n });\r\n }\r\n\r\n async me(): Promise<CurrentUserResponse> {\r\n return this.request(\"GET\", \"/auth/me\", { project: false });\r\n }\r\n\r\n async logoutAll(): Promise<void> {\r\n return this.request(\"POST\", \"/auth/logout-all\", { project: false });\r\n }\r\n\r\n async getCurrentPlan(options: ControlPlaneRequestOptions = {}): Promise<CurrentPlanResponse> {\r\n return this.request(\"GET\", \"/org/billing/current-plan\", options);\r\n }\r\n\r\n async listSessions(options: ControlPlaneRequestOptions = {}): Promise<SessionListResponse> {\r\n return this.request(\"GET\", \"/auth/sessions\", options);\r\n }\r\n\r\n async revokeSession(sessionId: number, options: ControlPlaneRequestOptions = {}): Promise<void> {\r\n positiveId(sessionId, \"sessionId\");\r\n return this.request(\"POST\", `/auth/sessions/${sessionId}/revoke`, options);\r\n }\r\n\r\n async listIntegrations(\r\n query: IntegrationQuery = {},\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<Integration[]> {\r\n if (query.category !== undefined) nonEmpty(query.category, \"category\");\r\n const path = \"/api/v1/integrations/catalog\" + queryString({ category: query.category });\r\n return this.request(\"GET\", path, options);\r\n }\r\n\r\n async createOrganization(\r\n request: CreateOrganizationRequest,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<OrganizationMembership> {\r\n nonEmpty(request.name, \"name\");\r\n if (request.domain !== undefined) nonEmpty(request.domain, \"domain\");\r\n const body: WireObject = { name: request.name };\r\n if (request.domain !== undefined) body.domain = request.domain;\r\n return this.request(\"POST\", \"/organizations\", { ...options, body });\r\n }\r\n\r\n async listOrganizations(options: ControlPlaneRequestOptions = {}): Promise<OrganizationMembership[]> {\r\n return this.request(\"GET\", \"/organizations\", options);\r\n }\r\n\r\n async listProjects(options: ControlPlaneRequestOptions = {}): Promise<Project[]> {\r\n return this.request(\"GET\", \"/org/projects\", options);\r\n }\r\n\r\n async createProject(\r\n request: CreateProjectRequest,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<Project> {\r\n projectName(request.name);\r\n return this.request(\"POST\", \"/org/projects\", { ...options, body: { name: request.name } });\r\n }\r\n\r\n async renameProject(\r\n projectId: string,\r\n request: RenameProjectRequest,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<Project> {\r\n const encodedId = pathId(projectId, \"projectId\");\r\n projectName(request.name);\r\n return this.request(\"PATCH\", `/org/projects/${encodedId}`, { ...options, body: { name: request.name } });\r\n }\r\n\r\n async archiveProject(projectId: string, options: ControlPlaneRequestOptions = {}): Promise<Project> {\r\n return this.request(\"POST\", `/org/projects/${pathId(projectId, \"projectId\")}/archive`, options);\r\n }\r\n\r\n async unarchiveProject(projectId: string, options: ControlPlaneRequestOptions = {}): Promise<Project> {\r\n return this.request(\"POST\", `/org/projects/${pathId(projectId, \"projectId\")}/unarchive`, options);\r\n }\r\n\r\n async deleteProject(projectId: string, options: ControlPlaneRequestOptions = {}): Promise<void> {\r\n return this.request(\"DELETE\", `/org/projects/${pathId(projectId, \"projectId\")}`, options);\r\n }\r\n\r\n async createWebhook(\r\n request: CreateWebhookRequest,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<CreatedWebhook> {\r\n validateWebhook(request.name, request.url, request.events);\r\n if (request.description !== undefined && request.description.length > 500) {\r\n throw new ValidationError(\"description may contain at most 500 characters\");\r\n }\r\n if (request.projectId !== undefined) {\r\n nonEmpty(request.projectId, \"projectId\");\r\n if (request.projectId.length > 64) throw new ValidationError(\"projectId may contain at most 64 characters\");\r\n }\r\n if (options.projectId !== undefined) nonEmpty(options.projectId, \"projectId override\");\r\n if (request.projectId && options.projectId && request.projectId.trim() !== options.projectId.trim()) {\r\n throw new ValidationError(\"request projectId and options projectId must match\");\r\n }\r\n const body: WireObject = { name: request.name, url: request.url, events: request.events };\r\n if (request.description !== undefined) body.description = request.description;\r\n if (request.retryConfig !== undefined) body.retry_config = webhookRetryConfig(request.retryConfig);\r\n if (request.signatureConfig !== undefined) body.signature_config = webhookSignatureConfig(request.signatureConfig);\r\n if (request.projectId !== undefined) body.project_id = request.projectId;\r\n return this.request(\"POST\", \"/org/webhooks\", {\r\n ...options,\r\n projectId: options.projectId ?? request.projectId,\r\n body,\r\n });\r\n }\r\n async listWebhooks(options: ControlPlaneRequestOptions = {}): Promise<WebhookListResponse> {\r\n return this.request(\"GET\", \"/org/webhooks\", options);\r\n }\r\n\r\n async getWebhook(endpointId: number, options: ControlPlaneRequestOptions = {}): Promise<Webhook> {\r\n positiveId(endpointId, \"endpointId\");\r\n return this.request(\"GET\", `/org/webhooks/${endpointId}`, options);\r\n }\r\n\r\n async getWebhookEventTypes(options: ControlPlaneRequestOptions = {}): Promise<WebhookEventTypesResponse> {\r\n return this.request(\"GET\", \"/org/webhooks/event-types\", options);\r\n }\r\n\r\n async getWebhookHealth(options: ControlPlaneRequestOptions = {}): Promise<WebhookHealth> {\r\n return this.request(\"GET\", \"/org/webhooks/health\", options);\r\n }\r\n\r\n async pauseWebhook(endpointId: number, options: ControlPlaneRequestOptions = {}): Promise<Webhook> {\r\n positiveId(endpointId, \"endpointId\");\r\n return this.request(\"POST\", `/org/webhooks/${endpointId}/pause`, options);\r\n }\r\n\r\n async resumeWebhook(endpointId: number, options: ControlPlaneRequestOptions = {}): Promise<Webhook> {\r\n positiveId(endpointId, \"endpointId\");\r\n return this.request(\"POST\", `/org/webhooks/${endpointId}/resume`, options);\r\n }\r\n\r\n async rotateWebhookSecret(\r\n endpointId: number,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<CreatedWebhook> {\r\n positiveId(endpointId, \"endpointId\");\r\n return this.request(\"POST\", `/org/webhooks/${endpointId}/rotate-secret`, options);\r\n }\r\n\r\n async updateWebhook(\r\n endpointId: number,\r\n request: UpdateWebhookRequest,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<Webhook> {\r\n positiveId(endpointId, \"endpointId\");\r\n const body: WireObject = {};\r\n if (request.name !== undefined) {\r\n nonEmpty(request.name, \"name\");\r\n if (request.name.length > 128) throw new ValidationError(\"name may contain at most 128 characters\");\r\n body.name = request.name;\r\n }\r\n if (request.url !== undefined) {\r\n validateWebhookUrl(request.url);\r\n body.url = request.url;\r\n }\r\n if (request.description !== undefined) {\r\n if (request.description.length > 500) {\r\n throw new ValidationError(\"description may contain at most 500 characters\");\r\n }\r\n body.description = request.description;\r\n }\r\n if (request.events !== undefined) {\r\n nonEmptyStrings(request.events, \"events\");\r\n body.events = request.events;\r\n }\r\n if (request.retryConfig !== undefined) body.retry_config = webhookRetryConfig(request.retryConfig);\r\n if (request.signatureConfig !== undefined) body.signature_config = webhookSignatureConfig(request.signatureConfig);\r\n if (Object.keys(body).length === 0) {\r\n throw new ValidationError(\"updateWebhook requires at least one editable field\");\r\n }\r\n return this.request(\"PATCH\", `/org/webhooks/${endpointId}`, { ...options, body });\r\n }\r\n\r\n async deleteWebhook(endpointId: number, options: ControlPlaneRequestOptions = {}): Promise<void> {\r\n positiveId(endpointId, \"endpointId\");\r\n return this.request(\"DELETE\", `/org/webhooks/${endpointId}`, options);\r\n }\r\n\r\n async testWebhook(\r\n endpointId: number,\r\n request: TestWebhookRequest = {},\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<TestWebhookResponse> {\r\n positiveId(endpointId, \"endpointId\");\r\n const body: WireObject = {};\r\n if (request.eventType !== undefined) {\r\n nonEmpty(request.eventType, \"eventType\");\r\n body.event_type = request.eventType;\r\n }\r\n return this.request(\"POST\", `/org/webhooks/${endpointId}/test`, { ...options, body });\r\n }\r\n async replayWebhookDeliveries(\r\n endpointId: number,\r\n request: ReplayWebhookDeliveriesRequest = {},\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<ReplayWebhookDeliveriesResponse> {\r\n positiveId(endpointId, \"endpointId\");\r\n if (request.sinceMinutes !== undefined &&\r\n (!Number.isInteger(request.sinceMinutes) || request.sinceMinutes < 1 || request.sinceMinutes > 10_080)) {\r\n throw new ValidationError(\"sinceMinutes must be an integer between 1 and 10080\");\r\n }\r\n if (request.limit !== undefined &&\r\n (!Number.isInteger(request.limit) || request.limit < 1 || request.limit > 1_000)) {\r\n throw new ValidationError(\"limit must be an integer between 1 and 1000\");\r\n }\r\n if (request.statuses !== undefined) nonEmptyStrings(request.statuses, \"statuses\");\r\n const body: WireObject = {};\r\n if (request.sinceMinutes !== undefined) body.since_minutes = request.sinceMinutes;\r\n if (request.statuses !== undefined) body.statuses = request.statuses;\r\n if (request.limit !== undefined) body.limit = request.limit;\r\n return this.request(\"POST\", `/org/webhooks/${endpointId}/replay`, { ...options, body });\r\n }\r\n\r\n async listWebhookDeliveries(\r\n endpointId: number,\r\n query: WebhookDeliveryQuery = {},\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<WebhookDeliveryListResponse> {\r\n positiveId(endpointId, \"endpointId\");\r\n if (query.page !== undefined) positiveId(query.page, \"page\");\r\n if (query.pageSize !== undefined) boundedInteger(query.pageSize, \"pageSize\", 1, 100);\r\n if (query.status !== undefined) nonEmpty(query.status, \"status\");\r\n const path = `/org/webhooks/${endpointId}/deliveries` + queryString({\r\n page: query.page,\r\n page_size: query.pageSize,\r\n status_filter: query.status,\r\n });\r\n return this.request(\"GET\", path, options);\r\n }\r\n\r\n async getLatestWebhookDelivery(\r\n endpointId: number,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<WebhookDelivery | null> {\r\n positiveId(endpointId, \"endpointId\");\r\n return this.request(\"GET\", `/org/webhooks/${endpointId}/deliveries/latest`, options);\r\n }\r\n\r\n async listRecentWebhookDeliveries(\r\n query: RecentWebhookDeliveryQuery = {},\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<WebhookDeliveryListResponse> {\r\n if (query.page !== undefined) positiveId(query.page, \"page\");\r\n if (query.pageSize !== undefined) boundedInteger(query.pageSize, \"pageSize\", 1, 100);\r\n if (query.endpointId !== undefined) positiveId(query.endpointId, \"endpointId\");\r\n if (query.status !== undefined) nonEmpty(query.status, \"status\");\r\n const path = \"/org/webhooks/deliveries/recent\" + queryString({\r\n page: query.page,\r\n page_size: query.pageSize,\r\n endpoint_id: query.endpointId,\r\n status_filter: query.status,\r\n });\r\n return this.request(\"GET\", path, options);\r\n }\r\n\r\n async getWebhookDelivery(\r\n deliveryId: number,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<WebhookDelivery> {\r\n positiveId(deliveryId, \"deliveryId\");\r\n return this.request(\"GET\", `/org/webhooks/deliveries/${deliveryId}`, options);\r\n }\r\n\r\n async retryWebhookDelivery(\r\n deliveryId: number,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<WebhookDelivery> {\r\n positiveId(deliveryId, \"deliveryId\");\r\n return this.request(\"POST\", `/org/webhooks/deliveries/${deliveryId}/retry`, options);\r\n }\r\n\r\n async createExport(\r\n request: CreateExportRequest,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<CreateExportResponse> {\r\n const format = request.format ?? \"csv\";\r\n const scope = request.scope ?? \"filtered\";\r\n if (format !== \"csv\" && format !== \"jsonl\") throw new ValidationError(\"format must be 'csv' or 'jsonl'\");\r\n if (scope !== \"filtered\" && scope !== \"all\" && scope !== \"date_range\") {\r\n throw new ValidationError(\"scope must be 'filtered', 'all', or 'date_range'\");\r\n }\r\n const body: WireObject = { format, scope };\r\n if (request.filters !== undefined) body.filters = request.filters === null ? null : exportFilters(request.filters);\r\n return this.request(\"POST\", \"/exports\", { ...options, body });\r\n }\r\n\r\n async listExports(\r\n query: ExportListQuery = {},\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<ExportJobListResponse> {\r\n if (query.limit !== undefined) boundedInteger(query.limit, \"limit\", 1, 100);\r\n return this.request(\"GET\", \"/exports\" + queryString({ limit: query.limit }), options);\r\n }\r\n\r\n async getExport(jobId: string, options: ControlPlaneRequestOptions = {}): Promise<ExportJob> {\r\n return this.request(\"GET\", `/exports/${pathId(jobId, \"jobId\", 8, 64)}`, options);\r\n }\r\n\r\n async cancelExport(jobId: string, options: ControlPlaneRequestOptions = {}): Promise<ExportJob> {\r\n return this.request(\"POST\", `/exports/${pathId(jobId, \"jobId\", 8, 64)}/cancel`, options);\r\n }\r\n\r\n async retryExport(jobId: string, options: ControlPlaneRequestOptions = {}): Promise<CreateExportResponse> {\r\n return this.request(\"POST\", `/exports/${pathId(jobId, \"jobId\", 8, 64)}/retry`, options);\r\n }\r\n\r\n async getExportDownloadUrl(\r\n jobId: string,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<ExportDownloadUrl> {\r\n return this.request(\"GET\", `/exports/${pathId(jobId, \"jobId\", 8, 64)}/download-url`, options);\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;;;ACMO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAKzC,YAAY,SAAiB,UAAwB,CAAC,GAAG;AACvD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa,QAAQ;AAC1B,SAAK,WAAW,QAAQ;AACxB,SAAK,YAAY,QAAQ;AAAA,EAC3B;AACF;AAEO,IAAM,YAAN,cAAwB,gBAAgB;AAAA,EAC7C,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,kBAAN,cAA8B,gBAAgB;AAAA,EACnD,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,gBAAN,cAA4B,gBAAgB;AAAA,EACjD,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AAAA,EACd;AACF;AACO,IAAM,iBAAN,cAA6B,gBAAgB;AAAA,EAGlD,YAAY,SAAiB,mBAA2B,SAAwB;AAC9E,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,SAAK,oBAAoB;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,MAAM,OAAW,MAAK,IAAI,IAAI;AACtC,QAAI,IAAI,UAAU,OAAW,MAAK,QAAQ,IAAI;AAC9C,WACG,MAAM,KAAK,QAAiC,QAAQ,qBAAqB,EAAE,KAAK,CAAC,KAAM,CAAC;AAAA,EAE7F;AAAA;AAAA,EAGA,MAAM,OAAO,UAAoD;AAC/D,QAAI,CAAC,OAAO,UAAU,QAAQ,KAAK,YAAY,GAAG;AAChD,YAAM,IAAI,gBAAgB,qCAAqC;AAAA,IACjE;AACA,WACG,MAAM,KAAK,QAAiC,OAAO,qBAAqB,QAAQ,EAAE,KAAM,CAAC;AAAA,EAE9F;AAAA;AAAA,EAGA,MAAM,aAAa,KAKkB;AACnC,WACG,MAAM,KAAK;AAAA,MACV;AAAA,MACA,cAAc,mBAAmB,IAAI,QAAQ,CAAC,IAAI,mBAAmB,IAAI,MAAM,CAAC;AAAA,MAChF,EAAE,OAAO,EAAE,OAAO,IAAI,OAAO,QAAQ,IAAI,OAAO,EAAE;AAAA,IACpD,KAAM,CAAC;AAAA,EAEX;AACF;AAEA,SAAS,WAAW,KAA2D;AAC7E,SAAO;AAAA,IACL,cAAe,KAAK,iBAA8B,CAAC;AAAA,IACnD,eAAgB,KAAK,kBAA+B,CAAC;AAAA,IACrD,qBAAsB,KAAK,yBAAsC,CAAC;AAAA,IAClE,sBAAuB,KAAK,0BAAuC,CAAC;AAAA,IACpE,oBAAqB,KAAK,wBAAqC,CAAC;AAAA,IAChE,qBAAsB,KAAK,yBAAsC,CAAC;AAAA,IAClE,gBAAiB,KAAK,oBAA+B;AAAA,EACvD;AACF;","names":["SDK_VERSION","safeJson","extractDetail"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/connections.ts","../src/control-plane.ts"],"sourcesContent":["/**\r\n * MemorySync SDK — JavaScript / TypeScript client.\r\n *\r\n * Wraps the public REST surface of MemorySync. Every method here maps 1:1\r\n * to a route that exists in the backend; field names mirror the on-the-wire\r\n * JSON exactly (snake_case is preserved on payloads, camelCase is exposed\r\n * on the public TypeScript API).\r\n */\r\n\r\n// ───────────────────────────────────────────────────────────────────────\r\n// Types\r\n// ───────────────────────────────────────────────────────────────────────\r\n\r\nexport interface MemorySyncConfig {\r\n apiKey: string;\r\n baseUrl: string;\r\n projectId?: string;\r\n endUserId?: string;\r\n timeoutMs?: number;\r\n fetch?: typeof fetch;\r\n}\r\n\r\nexport interface AddRequest {\r\n text: string;\r\n source?: string;\r\n tags?: string[];\r\n importance?: number;\r\n sessionId?: string;\r\n metadata?: Record<string, unknown>;\r\n endUserId?: string;\r\n}\r\n\r\nexport interface MemoryRecord {\r\n id: number;\r\n text: string;\r\n summary?: string | null;\r\n tags?: string[] | null;\r\n source?: string | null;\r\n eventType?: string | null;\r\n importance?: number | null;\r\n metadata?: Record<string, unknown> | null;\r\n isSummary: boolean;\r\n createdAt: string;\r\n updatedAt?: string | null;\r\n score?: number | null;\r\n}\r\n\r\nexport interface AddSkippedResponse {\r\n status: \"skipped\";\r\n reason: string;\r\n memoryIds: number[];\r\n candidatesExtracted: number;\r\n candidatesStored: number;\r\n}\r\n\r\nexport type AddResponse = MemoryRecord | AddSkippedResponse;\r\n\r\nexport interface BulkAddItem {\r\n text: string;\r\n source?: string;\r\n eventType?: string;\r\n tags?: string[];\r\n metadata?: Record<string, unknown>;\r\n importance?: number;\r\n endUserId?: string;\r\n}\r\n\r\nexport interface BulkAddItemResult {\r\n index: number;\r\n status: \"created\" | \"skipped\" | \"rejected\";\r\n memoryIds: number[];\r\n reason: string | null;\r\n}\r\n\r\nexport interface BulkAddResponse {\r\n total: number;\r\n created: number;\r\n skipped: number;\r\n rejected: number;\r\n results: BulkAddItemResult[];\r\n}\r\n\r\nexport interface QueryFilters {\r\n memoryType?: string;\r\n source?: string;\r\n tags?: string[];\r\n since?: string;\r\n until?: string;\r\n includeSummaries?: boolean;\r\n tier?: \"hot\" | \"warm\" | \"cold\";\r\n}\r\n\r\nexport interface QueryRequest {\r\n query: string;\r\n k?: number;\r\n filters?: QueryFilters;\r\n sessionId?: string;\r\n traversalDepth?: number;\r\n}\r\n\r\nexport interface QueryResponse {\r\n memories: MemoryRecord[];\r\n context?: string | null;\r\n latencyMs?: number | null;\r\n sessionId?: string | null;\r\n queryIntent?: string | null;\r\n}\r\n\r\nexport interface UpdateRequest {\r\n tags?: string[];\r\n importance?: number;\r\n metadata?: Record<string, unknown>;\r\n source?: string;\r\n eventType?: string;\r\n}\r\n\r\nexport interface SummarizeRequest {\r\n memoryIds: number[];\r\n lossless?: boolean;\r\n}\r\n\r\nexport interface ComposeRequest {\r\n promptTemplate: string;\r\n recallK?: number;\r\n maxTokens?: number;\r\n}\r\n\r\nexport interface ComposeResponse {\r\n composedPrompt: string;\r\n memoriesUsed: number;\r\n tokenCount: number;\r\n truncated: boolean;\r\n}\r\n\r\nexport type RelationshipType =\r\n | \"similar\"\r\n | \"derived_from\"\r\n | \"continuation\"\r\n | \"contradiction\"\r\n | \"summary_of\"\r\n | \"detail_of\"\r\n | \"caused_by\"\r\n | \"references\"\r\n | \"supports\"\r\n | \"extends\";\r\n\r\nexport interface RelationCreateRequest {\r\n toMemoryId: number;\r\n relationshipType: RelationshipType;\r\n confidence?: number;\r\n metadata?: Record<string, unknown>;\r\n}\r\n\r\nexport interface RelationRecord {\r\n id: number;\r\n fromMemoryId: number;\r\n toMemoryId: number;\r\n relationshipType: RelationshipType;\r\n confidence: number;\r\n metadata?: Record<string, unknown> | null;\r\n createdAt: string;\r\n}\r\n\r\nexport interface ExportResponse {\r\n userId: number;\r\n memories: Array<Record<string, unknown>>;\r\n generatedAt: string;\r\n}\r\n\r\n// ───────────────────────────────────────────────────────────────────────\r\n// Errors\r\n// ───────────────────────────────────────────────────────────────────────\r\n\r\nimport {\r\n AuthError,\r\n ErrorOptions,\r\n MemorySyncError,\r\n NotFoundError,\r\n RateLimitError,\r\n ServerError,\r\n ValidationError,\r\n} from \"./errors\";\r\n\r\nexport {\r\n AuthError,\r\n MemorySyncError,\r\n NotFoundError,\r\n RateLimitError,\r\n ServerError,\r\n ValidationError,\r\n} from \"./errors\";\r\n\r\ntype ErrorOpts = ErrorOptions;\r\n\r\n// ───────────────────────────────────────────────────────────────────────\r\n// Internals\r\n// ───────────────────────────────────────────────────────────────────────\r\n\r\nconst SDK_VERSION = \"1.7.1\";\r\n\r\n// ── Phase 1 feature types ────────────────────────────────────────────\r\n\r\n/** One edit inside a {@link MemorySyncClient.batchUpdate} call. */\r\nexport interface BatchUpdateItem {\r\n memoryId: number;\r\n tags?: string[];\r\n importance?: number;\r\n metadata?: Record<string, unknown>;\r\n source?: string;\r\n eventType?: string;\r\n}\r\n\r\nexport interface BatchUpdateItemResult {\r\n index: number;\r\n memoryId: number;\r\n status: \"updated\" | \"not_found\";\r\n changedFields: string[];\r\n}\r\n\r\n/**\r\n * Result of a batch update.\r\n *\r\n * The server answers `207 Multi-Status`: a batch may legitimately name a memory\r\n * the caller cannot see, and the caller needs to know which one rather than\r\n * losing the whole request. `notFound` is an ordinary outcome, not an error.\r\n */\r\nexport interface BatchUpdateResponse {\r\n total: number;\r\n updated: number;\r\n notFound: number;\r\n results: BatchUpdateItemResult[];\r\n}\r\n\r\n/**\r\n * Criteria for a filter-based delete.\r\n *\r\n * At least one field must be set — an all-empty filter would mean \"delete\r\n * everything I own\", which has to be asked for explicitly rather than being the\r\n * result of omitting a field.\r\n *\r\n * To clear everything for an end user, say so with a wide criterion such as\r\n * `{ before: new Date() }`. Not `purgeUser()`: an earlier version of this\r\n * comment pointed there, and it erases the account rather than its memories.\r\n *\r\n * `tags` matches memories carrying **all** the listed tags, not any of them.\r\n */\r\nexport interface ForgetFilters {\r\n source?: string;\r\n eventType?: string;\r\n tags?: string[];\r\n tier?: string;\r\n before?: string;\r\n after?: string;\r\n}\r\n\r\nexport interface ForgetRequest {\r\n memoryIds?: number[];\r\n filters?: ForgetFilters;\r\n /** Return the ids that *would* be deleted without deleting anything. */\r\n dryRun?: boolean;\r\n reason?: string;\r\n}\r\n\r\nexport type RevisionEvent =\r\n | \"created\"\r\n | \"updated\"\r\n | \"superseded\"\r\n | \"soft_deleted\"\r\n | \"restored\"\r\n | \"archived\"\r\n | \"purged\";\r\n\r\n/**\r\n * One recorded change to a memory.\r\n *\r\n * Revision 0 is the creation entry, synthesised by the server. `actor` is `null`\r\n * for changes made by background workers, which have no request behind them —\r\n * that is expected rather than missing data.\r\n */\r\nexport interface RevisionEntry {\r\n revision: number;\r\n event: RevisionEvent;\r\n changedFields: string[];\r\n diff: Record<string, { old?: unknown; new?: unknown }>;\r\n actor: string | null;\r\n createdAt: string;\r\n}\r\n\r\nexport interface HistoryResponse {\r\n memoryId: number;\r\n total: number;\r\n revisions: RevisionEntry[];\r\n /**\r\n * The fields changes are recorded for. Worth reading: only user-meaningful\r\n * fields are tracked, so without this you cannot tell \"nothing changed\" from\r\n * \"that change is not recorded\".\r\n */\r\n trackedFields: string[];\r\n}\r\n\r\nexport type FeedbackSignal = \"positive\" | \"negative\" | \"retrieved\" | \"ignored\";\r\n\r\nexport interface FeedbackTrend {\r\n momentum: string;\r\n consistency: number;\r\n trendMultiplier: number;\r\n recentCount: number;\r\n}\r\n\r\nexport interface FeedbackSummary {\r\n totalSignals: number;\r\n signalCounts: Record<string, number>;\r\n trend: FeedbackTrend;\r\n}\r\n\r\nexport interface FeedbackResponse {\r\n memoryId: number;\r\n signal: FeedbackSignal;\r\n importanceBefore: number;\r\n importanceAfter: number;\r\n /** Delta actually applied. `0` when ranking influence is off, or when the change was clamped at the bounds. */\r\n adjustment: number;\r\n /** Whether this signal was allowed to change ranking. Reported, not assumed. */\r\n influencedRanking: boolean;\r\n summary: FeedbackSummary;\r\n}\r\n\r\n/**\r\n * The memory vocabulary in effect for an organization.\r\n *\r\n * The built-in types are a floor: they always apply and cannot be removed,\r\n * because dropping a type would leave memories already filed under it invisible\r\n * to any typed retrieval. Only `custom*` entries are removable.\r\n */\r\nexport interface Ontology {\r\n contentTypes: string[];\r\n relationTypes: string[];\r\n builtinContentTypes: string[];\r\n builtinRelationTypes: string[];\r\n customContentTypes: string[];\r\n customRelationTypes: string[];\r\n maxCustomTypes: number;\r\n}\r\n\r\nexport interface OntologyUpdateRequest {\r\n contentTypes?: string[];\r\n relationTypes?: string[];\r\n}\r\n\r\nexport interface UploadRequest {\r\n /** File contents. A `Blob`/`File` in browsers and Node 18+, or a `Uint8Array`. */\r\n file: Blob | Uint8Array;\r\n /** Required: the server picks its parser from the extension. */\r\n filename: string;\r\n contentType?: string;\r\n source?: string;\r\n metadata?: Record<string, unknown>;\r\n endUserId?: string;\r\n}\r\n\r\nimport {\r\n ConnectionsNamespace,\r\n IntegrationsNamespace,\r\n ObjectsNamespace,\r\n ProvidersNamespace,\r\n SyncJobsNamespace,\r\n type RequestFn,\r\n} from \"./connections\";\r\n\r\nfunction camelToSnakeKey(key: string): string {\r\n return key.replace(/([A-Z])/g, \"_$1\").toLowerCase();\r\n}\r\n\r\nfunction camelToSnakeShallow(obj: Record<string, unknown> | undefined | null): Record<string, unknown> | undefined {\r\n if (!obj) return undefined;\r\n const out: Record<string, unknown> = {};\r\n for (const [k, v] of Object.entries(obj)) {\r\n if (v === undefined) continue;\r\n out[camelToSnakeKey(k)] = v;\r\n }\r\n return out;\r\n}\r\n\r\nfunction snakeToCamelMemory(m: Record<string, unknown>): MemoryRecord {\r\n return {\r\n id: m.id as number,\r\n text: (m.text as string) ?? \"\",\r\n summary: (m.summary as string | null) ?? null,\r\n tags: (m.tags as string[] | null) ?? null,\r\n source: (m.source as string | null) ?? null,\r\n eventType: (m.event_type as string | null) ?? null,\r\n importance: (m.importance as number | null) ?? null,\r\n metadata: (m.metadata as Record<string, unknown> | null) ?? null,\r\n isSummary: Boolean(m.is_summary),\r\n createdAt: m.created_at as string,\r\n updatedAt: (m.updated_at as string | null) ?? null,\r\n score: (m.score as number | null) ?? null,\r\n };\r\n}\r\n\r\n/**\r\n * Render a query string, omitting anything the caller did not set.\r\n *\r\n * `undefined` and `null` are dropped rather than serialised: sending `depth=`\r\n * makes the server parse an empty string, which is a different request from not\r\n * asking for a depth at all.\r\n */\r\nfunction buildQuery(params?: Record<string, unknown>): string {\r\n if (!params) return \"\";\r\n const search = new URLSearchParams();\r\n for (const [key, value] of Object.entries(params)) {\r\n if (value === undefined || value === null) continue;\r\n if (Array.isArray(value)) {\r\n for (const item of value) {\r\n if (item !== undefined && item !== null) search.append(key, String(item));\r\n }\r\n } else {\r\n search.append(key, String(value));\r\n }\r\n }\r\n const qs = search.toString();\r\n return qs ? `?${qs}` : \"\";\r\n}\r\n\r\nfunction safeJson(text: string): unknown {\r\n try {\r\n return JSON.parse(text);\r\n } catch {\r\n return text;\r\n }\r\n}\r\n\r\nfunction extractDetail(body: unknown): string | undefined {\r\n if (!body || typeof body !== \"object\") return undefined;\r\n const b = body as Record<string, unknown>;\r\n if (typeof b.detail === \"string\") return b.detail;\r\n if (b.error && typeof b.error === \"object\") {\r\n const e = b.error as Record<string, unknown>;\r\n if (typeof e.message === \"string\") return e.message;\r\n }\r\n if (Array.isArray(b.detail) && b.detail.length > 0) {\r\n const first = b.detail[0] as Record<string, unknown>;\r\n if (typeof first.msg === \"string\") return first.msg;\r\n }\r\n return undefined;\r\n}\r\n\r\nfunction extractRetryAfter(body: unknown): number {\r\n if (!body || typeof body !== \"object\") return 0;\r\n const b = body as Record<string, unknown>;\r\n if (typeof b.retry_after === \"number\") return b.retry_after;\r\n if (b.error && typeof b.error === \"object\") {\r\n const e = b.error as Record<string, unknown>;\r\n if (typeof e.retry_after === \"number\") return e.retry_after;\r\n }\r\n return 0;\r\n}\r\n\r\n// ───────────────────────────────────────────────────────────────────────\r\n// Client\r\n// ───────────────────────────────────────────────────────────────────────\r\n\r\nexport class MemorySyncClient {\r\n private readonly apiKey: string;\r\n private readonly baseUrl: string;\r\n private readonly projectId?: string;\r\n private readonly endUserId?: string;\r\n private readonly timeoutMs: number;\r\n private readonly fetchImpl: typeof fetch;\r\n\r\n /** Connections to external sources, with provider sub-namespaces. */\r\n readonly connections: ConnectionsNamespace;\r\n /** Individual objects a connector ingested. */\r\n readonly objects: ObjectsNamespace;\r\n /** Connectors this deployment supports. */\r\n readonly providers: ProvidersNamespace;\r\n /** Individual sync runs. */\r\n readonly syncJobs: SyncJobsNamespace;\r\n /** The legacy `/api/v1/integrations` surface, including the web crawler. */\r\n readonly integrations: IntegrationsNamespace;\r\n\r\n constructor(config: MemorySyncConfig) {\r\n if (!config.apiKey?.trim()) throw new Error(\"apiKey is required\");\r\n if (!config.baseUrl?.trim()) throw new Error(\"baseUrl is required\");\r\n this.apiKey = config.apiKey;\r\n this.baseUrl = config.baseUrl.replace(/\\/$/, \"\");\r\n this.projectId = config.projectId;\r\n this.endUserId = config.endUserId;\r\n this.timeoutMs = config.timeoutMs ?? 30_000;\r\n const f = config.fetch ?? (typeof fetch !== \"undefined\" ? fetch : undefined);\r\n if (!f) {\r\n throw new Error(\"No fetch implementation available. Pass `fetch` in config or use Node 18+.\");\r\n }\r\n this.fetchImpl = f;\r\n\r\n // Bound so the namespaces carry no transport of their own and inherit every\r\n // header, timeout and error mapping this client applies.\r\n const request: RequestFn = (method, path, options) =>\r\n this.request(method, path, options ?? {});\r\n this.connections = new ConnectionsNamespace(request);\r\n this.objects = new ObjectsNamespace(request);\r\n this.providers = new ProvidersNamespace(request);\r\n this.syncJobs = new SyncJobsNamespace(request);\r\n this.integrations = new IntegrationsNamespace(request);\r\n }\r\n\r\n private headers(extra: Record<string, string> = {}): Record<string, string> {\r\n const h: Record<string, string> = {\r\n \"X-API-Key\": this.apiKey,\r\n \"Content-Type\": \"application/json\",\r\n \"Accept\": \"application/json\",\r\n \"User-Agent\": `memorysync-sdk-js/${SDK_VERSION}`,\r\n ...extra,\r\n };\r\n if (this.projectId) h[\"X-Project-ID\"] = this.projectId;\r\n if (this.endUserId) h[\"X-End-User-ID\"] = this.endUserId;\r\n return h;\r\n }\r\n\r\n private async request<T>(\r\n method: string,\r\n path: string,\r\n options: {\r\n body?: unknown;\r\n query?: Record<string, unknown>;\r\n form?: FormData;\r\n endUserOverride?: string;\r\n } = {},\r\n ): Promise<T> {\r\n const url = `${this.baseUrl}${path}${buildQuery(options.query)}`;\r\n const controller = new AbortController();\r\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\r\n try {\r\n const headers = this.headers(\r\n options.endUserOverride ? { \"X-End-User-ID\": options.endUserOverride } : {},\r\n );\r\n if (options.form) {\r\n // fetch sets multipart/form-data together with the boundary. Sending our\r\n // own Content-Type produces a body the server cannot parse, and the\r\n // symptom is misleading: every form field comes back \"field required\".\r\n delete headers[\"Content-Type\"];\r\n }\r\n const res = await this.fetchImpl(url, {\r\n method,\r\n headers,\r\n body: options.form\r\n ? options.form\r\n : options.body !== undefined\r\n ? JSON.stringify(options.body)\r\n : undefined,\r\n signal: controller.signal,\r\n });\r\n const requestId = res.headers.get(\"X-Request-ID\") ?? undefined;\r\n\r\n if (res.status === 204) return undefined as unknown as T;\r\n\r\n const text = await res.text();\r\n const parsed: unknown = text ? safeJson(text) : null;\r\n\r\n if (!res.ok) this.throwForStatus(res.status, parsed, requestId);\r\n return parsed as T;\r\n } catch (e) {\r\n if (e instanceof MemorySyncError) throw e;\r\n if (e instanceof Error && e.name === \"AbortError\") {\r\n throw new MemorySyncError(`Request timed out after ${this.timeoutMs}ms`);\r\n }\r\n throw new MemorySyncError(`Network error: ${(e as Error).message}`);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n\r\n private throwForStatus(status: number, body: unknown, requestId?: string): never {\r\n const detail = extractDetail(body);\r\n const opts: ErrorOpts = { statusCode: status, response: body, requestId };\r\n if (status === 401) throw new AuthError(detail || \"Unauthenticated\", opts);\r\n if (status === 403) throw new AuthError(detail || \"Forbidden\", opts);\r\n if (status === 404) throw new NotFoundError(detail || \"Not found\", opts);\r\n if (status === 400 || status === 409 || status === 422) {\r\n throw new ValidationError(detail || \"Validation error\", opts);\r\n }\r\n if (status === 429) {\r\n const retryAfter = extractRetryAfter(body);\r\n throw new RateLimitError(detail || \"Rate limited\", retryAfter, opts);\r\n }\r\n if (status >= 500) throw new ServerError(detail || `Server error (${status})`, opts);\r\n throw new MemorySyncError(detail || `Unexpected status ${status}`, opts);\r\n }\r\n\r\n // ── Memory ─────────────────────────────────────────────────────────\r\n\r\n async add(req: AddRequest): Promise<AddResponse> {\r\n const body: Record<string, unknown> = { text: req.text };\r\n if (req.source !== undefined) body.source = req.source;\r\n if (req.tags !== undefined) body.tags = req.tags;\r\n if (req.importance !== undefined) body.importance = req.importance;\r\n if (req.sessionId !== undefined) body.session_id = req.sessionId;\r\n if (req.metadata !== undefined) body.metadata = req.metadata;\r\n if (req.endUserId !== undefined) body.end_user_id = req.endUserId;\r\n\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/add\", {\r\n body,\r\n endUserOverride: req.endUserId,\r\n });\r\n if (raw && raw.status === \"skipped\") {\r\n return {\r\n status: \"skipped\",\r\n reason: (raw.reason as string) ?? \"no_high_value_content\",\r\n memoryIds: (raw.memory_ids as number[]) ?? [],\r\n candidatesExtracted: (raw.candidates_extracted as number) ?? 0,\r\n candidatesStored: (raw.candidates_stored as number) ?? 0,\r\n };\r\n }\r\n return snakeToCamelMemory(raw);\r\n }\r\n\r\n async bulkAdd(items: BulkAddItem[], opts: { deduplicate?: boolean } = {}): Promise<BulkAddResponse> {\r\n if (items.length === 0) throw new ValidationError(\"items must contain at least one entry\");\r\n if (items.length > 50) throw new ValidationError(\"items may contain at most 50 entries per request\");\r\n const body = {\r\n items: items.map((i) => {\r\n const o: Record<string, unknown> = { text: i.text };\r\n if (i.source !== undefined) o.source = i.source;\r\n if (i.eventType !== undefined) o.event_type = i.eventType;\r\n if (i.tags !== undefined) o.tags = i.tags;\r\n if (i.metadata !== undefined) o.metadata = i.metadata;\r\n if (i.importance !== undefined) o.importance = i.importance;\r\n if (i.endUserId !== undefined) o.end_user_id = i.endUserId;\r\n return o;\r\n }),\r\n deduplicate: opts.deduplicate ?? true,\r\n };\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/bulk-add\", { body });\r\n return {\r\n total: raw.total as number,\r\n created: raw.created as number,\r\n skipped: raw.skipped as number,\r\n rejected: raw.rejected as number,\r\n results: ((raw.results as Array<Record<string, unknown>>) ?? []).map((r) => ({\r\n index: r.index as number,\r\n status: r.status as BulkAddItemResult[\"status\"],\r\n memoryIds: (r.memory_ids as number[]) ?? [],\r\n reason: (r.reason as string | null) ?? null,\r\n })),\r\n };\r\n }\r\n\r\n async query(req: QueryRequest): Promise<QueryResponse> {\r\n const body: Record<string, unknown> = { query: req.query };\r\n if (req.k !== undefined) body.k = req.k;\r\n if (req.sessionId !== undefined) body.session_id = req.sessionId;\r\n if (req.traversalDepth !== undefined) body.traversal_depth = req.traversalDepth;\r\n if (req.filters) body.filters = camelToSnakeShallow(req.filters as Record<string, unknown>);\r\n\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/query\", { body });\r\n return {\r\n memories: ((raw.memories as Array<Record<string, unknown>>) ?? []).map(snakeToCamelMemory),\r\n context: (raw.context as string | null) ?? null,\r\n latencyMs: (raw.latency_ms as number | null) ?? null,\r\n sessionId: (raw.session_id as string | null) ?? null,\r\n queryIntent: (raw.query_intent as string | null) ?? null,\r\n };\r\n }\r\n\r\n async get(memoryId: number): Promise<MemoryRecord> {\r\n if (!Number.isInteger(memoryId) || memoryId <= 0) {\r\n throw new ValidationError(\"memoryId must be a positive integer\");\r\n }\r\n const raw = await this.request<Record<string, unknown>>(\"GET\", `/memory/${memoryId}`);\r\n return snakeToCamelMemory(raw);\r\n }\r\n\r\n async update(memoryId: number, req: UpdateRequest): Promise<MemoryRecord> {\r\n if (!Number.isInteger(memoryId) || memoryId <= 0) {\r\n throw new ValidationError(\"memoryId must be a positive integer\");\r\n }\r\n const body: Record<string, unknown> = {};\r\n if (req.tags !== undefined) body.tags = req.tags;\r\n if (req.importance !== undefined) body.importance = req.importance;\r\n if (req.metadata !== undefined) body.metadata = req.metadata;\r\n if (req.source !== undefined) body.source = req.source;\r\n if (req.eventType !== undefined) body.event_type = req.eventType;\r\n if (Object.keys(body).length === 0) {\r\n throw new ValidationError(\"update() requires at least one editable field\");\r\n }\r\n const raw = await this.request<Record<string, unknown>>(\"PATCH\", `/memory/${memoryId}`, { body });\r\n return snakeToCamelMemory(raw);\r\n }\r\n\r\n /**\r\n * Delete memories, either by id or by filter. Returns the deleted ids.\r\n *\r\n * Accepts the legacy positional form `forget([1,2], \"reason\")` as well as\r\n * `forget({ filters, dryRun })`. The positional form is kept because it ships\r\n * in 1.1.x and removing it would break installed callers for no benefit.\r\n *\r\n * Exactly one selector. Passing both is rejected rather than resolved by a\r\n * precedence rule, because getting that wrong on a delete cannot be undone.\r\n * Deletion is scoped to the calling end user, so a filter never reaches\r\n * another end user's memories — including the organisation's connector history.\r\n */\r\n async forget(request: ForgetRequest): Promise<number[]>;\r\n async forget(memoryIds: number[], reason?: string): Promise<number[]>;\r\n async forget(\r\n arg: ForgetRequest | number[],\r\n legacyReason?: string,\r\n ): Promise<number[]> {\r\n const req: ForgetRequest = Array.isArray(arg)\r\n ? { memoryIds: arg, reason: legacyReason }\r\n : arg;\r\n\r\n const hasIds = req.memoryIds !== undefined;\r\n const hasFilters = req.filters !== undefined;\r\n if (hasIds && hasFilters) {\r\n throw new ValidationError(\"Provide either memoryIds or filters, not both\");\r\n }\r\n if (!hasIds && !hasFilters) {\r\n throw new ValidationError(\"Provide either memoryIds or filters\");\r\n }\r\n\r\n const body: Record<string, unknown> = {};\r\n if (hasIds) {\r\n if (!Array.isArray(req.memoryIds) || req.memoryIds.length === 0) {\r\n throw new ValidationError(\"memoryIds must be a non-empty array\");\r\n }\r\n body.memory_ids = req.memoryIds;\r\n } else {\r\n const f = req.filters!;\r\n const filters: Record<string, unknown> = {};\r\n if (f.source !== undefined) filters.source = f.source;\r\n if (f.eventType !== undefined) filters.event_type = f.eventType;\r\n if (f.tags !== undefined) filters.tags = f.tags;\r\n if (f.tier !== undefined) filters.tier = f.tier;\r\n if (f.before !== undefined) filters.before = f.before;\r\n if (f.after !== undefined) filters.after = f.after;\r\n if (Object.keys(filters).length === 0) {\r\n throw new ValidationError(\r\n 'filters must set at least one criterion; to remove everything for an end user use a wide criterion such as { before: new Date() }',\r\n );\r\n }\r\n body.filters = filters;\r\n if (req.dryRun) body.dry_run = true;\r\n }\r\n if (req.reason !== undefined) body.reason = req.reason;\r\n return await this.request<number[]>(\"DELETE\", \"/memory/forget\", { body });\r\n }\r\n\r\n /**\r\n * Not a memory operation, and not callable from this SDK. Always throws.\r\n *\r\n * `DELETE /memory/user/purge` reads as if it clears one end user's memories.\r\n * It does neither. It ignores `endUserId` and erases the **account** behind\r\n * the credential, cascading to the password hash, every API key, memberships,\r\n * auth providers and MFA credentials. Nobody can sign in afterwards, and the\r\n * API cannot repair it, because the credential that would authorise a repair\r\n * is one of the things it destroys.\r\n *\r\n * Earlier versions of this method described it as \"delete every memory\r\n * belonging to the calling end user\", and callers who believed that lost\r\n * accounts.\r\n *\r\n * The server now refuses account erasure for every API-key caller, and this\r\n * client authenticates only with an API key, so the call could never succeed.\r\n * It throws locally rather than sending a request that can only come back 403,\r\n * so the reason arrives immediately and no destructive intent leaves the\r\n * process. Erase an account from the dashboard, where a human is present.\r\n *\r\n * @deprecated Use {@link forget} for anything memory-related: by ids, or with\r\n * a wide criterion such as `{ before: new Date() }` to clear an end user.\r\n * @throws {ValidationError} Always.\r\n */\r\n async purgeUser(): Promise<Record<string, unknown>> {\r\n throw new ValidationError(\r\n \"purgeUser() erases the whole account, not its memories: the password hash, \" +\r\n \"every API key and all sign-in credentials go with it. The API refuses this \" +\r\n \"for API-key callers, and this client only supports API keys, so the call \" +\r\n \"cannot succeed. To delete memories use forget(), either with ids or a wide \" +\r\n \"criterion such as { before: new Date() }. To close an account, use the \" +\r\n \"dashboard.\",\r\n );\r\n }\r\n\r\n async summarize(req: SummarizeRequest): Promise<MemoryRecord> {\r\n if (!req.memoryIds || req.memoryIds.length === 0) {\r\n throw new ValidationError(\"summarize() requires memoryIds\");\r\n }\r\n const body: Record<string, unknown> = { memory_ids: req.memoryIds };\r\n if (req.lossless !== undefined) body.lossless = req.lossless;\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/summarize\", { body });\r\n return snakeToCamelMemory(raw);\r\n }\r\n\r\n async compose(req: ComposeRequest): Promise<ComposeResponse> {\r\n const body: Record<string, unknown> = { prompt_template: req.promptTemplate };\r\n if (req.recallK !== undefined) body.recall_k = req.recallK;\r\n if (req.maxTokens !== undefined) body.max_tokens = req.maxTokens;\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/compose\", { body });\r\n return {\r\n composedPrompt: (raw.composed_prompt as string) ?? \"\",\r\n memoriesUsed: (raw.memories_used as number) ?? 0,\r\n tokenCount: (raw.token_count as number) ?? 0,\r\n truncated: Boolean(raw.truncated),\r\n };\r\n }\r\n\r\n async exportAll(): Promise<ExportResponse> {\r\n const raw = await this.request<Record<string, unknown>>(\"GET\", \"/memory/export\");\r\n return {\r\n userId: raw.user_id as number,\r\n memories: (raw.memories as Array<Record<string, unknown>>) ?? [],\r\n generatedAt: raw.generated_at as string,\r\n };\r\n }\r\n\r\n async createRelation(fromMemoryId: number, req: RelationCreateRequest): Promise<RelationRecord> {\r\n if (!Number.isInteger(fromMemoryId) || fromMemoryId <= 0) {\r\n throw new ValidationError(\"fromMemoryId must be a positive integer\");\r\n }\r\n if (fromMemoryId === req.toMemoryId) {\r\n throw new ValidationError(\"fromMemoryId must differ from toMemoryId (no self-loops)\");\r\n }\r\n const body: Record<string, unknown> = {\r\n to_memory_id: req.toMemoryId,\r\n relationship_type: req.relationshipType,\r\n };\r\n if (req.confidence !== undefined) body.confidence = req.confidence;\r\n if (req.metadata !== undefined) body.metadata = req.metadata;\r\n const raw = await this.request<Record<string, unknown>>(\r\n \"POST\",\r\n `/memory/${fromMemoryId}/relations`,\r\n { body },\r\n );\r\n return {\r\n id: raw.id as number,\r\n fromMemoryId: raw.from_memory_id as number,\r\n toMemoryId: raw.to_memory_id as number,\r\n relationshipType: raw.relationship_type as RelationshipType,\r\n confidence: raw.confidence as number,\r\n metadata: (raw.metadata as Record<string, unknown> | null) ?? null,\r\n createdAt: raw.created_at as string,\r\n };\r\n }\r\n\r\n // ── Files ──────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Ingest a document and store the memories extracted from its text.\r\n *\r\n * Accepts the formats the connectors accept — PDF, DOCX, PPTX, XLSX, CSV,\r\n * text, Markdown, HTML, source code, and images/audio/video where\r\n * transcription is configured.\r\n *\r\n * Billed as an add, one unit per memory created. Resolves to the first stored\r\n * memory, or an {@link AddSkippedResponse} when the file yielded nothing worth\r\n * keeping — a blank scan, a sheet of empty cells, or content the extractor\r\n * judges trivial are all normal outcomes rather than errors.\r\n */\r\n async upload(req: UploadRequest): Promise<AddResponse> {\r\n if (!req.filename?.trim()) {\r\n throw new ValidationError(\"filename is required so the server can pick a parser\");\r\n }\r\n const form = new FormData();\r\n const blob =\r\n req.file instanceof Uint8Array\r\n ? new Blob([req.file as unknown as BlobPart], {\r\n type: req.contentType ?? \"application/octet-stream\",\r\n })\r\n : req.file;\r\n form.append(\"file\", blob, req.filename);\r\n if (req.source !== undefined) form.append(\"source\", req.source);\r\n if (req.metadata !== undefined) form.append(\"metadata\", JSON.stringify(req.metadata));\r\n if (req.endUserId !== undefined) form.append(\"end_user_id\", req.endUserId);\r\n\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/upload\", {\r\n form,\r\n endUserOverride: req.endUserId,\r\n });\r\n if (raw && raw.status === \"skipped\") {\r\n return {\r\n status: \"skipped\",\r\n reason: (raw.reason as string) ?? \"no_extractable_text\",\r\n memoryIds: (raw.memory_ids as number[]) ?? [],\r\n candidatesExtracted: (raw.candidates_extracted as number) ?? 0,\r\n candidatesStored: (raw.candidates_stored as number) ?? 0,\r\n };\r\n }\r\n return snakeToCamelMemory(raw);\r\n }\r\n\r\n // ── Bulk edit ──────────────────────────────────────────────────────\r\n\r\n /**\r\n * Apply many metadata edits in one request.\r\n *\r\n * Editable: `tags`, `importance`, `metadata`, `source`, `eventType`. A memory's\r\n * text, embeddings, owner, environment and project are not editable.\r\n *\r\n * Applied in one transaction, so the batch either lands or it does not — but an\r\n * id the caller cannot see is reported per item rather than failing the request.\r\n */\r\n async batchUpdate(items: BatchUpdateItem[]): Promise<BatchUpdateResponse> {\r\n if (!Array.isArray(items) || items.length === 0) {\r\n throw new ValidationError(\"items must contain at least one entry\");\r\n }\r\n if (items.length > 100) {\r\n throw new ValidationError(\"items may contain at most 100 entries per request\");\r\n }\r\n const seen = new Map<number, number>();\r\n const payload = items.map((item, index) => {\r\n if (!Number.isInteger(item.memoryId) || item.memoryId <= 0) {\r\n throw new ValidationError(`items[${index}].memoryId must be a positive integer`);\r\n }\r\n const o: Record<string, unknown> = { memory_id: item.memoryId };\r\n if (item.tags !== undefined) o.tags = item.tags;\r\n if (item.importance !== undefined) o.importance = item.importance;\r\n if (item.metadata !== undefined) o.metadata = item.metadata;\r\n if (item.source !== undefined) o.source = item.source;\r\n if (item.eventType !== undefined) o.event_type = item.eventType;\r\n if (Object.keys(o).length === 1) {\r\n throw new ValidationError(\r\n `items[${index}] (memoryId ${item.memoryId}): at least one updatable field must be provided`,\r\n );\r\n }\r\n const previous = seen.get(item.memoryId);\r\n if (previous !== undefined) {\r\n // Two edits to one memory have no defined order, so the outcome would\r\n // depend on array position.\r\n throw new ValidationError(\r\n `items must not contain the same memoryId twice: ${item.memoryId} appears at index ${previous} and ${index}`,\r\n );\r\n }\r\n seen.set(item.memoryId, index);\r\n return o;\r\n });\r\n\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/batch-update\", {\r\n body: { items: payload },\r\n });\r\n return {\r\n total: (raw?.total as number) ?? 0,\r\n updated: (raw?.updated as number) ?? 0,\r\n notFound: (raw?.not_found as number) ?? 0,\r\n results: ((raw?.results as Array<Record<string, unknown>>) ?? []).map((r) => ({\r\n index: r.index as number,\r\n memoryId: r.memory_id as number,\r\n status: r.status as \"updated\" | \"not_found\",\r\n changedFields: (r.changed_fields as string[]) ?? [],\r\n })),\r\n };\r\n }\r\n\r\n // ── History and feedback ───────────────────────────────────────────\r\n\r\n /**\r\n * Recorded changes to one memory, oldest first.\r\n *\r\n * Entry 0 is the creation. Later entries carry the old and new value per field.\r\n * Entries written by background workers have `actor: null`. Only\r\n * user-meaningful fields are tracked; the watched list comes back in\r\n * `trackedFields`.\r\n */\r\n async history(\r\n memoryId: number,\r\n opts: { limit?: number; offset?: number } = {},\r\n ): Promise<HistoryResponse> {\r\n if (!Number.isInteger(memoryId) || memoryId <= 0) {\r\n throw new ValidationError(\"memoryId must be a positive integer\");\r\n }\r\n const raw = await this.request<Record<string, unknown>>(\r\n \"GET\",\r\n `/memory/${memoryId}/history`,\r\n { query: { limit: opts.limit ?? 100, offset: opts.offset ?? 0 } },\r\n );\r\n return {\r\n memoryId: (raw?.memory_id as number) ?? memoryId,\r\n total: (raw?.total as number) ?? 0,\r\n revisions: ((raw?.revisions as Array<Record<string, unknown>>) ?? []).map((r) => ({\r\n revision: r.revision as number,\r\n event: r.event as RevisionEvent,\r\n changedFields: (r.changed_fields as string[]) ?? [],\r\n diff: (r.diff as Record<string, { old?: unknown; new?: unknown }>) ?? {},\r\n actor: (r.actor as string | null) ?? null,\r\n createdAt: r.created_at as string,\r\n })),\r\n trackedFields: (raw?.tracked_fields as string[]) ?? [],\r\n };\r\n }\r\n\r\n /**\r\n * Tell MemorySync whether a memory was useful.\r\n *\r\n * By default this moves the memory's `importance`, a weighted retrieval-ranking\r\n * factor, so a memory marked useful surfaces more readily and one marked wrong\r\n * surfaces less. The size of the move is adaptive: consistent signals amplify\r\n * it, mixed signals damp it. Importance is clamped to [0.05, 1.0], so no run of\r\n * negative feedback can make a memory permanently unreachable. Not billed.\r\n */\r\n async feedback(\r\n memoryId: number,\r\n signal: FeedbackSignal,\r\n opts: { comment?: string } = {},\r\n ): Promise<FeedbackResponse> {\r\n if (!Number.isInteger(memoryId) || memoryId <= 0) {\r\n throw new ValidationError(\"memoryId must be a positive integer\");\r\n }\r\n const valid: FeedbackSignal[] = [\"positive\", \"negative\", \"retrieved\", \"ignored\"];\r\n if (!valid.includes(signal)) {\r\n throw new ValidationError(`signal must be one of ${valid.join(\", \")}; got ${String(signal)}`);\r\n }\r\n const body: Record<string, unknown> = { signal };\r\n if (opts.comment !== undefined) body.comment = opts.comment;\r\n const raw = await this.request<Record<string, unknown>>(\r\n \"POST\",\r\n `/memory/${memoryId}/feedback`,\r\n { body },\r\n );\r\n const summary = (raw?.summary as Record<string, unknown>) ?? {};\r\n const trend = (summary.trend as Record<string, unknown>) ?? {};\r\n return {\r\n memoryId: (raw?.memory_id as number) ?? memoryId,\r\n signal: (raw?.signal as FeedbackSignal) ?? signal,\r\n importanceBefore: (raw?.importance_before as number) ?? 0,\r\n importanceAfter: (raw?.importance_after as number) ?? 0,\r\n adjustment: (raw?.adjustment as number) ?? 0,\r\n influencedRanking: Boolean(raw?.influenced_ranking),\r\n summary: {\r\n totalSignals: (summary.total_signals as number) ?? 0,\r\n signalCounts: (summary.signal_counts as Record<string, number>) ?? {},\r\n trend: {\r\n momentum: (trend.momentum as string) ?? \"neutral\",\r\n consistency: (trend.consistency as number) ?? 0,\r\n trendMultiplier: (trend.trend_multiplier as number) ?? 1,\r\n recentCount: (trend.recent_count as number) ?? 0,\r\n },\r\n },\r\n };\r\n }\r\n\r\n // ── Ontology ───────────────────────────────────────────────────────\r\n\r\n /** The memory vocabulary in effect for this organization. */\r\n async getOntology(): Promise<Ontology> {\r\n const raw = await this.request<Record<string, unknown>>(\"GET\", \"/memory/ontology\");\r\n return toOntology(raw);\r\n }\r\n\r\n /**\r\n * Replace this organization's *additions* to the vocabulary.\r\n *\r\n * The two vocabularies are independent: omit one and it is left untouched, so\r\n * adding a content type cannot wipe your relation types. Pass an empty array to\r\n * clear a vocabulary's custom entries. The built-in types always remain.\r\n */\r\n async updateOntology(req: OntologyUpdateRequest): Promise<Ontology> {\r\n if (req.contentTypes === undefined && req.relationTypes === undefined) {\r\n throw new ValidationError(\r\n \"provide contentTypes, relationTypes, or both; an empty request would silently do nothing\",\r\n );\r\n }\r\n const body: Record<string, unknown> = {};\r\n if (req.contentTypes !== undefined) body.content_types = req.contentTypes;\r\n if (req.relationTypes !== undefined) body.relation_types = req.relationTypes;\r\n const raw = await this.request<Record<string, unknown>>(\"PUT\", \"/memory/ontology\", { body });\r\n return toOntology(raw);\r\n }\r\n\r\n // ── Retrieval variants ─────────────────────────────────────────────\r\n\r\n /**\r\n * Alias of {@link query} against `/memory/retrieve`.\r\n *\r\n * Both paths are live, and integrators arriving from other platforms reach for\r\n * `retrieve`. Identical semantics.\r\n */\r\n async retrieve(req: QueryRequest): Promise<QueryResponse> {\r\n const body: Record<string, unknown> = { query: req.query };\r\n if (req.k !== undefined) body.k = req.k;\r\n if (req.filters !== undefined) body.filters = camelToSnakeShallow(req.filters as Record<string, unknown>);\r\n if (req.sessionId !== undefined) body.session_id = req.sessionId;\r\n if (req.traversalDepth !== undefined) body.traversal_depth = req.traversalDepth;\r\n const raw = await this.request<Record<string, unknown>>(\"POST\", \"/memory/retrieve\", { body });\r\n return {\r\n memories: ((raw.memories as Array<Record<string, unknown>>) ?? []).map(snakeToCamelMemory),\r\n context: (raw.context as string | null) ?? null,\r\n latencyMs: (raw.latency_ms as number | null) ?? null,\r\n sessionId: (raw.session_id as string | null) ?? null,\r\n queryIntent: (raw.query_intent as string | null) ?? null,\r\n };\r\n }\r\n\r\n /**\r\n * Route a question to the best knowledge source and answer from it.\r\n *\r\n * Returns the raw payload: the response carries routing diagnostics whose shape\r\n * is richer and more volatile than an SDK should freeze into an interface.\r\n */\r\n async searchRouted(\r\n query: string,\r\n opts: { k?: number; route?: string; includeReasoning?: boolean } = {},\r\n ): Promise<Record<string, unknown>> {\r\n const body: Record<string, unknown> = { query };\r\n if (opts.k !== undefined) body.k = opts.k;\r\n if (opts.route !== undefined) body.route = opts.route;\r\n if (opts.includeReasoning !== undefined) body.include_reasoning = opts.includeReasoning;\r\n return (\r\n (await this.request<Record<string, unknown>>(\"POST\", \"/memory/search/routed\", { body })) ?? {}\r\n );\r\n }\r\n\r\n /** Compose an answer across several memories, with citations. */\r\n async synthesize(\r\n opts: { query?: string; memoryIds?: number[]; maxMemories?: number } = {},\r\n ): Promise<Record<string, unknown>> {\r\n const body: Record<string, unknown> = {};\r\n if (opts.query !== undefined) body.query = opts.query;\r\n if (opts.memoryIds !== undefined) body.memory_ids = opts.memoryIds;\r\n if (opts.maxMemories !== undefined) body.max_memories = opts.maxMemories;\r\n return (\r\n (await this.request<Record<string, unknown>>(\"POST\", \"/memory/synthesize\", { body })) ?? {}\r\n );\r\n }\r\n\r\n /** Re-embed this end user's memories. Returns immediately (`202`). */\r\n async refresh(): Promise<Record<string, unknown>> {\r\n return (await this.request<Record<string, unknown>>(\"POST\", \"/memory/refresh\")) ?? {};\r\n }\r\n\r\n // ── Intelligence and graph ─────────────────────────────────────────\r\n\r\n /** Nodes and typed edges for this end user's memory graph. */\r\n async graph(\r\n opts: { limit?: number; memoryId?: number; depth?: number } = {},\r\n ): Promise<Record<string, unknown>> {\r\n return (\r\n (await this.request<Record<string, unknown>>(\"GET\", \"/memory/graph\", {\r\n query: { limit: opts.limit, memory_id: opts.memoryId, depth: opts.depth },\r\n })) ?? {}\r\n );\r\n }\r\n\r\n /** Semantic clusters over this end user's memories. */\r\n async clusters(opts: { limit?: number } = {}): Promise<Record<string, unknown>> {\r\n return (\r\n (await this.request<Record<string, unknown>>(\"GET\", \"/memory/clusters\", {\r\n query: { limit: opts.limit },\r\n })) ?? {}\r\n );\r\n }\r\n\r\n /** Contradictions and open decisions detected across memories. */\r\n async decisions(opts: { limit?: number } = {}): Promise<Record<string, unknown>> {\r\n return (\r\n (await this.request<Record<string, unknown>>(\"GET\", \"/memory/decisions\", {\r\n query: { limit: opts.limit },\r\n })) ?? {}\r\n );\r\n }\r\n\r\n /** Record which side of a contradiction wins. */\r\n async resolveDecision(\r\n opts: {\r\n decisionId?: string;\r\n winningMemoryId?: number;\r\n resolution?: string;\r\n note?: string;\r\n } = {},\r\n ): Promise<Record<string, unknown>> {\r\n const body: Record<string, unknown> = {};\r\n if (opts.decisionId !== undefined) body.decision_id = opts.decisionId;\r\n if (opts.winningMemoryId !== undefined) body.winning_memory_id = opts.winningMemoryId;\r\n if (opts.resolution !== undefined) body.resolution = opts.resolution;\r\n if (opts.note !== undefined) body.note = opts.note;\r\n return (\r\n (await this.request<Record<string, unknown>>(\"POST\", \"/memory/decision/resolve\", { body })) ??\r\n {}\r\n );\r\n }\r\n\r\n /**\r\n * The intelligence report: themes, entities, patterns, dual-horizon view.\r\n *\r\n * `scope` is explicit by design server-side — nothing is inferred, so if you do\r\n * not ask for a scope you do not get it.\r\n */\r\n async intelligence(\r\n opts: { limit?: number; scope?: string; projectId?: string } = {},\r\n ): Promise<Record<string, unknown>> {\r\n return (\r\n (await this.request<Record<string, unknown>>(\"GET\", \"/memory/intelligence\", {\r\n query: { limit: opts.limit, scope: opts.scope, project_id: opts.projectId },\r\n })) ?? {}\r\n );\r\n }\r\n\r\n /** Counts and coverage for the knowledge base. */\r\n async knowledgeStats(): Promise<Record<string, unknown>> {\r\n return (await this.request<Record<string, unknown>>(\"GET\", \"/memory/knowledge/stats\")) ?? {};\r\n }\r\n\r\n // ── v1 data plane ──────────────────────────────────────────────────\r\n\r\n /** Add a conversation turn and extract memories from it. */\r\n async addTurn(req: {\r\n tenantId: string;\r\n userId: string;\r\n messages: Array<Record<string, unknown>>;\r\n sessionId?: string;\r\n metadata?: Record<string, unknown>;\r\n }): Promise<Record<string, unknown>> {\r\n const body: Record<string, unknown> = {\r\n tenant_id: req.tenantId,\r\n user_id: req.userId,\r\n messages: req.messages,\r\n };\r\n if (req.sessionId !== undefined) body.session_id = req.sessionId;\r\n if (req.metadata !== undefined) body.metadata = req.metadata;\r\n return (\r\n (await this.request<Record<string, unknown>>(\"POST\", \"/v1/memory/add_turn\", { body })) ?? {}\r\n );\r\n }\r\n\r\n /**\r\n * Build a prompt-ready context block for an LLM call.\r\n *\r\n * `types` narrows the result to those content types. Names outside the\r\n * organization's vocabulary are dropped rather than rejected, so a stale client\r\n * gets a narrower answer instead of an error.\r\n */\r\n async recall(req: {\r\n tenantId: string;\r\n userId: string;\r\n prompt: string;\r\n k?: number;\r\n types?: string[];\r\n }): Promise<Record<string, unknown>> {\r\n const body: Record<string, unknown> = {\r\n tenant_id: req.tenantId,\r\n user_id: req.userId,\r\n prompt: req.prompt,\r\n };\r\n if (req.k !== undefined) body.k = req.k;\r\n if (req.types !== undefined) body.types = req.types;\r\n return (\r\n (await this.request<Record<string, unknown>>(\"POST\", \"/v1/memory/recall\", { body })) ?? {}\r\n );\r\n }\r\n\r\n /** Async ingestion status for one memory. */\r\n async status(memoryId: number): Promise<Record<string, unknown>> {\r\n if (!Number.isInteger(memoryId) || memoryId <= 0) {\r\n throw new ValidationError(\"memoryId must be a positive integer\");\r\n }\r\n return (\r\n (await this.request<Record<string, unknown>>(\"GET\", `/v1/memory/status/${memoryId}`)) ?? {}\r\n );\r\n }\r\n\r\n /** Page through a specific end user's memories. */\r\n async listMemories(req: {\r\n tenantId: string;\r\n userId: string;\r\n limit?: number;\r\n offset?: number;\r\n }): Promise<Record<string, unknown>> {\r\n return (\r\n (await this.request<Record<string, unknown>>(\r\n \"GET\",\r\n `/v1/memory/${encodeURIComponent(req.tenantId)}/${encodeURIComponent(req.userId)}/list`,\r\n { query: { limit: req.limit, offset: req.offset } },\r\n )) ?? {}\r\n );\r\n }\r\n}\r\n\r\nfunction toOntology(raw: Record<string, unknown> | null | undefined): Ontology {\r\n return {\r\n contentTypes: (raw?.content_types as string[]) ?? [],\r\n relationTypes: (raw?.relation_types as string[]) ?? [],\r\n builtinContentTypes: (raw?.builtin_content_types as string[]) ?? [],\r\n builtinRelationTypes: (raw?.builtin_relation_types as string[]) ?? [],\r\n customContentTypes: (raw?.custom_content_types as string[]) ?? [],\r\n customRelationTypes: (raw?.custom_relation_types as string[]) ?? [],\r\n maxCustomTypes: (raw?.max_custom_types as number) ?? 32,\r\n };\r\n}\r\n\r\nexport * from \"./control-plane\";\r\nexport {\r\n ConnectionOAuthNamespace,\r\n ConnectionsNamespace,\r\n GoogleDriveNamespace,\r\n GranolaNamespace,\r\n IntegrationsNamespace,\r\n ObjectsNamespace,\r\n ProvidersNamespace,\r\n S3Namespace,\r\n SlackNamespace,\r\n SyncJobsNamespace,\r\n WebCrawlerNamespace,\r\n} from \"./connections\";\r\n","export interface ErrorOptions {\r\n statusCode?: number;\r\n response?: unknown;\r\n requestId?: string;\r\n}\r\n\r\nexport class MemorySyncError extends Error {\r\n readonly statusCode?: number;\r\n readonly response?: unknown;\r\n readonly requestId?: string;\r\n\r\n constructor(message: string, options: ErrorOptions = {}) {\r\n super(message);\r\n this.name = \"MemorySyncError\";\r\n this.statusCode = options.statusCode;\r\n this.response = options.response;\r\n this.requestId = options.requestId;\r\n }\r\n}\r\n\r\nexport class AuthError extends MemorySyncError {\r\n constructor(message: string, options?: ErrorOptions) {\r\n super(message, options);\r\n this.name = \"AuthError\";\r\n }\r\n}\r\n\r\nexport class ValidationError extends MemorySyncError {\r\n constructor(message: string, options?: ErrorOptions) {\r\n super(message, options);\r\n this.name = \"ValidationError\";\r\n }\r\n}\r\n\r\nexport class NotFoundError extends MemorySyncError {\r\n constructor(message: string, options?: ErrorOptions) {\r\n super(message, options);\r\n this.name = \"NotFoundError\";\r\n }\r\n}\r\nexport class RateLimitError extends MemorySyncError {\r\n readonly retryAfterSeconds: number;\r\n\r\n constructor(message: string, retryAfterSeconds: number, options?: ErrorOptions) {\r\n super(message, options);\r\n this.name = \"RateLimitError\";\r\n this.retryAfterSeconds = retryAfterSeconds;\r\n }\r\n}\r\n\r\nexport class ServerError extends MemorySyncError {\r\n constructor(message: string, options?: ErrorOptions) {\r\n super(message, options);\r\n this.name = \"ServerError\";\r\n }\r\n}\r\n","/**\r\n * Connector namespaces — `client.connections`, `client.objects` and friends.\r\n *\r\n * Covers the connector API: creating and managing connections to Slack, Google\r\n * Drive, S3 and Granola, driving syncs, and inspecting the objects a sync\r\n * produced. Shaped after `client.connections.*` in comparable SDKs so the layout\r\n * is familiar.\r\n *\r\n * ## Why these return raw payloads\r\n *\r\n * Connector responses are large, provider-shaped and still moving — a Slack\r\n * channel listing looks nothing like an S3 prefix listing, and both carry\r\n * provider fields that change when the provider changes. Freezing them into\r\n * interfaces would mean an SDK release every time a provider adds a field, and\r\n * callers unable to see the new field until then. Typed models are reserved for\r\n * the small, stable, first-party shapes (memories, history, feedback, ontology).\r\n */\r\n\r\nconst V2 = \"/api/v2/integrations\";\r\nconst V1 = \"/api/v1/integrations\";\r\n\r\n/** The client's request function, injected so namespaces carry no transport. */\r\nexport type RequestFn = <T>(\r\n method: string,\r\n path: string,\r\n options?: { body?: unknown; query?: Record<string, unknown> },\r\n) => Promise<T>;\r\n\r\ntype Json = Record<string, unknown>;\r\n\r\n/**\r\n * Percent-encode one path segment.\r\n *\r\n * Connection, object and resource ids come from providers, not from us. A Slack\r\n * channel id is tame but a Drive resource id or an S3 prefix is not, and an\r\n * unencoded `/` in one of them would silently change which route is called.\r\n */\r\nfunction seg(value: string | number): string {\r\n return encodeURIComponent(String(value));\r\n}\r\n\r\n/**\r\n * Normalize one selection entry into the object the API expects.\r\n *\r\n * Two of the approval endpoints take a list of objects rather than a list of\r\n * ids — Slack channels carry an optional name and type, S3 prefixes carry an\r\n * optional bucket and label. Callers almost always have just the id, so both\r\n * forms are accepted and widened to the object form here, rather than making\r\n * every caller write `{ id: channelId }` and making the simple case ugly.\r\n */\r\nfunction asItem(value: string | Json, key: string): Json {\r\n return typeof value === \"string\" ? { [key]: value } : value;\r\n}\r\n\r\nclass Namespace {\r\n protected readonly req: RequestFn;\r\n constructor(request: RequestFn) {\r\n this.req = request;\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────\r\n// Provider-specific namespaces\r\n// ─────────────────────────────────────────────────────────────────────\r\n\r\n/** Slack connection settings. */\r\nexport class SlackNamespace extends Namespace {\r\n /**\r\n * Channels the app can see and could be added.\r\n *\r\n * Private channels appear only where the deployment allows them *and* a human\r\n * has invited the app, so this never widens what someone already granted.\r\n */\r\n availableChannels(connectionId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/slack/available-channels`, { query });\r\n }\r\n\r\n /** Channels currently selected for syncing. */\r\n channels(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/slack/channels`);\r\n }\r\n\r\n /**\r\n * Select channels for syncing.\r\n *\r\n * Accepts bare channel ids, which is the common case, or objects carrying the\r\n * name and type across so the server does not have to look them up again:\r\n *\r\n * ```ts\r\n * await client.connections.slack.addChannels(\"c1\", [\"C0123\", \"C0456\"]);\r\n * await client.connections.slack.addChannels(\"c1\", [\r\n * { id: \"C0123\", name: \"support\", is_private: false },\r\n * ]);\r\n * ```\r\n */\r\n addChannels(connectionId: string, channels: Array<string | Json>): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/slack/channels`, {\r\n body: { channels: channels.map((c) => asItem(c, \"id\")) },\r\n });\r\n }\r\n\r\n /** Stop syncing one channel. */\r\n removeChannel(connectionId: string, channelId: string): Promise<Json> {\r\n return this.req(\r\n \"DELETE\",\r\n `${V2}/connections/${seg(connectionId)}/slack/channels/${seg(channelId)}`,\r\n );\r\n }\r\n\r\n /**\r\n * Channels this connection will never sync.\r\n *\r\n * The deployment-wide floor cannot be removed here; a tenant may only add to it.\r\n */\r\n exclusionPolicy(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/slack/exclusion-policy`);\r\n }\r\n\r\n /** Replace this connection's additions to the exclusion policy. */\r\n setExclusionPolicy(connectionId: string, policy: Json): Promise<Json> {\r\n return this.req(\"PUT\", `${V2}/connections/${seg(connectionId)}/slack/exclusion-policy`, {\r\n body: policy,\r\n });\r\n }\r\n\r\n /** Slack users seen on this connection and who they map to. */\r\n identities(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/slack/identities`);\r\n }\r\n\r\n /** Map a Slack user to a MemorySync end user. */\r\n linkIdentity(connectionId: string, body: Json): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/slack/identities/link`, { body });\r\n }\r\n\r\n /** Re-read the Slack member list and refresh the identity table. */\r\n syncIdentities(connectionId: string): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/slack/identities/sync`);\r\n }\r\n}\r\n\r\n/** Google Drive connection settings. */\r\nexport class GoogleDriveNamespace extends Namespace {\r\n /** Config for rendering Google's own file picker in your UI. */\r\n pickerConfig(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/gdrive/picker-config`);\r\n }\r\n\r\n /** Files and folders selected for syncing. */\r\n resources(connectionId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/gdrive/resources`, { query });\r\n }\r\n\r\n /** Select files or folders for syncing. */\r\n addResources(connectionId: string, body: Json): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/gdrive/resources`, { body });\r\n }\r\n\r\n /** Stop syncing one file or folder. */\r\n removeResource(connectionId: string, resourceId: string): Promise<Json> {\r\n return this.req(\r\n \"DELETE\",\r\n `${V2}/connections/${seg(connectionId)}/gdrive/resources/${seg(resourceId)}`,\r\n );\r\n }\r\n}\r\n\r\n/** S3 connection settings. */\r\nexport class S3Namespace extends Namespace {\r\n /** Prefixes visible in the bucket that could be added. */\r\n availablePrefixes(connectionId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/s3/available-prefixes`, { query });\r\n }\r\n\r\n /** Prefixes currently selected for syncing. */\r\n prefixes(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/s3/prefixes`);\r\n }\r\n\r\n /**\r\n * Select prefixes for syncing.\r\n *\r\n * Accepts bare prefixes, or objects carrying `bucket` and `label`:\r\n *\r\n * ```ts\r\n * await client.connections.s3.addPrefixes(\"c1\", [\"handbook/\", \"policies/\"]);\r\n * await client.connections.s3.addPrefixes(\"c1\", [\r\n * { prefix: \"handbook/\", label: \"Handbook\" },\r\n * ]);\r\n * ```\r\n *\r\n * An empty string means the bucket root. The bucket defaults to the one the\r\n * connection's credentials were validated against, and the API rejects any\r\n * other bucket rather than indexing one nobody proved access to.\r\n */\r\n addPrefixes(connectionId: string, prefixes: Array<string | Json>): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/s3/prefixes`, {\r\n body: { prefixes: prefixes.map((p) => asItem(p, \"prefix\")) },\r\n });\r\n }\r\n\r\n /**\r\n * Revoke one prefix approval, optionally purging what it produced.\r\n *\r\n * The prefix travels as a query parameter, not in the body and not as a path\r\n * segment: prefixes contain slashes, which a path segment cannot carry\r\n * unambiguously, and this endpoint reads no body at all.\r\n *\r\n * Pass `purge: true` to also delete the memories already derived from the\r\n * prefix. The default leaves them in place, so revoking an approval does not\r\n * silently destroy knowledge.\r\n */\r\n removePrefix(\r\n connectionId: string,\r\n prefix = \"\",\r\n options: { bucket?: string; purge?: boolean } = {},\r\n ): Promise<Json> {\r\n const query: Record<string, unknown> = { prefix, purge: options.purge ?? false };\r\n if (options.bucket !== undefined) query.bucket = options.bucket;\r\n return this.req(\"DELETE\", `${V2}/connections/${seg(connectionId)}/s3/prefixes`, { query });\r\n }\r\n\r\n /** Keys and patterns this connection will never sync. */\r\n exclusionPolicy(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/s3/exclusion-policy`);\r\n }\r\n\r\n /** Replace this connection's additions to the exclusion policy. */\r\n setExclusionPolicy(connectionId: string, policy: Json): Promise<Json> {\r\n return this.req(\"PUT\", `${V2}/connections/${seg(connectionId)}/s3/exclusion-policy`, {\r\n body: policy,\r\n });\r\n }\r\n\r\n /** Effective S3 settings, including the per-object size ceiling. */\r\n settings(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/s3/settings`);\r\n }\r\n}\r\n\r\n/** Granola connection settings. */\r\nexport class GranolaNamespace extends Namespace {\r\n /** Folders that could be added. */\r\n availableFolders(connectionId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/granola/available-folders`, { query });\r\n }\r\n\r\n /** Folders currently selected for syncing. */\r\n folders(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/granola/folders`);\r\n }\r\n\r\n /** Select folders for syncing. */\r\n addFolders(connectionId: string, body: Json): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/granola/folders`, { body });\r\n }\r\n\r\n /** Stop syncing one folder. */\r\n removeFolder(connectionId: string, folderId: string): Promise<Json> {\r\n return this.req(\r\n \"DELETE\",\r\n `${V2}/connections/${seg(connectionId)}/granola/folders/${seg(folderId)}`,\r\n );\r\n }\r\n\r\n /** Folders and meetings this connection will never sync. */\r\n exclusionPolicy(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/granola/exclusion-policy`);\r\n }\r\n\r\n /** Replace this connection's additions to the exclusion policy. */\r\n setExclusionPolicy(connectionId: string, policy: Json): Promise<Json> {\r\n return this.req(\"PUT\", `${V2}/connections/${seg(connectionId)}/granola/exclusion-policy`, {\r\n body: policy,\r\n });\r\n }\r\n\r\n /** Meeting participants seen on this connection and who they map to. */\r\n identities(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/granola/identities`);\r\n }\r\n\r\n /** Map a participant to a MemorySync end user. */\r\n linkIdentity(connectionId: string, body: Json): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/granola/identities/link`, { body });\r\n }\r\n\r\n /**\r\n * Re-run identity matching for this connection.\r\n *\r\n * Takes no arguments: the route reads no body and re-matches the whole roster.\r\n * `body` is kept optional only so a forward-compatible field can be passed\r\n * once the route grows one.\r\n */\r\n relinkIdentity(connectionId: string, body: Json = {}): Promise<Json> {\r\n const hasFields = Object.keys(body).length > 0;\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/granola/identities/relink`, {\r\n body: hasFields ? body : undefined,\r\n });\r\n }\r\n\r\n /** Effective Granola settings for this connection. */\r\n settings(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/granola/settings`);\r\n }\r\n\r\n /** Update Granola settings for this connection. */\r\n setSettings(connectionId: string, settings: Json): Promise<Json> {\r\n return this.req(\"PUT\", `${V2}/connections/${seg(connectionId)}/granola/settings`, {\r\n body: settings,\r\n });\r\n }\r\n}\r\n\r\n/** Starting an OAuth connection. */\r\nexport class ConnectionOAuthNamespace extends Namespace {\r\n /**\r\n * Begin an OAuth connection and get the URL to send the user to.\r\n *\r\n * The user completes consent in a browser and the provider calls the platform\r\n * back — not your backend. Poll {@link status} to find out how it went.\r\n */\r\n initiate(provider: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/oauth/initiate`, {\r\n body: { provider_id: provider, ...body },\r\n });\r\n }\r\n\r\n /** Where an in-flight OAuth connection got to. */\r\n status(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/oauth/status`, { query });\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────\r\n// Connections\r\n// ─────────────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * Connections to external sources.\r\n *\r\n * Provider-specific settings live in sub-namespaces: `connections.slack`,\r\n * `connections.gdrive`, `connections.s3`, `connections.granola`.\r\n */\r\nexport class ConnectionsNamespace extends Namespace {\r\n readonly slack: SlackNamespace;\r\n readonly gdrive: GoogleDriveNamespace;\r\n readonly s3: S3Namespace;\r\n readonly granola: GranolaNamespace;\r\n readonly oauth: ConnectionOAuthNamespace;\r\n\r\n constructor(request: RequestFn) {\r\n super(request);\r\n this.slack = new SlackNamespace(request);\r\n this.gdrive = new GoogleDriveNamespace(request);\r\n this.s3 = new S3Namespace(request);\r\n this.granola = new GranolaNamespace(request);\r\n this.oauth = new ConnectionOAuthNamespace(request);\r\n }\r\n\r\n /** Every connection in this organization. */\r\n list(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections`, { query });\r\n }\r\n\r\n /** One connection, including its status and last sync. */\r\n get(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}`);\r\n }\r\n\r\n /** Connect a provider that authenticates with an API key or bot token. */\r\n /**\r\n * Connect a provider that authenticates with an API key or bot token.\r\n *\r\n * The wire field is `provider_id`; the argument is named `provider` because\r\n * that is what the rest of this namespace calls it.\r\n */\r\n createWithApiKey(provider: string, apiKey: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/api-key`, {\r\n body: { provider_id: provider, api_key: apiKey, ...body },\r\n });\r\n }\r\n\r\n /** Connect a provider that needs a credential bundle, such as S3 keys. */\r\n createWithCredentials(provider: string, credentials: Json, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/credentials`, {\r\n body: { provider_id: provider, credentials, ...body },\r\n });\r\n }\r\n\r\n /** Change a connection's name, schedule or settings. */\r\n update(connectionId: string, body: Json): Promise<Json> {\r\n return this.req(\"PATCH\", `${V2}/connections/${seg(connectionId)}`, { body });\r\n }\r\n\r\n /**\r\n * Remove a connection.\r\n *\r\n * Stops future syncing. Memories already extracted are left in place — use\r\n * {@link purge} for those, so disconnecting never silently deletes knowledge\r\n * someone still depends on.\r\n */\r\n delete(connectionId: string): Promise<Json> {\r\n return this.req(\"DELETE\", `${V2}/connections/${seg(connectionId)}`);\r\n }\r\n\r\n /** Re-authorise a connection whose credentials expired or were revoked. */\r\n reconnect(connectionId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/reconnect`, { body });\r\n }\r\n\r\n /**\r\n * Delete the memories this connection produced.\r\n *\r\n * Separate from {@link delete} on purpose: removing a connection and removing\r\n * what it taught you are different decisions.\r\n */\r\n purge(connectionId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/purge`, { body });\r\n }\r\n\r\n /** Current and recent sync state for a connection. */\r\n syncStatus(connectionId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/sync`);\r\n }\r\n\r\n /** Start a sync now instead of waiting for the schedule. */\r\n triggerSync(connectionId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/sync`, { body });\r\n }\r\n\r\n /** Objects a connection has ingested — files, messages, meetings. */\r\n objects(connectionId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/objects`, { query });\r\n }\r\n\r\n /** Object listing with richer filtering and paging than {@link objects}. */\r\n objectsV2(connectionId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/connections/${seg(connectionId)}/objects/v2`, { query });\r\n }\r\n\r\n /** Apply one action to many objects — pause, resume, re-extract. */\r\n bulkObjectAction(connectionId: string, body: Json): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/connections/${seg(connectionId)}/objects/bulk`, { body });\r\n }\r\n\r\n /** Connector totals: connections, objects synced, memories produced. */\r\n stats(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/stats`, { query });\r\n }\r\n\r\n /** Audit trail of connector activity. */\r\n auditLogs(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/audit-logs`, { query });\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────\r\n// Objects\r\n// ─────────────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * A single synced object: a Drive file, a Slack message batch, an S3 key, a\r\n * meeting transcript.\r\n */\r\nexport class ObjectsNamespace extends Namespace {\r\n /** Metadata and sync state for one object. */\r\n get(objectId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/objects/${seg(objectId)}`);\r\n }\r\n\r\n /** What extraction made of this object. */\r\n analysis(objectId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/objects/${seg(objectId)}/analysis`);\r\n }\r\n\r\n /** Every action taken on this object. */\r\n audit(objectId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/objects/${seg(objectId)}/audit`, { query });\r\n }\r\n\r\n /** Versions of this object seen across syncs. */\r\n history(objectId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/objects/${seg(objectId)}/history`, { query });\r\n }\r\n\r\n /** Which memories this object produced, and whether extraction finished. */\r\n memoryStatus(objectId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/objects/${seg(objectId)}/memory-status`);\r\n }\r\n\r\n /** Row and column statistics for spreadsheet-shaped objects. */\r\n structuredStats(objectId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/objects/${seg(objectId)}/structured-stats`);\r\n }\r\n\r\n /** Score this object for extraction worthiness without extracting. */\r\n evaluate(objectId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/objects/${seg(objectId)}/evaluate`, { body });\r\n }\r\n\r\n /** Stop re-syncing this object, leaving its memories in place. */\r\n pause(objectId: string): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/objects/${seg(objectId)}/pause`);\r\n }\r\n\r\n /** Resume syncing a paused object. */\r\n resume(objectId: string): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/objects/${seg(objectId)}/resume`);\r\n }\r\n\r\n /**\r\n * Run extraction again over content already fetched.\r\n *\r\n * Counts against the plan's add allowance, exactly like the first extraction,\r\n * because it creates memories the same way.\r\n */\r\n reextract(objectId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/objects/${seg(objectId)}/reextract`, { body });\r\n }\r\n\r\n /** Fetch this object from the provider again, then extract. */\r\n resync(objectId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/objects/${seg(objectId)}/resync`, { body });\r\n }\r\n\r\n /** Remove the memories this object produced, keeping the object record. */\r\n deleteMemories(objectId: string, query?: Json): Promise<Json> {\r\n return this.req(\"DELETE\", `${V2}/objects/${seg(objectId)}/memories`, { query });\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────\r\n// Providers and sync jobs\r\n// ─────────────────────────────────────────────────────────────────────\r\n\r\n/** Connectors this deployment supports. */\r\nexport class ProvidersNamespace extends Namespace {\r\n /** Every available provider and what it needs to connect. */\r\n list(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/providers`, { query });\r\n }\r\n\r\n /** One provider's capabilities, scopes and settings schema. */\r\n get(providerId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/providers/${seg(providerId)}`);\r\n }\r\n}\r\n\r\n/** Individual sync runs. */\r\nexport class SyncJobsNamespace extends Namespace {\r\n /** Progress and outcome of one sync run. */\r\n get(jobId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V2}/sync-jobs/${seg(jobId)}`);\r\n }\r\n\r\n /** Stop a running sync. Objects already ingested are kept. */\r\n cancel(jobId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V2}/sync-jobs/${seg(jobId)}/cancel`, { body });\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────\r\n// Web crawler\r\n// ─────────────────────────────────────────────────────────────────────\r\n\r\n/** Turn websites into memories. */\r\nexport class WebCrawlerNamespace extends Namespace {\r\n /** Check a URL is reachable and crawlable before committing to a job. */\r\n validate(url: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V1}/web-crawler/validate`, { body: { url, ...body } });\r\n }\r\n\r\n /**\r\n * Start a crawl. Returns a job to poll.\r\n *\r\n * Crawling only fetches and stores page content. Nothing becomes a memory until\r\n * you call {@link importJob}, so a large crawl cannot quietly consume your add\r\n * allowance.\r\n */\r\n crawl(url: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V1}/web-crawler/crawl`, { body: { url, ...body } });\r\n }\r\n\r\n /** Crawl jobs for this organization. */\r\n jobs(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/web-crawler/jobs`, { query });\r\n }\r\n\r\n /** One crawl job's status and progress. */\r\n job(jobId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/web-crawler/jobs/${seg(jobId)}`);\r\n }\r\n\r\n /** Stop a running crawl. Pages already fetched are kept. */\r\n cancelJob(jobId: string): Promise<Json> {\r\n return this.req(\"POST\", `${V1}/web-crawler/jobs/${seg(jobId)}/cancel`);\r\n }\r\n\r\n /** Delete a crawl job and its fetched pages. */\r\n deleteJob(jobId: string): Promise<Json> {\r\n return this.req(\"DELETE\", `${V1}/web-crawler/jobs/${seg(jobId)}`);\r\n }\r\n\r\n /** Pages a crawl fetched, before any import. */\r\n jobContent(jobId: string, query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/web-crawler/jobs/${seg(jobId)}/content`, { query });\r\n }\r\n\r\n /** Page counts, byte totals and error breakdown for a crawl. */\r\n jobStatistics(jobId: string): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/web-crawler/jobs/${seg(jobId)}/statistics`);\r\n }\r\n\r\n /**\r\n * Turn a completed crawl's pages into memories.\r\n *\r\n * This is the step that creates memories, so this is the step that is billed —\r\n * one unit per memory created, like every other ingestion path.\r\n */\r\n importJob(jobId: string, body: Json = {}): Promise<Json> {\r\n return this.req(\"POST\", `${V1}/web-crawler/jobs/${seg(jobId)}/import`, { body });\r\n }\r\n\r\n /** Crawls running right now. */\r\n active(): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/web-crawler/active`);\r\n }\r\n\r\n /** Crawler limits in force: depth, page ceiling, rate, timeouts. */\r\n config(): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/web-crawler/config`);\r\n }\r\n}\r\n\r\n/**\r\n * The `/api/v1/integrations` surface.\r\n *\r\n * Kept because the catalog and the web crawler live here and have no v2\r\n * equivalent. For connection lifecycle use `client.connections`, which is the\r\n * current API — `connected()` and `stats()` here are older, thinner views of the\r\n * same data.\r\n */\r\nexport class IntegrationsNamespace extends Namespace {\r\n readonly webCrawler: WebCrawlerNamespace;\r\n\r\n constructor(request: RequestFn) {\r\n super(request);\r\n this.webCrawler = new WebCrawlerNamespace(request);\r\n }\r\n\r\n /** Every integration this deployment offers, for building a picker UI. */\r\n catalog(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/catalog`, { query });\r\n }\r\n\r\n /** Integrations currently connected. Older view of `connections.list()`. */\r\n connected(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/connected`, { query });\r\n }\r\n\r\n /** Legacy integration counters. Prefer `connections.stats()`. */\r\n stats(query?: Json): Promise<Json> {\r\n return this.req(\"GET\", `${V1}/stats`, { query });\r\n }\r\n\r\n /** Update a legacy integration record. */\r\n update(integrationId: string, body: Json): Promise<Json> {\r\n return this.req(\"PATCH\", `${V1}/${seg(integrationId)}`, { body });\r\n }\r\n\r\n /** Delete a legacy integration record. */\r\n delete(integrationId: string): Promise<Json> {\r\n return this.req(\"DELETE\", `${V1}/${seg(integrationId)}`);\r\n }\r\n}\r\n","import {\r\n AuthError,\r\n ErrorOptions,\r\n MemorySyncError,\r\n NotFoundError,\r\n RateLimitError,\r\n ServerError,\r\n ValidationError,\r\n} from \"./errors\";\r\n\r\n// Kept in step with package.json and with index.ts: this is the version the\r\n// control-plane client reports in its User-Agent, and it sat at 1.1.1 through two\r\n// releases while the data-plane client moved on.\r\nconst SDK_VERSION = \"1.7.1\";\r\n\r\nexport interface ControlPlaneConfig {\r\n baseUrl: string;\r\n accessToken?: string;\r\n projectId?: string;\r\n timeoutMs?: number;\r\n fetch?: typeof fetch;\r\n}\r\n\r\nexport interface ControlPlaneRequestOptions {\r\n projectId?: string;\r\n}\r\n\r\nexport interface SignupRequest {\r\n email: string;\r\n password: string;\r\n organizationName: string;\r\n fullName?: string;\r\n}\r\n\r\nexport interface SignupResponse {\r\n message: string;\r\n email: string;\r\n requiresVerification: boolean;\r\n}\r\n\r\nexport interface LoginRequest {\r\n email: string;\r\n password: string;\r\n}\r\n\r\nexport interface TokenPair {\r\n accessToken: string;\r\n refreshToken: string;\r\n tokenType: string;\r\n}\r\n\r\nexport interface RefreshRequest {\r\n refreshToken: string;\r\n}\r\n\r\nexport interface CurrentUserResponse {\r\n userId: string;\r\n role: string | null;\r\n org: string | number | null;\r\n sid: number | null;\r\n oauthScopes?: string[];\r\n oauthAppId?: string | null;\r\n}\r\n\r\nexport interface LoginResponse {\r\n tokens: TokenPair;\r\n session: {\r\n userId: number;\r\n organizationId: number;\r\n role: string;\r\n };\r\n mfaRequired: boolean;\r\n mfaSetupRequired: boolean;\r\n}\r\n\r\nexport type ApiKeyTestStatus = \"active\" | \"revoked\" | \"expired\" | string;\r\nexport interface BulkRevokeApiKeysRequest {\r\n keyIds: number[];\r\n}\r\n\r\nexport interface BulkRevokeApiKeyResult {\r\n keyId: number;\r\n status: \"revoked\" | \"already_revoked\" | \"not_found\" | \"forbidden\";\r\n}\r\n\r\nexport interface BulkRevokeApiKeysResponse {\r\n revoked: number;\r\n alreadyRevoked: number;\r\n notFound: number;\r\n results: BulkRevokeApiKeyResult[];\r\n}\r\n\r\nexport interface ApiKeyTestResponse {\r\n keyId: number;\r\n valid: boolean;\r\n status: ApiKeyTestStatus;\r\n environment: string;\r\n rateLimitTier: string;\r\n scopes: string[];\r\n projectId: string | null;\r\n lastUsedAt: string | null;\r\n expiresAt: string | null;\r\n expired: boolean;\r\n serverTime: string;\r\n}\r\n\r\nexport interface PlanLimits {\r\n addRequests: number | null;\r\n retrievalRequests: number | null;\r\n}\r\n\r\nexport interface Plan {\r\n id: string;\r\n name: string;\r\n priceCents?: number | null;\r\n priceLabel: string;\r\n description?: string;\r\n limits: PlanLimits;\r\n features?: string[];\r\n ctaLabel?: string;\r\n isEnterprise?: boolean;\r\n}\r\n\r\nexport interface CurrentPlanResponse {\r\n plan: Plan;\r\n status: string;\r\n billingPeriodStart: string | null;\r\n billingPeriodEnd: string | null;\r\n nextResetAt?: string | null;\r\n planLimitAdd?: number | null;\r\n planLimitRetrieval?: number | null;\r\n paymentFailed: boolean;\r\n paymentStatus?: string;\r\n scheduledPlanId: string | null;\r\n cancelAtPeriodEnd: boolean;\r\n}\r\nexport interface Session {\r\n id: number;\r\n isCurrent: boolean;\r\n sessionType: string;\r\n sessionName: string;\r\n userAgent: string;\r\n ip: string;\r\n location: string | null;\r\n geo: Record<string, unknown> | null;\r\n createdAt: string;\r\n lastActivityAt: string;\r\n expiresAt: string;\r\n}\r\n\r\nexport interface SessionListResponse {\r\n sessions: Session[];\r\n currentSessionId: number | null;\r\n}\r\n\r\nexport interface IntegrationQuery {\r\n category?: string;\r\n}\r\n\r\nexport interface Integration {\r\n id: string;\r\n name: string;\r\n description: string;\r\n category: string;\r\n features: string[];\r\n authType: string;\r\n isConfigured: boolean;\r\n isConnected: boolean;\r\n comingSoon: boolean;\r\n}\r\n\r\nexport interface CreateOrganizationRequest {\r\n name: string;\r\n domain?: string;\r\n}\r\n\r\nexport interface OrganizationMembership {\r\n userId: number;\r\n organizationId: number;\r\n role: string;\r\n}\r\n\r\nexport interface Project {\r\n id: string;\r\n name: string;\r\n tenantId: string;\r\n isDefault: boolean;\r\n memoryCount: number;\r\n archivedAt: string | null;\r\n createdAt: string;\r\n updatedAt: string;\r\n}\r\n\r\nexport interface CreateProjectRequest {\r\n name: string;\r\n}\r\n\r\nexport interface RenameProjectRequest {\r\n name: string;\r\n}\r\n\r\nexport interface WebhookRetryConfig {\r\n enabled?: boolean;\r\n maxRetries?: number;\r\n initialDelaySeconds?: number;\r\n maxDelaySeconds?: number;\r\n backoffMultiplier?: number;\r\n retryStatusCodes?: string[];\r\n}\r\n\r\nexport interface WebhookSignatureConfig {\r\n algorithm?: \"hmac-sha256\" | \"hmac-sha512\";\r\n headerName?: string;\r\n timestampHeader?: string;\r\n toleranceSeconds?: number;\r\n}\r\n\r\nexport interface CreateWebhookRequest {\r\n name: string;\r\n url: string;\r\n events: string[];\r\n description?: string;\r\n retryConfig?: WebhookRetryConfig;\r\n signatureConfig?: WebhookSignatureConfig;\r\n projectId?: string;\r\n}\r\n\r\nexport interface UpdateWebhookRequest {\r\n name?: string;\r\n url?: string;\r\n description?: string;\r\n events?: string[];\r\n retryConfig?: WebhookRetryConfig;\r\n signatureConfig?: WebhookSignatureConfig;\r\n}\r\n\r\nexport interface Webhook {\r\n id: number;\r\n name: string;\r\n url: string;\r\n description: string | null;\r\n secretPrefix: string;\r\n events: string[];\r\n enabled: boolean;\r\n signatureAlgorithm: string;\r\n signatureHeader?: string;\r\n timestampHeader?: string;\r\n signatureTolerance?: number;\r\n retryEnabled?: boolean;\r\n maxRetries?: number;\r\n initialDelaySeconds?: number;\r\n maxDelaySeconds?: number;\r\n backoffMultiplier?: number;\r\n retryStatusCodes?: string[];\r\n totalDeliveries?: number;\r\n successfulDeliveries?: number;\r\n failedDeliveries?: number;\r\n consecutiveFailures?: number;\r\n successRate?: number;\r\n lastTriggeredAt?: string | null;\r\n lastSuccessAt?: string | null;\r\n lastFailureAt?: string | null;\r\n lastError?: string | null;\r\n lastStatusCode?: number | null;\r\n createdAt?: string;\r\n updatedAt?: string;\r\n createdByName?: string | null;\r\n projectId: string | null;\r\n}\r\n\r\nexport interface CreatedWebhook extends Webhook {\r\n secret: string;\r\n}\r\n\r\nexport interface WebhookListResponse {\r\n endpoints: Webhook[];\r\n totalEndpoints: number;\r\n activeEndpoints: number;\r\n totalDeliveries: number;\r\n avgSuccessRate: number;\r\n failingEndpoints: number;\r\n}\r\n\r\nexport interface TestWebhookRequest {\r\n eventType?: string;\r\n}\r\n\r\nexport interface TestWebhookResponse {\r\n deliveryId: number;\r\n eventId: string;\r\n eventType: string;\r\n endpointId: number;\r\n status: string;\r\n payload: Record<string, unknown>;\r\n message: string;\r\n}\r\n\r\nexport interface ReplayWebhookDeliveriesRequest {\r\n sinceMinutes?: number;\r\n statuses?: string[];\r\n limit?: number;\r\n}\r\n\r\nexport interface ReplayWebhookDeliveriesResponse {\r\n endpointId: number;\r\n eligible: number;\r\n replayed: number;\r\n skipped: number;\r\n deliveryIds: number[];\r\n}\r\n\r\nexport interface WebhookDeliveryQuery {\r\n page?: number;\r\n pageSize?: number;\r\n status?: string;\r\n}\r\nexport interface WebhookDelivery {\r\n id: number;\r\n endpointId: number;\r\n eventType: string;\r\n eventId: string;\r\n status: string;\r\n payload?: Record<string, unknown>;\r\n payloadHash: string;\r\n signature?: string | null;\r\n statusCode: number | null;\r\n responseBody?: string | null;\r\n errorMessage?: string | null;\r\n latencyMs: number | null;\r\n attemptNumber: number;\r\n maxAttempts: number;\r\n nextRetryAt?: string | null;\r\n createdAt: string;\r\n completedAt: string | null;\r\n}\r\n\r\nexport interface WebhookDeliveryListResponse {\r\n deliveries: WebhookDelivery[];\r\n total: number;\r\n page: number;\r\n pageSize: number;\r\n}\r\n\r\nexport interface WebhookEventTypesResponse {\r\n eventTypes: string[];\r\n categories: Record<string, string[]>;\r\n}\r\n\r\nexport interface WebhookHealth {\r\n activeWebhooks: number;\r\n totalWebhooks: number;\r\n totalDeliveriesAllTime: number;\r\n totalDeliveries24h: number;\r\n successRate7d: number;\r\n failingEndpoints: number;\r\n pendingRetries: number;\r\n deadLetterCount: number;\r\n}\r\n\r\nexport interface RecentWebhookDeliveryQuery extends WebhookDeliveryQuery {\r\n endpointId?: number;\r\n}\r\n\r\nexport type ExportFormat = \"csv\" | \"jsonl\";\r\nexport type ExportScope = \"filtered\" | \"all\" | \"date_range\";\r\nexport type ExportJobStatus =\r\n | \"queued\"\r\n | \"processing\"\r\n | \"generating\"\r\n | \"completed\"\r\n | \"failed\"\r\n | \"cancelled\"\r\n | \"expired\";\r\n\r\nexport interface ExportFilters {\r\n q?: string | null;\r\n userId?: string | null;\r\n isSummary?: boolean | null;\r\n tier?: string | null;\r\n source?: string | null;\r\n timeRange?: string | null;\r\n dateFrom?: string | null;\r\n dateTo?: string | null;\r\n includeSoftDeleted?: boolean;\r\n}\r\n\r\nexport interface CreateExportRequest {\r\n format?: ExportFormat;\r\n scope?: ExportScope;\r\n filters?: ExportFilters | null;\r\n}\r\n\r\nexport interface ExportJob {\r\n id: string;\r\n projectId: string | null;\r\n environment: string;\r\n format: ExportFormat;\r\n scope: ExportScope;\r\n filters: ExportFilters;\r\n status: ExportJobStatus;\r\n errorMessage: string | null;\r\n retryCount: number;\r\n totalRows: number | null;\r\n processedRows: number;\r\n progressPercentage: number;\r\n fileSizeBytes: number | null;\r\n sha256Hash: string | null;\r\n downloadCount: number;\r\n createdAt: string | null;\r\n startedAt: string | null;\r\n completedAt: string | null;\r\n expiresAt: string | null;\r\n downloadUrl: string | null;\r\n}\r\n\r\nexport interface CreateExportResponse {\r\n job: ExportJob;\r\n estimatedTotal: number | null;\r\n}\r\n\r\nexport interface ExportListQuery {\r\n limit?: number;\r\n}\r\n\r\nexport interface ExportJobListResponse {\r\n jobs: ExportJob[];\r\n total: number;\r\n}\r\n\r\nexport interface ExportDownloadUrl {\r\n downloadUrl: string;\r\n expiresAt: string | null;\r\n fileSizeBytes: number | null;\r\n filename: string;\r\n}\r\n\r\ntype QueryValue = string | number | boolean | null | undefined;\r\ntype WireObject = Record<string, unknown>;\r\n\r\nfunction safeJson(text: string): unknown {\r\n try {\r\n return JSON.parse(text);\r\n } catch {\r\n return text;\r\n }\r\n}\r\n\r\nfunction extractDetail(body: unknown): string | undefined {\r\n if (!body || typeof body !== \"object\") return undefined;\r\n const value = body as Record<string, unknown>;\r\n if (typeof value.detail === \"string\") return value.detail;\r\n if (value.error && typeof value.error === \"object\") {\r\n const error = value.error as Record<string, unknown>;\r\n if (typeof error.message === \"string\") return error.message;\r\n }\r\n if (Array.isArray(value.detail) && value.detail.length > 0) {\r\n const first = value.detail[0];\r\n if (first && typeof first === \"object\" && typeof (first as Record<string, unknown>).msg === \"string\") {\r\n return (first as Record<string, unknown>).msg as string;\r\n }\r\n }\r\n return undefined;\r\n}\r\nfunction extractBodyRetryAfter(body: unknown): number {\r\n if (!body || typeof body !== \"object\") return 0;\r\n const value = body as Record<string, unknown>;\r\n if (typeof value.retry_after === \"number\") return value.retry_after;\r\n if (value.error && typeof value.error === \"object\") {\r\n const retryAfter = (value.error as Record<string, unknown>).retry_after;\r\n if (typeof retryAfter === \"number\") return retryAfter;\r\n }\r\n return 0;\r\n}\r\n\r\nfunction parseRetryAfter(value: string | null): number | undefined {\r\n if (!value) return undefined;\r\n const seconds = Number(value);\r\n if (Number.isFinite(seconds) && seconds >= 0) return seconds;\r\n const date = Date.parse(value);\r\n if (Number.isNaN(date)) return undefined;\r\n return Math.max(0, Math.ceil((date - Date.now()) / 1000));\r\n}\r\n\r\nfunction snakeToCamel(key: string): string {\r\n return key.replace(/_([a-z0-9])/g, (_, character: string) => character.toUpperCase());\r\n}\r\n\r\nconst OPAQUE_RESPONSE_KEYS = new Set([\"payload\", \"metadata\", \"geo\", \"configuration\"]);\r\n\r\nfunction normalizeResponse(value: unknown): unknown {\r\n if (Array.isArray(value)) return value.map(normalizeResponse);\r\n if (!value || typeof value !== \"object\") return value;\r\n const normalized: Record<string, unknown> = {};\r\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\r\n const camelKey = snakeToCamel(key);\r\n normalized[camelKey] = OPAQUE_RESPONSE_KEYS.has(camelKey) ? item : normalizeResponse(item);\r\n }\r\n return normalized;\r\n}\r\n\r\nfunction queryString(values: Record<string, QueryValue>): string {\r\n const params = new URLSearchParams();\r\n for (const [key, value] of Object.entries(values)) {\r\n if (value !== undefined && value !== null) params.set(key, String(value));\r\n }\r\n const encoded = params.toString();\r\n return encoded ? `?${encoded}` : \"\";\r\n}\r\n\r\nfunction positiveId(value: number, name: string): void {\r\n if (!Number.isInteger(value) || value <= 0) {\r\n throw new ValidationError(`${name} must be a positive integer`);\r\n }\r\n}\r\n\r\nfunction nonEmpty(value: string, name: string): void {\r\n if (typeof value !== \"string\" || !value.trim()) throw new ValidationError(`${name} must not be empty`);\r\n}\r\n\r\nfunction boundedInteger(value: number, name: string, minimum: number, maximum: number): void {\r\n if (!Number.isInteger(value) || value < minimum || value > maximum) {\r\n throw new ValidationError(`${name} must be an integer between ${minimum} and ${maximum}`);\r\n }\r\n}\r\n\r\nfunction nonNegativeInteger(value: number, name: string): void {\r\n if (!Number.isInteger(value) || value < 0) {\r\n throw new ValidationError(`${name} must be a non-negative integer`);\r\n }\r\n}\r\n\r\nfunction nonEmptyStrings(values: string[], name: string): void {\r\n if (!Array.isArray(values) || values.length === 0 ||\r\n values.some((value) => typeof value !== \"string\" || !value.trim())) {\r\n throw new ValidationError(`${name} must contain at least one non-empty string`);\r\n }\r\n}\r\n\r\nfunction projectName(value: string): void {\r\n nonEmpty(value, \"name\");\r\n if (value.length > 200) throw new ValidationError(\"name may contain at most 200 characters\");\r\n}\r\n\r\nfunction pathId(value: string, name: string, minimum = 1, maximum?: number): string {\r\n nonEmpty(value, name);\r\n const trimmed = value.trim();\r\n if (trimmed.length < minimum || (maximum !== undefined && trimmed.length > maximum)) {\r\n const range = maximum === undefined ? `at least ${minimum}` : `between ${minimum} and ${maximum}`;\r\n throw new ValidationError(`${name} must contain ${range} characters`);\r\n }\r\n return encodeURIComponent(trimmed);\r\n}\r\n\r\nfunction validateWebhookRetryConfig(config: WebhookRetryConfig): void {\r\n if (config.maxRetries !== undefined) boundedInteger(config.maxRetries, \"maxRetries\", 1, 10);\r\n if (config.initialDelaySeconds !== undefined) boundedInteger(config.initialDelaySeconds, \"initialDelaySeconds\", 1, 60);\r\n if (config.maxDelaySeconds !== undefined) boundedInteger(config.maxDelaySeconds, \"maxDelaySeconds\", 60, 86_400);\r\n if (config.backoffMultiplier !== undefined &&\r\n (!Number.isFinite(config.backoffMultiplier) || config.backoffMultiplier < 1 || config.backoffMultiplier > 5)) {\r\n throw new ValidationError(\"backoffMultiplier must be between 1 and 5\");\r\n }\r\n if (config.retryStatusCodes !== undefined &&\r\n (!Array.isArray(config.retryStatusCodes) || config.retryStatusCodes.length === 0 ||\r\n config.retryStatusCodes.some((value) => typeof value !== \"string\" || value.trim().length === 0))) {\r\n throw new ValidationError(\"retryStatusCodes must contain at least one non-empty string\");\r\n }\r\n}\r\n\r\nfunction validateWebhookSignatureConfig(config: WebhookSignatureConfig): void {\r\n if (config.algorithm !== undefined && config.algorithm !== \"hmac-sha256\" && config.algorithm !== \"hmac-sha512\") {\r\n throw new ValidationError(\"algorithm must be 'hmac-sha256' or 'hmac-sha512'\");\r\n }\r\n for (const [name, value] of [[\"headerName\", config.headerName], [\"timestampHeader\", config.timestampHeader]] as const) {\r\n if (value !== undefined && value.trim().length === 0) {\r\n throw new ValidationError(`${name} must be a non-empty string`);\r\n }\r\n if (value !== undefined && value.length > 64) {\r\n throw new ValidationError(`${name} may contain at most 64 characters`);\r\n }\r\n }\r\n if (config.toleranceSeconds !== undefined) boundedInteger(config.toleranceSeconds, \"toleranceSeconds\", 60, 3_600);\r\n}\r\n\r\nfunction webhookRetryConfig(config: WebhookRetryConfig): WireObject {\r\n validateWebhookRetryConfig(config);\r\n const wire: WireObject = {};\r\n if (config.enabled !== undefined) wire.enabled = config.enabled;\r\n if (config.maxRetries !== undefined) wire.max_retries = config.maxRetries;\r\n if (config.initialDelaySeconds !== undefined) wire.initial_delay_seconds = config.initialDelaySeconds;\r\n if (config.maxDelaySeconds !== undefined) wire.max_delay_seconds = config.maxDelaySeconds;\r\n if (config.backoffMultiplier !== undefined) wire.backoff_multiplier = config.backoffMultiplier;\r\n if (config.retryStatusCodes !== undefined) wire.retry_status_codes = config.retryStatusCodes;\r\n return wire;\r\n}\r\n\r\nfunction webhookSignatureConfig(config: WebhookSignatureConfig): WireObject {\r\n validateWebhookSignatureConfig(config);\r\n const wire: WireObject = {};\r\n if (config.algorithm !== undefined) wire.algorithm = config.algorithm;\r\n if (config.headerName !== undefined) wire.header_name = config.headerName;\r\n if (config.timestampHeader !== undefined) wire.timestamp_header = config.timestampHeader;\r\n if (config.toleranceSeconds !== undefined) wire.tolerance_seconds = config.toleranceSeconds;\r\n return wire;\r\n}\r\n\r\nfunction exportFilters(filters: ExportFilters): WireObject {\r\n const wire: WireObject = {};\r\n if (filters.q !== undefined) wire.q = filters.q;\r\n if (filters.userId !== undefined) wire.user_id = filters.userId;\r\n if (filters.isSummary !== undefined) wire.is_summary = filters.isSummary;\r\n if (filters.tier !== undefined) wire.tier = filters.tier;\r\n if (filters.source !== undefined) wire.source = filters.source;\r\n if (filters.timeRange !== undefined) wire.time_range = filters.timeRange;\r\n if (filters.dateFrom !== undefined) wire.date_from = filters.dateFrom;\r\n if (filters.dateTo !== undefined) wire.date_to = filters.dateTo;\r\n if (filters.includeSoftDeleted !== undefined) wire.include_soft_deleted = filters.includeSoftDeleted;\r\n return wire;\r\n}\r\n\r\nfunction validateWebhook(name: string, url: string, events: string[]): void {\r\n nonEmpty(name, \"name\");\r\n if (name.length > 128) throw new ValidationError(\"name may contain at most 128 characters\");\r\n nonEmptyStrings(events, \"events\");\r\n validateWebhookUrl(url);\r\n}\r\n\r\nfunction validateWebhookUrl(url: string): void {\r\n nonEmpty(url, \"url\");\r\n let parsed: URL;\r\n try {\r\n parsed = new URL(url);\r\n } catch {\r\n throw new ValidationError(\"url must be a valid HTTP or HTTPS URL\");\r\n }\r\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\r\n throw new ValidationError(\"url must be a valid HTTP or HTTPS URL\");\r\n }\r\n if (parsed.username || parsed.password) throw new ValidationError(\"url must not contain credentials\");\r\n}\r\n\r\ninterface RequestOptions extends ControlPlaneRequestOptions {\r\n body?: unknown;\r\n auth?: boolean;\r\n project?: boolean;\r\n}\r\n\r\nexport class ControlPlaneClient {\r\n private readonly baseUrl: string;\r\n private readonly accessToken?: string;\r\n private readonly projectId?: string;\r\n private readonly timeoutMs: number;\r\n private readonly fetchImpl: typeof fetch;\r\n constructor(config: ControlPlaneConfig) {\r\n if (!config.baseUrl?.trim()) throw new ValidationError(\"baseUrl is required\");\r\n let parsed: URL;\r\n try {\r\n parsed = new URL(config.baseUrl);\r\n } catch {\r\n throw new ValidationError(\"baseUrl must be an absolute HTTP or HTTPS URL\");\r\n }\r\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\r\n throw new ValidationError(\"baseUrl must be an absolute HTTP or HTTPS URL\");\r\n }\r\n if (config.accessToken !== undefined && !config.accessToken.trim()) {\r\n throw new ValidationError(\"accessToken must not be empty when provided\");\r\n }\r\n if (config.projectId !== undefined && !config.projectId.trim()) {\r\n throw new ValidationError(\"projectId must not be empty when provided\");\r\n }\r\n if (config.timeoutMs !== undefined && (!Number.isFinite(config.timeoutMs) || config.timeoutMs <= 0)) {\r\n throw new ValidationError(\"timeoutMs must be greater than zero\");\r\n }\r\n this.baseUrl = config.baseUrl.replace(/\\/+$/, \"\");\r\n this.accessToken = config.accessToken?.trim();\r\n this.projectId = config.projectId?.trim();\r\n this.timeoutMs = config.timeoutMs ?? 30_000;\r\n const implementation = config.fetch ?? (typeof fetch !== \"undefined\" ? fetch : undefined);\r\n if (!implementation) {\r\n throw new Error(\"No fetch implementation available. Pass `fetch` in config or use Node 18+.\");\r\n }\r\n this.fetchImpl = implementation;\r\n }\r\n\r\n private async request<T>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\r\n const requiresAuth = options.auth !== false;\r\n if (requiresAuth && !this.accessToken) {\r\n throw new AuthError(\"accessToken is required for this operation\");\r\n }\r\n if (options.projectId !== undefined && !options.projectId.trim()) {\r\n throw new ValidationError(\"projectId override must not be empty\");\r\n }\r\n const headers: Record<string, string> = {\r\n Accept: \"application/json\",\r\n \"User-Agent\": `memorysync-sdk-js/${SDK_VERSION}`,\r\n };\r\n if (requiresAuth) headers.Authorization = `Bearer ${this.accessToken}`;\r\n const selectedProject = options.project === false\r\n ? undefined\r\n : options.projectId?.trim() ?? this.projectId;\r\n if (selectedProject) headers[\"X-Project-ID\"] = selectedProject;\r\n if (options.body !== undefined) headers[\"Content-Type\"] = \"application/json\";\r\n\r\n const controller = new AbortController();\r\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\r\n try {\r\n const response = await this.fetchImpl(`${this.baseUrl}${path}`, {\r\n method,\r\n headers,\r\n body: options.body === undefined ? undefined : JSON.stringify(options.body),\r\n signal: controller.signal,\r\n });\r\n const requestId = response.headers.get(\"X-Request-ID\") ?? undefined;\r\n if (response.status === 204) return undefined as T;\r\n const text = await response.text();\r\n const parsedBody = text ? safeJson(text) : null;\r\n if (!response.ok) {\r\n this.throwForStatus(response.status, parsedBody, requestId, response.headers.get(\"Retry-After\"));\r\n }\r\n return normalizeResponse(parsedBody) as T;\r\n } catch (error) {\r\n if (error instanceof MemorySyncError) throw error;\r\n if (error instanceof Error && error.name === \"AbortError\") {\r\n throw new MemorySyncError(`Request timed out after ${this.timeoutMs}ms`);\r\n }\r\n const message = error instanceof Error ? error.message : String(error);\r\n throw new MemorySyncError(`Network error: ${message}`);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n }\r\n private throwForStatus(\r\n status: number,\r\n body: unknown,\r\n requestId: string | undefined,\r\n retryAfterHeader: string | null,\r\n ): never {\r\n const detail = extractDetail(body);\r\n const options: ErrorOptions = { statusCode: status, response: body, requestId };\r\n if (status === 401) throw new AuthError(detail || \"Unauthenticated\", options);\r\n if (status === 403) throw new AuthError(detail || \"Forbidden\", options);\r\n if (status === 404) throw new NotFoundError(detail || \"Not found\", options);\r\n if (status === 400 || status === 409 || status === 422) {\r\n throw new ValidationError(detail || \"Validation error\", options);\r\n }\r\n if (status === 429) {\r\n const retryAfter = parseRetryAfter(retryAfterHeader) ?? extractBodyRetryAfter(body);\r\n throw new RateLimitError(detail || \"Rate limited\", retryAfter, options);\r\n }\r\n if (status >= 500) throw new ServerError(detail || `Server error (${status})`, options);\r\n throw new MemorySyncError(detail || `Unexpected status ${status}`, options);\r\n }\r\n\r\n async bulkRevokeApiKeys(\r\n request: BulkRevokeApiKeysRequest,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<BulkRevokeApiKeysResponse> {\r\n if (!Array.isArray(request.keyIds) || request.keyIds.length < 1 || request.keyIds.length > 100) {\r\n throw new ValidationError(\"keyIds must contain between 1 and 100 entries\");\r\n }\r\n request.keyIds.forEach((id) => positiveId(id, \"keyIds entry\"));\r\n return this.request(\"POST\", \"/org/api-keys/bulk-revoke\", {\r\n ...options,\r\n body: { key_ids: request.keyIds },\r\n });\r\n }\r\n\r\n async testApiKey(keyId: number, options: ControlPlaneRequestOptions = {}): Promise<ApiKeyTestResponse> {\r\n positiveId(keyId, \"keyId\");\r\n return this.request(\"POST\", `/org/api-keys/${keyId}/test`, options);\r\n }\r\n\r\n async signup(request: SignupRequest): Promise<SignupResponse> {\r\n nonEmpty(request.email, \"email\");\r\n if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(request.email)) {\r\n throw new ValidationError(\"email must be a valid email address\");\r\n }\r\n nonEmpty(request.password, \"password\");\r\n if (request.password.length < 8) {\r\n throw new ValidationError(\"password must contain at least 8 characters\");\r\n }\r\n nonEmpty(request.organizationName, \"organizationName\");\r\n const organizationLength = request.organizationName.trim().length;\r\n if (organizationLength < 2 || organizationLength > 100) {\r\n throw new ValidationError(\"organizationName must contain between 2 and 100 characters\");\r\n }\r\n return this.request(\"POST\", \"/auth/signup\", {\r\n auth: false,\r\n project: false,\r\n body: {\r\n email: request.email,\r\n password: request.password,\r\n organization_name: request.organizationName,\r\n ...(request.fullName === undefined ? {} : { full_name: request.fullName }),\r\n },\r\n });\r\n }\r\n\r\n async login(request: LoginRequest, options: ControlPlaneRequestOptions = {}): Promise<LoginResponse> {\r\n nonEmpty(request.email, \"email\");\r\n nonEmpty(request.password, \"password\");\r\n if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(request.email)) {\r\n throw new ValidationError(\"email must be a valid email address\");\r\n }\r\n return this.request(\"POST\", \"/auth/login\", {\r\n ...options,\r\n auth: false,\r\n project: false,\r\n body: { email: request.email, password: request.password },\r\n });\r\n }\r\n\r\n async refresh(request: RefreshRequest): Promise<TokenPair> {\r\n nonEmpty(request.refreshToken, \"refreshToken\");\r\n return this.request(\"POST\", \"/auth/refresh\", {\r\n auth: false,\r\n project: false,\r\n body: { refresh_token: request.refreshToken },\r\n });\r\n }\r\n\r\n async logout(request: RefreshRequest): Promise<void> {\r\n nonEmpty(request.refreshToken, \"refreshToken\");\r\n return this.request(\"POST\", \"/auth/logout\", {\r\n auth: false,\r\n project: false,\r\n body: { refresh_token: request.refreshToken },\r\n });\r\n }\r\n\r\n async me(): Promise<CurrentUserResponse> {\r\n return this.request(\"GET\", \"/auth/me\", { project: false });\r\n }\r\n\r\n async logoutAll(): Promise<void> {\r\n return this.request(\"POST\", \"/auth/logout-all\", { project: false });\r\n }\r\n\r\n async getCurrentPlan(options: ControlPlaneRequestOptions = {}): Promise<CurrentPlanResponse> {\r\n return this.request(\"GET\", \"/org/billing/current-plan\", options);\r\n }\r\n\r\n async listSessions(options: ControlPlaneRequestOptions = {}): Promise<SessionListResponse> {\r\n return this.request(\"GET\", \"/auth/sessions\", options);\r\n }\r\n\r\n async revokeSession(sessionId: number, options: ControlPlaneRequestOptions = {}): Promise<void> {\r\n positiveId(sessionId, \"sessionId\");\r\n return this.request(\"POST\", `/auth/sessions/${sessionId}/revoke`, options);\r\n }\r\n\r\n async listIntegrations(\r\n query: IntegrationQuery = {},\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<Integration[]> {\r\n if (query.category !== undefined) nonEmpty(query.category, \"category\");\r\n const path = \"/api/v1/integrations/catalog\" + queryString({ category: query.category });\r\n return this.request(\"GET\", path, options);\r\n }\r\n\r\n async createOrganization(\r\n request: CreateOrganizationRequest,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<OrganizationMembership> {\r\n nonEmpty(request.name, \"name\");\r\n if (request.domain !== undefined) nonEmpty(request.domain, \"domain\");\r\n const body: WireObject = { name: request.name };\r\n if (request.domain !== undefined) body.domain = request.domain;\r\n return this.request(\"POST\", \"/organizations\", { ...options, body });\r\n }\r\n\r\n async listOrganizations(options: ControlPlaneRequestOptions = {}): Promise<OrganizationMembership[]> {\r\n return this.request(\"GET\", \"/organizations\", options);\r\n }\r\n\r\n async listProjects(options: ControlPlaneRequestOptions = {}): Promise<Project[]> {\r\n return this.request(\"GET\", \"/org/projects\", options);\r\n }\r\n\r\n async createProject(\r\n request: CreateProjectRequest,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<Project> {\r\n projectName(request.name);\r\n return this.request(\"POST\", \"/org/projects\", { ...options, body: { name: request.name } });\r\n }\r\n\r\n async renameProject(\r\n projectId: string,\r\n request: RenameProjectRequest,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<Project> {\r\n const encodedId = pathId(projectId, \"projectId\");\r\n projectName(request.name);\r\n return this.request(\"PATCH\", `/org/projects/${encodedId}`, { ...options, body: { name: request.name } });\r\n }\r\n\r\n async archiveProject(projectId: string, options: ControlPlaneRequestOptions = {}): Promise<Project> {\r\n return this.request(\"POST\", `/org/projects/${pathId(projectId, \"projectId\")}/archive`, options);\r\n }\r\n\r\n async unarchiveProject(projectId: string, options: ControlPlaneRequestOptions = {}): Promise<Project> {\r\n return this.request(\"POST\", `/org/projects/${pathId(projectId, \"projectId\")}/unarchive`, options);\r\n }\r\n\r\n async deleteProject(projectId: string, options: ControlPlaneRequestOptions = {}): Promise<void> {\r\n return this.request(\"DELETE\", `/org/projects/${pathId(projectId, \"projectId\")}`, options);\r\n }\r\n\r\n async createWebhook(\r\n request: CreateWebhookRequest,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<CreatedWebhook> {\r\n validateWebhook(request.name, request.url, request.events);\r\n if (request.description !== undefined && request.description.length > 500) {\r\n throw new ValidationError(\"description may contain at most 500 characters\");\r\n }\r\n if (request.projectId !== undefined) {\r\n nonEmpty(request.projectId, \"projectId\");\r\n if (request.projectId.length > 64) throw new ValidationError(\"projectId may contain at most 64 characters\");\r\n }\r\n if (options.projectId !== undefined) nonEmpty(options.projectId, \"projectId override\");\r\n if (request.projectId && options.projectId && request.projectId.trim() !== options.projectId.trim()) {\r\n throw new ValidationError(\"request projectId and options projectId must match\");\r\n }\r\n const body: WireObject = { name: request.name, url: request.url, events: request.events };\r\n if (request.description !== undefined) body.description = request.description;\r\n if (request.retryConfig !== undefined) body.retry_config = webhookRetryConfig(request.retryConfig);\r\n if (request.signatureConfig !== undefined) body.signature_config = webhookSignatureConfig(request.signatureConfig);\r\n if (request.projectId !== undefined) body.project_id = request.projectId;\r\n return this.request(\"POST\", \"/org/webhooks\", {\r\n ...options,\r\n projectId: options.projectId ?? request.projectId,\r\n body,\r\n });\r\n }\r\n async listWebhooks(options: ControlPlaneRequestOptions = {}): Promise<WebhookListResponse> {\r\n return this.request(\"GET\", \"/org/webhooks\", options);\r\n }\r\n\r\n async getWebhook(endpointId: number, options: ControlPlaneRequestOptions = {}): Promise<Webhook> {\r\n positiveId(endpointId, \"endpointId\");\r\n return this.request(\"GET\", `/org/webhooks/${endpointId}`, options);\r\n }\r\n\r\n async getWebhookEventTypes(options: ControlPlaneRequestOptions = {}): Promise<WebhookEventTypesResponse> {\r\n return this.request(\"GET\", \"/org/webhooks/event-types\", options);\r\n }\r\n\r\n async getWebhookHealth(options: ControlPlaneRequestOptions = {}): Promise<WebhookHealth> {\r\n return this.request(\"GET\", \"/org/webhooks/health\", options);\r\n }\r\n\r\n async pauseWebhook(endpointId: number, options: ControlPlaneRequestOptions = {}): Promise<Webhook> {\r\n positiveId(endpointId, \"endpointId\");\r\n return this.request(\"POST\", `/org/webhooks/${endpointId}/pause`, options);\r\n }\r\n\r\n async resumeWebhook(endpointId: number, options: ControlPlaneRequestOptions = {}): Promise<Webhook> {\r\n positiveId(endpointId, \"endpointId\");\r\n return this.request(\"POST\", `/org/webhooks/${endpointId}/resume`, options);\r\n }\r\n\r\n async rotateWebhookSecret(\r\n endpointId: number,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<CreatedWebhook> {\r\n positiveId(endpointId, \"endpointId\");\r\n return this.request(\"POST\", `/org/webhooks/${endpointId}/rotate-secret`, options);\r\n }\r\n\r\n async updateWebhook(\r\n endpointId: number,\r\n request: UpdateWebhookRequest,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<Webhook> {\r\n positiveId(endpointId, \"endpointId\");\r\n const body: WireObject = {};\r\n if (request.name !== undefined) {\r\n nonEmpty(request.name, \"name\");\r\n if (request.name.length > 128) throw new ValidationError(\"name may contain at most 128 characters\");\r\n body.name = request.name;\r\n }\r\n if (request.url !== undefined) {\r\n validateWebhookUrl(request.url);\r\n body.url = request.url;\r\n }\r\n if (request.description !== undefined) {\r\n if (request.description.length > 500) {\r\n throw new ValidationError(\"description may contain at most 500 characters\");\r\n }\r\n body.description = request.description;\r\n }\r\n if (request.events !== undefined) {\r\n nonEmptyStrings(request.events, \"events\");\r\n body.events = request.events;\r\n }\r\n if (request.retryConfig !== undefined) body.retry_config = webhookRetryConfig(request.retryConfig);\r\n if (request.signatureConfig !== undefined) body.signature_config = webhookSignatureConfig(request.signatureConfig);\r\n if (Object.keys(body).length === 0) {\r\n throw new ValidationError(\"updateWebhook requires at least one editable field\");\r\n }\r\n return this.request(\"PATCH\", `/org/webhooks/${endpointId}`, { ...options, body });\r\n }\r\n\r\n async deleteWebhook(endpointId: number, options: ControlPlaneRequestOptions = {}): Promise<void> {\r\n positiveId(endpointId, \"endpointId\");\r\n return this.request(\"DELETE\", `/org/webhooks/${endpointId}`, options);\r\n }\r\n\r\n async testWebhook(\r\n endpointId: number,\r\n request: TestWebhookRequest = {},\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<TestWebhookResponse> {\r\n positiveId(endpointId, \"endpointId\");\r\n const body: WireObject = {};\r\n if (request.eventType !== undefined) {\r\n nonEmpty(request.eventType, \"eventType\");\r\n body.event_type = request.eventType;\r\n }\r\n return this.request(\"POST\", `/org/webhooks/${endpointId}/test`, { ...options, body });\r\n }\r\n async replayWebhookDeliveries(\r\n endpointId: number,\r\n request: ReplayWebhookDeliveriesRequest = {},\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<ReplayWebhookDeliveriesResponse> {\r\n positiveId(endpointId, \"endpointId\");\r\n if (request.sinceMinutes !== undefined &&\r\n (!Number.isInteger(request.sinceMinutes) || request.sinceMinutes < 1 || request.sinceMinutes > 10_080)) {\r\n throw new ValidationError(\"sinceMinutes must be an integer between 1 and 10080\");\r\n }\r\n if (request.limit !== undefined &&\r\n (!Number.isInteger(request.limit) || request.limit < 1 || request.limit > 1_000)) {\r\n throw new ValidationError(\"limit must be an integer between 1 and 1000\");\r\n }\r\n if (request.statuses !== undefined) nonEmptyStrings(request.statuses, \"statuses\");\r\n const body: WireObject = {};\r\n if (request.sinceMinutes !== undefined) body.since_minutes = request.sinceMinutes;\r\n if (request.statuses !== undefined) body.statuses = request.statuses;\r\n if (request.limit !== undefined) body.limit = request.limit;\r\n return this.request(\"POST\", `/org/webhooks/${endpointId}/replay`, { ...options, body });\r\n }\r\n\r\n async listWebhookDeliveries(\r\n endpointId: number,\r\n query: WebhookDeliveryQuery = {},\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<WebhookDeliveryListResponse> {\r\n positiveId(endpointId, \"endpointId\");\r\n if (query.page !== undefined) positiveId(query.page, \"page\");\r\n if (query.pageSize !== undefined) boundedInteger(query.pageSize, \"pageSize\", 1, 100);\r\n if (query.status !== undefined) nonEmpty(query.status, \"status\");\r\n const path = `/org/webhooks/${endpointId}/deliveries` + queryString({\r\n page: query.page,\r\n page_size: query.pageSize,\r\n status_filter: query.status,\r\n });\r\n return this.request(\"GET\", path, options);\r\n }\r\n\r\n async getLatestWebhookDelivery(\r\n endpointId: number,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<WebhookDelivery | null> {\r\n positiveId(endpointId, \"endpointId\");\r\n return this.request(\"GET\", `/org/webhooks/${endpointId}/deliveries/latest`, options);\r\n }\r\n\r\n async listRecentWebhookDeliveries(\r\n query: RecentWebhookDeliveryQuery = {},\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<WebhookDeliveryListResponse> {\r\n if (query.page !== undefined) positiveId(query.page, \"page\");\r\n if (query.pageSize !== undefined) boundedInteger(query.pageSize, \"pageSize\", 1, 100);\r\n if (query.endpointId !== undefined) positiveId(query.endpointId, \"endpointId\");\r\n if (query.status !== undefined) nonEmpty(query.status, \"status\");\r\n const path = \"/org/webhooks/deliveries/recent\" + queryString({\r\n page: query.page,\r\n page_size: query.pageSize,\r\n endpoint_id: query.endpointId,\r\n status_filter: query.status,\r\n });\r\n return this.request(\"GET\", path, options);\r\n }\r\n\r\n async getWebhookDelivery(\r\n deliveryId: number,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<WebhookDelivery> {\r\n positiveId(deliveryId, \"deliveryId\");\r\n return this.request(\"GET\", `/org/webhooks/deliveries/${deliveryId}`, options);\r\n }\r\n\r\n async retryWebhookDelivery(\r\n deliveryId: number,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<WebhookDelivery> {\r\n positiveId(deliveryId, \"deliveryId\");\r\n return this.request(\"POST\", `/org/webhooks/deliveries/${deliveryId}/retry`, options);\r\n }\r\n\r\n async createExport(\r\n request: CreateExportRequest,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<CreateExportResponse> {\r\n const format = request.format ?? \"csv\";\r\n const scope = request.scope ?? \"filtered\";\r\n if (format !== \"csv\" && format !== \"jsonl\") throw new ValidationError(\"format must be 'csv' or 'jsonl'\");\r\n if (scope !== \"filtered\" && scope !== \"all\" && scope !== \"date_range\") {\r\n throw new ValidationError(\"scope must be 'filtered', 'all', or 'date_range'\");\r\n }\r\n const body: WireObject = { format, scope };\r\n if (request.filters !== undefined) body.filters = request.filters === null ? null : exportFilters(request.filters);\r\n return this.request(\"POST\", \"/exports\", { ...options, body });\r\n }\r\n\r\n async listExports(\r\n query: ExportListQuery = {},\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<ExportJobListResponse> {\r\n if (query.limit !== undefined) boundedInteger(query.limit, \"limit\", 1, 100);\r\n return this.request(\"GET\", \"/exports\" + queryString({ limit: query.limit }), options);\r\n }\r\n\r\n async getExport(jobId: string, options: ControlPlaneRequestOptions = {}): Promise<ExportJob> {\r\n return this.request(\"GET\", `/exports/${pathId(jobId, \"jobId\", 8, 64)}`, options);\r\n }\r\n\r\n async cancelExport(jobId: string, options: ControlPlaneRequestOptions = {}): Promise<ExportJob> {\r\n return this.request(\"POST\", `/exports/${pathId(jobId, \"jobId\", 8, 64)}/cancel`, options);\r\n }\r\n\r\n async retryExport(jobId: string, options: ControlPlaneRequestOptions = {}): Promise<CreateExportResponse> {\r\n return this.request(\"POST\", `/exports/${pathId(jobId, \"jobId\", 8, 64)}/retry`, options);\r\n }\r\n\r\n async getExportDownloadUrl(\r\n jobId: string,\r\n options: ControlPlaneRequestOptions = {},\r\n ): Promise<ExportDownloadUrl> {\r\n return this.request(\"GET\", `/exports/${pathId(jobId, \"jobId\", 8, 64)}/download-url`, options);\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;;;ACMO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAKzC,YAAY,SAAiB,UAAwB,CAAC,GAAG;AACvD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa,QAAQ;AAC1B,SAAK,WAAW,QAAQ;AACxB,SAAK,YAAY,QAAQ;AAAA,EAC3B;AACF;AAEO,IAAM,YAAN,cAAwB,gBAAgB;AAAA,EAC7C,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,S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