kagura-memory 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2234 @@
1
+ /**
2
+ * Wire-format models for the Kagura Memory SDK (port of models.py).
3
+ *
4
+ * These interfaces describe the JSON wire shapes exchanged with the Kagura
5
+ * Memory server, so field names stay snake_case exactly as pydantic
6
+ * serializes them. All `datetime` fields from the Python SDK arrive as
7
+ * ISO 8601 strings on the wire and are typed `string` here.
8
+ *
9
+ * Fields that carry a default in the Python models (including `None`
10
+ * defaults) are optional here — servers may omit them.
11
+ */
12
+ /** A message in a conversation session. */
13
+ interface Message {
14
+ role: "user" | "assistant" | "system";
15
+ content: string;
16
+ }
17
+ /** An artifact attached to a session (code, document, etc.). */
18
+ interface Artifact {
19
+ type: "code" | "document" | "error" | "config";
20
+ content: string;
21
+ source?: string | null;
22
+ language?: string | null;
23
+ }
24
+ /** A conversation session with messages and optional artifacts. */
25
+ interface Session {
26
+ messages: Message[];
27
+ artifacts?: Artifact[];
28
+ }
29
+ /** Information about a remembered memory. */
30
+ interface MemoryInfo {
31
+ memory_id: string;
32
+ summary: string;
33
+ }
34
+ /** A recalled memory with relevance score. */
35
+ interface Memory {
36
+ memory_id: string;
37
+ summary: string;
38
+ score: number;
39
+ }
40
+ /** LLM token usage statistics. */
41
+ interface LLMUsage {
42
+ prompt_tokens: number;
43
+ completion_tokens: number;
44
+ total_tokens: number;
45
+ model: string;
46
+ }
47
+ /** A memory to be stored, as determined by LLM analysis. */
48
+ interface MemoryToStore {
49
+ /** 1-250 characters. */
50
+ summary: string;
51
+ content: string;
52
+ /** @default "note" */
53
+ type?: "code" | "note" | "decision" | "bug-fix" | "feature" | "learning";
54
+ /** Range 0.0-1.0. @default 0.5 */
55
+ importance?: number;
56
+ tags?: string[];
57
+ }
58
+ /** A recall query, as determined by LLM analysis. */
59
+ interface RecallQuery {
60
+ query: string;
61
+ /** @default "" */
62
+ reason?: string;
63
+ filters?: Record<string, unknown> | null;
64
+ }
65
+ /** Internal model for LLM analysis results. */
66
+ interface AnalysisResult {
67
+ should_remember: boolean;
68
+ memories_to_store?: MemoryToStore[];
69
+ should_recall: boolean;
70
+ recall_queries?: RecallQuery[];
71
+ llm_usage?: LLMUsage | null;
72
+ }
73
+ /** Memory discovered through explore operation. */
74
+ interface ExploredMemory {
75
+ memory_id: string;
76
+ summary: string;
77
+ /** @default 0.0 */
78
+ activation?: number;
79
+ /** @default 0 */
80
+ hop?: number;
81
+ }
82
+ /** Result of processing a session. */
83
+ interface ProcessResult {
84
+ remembered?: MemoryInfo[];
85
+ recalled?: Memory[];
86
+ explored?: ExploredMemory[];
87
+ context_used: string;
88
+ actions?: string[];
89
+ llm_usage?: LLMUsage | null;
90
+ }
91
+ /** An embedding model available on the server. */
92
+ interface EmbeddingModel {
93
+ name: string;
94
+ dimensions: number;
95
+ provider: string;
96
+ available: boolean;
97
+ }
98
+ /** Response from the embedding models endpoint. */
99
+ interface EmbeddingModelsResponse {
100
+ models: EmbeddingModel[];
101
+ default_model: string;
102
+ }
103
+ /** Feature flags reported by the server. */
104
+ interface ServerFeatures {
105
+ /** @default false */
106
+ neural_memory?: boolean;
107
+ /** @default false */
108
+ research_tools?: boolean;
109
+ }
110
+ /** Server information from `/api/v1/system/info`. */
111
+ interface ServerInfo {
112
+ name: string;
113
+ version: string;
114
+ description?: string | null;
115
+ environment?: string | null;
116
+ features?: ServerFeatures;
117
+ }
118
+ /** Usage vs limit for a single resource category. */
119
+ interface UsageQuota {
120
+ used: number;
121
+ limit: number;
122
+ percentage?: number | null;
123
+ }
124
+ /** Quota with limit only (no usage counter). */
125
+ interface UsageQuotaLimitOnly {
126
+ limit: number;
127
+ }
128
+ /** Workspace usage and quota information. */
129
+ interface UsageInfo {
130
+ plan: string;
131
+ memories: UsageQuota;
132
+ contexts: UsageQuota;
133
+ members: UsageQuota;
134
+ mcp_calls_per_day: UsageQuotaLimitOnly;
135
+ }
136
+ /** Hybrid search configuration for a context. */
137
+ interface SearchConfig {
138
+ /** @default 0.6 */
139
+ semantic_weight?: number;
140
+ /** @default 0.4 */
141
+ bm25_weight?: number;
142
+ /** @default 3 */
143
+ fetch_factor?: number;
144
+ /** @default false */
145
+ use_rerank?: boolean;
146
+ reranker_provider?: string | null;
147
+ reranker_model?: string | null;
148
+ }
149
+ /** Context metadata returned by `get_context_info`. */
150
+ interface ContextDetail {
151
+ id: string;
152
+ name: string;
153
+ display_name?: string | null;
154
+ summary?: string | null;
155
+ usage_guide?: string | null;
156
+ /** @default true */
157
+ is_private?: boolean;
158
+ /** @default false */
159
+ is_locked?: boolean;
160
+ embedding_model?: string | null;
161
+ embedding_dimensions?: number | null;
162
+ search_config?: SearchConfig;
163
+ }
164
+ /** Workspace metadata in context info response. */
165
+ interface WorkspaceInfo {
166
+ id: string;
167
+ name: string;
168
+ description?: string | null;
169
+ }
170
+ /** Memory statistics for a context. */
171
+ interface ContextStats {
172
+ total_memories: number;
173
+ /** @default 0 */
174
+ working_memories?: number;
175
+ /** @default 0 */
176
+ persistent_memories?: number;
177
+ details?: Record<string, unknown> | null;
178
+ }
179
+ /** Full response from `get_context_info`. */
180
+ interface ContextInfo {
181
+ /** @default "success" */
182
+ status?: string;
183
+ context: ContextDetail;
184
+ workspace?: WorkspaceInfo | null;
185
+ stats?: ContextStats | null;
186
+ instructions?: string | null;
187
+ }
188
+ /** Info about a memory with failed embedding. */
189
+ interface FailedMemoryInfo {
190
+ id: string;
191
+ summary: string;
192
+ embedding_error?: string | null;
193
+ /** ISO 8601 datetime string. */
194
+ created_at: string;
195
+ /** ISO 8601 datetime string. */
196
+ updated_at?: string | null;
197
+ }
198
+ /** Embedding queue status for the workspace. */
199
+ interface EmbeddingStatus {
200
+ total: number;
201
+ by_status: Record<string, number>;
202
+ failed_memories: FailedMemoryInfo[];
203
+ }
204
+ /** Per-memory usage statistics. */
205
+ interface MemoryStatItem {
206
+ id: string;
207
+ summary: string;
208
+ type: string;
209
+ importance: number;
210
+ scope: string;
211
+ use_count: number;
212
+ access_count: number;
213
+ /** ISO 8601 datetime string. */
214
+ last_used_at?: string | null;
215
+ embedding_status: string;
216
+ /** ISO 8601 datetime string. */
217
+ created_at: string;
218
+ }
219
+ /** Response from memory-stats endpoint. */
220
+ interface MemoryStatsResponse {
221
+ memories: MemoryStatItem[];
222
+ total: number;
223
+ sort_by: string;
224
+ sort_order: string;
225
+ }
226
+ /**
227
+ * A single memory row in a paginated `list_memories` response.
228
+ *
229
+ * Mirrors the server's `MemoryListItem` wire shape. `created_at` /
230
+ * `updated_at` are ISO 8601 strings (`Z`-tagged) on the wire.
231
+ */
232
+ interface MemoryListItem {
233
+ id: string;
234
+ summary: string;
235
+ type: string;
236
+ scope: string;
237
+ importance: number;
238
+ /** ISO 8601 datetime string. */
239
+ created_at: string;
240
+ /** ISO 8601 datetime string. */
241
+ updated_at: string;
242
+ }
243
+ /** Paginated response from `list_memories` (`GET /api/v1/memory/list`). */
244
+ interface MemoryListResponse {
245
+ memories?: MemoryListItem[];
246
+ total: number;
247
+ has_more: boolean;
248
+ }
249
+ /** Memory info for duplicate pair display. */
250
+ interface DuplicateMemoryInfo {
251
+ id: string;
252
+ summary: string;
253
+ type: string;
254
+ /** ISO 8601 datetime string. */
255
+ created_at: string;
256
+ }
257
+ /** A pair of similar memories. */
258
+ interface DuplicatePair {
259
+ memory_a: DuplicateMemoryInfo;
260
+ memory_b: DuplicateMemoryInfo;
261
+ similarity: number;
262
+ }
263
+ /** Response from duplicate detection endpoint. */
264
+ interface DuplicatesResponse {
265
+ pairs: DuplicatePair[];
266
+ total_pairs: number;
267
+ threshold: number;
268
+ memories_scanned: number;
269
+ }
270
+ /** Request model for creating a resource token. */
271
+ interface ResourceTokenCreate {
272
+ /** 1-255 characters. */
273
+ resource_id: string;
274
+ description?: string | null;
275
+ /** Range 1-10000. @default 1000 */
276
+ quota_events_per_hour?: number;
277
+ }
278
+ /** Request model for updating a resource token. */
279
+ interface ResourceTokenUpdate {
280
+ description?: string | null;
281
+ /** Range 1-10000. */
282
+ quota_events_per_hour?: number | null;
283
+ }
284
+ /** Resource token metadata (no plaintext token). */
285
+ interface ResourceTokenResponse {
286
+ id: number;
287
+ resource_id: string;
288
+ description?: string | null;
289
+ quota_events_per_hour: number;
290
+ created_by?: string | null;
291
+ /** ISO 8601 datetime string. */
292
+ created_at: string;
293
+ /** ISO 8601 datetime string. */
294
+ last_used_at?: string | null;
295
+ is_active: boolean;
296
+ status: "active" | "revoked";
297
+ }
298
+ /** Resource token creation response (includes plaintext token, shown once). */
299
+ interface ResourceTokenCreateResponse extends ResourceTokenResponse {
300
+ token: string;
301
+ }
302
+ /** Paginated list of resource tokens. */
303
+ interface PaginatedResourceTokensResponse {
304
+ tokens: ResourceTokenResponse[];
305
+ total: number;
306
+ limit: number;
307
+ offset: number;
308
+ }
309
+ /**
310
+ * Atomic resource setup response (server v0.14+).
311
+ *
312
+ * Returned by `setup_resource`, which creates a Context, Resource entity,
313
+ * and ingestion token in a single transaction. The plaintext `token` is
314
+ * shown only once — save it immediately.
315
+ */
316
+ interface ResourceSetupResponse {
317
+ context_id: string;
318
+ context_name: string;
319
+ resource_id: string;
320
+ token: string;
321
+ token_id: number;
322
+ warning?: string | null;
323
+ }
324
+ /** Request model for resource event ingestion. */
325
+ interface ResourceEventRequest {
326
+ op: "upsert" | "delete";
327
+ /** 1-255 characters. */
328
+ doc_id: string;
329
+ /** Minimum 1. */
330
+ version?: number | null;
331
+ payload?: Record<string, unknown> | null;
332
+ /** 1-255 characters. */
333
+ idempotency_key?: string | null;
334
+ event_metadata?: Record<string, unknown>;
335
+ /** Range 0.0-1.0. */
336
+ importance?: number | null;
337
+ }
338
+ /** Response from single event ingestion. */
339
+ interface ResourceEventResponse {
340
+ /** @default "success" */
341
+ status?: string;
342
+ event_id: number;
343
+ /** @default true */
344
+ queued?: boolean;
345
+ estimated_indexing_time_seconds?: number | null;
346
+ }
347
+ /** Request model for batch event ingestion (1-100 events). */
348
+ interface ResourceEventBatchRequest {
349
+ events: ResourceEventRequest[];
350
+ }
351
+ /** Response from batch event ingestion. */
352
+ interface ResourceEventBatchResponse {
353
+ /** @default "success" */
354
+ status?: string;
355
+ created_count: number;
356
+ /** @default 0 */
357
+ failed_count?: number;
358
+ event_ids?: number[];
359
+ errors?: Record<string, unknown>[];
360
+ }
361
+ /**
362
+ * A single ingested event row returned by `list_resource_events`.
363
+ *
364
+ * Mirrors the server's `ResourceEventRecord` for
365
+ * `GET /api/v1/resources/{resource_id}/events`. This is the full read
366
+ * shape — distinct from `ResourceEventItem`, the 5-field minimal row
367
+ * embedded in `IndexerStatusResponse.recent_events`.
368
+ */
369
+ interface ResourceEventRecord {
370
+ id: number;
371
+ op: "upsert" | "delete";
372
+ doc_id: string;
373
+ version?: number | null;
374
+ idempotency_key?: string | null;
375
+ importance?: number | null;
376
+ /** ISO 8601 datetime string. */
377
+ created_at?: string | null;
378
+ payload?: Record<string, unknown> | null;
379
+ event_metadata?: Record<string, unknown>;
380
+ payload_bytes?: number | null;
381
+ /** True when the server truncated `payload` for size. @default false */
382
+ payload_truncated?: boolean;
383
+ }
384
+ /**
385
+ * Paginated resource events response.
386
+ *
387
+ * Mirrors the server's `ResourceEventsResponse`: a page of events plus an
388
+ * opaque `next_cursor` (`null` on the last page). Pass the cursor back to
389
+ * `list_resource_events` to page forward. Unlike the `limit`/`offset`
390
+ * token list, events use `limit`/`cursor` pagination.
391
+ */
392
+ interface ResourceEventsListResponse {
393
+ events?: ResourceEventRecord[];
394
+ next_cursor?: string | null;
395
+ }
396
+ /** Resource impact statistics per resource_id. */
397
+ interface ResourceImpactResponse {
398
+ resource_id: string;
399
+ token_count: number;
400
+ memory_count: number;
401
+ current_schema_version?: number | null;
402
+ }
403
+ /** Field metadata definition within a resource schema. */
404
+ interface FieldDefinition {
405
+ name: string;
406
+ type: "text" | "number" | "boolean" | "date" | "array" | "object";
407
+ description: string;
408
+ /** @default "public" */
409
+ classification?: "public" | "internal" | "pii" | "confidential";
410
+ /** @default "" */
411
+ index_hint?: string;
412
+ unit?: string | null;
413
+ enum_values?: string[] | null;
414
+ example?: string | null;
415
+ /** @default false */
416
+ required?: boolean;
417
+ }
418
+ /** Resource schema with field definitions (schema registry). */
419
+ interface ResourceSchemaResponse {
420
+ resource_id: string;
421
+ schema_version: number;
422
+ field_definitions: FieldDefinition[];
423
+ /** ISO 8601 datetime string. */
424
+ created_at: string;
425
+ }
426
+ /** Single resource entry in the workspace resource list. */
427
+ interface ResourceListItem {
428
+ resource_id: string;
429
+ context_id: string;
430
+ context_name: string;
431
+ context_display_name?: string | null;
432
+ token_count: number;
433
+ memory_count: number;
434
+ current_schema_version?: number | null;
435
+ /** ISO 8601 datetime string. */
436
+ created_at: string;
437
+ /** ISO 8601 datetime string. */
438
+ updated_at: string;
439
+ }
440
+ /** Workspace resource list response (non-paginated; server caps at < 50). */
441
+ interface ResourceListResponse {
442
+ resources: ResourceListItem[];
443
+ total: number;
444
+ }
445
+ /**
446
+ * Indexer job status. Mirrors the server-side CHECK constraint on
447
+ * `indexer_state.job_status`.
448
+ */
449
+ type IndexerJobStatus = "idle" | "queued" | "running" | "failed";
450
+ /**
451
+ * Reasons the indexer may record under `metrics.skipped_reason` when a run
452
+ * was skipped. Server degrades unknown values to `null` on the wire.
453
+ */
454
+ type IndexerSkippedReason = "no_pending_events" | "schema_not_found" | "context_not_found" | "empty_valid_points" | "resource_entity_missing";
455
+ /** Per-run indexer metrics, flattened from the server JSONB column. */
456
+ interface IndexerStateMetrics {
457
+ /** @default 0 */
458
+ applied_upserts?: number;
459
+ /** @default 0 */
460
+ applied_deletes?: number;
461
+ /** @default 0 */
462
+ errors?: number;
463
+ skipped_reason?: IndexerSkippedReason | null;
464
+ }
465
+ /** Indexer state snapshot for one resource. */
466
+ interface IndexerState {
467
+ job_status: IndexerJobStatus;
468
+ /** ISO 8601 datetime string. */
469
+ last_run_at?: string | null;
470
+ /** ISO 8601 datetime string. */
471
+ next_run_at?: string | null;
472
+ active_version: number;
473
+ last_offset: number;
474
+ lag_seconds?: number | null;
475
+ metrics: IndexerStateMetrics;
476
+ }
477
+ /** Single row in the indexer's recent ingest events list. */
478
+ interface ResourceEventItem {
479
+ id: number;
480
+ op: "upsert" | "delete";
481
+ doc_id: string;
482
+ version?: number | null;
483
+ /** ISO 8601 datetime string. */
484
+ created_at?: string | null;
485
+ }
486
+ /**
487
+ * Response body for `GET /api/v1/resources/{resource_id}/indexer-status`.
488
+ *
489
+ * `state` is `null` when the indexer has never run for this resource (the
490
+ * endpoint still returns 200 in that case). A 404 means the resource slug
491
+ * does not exist in the caller's workspace.
492
+ */
493
+ interface IndexerStatusResponse {
494
+ resource_id: string;
495
+ state?: IndexerState | null;
496
+ recent_events?: ResourceEventItem[];
497
+ }
498
+ type SleepRunStatus = "running" | "completed" | "failed" | "cancelled" | "rolled_back";
499
+ /** Summary of a Sleep Maintenance run, returned by `get_sleep_history`. */
500
+ interface SleepReport {
501
+ report_id: string;
502
+ context_id?: string | null;
503
+ status: SleepRunStatus;
504
+ /** ISO 8601 datetime string. */
505
+ started_at?: string | null;
506
+ /** ISO 8601 datetime string. */
507
+ completed_at?: string | null;
508
+ memories_processed: number;
509
+ edges_created: number;
510
+ memories_merged: number;
511
+ memories_promoted: number;
512
+ llm_calls_made: number;
513
+ llm_tokens_used: number;
514
+ }
515
+ /**
516
+ * One audit log entry from a Sleep Maintenance run.
517
+ *
518
+ * `action_type` and `phase` are free-form strings — the server may add new
519
+ * types over time. Known `action_type` values include `create_edge`,
520
+ * `merge`, `update_importance`, `promote`, `archive`, and `flag`.
521
+ * `details` is a generic object whose shape depends on `action_type`.
522
+ */
523
+ interface SleepAction {
524
+ id: string;
525
+ phase: string;
526
+ action_type: string;
527
+ memory_id?: string | null;
528
+ target_id?: string | null;
529
+ details?: Record<string, unknown> | null;
530
+ /** ISO 8601 datetime string. */
531
+ created_at?: string | null;
532
+ }
533
+ /**
534
+ * Full Sleep Maintenance report with audit log, returned by `get_sleep_report`.
535
+ *
536
+ * Extends `SleepReport` with per-phase result blobs and the per-action
537
+ * audit log. Fields ending in `_result` are server-side phase outputs kept
538
+ * as raw objects because their shape evolves with the maintenance pipeline.
539
+ */
540
+ interface SleepReportDetail extends SleepReport {
541
+ memories_flagged: number;
542
+ embedding_calls_made: number;
543
+ error_message?: string | null;
544
+ edge_discovery_result?: Record<string, unknown> | null;
545
+ dedup_result?: Record<string, unknown> | null;
546
+ importance_result?: Record<string, unknown> | null;
547
+ consolidation_result?: Record<string, unknown> | null;
548
+ reindex_result?: Record<string, unknown> | null;
549
+ actions?: SleepAction[];
550
+ action_count: number;
551
+ }
552
+ /** Per-category counts of actions reversed by `rollback_sleep_run`. */
553
+ interface RollbackSummary {
554
+ /** @default 0 */
555
+ edges_deleted?: number;
556
+ /** @default 0 */
557
+ merges_reversed?: number;
558
+ /** @default 0 */
559
+ importance_restored?: number;
560
+ /** @default 0 */
561
+ promotions_reversed?: number;
562
+ /** @default 0 */
563
+ archives_restored?: number;
564
+ errors?: string[];
565
+ }
566
+ /** Result of `rollback_sleep_run` on a successful (no-error) run. */
567
+ interface RollbackResult {
568
+ report_id: string;
569
+ status: SleepRunStatus;
570
+ rollback_summary: RollbackSummary;
571
+ }
572
+ /**
573
+ * A neural memory edge between two memories.
574
+ *
575
+ * Represents a directed link from `source_id` to `target_id` with a
576
+ * semantic `edge_type` and a `weight`/`confidence` pair. Edges are created
577
+ * either by users (manual curation) or by server-side processes (Sleep
578
+ * Maintenance, k-NN seeding, declared links, tag co-occurrence).
579
+ *
580
+ * Note: `edge_type` is intentionally typed as `string` (not a literal
581
+ * union) because the server's `VALID_EDGE_TYPES` set is open-ended and
582
+ * grows with new auto-discovery processes (currently 7 values:
583
+ * `neural_association`, `related_to`, `depends_on`, `learned_from`,
584
+ * `semantic_similarity`, `declared_link`, `tag_cooccurrence`). The server
585
+ * is the authority on validation.
586
+ */
587
+ interface Edge {
588
+ source_id: string;
589
+ target_id: string;
590
+ edge_type: string;
591
+ /** Range 0.0-3.0. */
592
+ weight: number;
593
+ /** Range 0.0-1.0. */
594
+ confidence: number;
595
+ /** ISO 8601 datetime string. */
596
+ created_at?: string | null;
597
+ /** ISO 8601 datetime string. */
598
+ last_updated?: string | null;
599
+ }
600
+ /**
601
+ * A tag with its usage count and last-used timestamp.
602
+ *
603
+ * Mirrors the wire shape of the server's `RelatedTagItem` as emitted by
604
+ * the `list_tags` MCP tool. `sample_summary` from the server-side model is
605
+ * intentionally omitted because `list_tags` does not populate it (only
606
+ * `recall.related_tags` does). The schema is otherwise aligned so callers
607
+ * can unify their tag-info type between the two surfaces.
608
+ */
609
+ interface TagInfo {
610
+ tag: string;
611
+ count: number;
612
+ /** ISO 8601 datetime string. */
613
+ last_used_at?: string | null;
614
+ }
615
+ /** Response from `list_tags`: tag vocabulary for a context. */
616
+ interface ListTagsResponse {
617
+ context_id: string;
618
+ context_name: string;
619
+ tags?: TagInfo[];
620
+ total: number;
621
+ }
622
+ /**
623
+ * File metadata returned by upload / list / dedup operations.
624
+ *
625
+ * Mirrors the server's `FileObjectOut`. The `workspace_id` field name is
626
+ * preserved on the wire; SDK public methods accept the same value as
627
+ * `context_id` for vocabulary consistency with the rest of the SDK.
628
+ *
629
+ * `status` is typed as `string` (not a literal union) because the server
630
+ * may add new lifecycle states over time. Known values today: `reserved`,
631
+ * `uploaded`, `confirmed`.
632
+ *
633
+ * `context_id` is the owning context a file is bound to for access
634
+ * control (server v0.41.0+). It is `null` for legacy/workspace-scoped
635
+ * files that were uploaded with no binding context — those stay fully
636
+ * listable and accessible to the workspace.
637
+ */
638
+ interface FileObject {
639
+ id: string;
640
+ workspace_id: string;
641
+ filename: string;
642
+ content_type: string;
643
+ size_bytes: number;
644
+ sha256: string;
645
+ status: string;
646
+ /** ISO 8601 datetime string. */
647
+ created_at: string;
648
+ /** ISO 8601 datetime string. */
649
+ uploaded_at?: string | null;
650
+ context_id?: string | null;
651
+ }
652
+ /** Internal response from `POST /api/v1/files/reserve`. */
653
+ interface FileReserveResponse {
654
+ file_id: string;
655
+ upload_url: string;
656
+ /** ISO 8601 datetime string. */
657
+ expires_at: string;
658
+ }
659
+ /** Internal response from `GET /api/v1/files/{file_id}/download-url`. */
660
+ interface FileDownloadUrlResponse {
661
+ download_url: string;
662
+ }
663
+ /**
664
+ * Paginated list of files.
665
+ *
666
+ * `next_cursor` is forward-compatible — the current server (memory-cloud
667
+ * v0.15.x) returns at most `limit` items with no cursor field; the SDK
668
+ * preserves the field as `null` so a future server bump can populate it
669
+ * without breaking callers.
670
+ */
671
+ interface FileListResponse {
672
+ files: FileObject[];
673
+ next_cursor?: string | null;
674
+ }
675
+ /**
676
+ * Cost and token usage for one ingest operation.
677
+ *
678
+ * Used both for dry-run cost estimation (`is_estimate: true`, no network
679
+ * egress to LLM providers) and for the final cost reported by an actual
680
+ * ingestion. `null` token counts indicate the counter could not estimate
681
+ * that field.
682
+ */
683
+ interface CostBreakdown {
684
+ /** @default false */
685
+ is_estimate?: boolean;
686
+ prompt_tokens?: number | null;
687
+ completion_tokens?: number | null;
688
+ vision_tokens?: number | null;
689
+ est_usd?: number | null;
690
+ text_provider?: string | null;
691
+ vision_provider?: string | null;
692
+ }
693
+ /**
694
+ * A single per-step failure during ingestion.
695
+ *
696
+ * Best-effort ingestion collects these in `IngestResult.errors` instead of
697
+ * aborting — these records represent recoverable per-section issues.
698
+ */
699
+ interface IngestErrorRecord {
700
+ step: "fetch" | "extract" | "chunk" | "summarize" | "vision" | "remember" | "archive";
701
+ section_index?: number | null;
702
+ message: string;
703
+ exception_type?: string | null;
704
+ }
705
+ /**
706
+ * Result of a single `kagura ingest` invocation.
707
+ *
708
+ * Best-effort semantics: a non-empty `errors` list does NOT mean the
709
+ * overall ingestion failed — partial successes (e.g. 4 of 5 sections
710
+ * written) still return a populated result with the error recorded.
711
+ * Success means the overview memory was created, i.e.
712
+ * `overview_id != null` (the Python SDK exposes this as a computed
713
+ * `success` property, which has no wire field and is therefore not
714
+ * present here). Downstream sections are guaranteed to reference an
715
+ * existing overview when present.
716
+ */
717
+ interface IngestResult {
718
+ /** @default false */
719
+ is_dry_run?: boolean;
720
+ source_uri: string;
721
+ source_type: "file" | "url";
722
+ overview_id?: string | null;
723
+ section_ids?: string[];
724
+ /**
725
+ * Number of sections detected during dry-run extraction. Populated only
726
+ * on the dry-run path where no memories are written and `section_ids`
727
+ * is empty. `null` on actual ingest runs — use `section_ids.length` then.
728
+ */
729
+ estimated_section_count?: number | null;
730
+ /** @default 0 */
731
+ skipped_images?: number;
732
+ /**
733
+ * `FileObject.id` when the source was archived to R2, else `null`.
734
+ * `null` covers three cases: archival was opt-out, no files client was
735
+ * supplied, or the upload failed (also visible as an
736
+ * `errors[*].step === "archive"` record).
737
+ */
738
+ archived_file_id?: string | null;
739
+ cost: CostBreakdown;
740
+ warnings?: string[];
741
+ errors?: IngestErrorRecord[];
742
+ }
743
+ /**
744
+ * A workspace member row (#225).
745
+ *
746
+ * The list endpoint populates the display/audit fields (`user_name`,
747
+ * `user_email`, `last_login_at`, `allowed_context_ids`,
748
+ * `credentials_status`); add/set-role responses carry the minimal
749
+ * `user_id`/`role`/`joined_at` shape and leave the rest `null`.
750
+ * `credentials_status` stays an untyped mapping — its inner shape is
751
+ * server-owned display metadata (key counts / visibility booleans) that
752
+ * the SDK forwards without interpreting.
753
+ */
754
+ interface WorkspaceMember {
755
+ user_id: string;
756
+ role: string;
757
+ user_name?: string | null;
758
+ user_email?: string | null;
759
+ /** ISO 8601 datetime string. */
760
+ joined_at?: string | null;
761
+ /** ISO 8601 datetime string. */
762
+ last_login_at?: string | null;
763
+ allowed_context_ids?: string[] | null;
764
+ credentials_status?: Record<string, unknown> | null;
765
+ }
766
+ /**
767
+ * A workspace invitation (#225).
768
+ *
769
+ * Server shape (`WorkspaceInvitationResponse`): `id` is an INTEGER PK and
770
+ * there is no `status` field — pending is derived from
771
+ * `is_accepted`/`is_expired`. `token`/`invitation_url` are bearer
772
+ * join-credentials: the server nulls them on programmatic LIST responses,
773
+ * so they are optional here and only populated on create.
774
+ */
775
+ interface WorkspaceInvitation {
776
+ id: number;
777
+ email?: string | null;
778
+ role: string;
779
+ token?: string | null;
780
+ invitation_url?: string | null;
781
+ /** @default false */
782
+ is_accepted?: boolean;
783
+ /** @default false */
784
+ is_expired?: boolean;
785
+ /** ISO 8601 datetime string. */
786
+ created_at?: string | null;
787
+ /** ISO 8601 datetime string. */
788
+ expires_at?: string | null;
789
+ allowed_context_ids?: string[] | null;
790
+ }
791
+ /**
792
+ * A member API key row (#201, server v0.42.0+).
793
+ *
794
+ * Server shape (`MemberAPIKeyResponse`): `id` is an INTEGER PK and the
795
+ * plaintext field is named `plaintext_key` — non-null ONLY in the mint 201
796
+ * response. Owner-provisioned keys are force-hidden at creation, so no
797
+ * later call ever returns the plaintext.
798
+ */
799
+ interface MemberAPIKey {
800
+ id: number;
801
+ name: string;
802
+ key_prefix: string;
803
+ plaintext_key?: string | null;
804
+ /** @default false */
805
+ is_visible?: boolean;
806
+ /** ISO 8601 datetime string. */
807
+ visibility_expires_at?: string | null;
808
+ /** ISO 8601 datetime string. */
809
+ created_at?: string | null;
810
+ /** ISO 8601 datetime string. */
811
+ last_used_at?: string | null;
812
+ /** ISO 8601 datetime string. */
813
+ revoked_at?: string | null;
814
+ /** ISO 8601 datetime string. */
815
+ expires_at?: string | null;
816
+ bound_context_id?: string | null;
817
+ }
818
+
819
+ /** Low-level client for Kagura Memory Cloud MCP tools (port of client.py). */
820
+
821
+ /**
822
+ * Minimum memory-cloud server version this SDK was tested against.
823
+ *
824
+ * The check is opt-in: callers must explicitly invoke
825
+ * {@link KaguraClient.checkServerVersion} to log an advisory warning when
826
+ * the connected server is older. Plain construction and tool calls never
827
+ * throw on version mismatch; older servers may silently ignore unknown
828
+ * parameters.
829
+ */
830
+ declare const MIN_SERVER_VERSION = "0.17.1";
831
+ /** Generic parsed-JSON result of an MCP tool call. */
832
+ type ToolResult = Record<string, unknown>;
833
+ type DeliveryMode = "always" | "on_recall" | "on_trigger";
834
+ type SearchMode = "hybrid" | "semantic" | "keyword";
835
+ type SourceType = "file" | "url" | "vault" | "api" | "manual";
836
+ interface KaguraClientOptions {
837
+ /** Explicit Kagura API key. When omitted, the resolution chain runs. */
838
+ apiKey?: string;
839
+ /** Explicit MCP URL. When omitted, derived from the credential source. */
840
+ mcpUrl?: string;
841
+ /** Request timeout in milliseconds (default: 30000). */
842
+ timeoutMs?: number;
843
+ /** Named OAuth profile to load (overrides KAGURA_PROFILE and the file default). */
844
+ profile?: string;
845
+ /** Fetch implementation override (for tests; default: globalThis.fetch). */
846
+ fetch?: typeof globalThis.fetch;
847
+ /** Environment source override (for tests; default: process.env). */
848
+ env?: Record<string, string | undefined>;
849
+ /** Home directory override (for tests). */
850
+ home?: string;
851
+ }
852
+ interface RememberOptions {
853
+ contextId: string;
854
+ /** Memory summary (10-500 chars). */
855
+ summary: string;
856
+ content: string;
857
+ /** Memory type; the server validates against its own vocabulary. */
858
+ type?: string;
859
+ /** Importance score (0.0-1.0). */
860
+ importance?: number;
861
+ tags?: string[];
862
+ /** Origin URI (e.g. `file:///`, `https://`, `vault://`). */
863
+ sourceUri?: string;
864
+ /** Existing memory UUIDs to declare as `declared_link` edges from this memory. */
865
+ linkedMemoryIds?: string[];
866
+ /** Source URIs to resolve into linked memories (unresolved URIs are skipped server-side). */
867
+ linkedSourceUris?: string[];
868
+ /** Origin classification; pairs with sourceUri for downstream filters. */
869
+ sourceType?: SourceType;
870
+ /** Why the memory exists and how to use it (max 2000 chars). */
871
+ contextSummary?: string;
872
+ /** Structured details JSON, stored as-is. */
873
+ details?: Record<string, unknown>;
874
+ /** Open-ended context metadata JSON. */
875
+ context?: Record<string, unknown>;
876
+ /**
877
+ * When the memory is surfaced. `"on_recall"` (default) leaves it to
878
+ * probabilistic recall; `"always"` pins it so every loadPinned call
879
+ * returns it. Only sent when it differs from the server default.
880
+ */
881
+ deliveryMode?: DeliveryMode;
882
+ }
883
+ interface RecallOptions {
884
+ /** Context ID for single-context search. */
885
+ contextId?: string;
886
+ query: string;
887
+ /** Number of results (default 5). */
888
+ k?: number;
889
+ /** Enable AI reranking for higher quality results. */
890
+ useRerank?: boolean;
891
+ /**
892
+ * Optional filters: `type`, `tags`, `tags_match` ("any"/"all"),
893
+ * `created_after`/`created_before`, `updated_after`/`updated_before`,
894
+ * `trust_tier` ("trusted" excludes external/connector-ingested memories).
895
+ */
896
+ filters?: Record<string, unknown>;
897
+ searchMode?: SearchMode;
898
+ /** Search across multiple contexts (2-20 IDs); contextId not required then. */
899
+ contextIds?: string[];
900
+ /** Include up to 3 graph discovery hints under `explore_hints`. */
901
+ includeExploreHints?: boolean;
902
+ }
903
+ interface UpdateMemoryOptions {
904
+ contextId: string;
905
+ /** UUID of memory to update in-place (provide exactly one of memoryId/externalId). */
906
+ memoryId?: string;
907
+ /** External resource ID for upsert lookup. */
908
+ externalId?: string;
909
+ summary?: string;
910
+ content?: string;
911
+ type?: string;
912
+ importance?: number;
913
+ tags?: string[];
914
+ contextSummary?: string;
915
+ /** `"always"` pins, `"on_recall"` unpins; omit to leave unchanged. */
916
+ deliveryMode?: DeliveryMode;
917
+ }
918
+ interface CreateContextOptions {
919
+ /** Context name (lowercase alphanumeric + hyphen/underscore). */
920
+ name: string;
921
+ displayName?: string;
922
+ description?: string;
923
+ /** LLM-oriented summary (200-500 chars). */
924
+ summary?: string;
925
+ /** LLM-oriented memory usage guidelines. */
926
+ usageGuide?: string;
927
+ /** Resource identifier for external data ingestion. */
928
+ resourceId?: string;
929
+ /** Privacy flag (default: true). */
930
+ isPrivate?: boolean;
931
+ /** Embedding model (immutable after creation); see listEmbeddingModels(). */
932
+ embeddingModel?: string;
933
+ }
934
+ interface UpdateContextOptions {
935
+ contextId: string;
936
+ displayName?: string;
937
+ description?: string;
938
+ summary?: string;
939
+ usageGuide?: string;
940
+ resourceId?: string;
941
+ /** Public visibility (required for resource tokens). */
942
+ isPublic?: boolean;
943
+ /** Locked contexts cannot be deleted. */
944
+ isLocked?: boolean;
945
+ }
946
+ interface SetupResourceOptions {
947
+ resourceId: string;
948
+ /** Context name (defaults to resourceId server-side). */
949
+ name?: string;
950
+ summary?: string;
951
+ /** Token description. */
952
+ description?: string;
953
+ /** Token quota (1-10000, default 1000). */
954
+ quotaEventsPerHour?: number;
955
+ }
956
+ interface ListTagsOptions {
957
+ contextId: string;
958
+ /** Maximum tags to return (1-500, default 50). */
959
+ limit?: number;
960
+ /** Minimum memory count per tag (1-10000, default 1). */
961
+ minCount?: number;
962
+ /** Sort order (default "count"). */
963
+ sort?: "count" | "recent" | "alpha";
964
+ /** Case-insensitive prefix filter (max 200 chars). */
965
+ prefix?: string;
966
+ }
967
+ interface ListMemoriesOptions {
968
+ /** Context UUID; omit for the caller's cross-context view. */
969
+ contextId?: string;
970
+ /** Case-insensitive substring filter on summaries (whitespace-only → no filter). */
971
+ q?: string;
972
+ scope?: "working" | "persistent";
973
+ type?: string;
974
+ /** Maximum results (1-500, default 50). */
975
+ limit?: number;
976
+ offset?: number;
977
+ /** Time-window overlap lower bound (naive ISO) for type="time" memories. */
978
+ triggerFrom?: string;
979
+ /** Time-window overlap upper bound (naive ISO). */
980
+ triggerUntil?: string;
981
+ /** "created_at" (default, newest-first) or "trigger_from" (soonest first). */
982
+ orderBy?: "created_at" | "trigger_from";
983
+ }
984
+ interface UpdateSearchConfigOptions {
985
+ contextId: string;
986
+ /** Semantic search weight (0.0-1.0); weights must sum to 1.0 (±0.01). */
987
+ semanticWeight?: number;
988
+ /** BM25 keyword search weight (0.0-1.0). */
989
+ bm25Weight?: number;
990
+ /** Candidate fetch multiplier (1-10). */
991
+ fetchFactor?: number;
992
+ useRerank?: boolean;
993
+ /** "voyage", "cohere", or "ollama". */
994
+ rerankerProvider?: string;
995
+ rerankerModel?: string;
996
+ }
997
+ /**
998
+ * Low-level client for Kagura Memory Cloud MCP tools.
999
+ *
1000
+ * All methods may throw KaguraAuthError (authentication failed),
1001
+ * KaguraConnectionError (connection failed), or KaguraRateLimitError.
1002
+ *
1003
+ * MCP tool methods additionally translate the server's structured domain
1004
+ * errors (`{"status": "error", ...}`) into exceptions rather than
1005
+ * returning them as data: a missing context/memory/report throws
1006
+ * {@link KaguraNotFoundError}, any other domain error throws
1007
+ * {@link KaguraError}. Use try/catch rather than inspecting
1008
+ * `result.status`.
1009
+ *
1010
+ * Authentication resolution order when `apiKey` is omitted:
1011
+ * 1. `KAGURA_API_KEY` env var (CI / service accounts always win).
1012
+ * 2. The OAuth profile from `~/.kagura/credentials.json`, selected by
1013
+ * `options.profile` or `KAGURA_PROFILE`, falling back to the file's
1014
+ * `default_profile`.
1015
+ * 3. `.kagura.json` (cwd or `~/`) plus its own env fallback.
1016
+ */
1017
+ declare class KaguraClient {
1018
+ readonly mcpUrl: string;
1019
+ readonly timeoutMs: number;
1020
+ private readonly baseUrl;
1021
+ private readonly auth;
1022
+ private readonly fetchImpl;
1023
+ private sessionId;
1024
+ private requestIdCounter;
1025
+ constructor(options?: KaguraClientOptions);
1026
+ /** Get next JSON-RPC request ID. */
1027
+ private nextRequestId;
1028
+ private post;
1029
+ /** Initialize the MCP session if not already initialized. */
1030
+ private initializeSession;
1031
+ private safeText;
1032
+ /** Make a JSON-RPC 2.0 request to the MCP server. */
1033
+ private makeJsonRpcRequest;
1034
+ /** GET a REST endpoint and parse the JSON body. */
1035
+ private restGet;
1036
+ /**
1037
+ * Call an MCP tool via JSON-RPC and parse `content[0].text` as JSON.
1038
+ */
1039
+ private callTool;
1040
+ /**
1041
+ * Call an MCP tool and translate domain errors into exceptions.
1042
+ *
1043
+ * A server `{"status": "error", ...}` response throws
1044
+ * KaguraNotFoundError / KaguraError instead of being returned as data.
1045
+ */
1046
+ private callToolChecked;
1047
+ /**
1048
+ * Translate an MCP tool's structured error response to an SDK error.
1049
+ *
1050
+ * The server's MCP tools return `{"status": "error", "error": <code>,
1051
+ * "message": <str>, ...}` for domain errors the JSON-RPC transport
1052
+ * cannot represent. HTTP-level errors are handled by the request layer.
1053
+ */
1054
+ private static raiseForMcpError;
1055
+ /** Store a memory. Returns the API response with `memory_id`. */
1056
+ remember(options: RememberOptions): Promise<ToolResult>;
1057
+ /**
1058
+ * Search memories. Returns the API response with a `results` list.
1059
+ *
1060
+ * @throws Error if `query` is empty/whitespace; if neither `contextId`
1061
+ * nor `contextIds` is provided; if `contextIds` has fewer than 2 or
1062
+ * more than 20 IDs; or if `searchMode` is invalid.
1063
+ */
1064
+ recall(options: RecallOptions): Promise<ToolResult>;
1065
+ /**
1066
+ * List Time Memories whose scheduled window overlaps a range, soonest
1067
+ * first. A deterministic time query over `type="time"` memories — not
1068
+ * semantic search, no Hebbian side-effects.
1069
+ */
1070
+ recallUpcoming(options: {
1071
+ contextId: string;
1072
+ /** Lower bound as naive ISO, or the literal "now". Omit for no lower bound. */
1073
+ from?: string;
1074
+ /** Upper bound as naive ISO. Omit for an open-ended future window. */
1075
+ until?: string;
1076
+ /** Maximum results (default 20, server max 100). */
1077
+ k?: number;
1078
+ }): Promise<ToolResult>;
1079
+ /**
1080
+ * Deterministically load a context's pinned (`delivery_mode="always"`)
1081
+ * memories — the complete, unranked pinned set on every call.
1082
+ *
1083
+ * The set is bounded, never silently dropped: when more pinned memories
1084
+ * exist than `cap`, the response `truncated` flag is true and
1085
+ * `total_available` reports the real count.
1086
+ */
1087
+ loadPinned(options: {
1088
+ contextId: string;
1089
+ /** Override the maximum number returned (1-1000); omit for server default. */
1090
+ cap?: number;
1091
+ }): Promise<ToolResult>;
1092
+ /**
1093
+ * Record whether a recalled memory was useful for a query — an
1094
+ * append-only usefulness signal, kept in a separate lane from knowledge
1095
+ * (never pollutes recall).
1096
+ */
1097
+ feedback(options: {
1098
+ contextId: string;
1099
+ memoryId: string;
1100
+ helpful: boolean;
1101
+ /** Recall query this feedback is about (max 1024 chars). */
1102
+ query?: string;
1103
+ /** Free-text note, e.g. why the result was wrong (max 2000 chars). */
1104
+ note?: string;
1105
+ }): Promise<ToolResult>;
1106
+ /**
1107
+ * Set ephemeral agent run-state at `(contextId, key)` — a TTL-bounded
1108
+ * key/value lane kept separate from memories and excluded from recall.
1109
+ * Use remember() for durable knowledge.
1110
+ */
1111
+ setState(options: {
1112
+ contextId: string;
1113
+ /** State key (max 255 chars); re-use overwrites. */
1114
+ key: string;
1115
+ /** Arbitrary JSON value. */
1116
+ value: unknown;
1117
+ /** TTL in seconds (server clamps to 30 days); omit for no expiry. */
1118
+ ttlSeconds?: number;
1119
+ }): Promise<ToolResult>;
1120
+ /**
1121
+ * Read ephemeral agent run-state. Supply `key` to read one value, omit
1122
+ * it to list all live keys for the context.
1123
+ */
1124
+ getState(options: {
1125
+ contextId: string;
1126
+ key?: string;
1127
+ }): Promise<ToolResult>;
1128
+ /** List available contexts. */
1129
+ listContexts(): Promise<ToolResult>;
1130
+ /**
1131
+ * List the tag vocabulary in a context with usage counts and recency.
1132
+ *
1133
+ * Call before remember() to reuse existing tag spellings, or before
1134
+ * recall() with tag filters. Requires memory-cloud server v0.15.4+.
1135
+ */
1136
+ listTags(options: ListTagsOptions): Promise<ListTagsResponse>;
1137
+ /**
1138
+ * Call tools/list to get available MCP tool definitions (names,
1139
+ * descriptions, parameter schemas).
1140
+ */
1141
+ getToolDefinitions(): Promise<Record<string, unknown>[]>;
1142
+ /** Neural graph traversal from a seed memory. */
1143
+ explore(options: {
1144
+ contextId: string;
1145
+ memoryId: string;
1146
+ /** Maximum traversal depth (1-5, default 2). */
1147
+ depth?: number;
1148
+ /** Minimum edge weight threshold (default 0.05). */
1149
+ minWeight?: number;
1150
+ }): Promise<ToolResult>;
1151
+ /**
1152
+ * Get full memory details. Memory data is in `result.memory`.
1153
+ */
1154
+ reference(options: {
1155
+ contextId: string;
1156
+ memoryId: string;
1157
+ }): Promise<ToolResult>;
1158
+ /**
1159
+ * Update an existing memory in-place (memoryId) or upsert by external
1160
+ * ID (externalId — requires summary, content, and type).
1161
+ *
1162
+ * @throws Error unless exactly one of memoryId/externalId is provided.
1163
+ */
1164
+ updateMemory(options: UpdateMemoryOptions): Promise<ToolResult>;
1165
+ /**
1166
+ * Soft-delete memories (30-day retention) by specific memoryId or by
1167
+ * search query.
1168
+ *
1169
+ * @throws Error if neither memoryId nor query is provided.
1170
+ */
1171
+ forget(options: {
1172
+ contextId: string;
1173
+ memoryId?: string;
1174
+ query?: string;
1175
+ /** Number of memories to delete in query mode (default 10). */
1176
+ k?: number;
1177
+ }): Promise<ToolResult>;
1178
+ /**
1179
+ * Create a new context in the current workspace.
1180
+ *
1181
+ * @throws KaguraQuotaError when the workspace context limit is reached.
1182
+ */
1183
+ createContext(options: CreateContextOptions): Promise<ToolResult>;
1184
+ /** Soft-delete a context and all its memories. */
1185
+ deleteContext(contextId: string): Promise<ToolResult>;
1186
+ /** Update an existing context's settings. */
1187
+ updateContext(options: UpdateContextOptions): Promise<ToolResult>;
1188
+ /**
1189
+ * Atomically create Context + Resource entity + ingestion token in a
1190
+ * single server-side transaction. The returned `token` is plaintext and
1191
+ * shown once.
1192
+ */
1193
+ setupResource(options: SetupResourceOptions): Promise<ToolResult>;
1194
+ /**
1195
+ * Merge memories from one context into another. Both contexts must use
1196
+ * the same embedding model and belong to the same workspace.
1197
+ *
1198
+ * @throws Error if sourceId and targetId are the same.
1199
+ */
1200
+ mergeContexts(options: {
1201
+ sourceId: string;
1202
+ targetId: string;
1203
+ /** Soft-delete the source context after merge. */
1204
+ deleteSource?: boolean;
1205
+ }): Promise<ToolResult>;
1206
+ /**
1207
+ * List neural memory edges connected to a memory (outgoing and
1208
+ * incoming, deduplicated).
1209
+ *
1210
+ * Note: the server applies `limit` to outgoing AND incoming queries
1211
+ * independently, so the practical maximum returned is `2 * limit`
1212
+ * minus dedup overlap.
1213
+ */
1214
+ listEdges(options: {
1215
+ contextId: string;
1216
+ memoryId: string;
1217
+ /** Minimum edge weight (0.0-3.0, default 0.0). */
1218
+ minWeight?: number;
1219
+ /** Restrict to these edge types; omit for all. */
1220
+ edgeTypes?: string[];
1221
+ /** Maximum edges per direction; omit for no limit. */
1222
+ limit?: number;
1223
+ }): Promise<Edge[]>;
1224
+ /**
1225
+ * Create or upsert a neural memory edge from source to target.
1226
+ *
1227
+ * The server uses `(user_id, source_id, target_id)` as a unique key
1228
+ * with max-weight UPSERT semantics — not a pure INSERT.
1229
+ *
1230
+ * @throws Error if sourceId === targetId (self-loops are rejected).
1231
+ */
1232
+ createEdge(options: {
1233
+ contextId: string;
1234
+ sourceId: string;
1235
+ targetId: string;
1236
+ /** Edge type label (default "related_to"). */
1237
+ edgeType?: string;
1238
+ /** Edge weight in [0.0, 3.0] (default 0.5). */
1239
+ weight?: number;
1240
+ /** Edge confidence in [0.0, 1.0] (default 1.0). */
1241
+ confidence?: number;
1242
+ }): Promise<Edge>;
1243
+ /**
1244
+ * Update an existing edge's weight and/or edge type, identified by the
1245
+ * `(sourceId, targetId)` pair. Omit a field to leave it unchanged.
1246
+ */
1247
+ updateEdge(options: {
1248
+ contextId: string;
1249
+ sourceId: string;
1250
+ targetId: string;
1251
+ /** New edge weight in [0.0, 3.0]; omit to keep. */
1252
+ weight?: number;
1253
+ /** New edge type label; omit to keep. */
1254
+ edgeType?: string;
1255
+ }): Promise<Edge>;
1256
+ /**
1257
+ * Delete the edge between sourceId and targetId. Returns true once the
1258
+ * server confirms deletion.
1259
+ */
1260
+ deleteEdge(options: {
1261
+ contextId: string;
1262
+ sourceId: string;
1263
+ targetId: string;
1264
+ }): Promise<boolean>;
1265
+ /** Get workspace usage and quota limits. */
1266
+ getUsage(): Promise<UsageInfo>;
1267
+ /** Get context information, usage guidelines, and search config. */
1268
+ getContextInfo(options: {
1269
+ contextId: string;
1270
+ /** Include memory count breakdown (default true). */
1271
+ includeDetails?: boolean;
1272
+ }): Promise<ContextInfo>;
1273
+ /**
1274
+ * Update hybrid search configuration for a context. Weights must sum
1275
+ * to 1.0 (±0.01). Requires owner or editor permission.
1276
+ */
1277
+ updateSearchConfig(options: UpdateSearchConfigOptions): Promise<ToolResult>;
1278
+ /** Get server name, version, environment, and feature flags. */
1279
+ getServerInfo(): Promise<ServerInfo>;
1280
+ /**
1281
+ * Check the connected server's version against the SDK's tested
1282
+ * minimum. Advisory only — logs a warning, never throws on mismatch.
1283
+ */
1284
+ checkServerVersion(): Promise<ServerInfo>;
1285
+ /** Get embedding queue status for the workspace. */
1286
+ getEmbeddingStatus(): Promise<EmbeddingStatus>;
1287
+ /** Get per-memory usage statistics for a context. */
1288
+ getMemoryStats(options: {
1289
+ contextId: string;
1290
+ /** Sort field (default "use_count"). */
1291
+ sortBy?: string;
1292
+ /** "asc" or "desc" (default "desc"). */
1293
+ sortOrder?: "asc" | "desc";
1294
+ /** Maximum results (1-200, default 50). */
1295
+ limit?: number;
1296
+ offset?: number;
1297
+ }): Promise<MemoryStatsResponse>;
1298
+ /** Find duplicate memory pairs in a context. */
1299
+ findDuplicates(options: {
1300
+ contextId: string;
1301
+ /** Similarity threshold (0.5-1.0, default 0.90). */
1302
+ threshold?: number;
1303
+ /** Maximum pairs (1-200, default 50). */
1304
+ limit?: number;
1305
+ }): Promise<DuplicatesResponse>;
1306
+ /**
1307
+ * List memories with optional substring, facet, and time-window
1308
+ * filters. Without `contextId` this returns the caller's own memories
1309
+ * across all contexts. `q` matches summaries only — use recall() for
1310
+ * semantic search.
1311
+ */
1312
+ listMemories(options?: ListMemoriesOptions): Promise<MemoryListResponse>;
1313
+ /**
1314
+ * List recent Sleep Maintenance runs for a context, newest first.
1315
+ */
1316
+ getSleepHistory(options: {
1317
+ contextId: string;
1318
+ /** Maximum runs (server clamps to 1-50, default 10). */
1319
+ limit?: number;
1320
+ }): Promise<SleepReport[]>;
1321
+ /**
1322
+ * Get a detailed Sleep Maintenance report including the per-action
1323
+ * audit log.
1324
+ */
1325
+ getSleepReport(options: {
1326
+ contextId: string;
1327
+ reportId: string;
1328
+ }): Promise<SleepReportDetail>;
1329
+ /**
1330
+ * Reverse the effects of a completed Sleep Maintenance run. The server
1331
+ * processes actions in reverse order with per-step commits — a partial
1332
+ * failure means SOME actions may have been reversed before the error.
1333
+ */
1334
+ rollbackSleepRun(options: {
1335
+ contextId: string;
1336
+ reportId: string;
1337
+ }): Promise<RollbackResult>;
1338
+ /** List available embedding models with provider info and availability. */
1339
+ listEmbeddingModels(): Promise<EmbeddingModelsResponse>;
1340
+ /** Release resources. (fetch has no persistent connection to close; kept for API parity.) */
1341
+ close(): Promise<void>;
1342
+ }
1343
+
1344
+ /** Configuration loading for the Kagura Memory SDK (port of config.py). */
1345
+ /**
1346
+ * Shape of `.kagura.json` — the config file format is shared with the
1347
+ * Python SDK/CLI, so keys stay snake_case on disk. Additional keys are
1348
+ * preserved.
1349
+ */
1350
+ interface KaguraConfig {
1351
+ api_key?: string;
1352
+ mcp_url?: string;
1353
+ model?: string;
1354
+ context_id?: string | null;
1355
+ llm_api_key?: string;
1356
+ workspace_id?: string;
1357
+ [key: string]: unknown;
1358
+ }
1359
+ interface LoadConfigOptions {
1360
+ /** Directory searched for `./.kagura.json` (default: process.cwd()). */
1361
+ cwd?: string;
1362
+ /** Home directory searched for `~/.kagura.json` (default: os.homedir()). */
1363
+ home?: string;
1364
+ /** Environment source (default: process.env). */
1365
+ env?: Record<string, string | undefined>;
1366
+ }
1367
+ /**
1368
+ * Load configuration from `.kagura.json` or environment variables.
1369
+ *
1370
+ * Search order:
1371
+ * 1. `./.kagura.json` (current directory)
1372
+ * 2. `~/.kagura.json` (home directory)
1373
+ * 3. Environment variables (KAGURA_API_KEY, KAGURA_MCP_URL, KAGURA_MODEL)
1374
+ */
1375
+ declare function loadConfig(options?: LoadConfigOptions): KaguraConfig;
1376
+
1377
+ /** Custom errors for the Kagura Memory SDK (port of exceptions.py). */
1378
+ /**
1379
+ * Subset of the standard DOM/Node `ErrorOptions`. Declared locally so the
1380
+ * published `.d.ts` does not force consumers onto an ES2022 `lib` just to
1381
+ * reference our error constructors.
1382
+ */
1383
+ interface KaguraErrorOptions {
1384
+ cause?: unknown;
1385
+ }
1386
+ /** Base error for the Kagura SDK. */
1387
+ declare class KaguraError extends Error {
1388
+ constructor(message: string, options?: KaguraErrorOptions);
1389
+ }
1390
+ /** Authentication failed. */
1391
+ declare class KaguraAuthError extends KaguraError {
1392
+ }
1393
+ /**
1394
+ * OAuth refresh token expired or invalid.
1395
+ *
1396
+ * Raised when an attempted refresh returns `invalid_grant` (or the server
1397
+ * otherwise indicates that the stored refresh token can no longer be used).
1398
+ * The caller must re-authenticate via `kagura auth login`.
1399
+ */
1400
+ declare class KaguraAuthExpiredError extends KaguraAuthError {
1401
+ readonly expiresAt: Date | null;
1402
+ constructor(message: string, expiresAt?: Date | null, options?: KaguraErrorOptions);
1403
+ }
1404
+ /** User denied authorization at the device-flow consent screen. */
1405
+ declare class KaguraAuthDeniedError extends KaguraAuthError {
1406
+ }
1407
+ /** Connection to Kagura server failed. */
1408
+ declare class KaguraConnectionError extends KaguraError {
1409
+ }
1410
+ /** Requested resource not found (HTTP 404). */
1411
+ declare class KaguraNotFoundError extends KaguraError {
1412
+ }
1413
+ /** Rate limit exceeded. */
1414
+ declare class KaguraRateLimitError extends KaguraError {
1415
+ readonly retryAfter: number | null;
1416
+ constructor(message: string, retryAfter?: number | null, options?: KaguraErrorOptions);
1417
+ }
1418
+ /** LLM call failed. */
1419
+ declare class KaguraLLMError extends KaguraError {
1420
+ }
1421
+ /** Context not found or invalid. */
1422
+ declare class KaguraContextError extends KaguraError {
1423
+ }
1424
+ /** Resource token quota exceeded (events per hour). */
1425
+ declare class KaguraQuotaError extends KaguraError {
1426
+ readonly retryAfter: number | null;
1427
+ constructor(message: string, retryAfter?: number | null, options?: KaguraErrorOptions);
1428
+ }
1429
+ /**
1430
+ * Object store rejected an upload with HTTP 400.
1431
+ *
1432
+ * Raised for any HTTP 400 response from the object store on a presigned
1433
+ * PUT — most commonly R2 `BadDigest` (the body's sha256 did not match the
1434
+ * value bound into the presigned PUT URL), but also covers other 400
1435
+ * causes such as a malformed presigned URL or a Content-Length mismatch.
1436
+ */
1437
+ declare class KaguraIntegrityError extends KaguraError {
1438
+ }
1439
+ /**
1440
+ * URL or file fetch failed (SSRF guard, byte cap, redirect loop, etc.).
1441
+ *
1442
+ * The original URL/path is exposed via the `url` property so callers can
1443
+ * present it without re-parsing the message.
1444
+ */
1445
+ declare class KaguraFetchError extends KaguraError {
1446
+ readonly url: string | null;
1447
+ constructor(message: string, url?: string | null, options?: KaguraErrorOptions);
1448
+ }
1449
+ /** File ingestion orchestration failed for a non-fetch reason. */
1450
+ declare class KaguraIngestError extends KaguraError {
1451
+ }
1452
+
1453
+ /**
1454
+ * Package version string, shared across client modules (User-Agent, MCP
1455
+ * clientInfo). Kept in sync with package.json by the release process.
1456
+ */
1457
+ declare const SDK_VERSION = "0.1.0";
1458
+
1459
+ /**
1460
+ * Auth contracts shared by the credential resolver and the HTTP clients.
1461
+ *
1462
+ * The Python SDK plugs OAuth refresh in via an httpx.Auth subclass; with
1463
+ * fetch there is no request-hook layer, so clients instead ask an
1464
+ * `AuthProvider` for a fresh `Authorization` header value before each
1465
+ * request.
1466
+ */
1467
+ /** Supplies the `Authorization` header value for each request. */
1468
+ interface AuthProvider {
1469
+ /**
1470
+ * Return the current `Authorization` header value (e.g. `Bearer xyz`),
1471
+ * refreshing the underlying token first when it is at/near expiry.
1472
+ */
1473
+ getAuthHeader(): Promise<string>;
1474
+ }
1475
+ /**
1476
+ * Which precedence branch produced a static auth result. Pairs an api_key
1477
+ * with the workspace it was provisioned for (issue #115).
1478
+ */
1479
+ type StaticSource = "explicit" | "env" | "config";
1480
+ /** Superset of StaticSource that also covers the OAuth branch. */
1481
+ type AuthSource = StaticSource | "oauth";
1482
+ /** Long-lived API key resolution result. */
1483
+ interface StaticAuthResult {
1484
+ kind: "static";
1485
+ apiKey: string;
1486
+ mcpUrl: string;
1487
+ source: StaticSource;
1488
+ }
1489
+ /** OAuth credentials.json resolution result. */
1490
+ interface OAuthAuthResult {
1491
+ kind: "oauth";
1492
+ oauth: AuthProvider;
1493
+ mcpUrl: string;
1494
+ /** Workspace bound to this token pair at resolution time. */
1495
+ workspaceId: string | null;
1496
+ }
1497
+ type ResolvedAuth = StaticAuthResult | OAuthAuthResult;
1498
+
1499
+ /**
1500
+ * Shared construction/auth/lifecycle/error spine for Kagura REST clients
1501
+ * (port of _rest_base.py).
1502
+ *
1503
+ * FilesClient, ResourceClient, SecretClient, and WorkspaceClient would
1504
+ * otherwise carry near-verbatim copies of the same scaffolding — and the
1505
+ * Python copies had already drifted (403 credential scrubbing and the
1506
+ * OAuth-aware 401 hint existed in some clients but not others).
1507
+ * {@link KaguraRestClient} owns the spine once; each client keeps only its
1508
+ * wire-contract differences via the `error401`/`error403`/`error429`
1509
+ * builder hooks.
1510
+ *
1511
+ * Invariants the base enforces for every client:
1512
+ *
1513
+ * - credentials are required up front (`apiKey` or an `AuthProvider`) with
1514
+ * an actionable error naming the class's factory;
1515
+ * - HTTPS-only base URLs (loopback exempt) via `validateHttpsUrl`;
1516
+ * - the API key is baked into the `Authorization` header closure exactly
1517
+ * once and never stored as an instance field;
1518
+ * - every request carries `User-Agent: kagura-memory-sdk/<version>` and an
1519
+ * `AbortSignal.timeout` deadline.
1520
+ */
1521
+
1522
+ type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
1523
+ /** Default REST API origin when no MCP URL or base URL is supplied. */
1524
+ declare const DEFAULT_REST_BASE_URL = "https://memory.kagura-ai.com";
1525
+ interface KaguraRestClientOptions {
1526
+ /**
1527
+ * Kagura API key (Bearer token). Required unless `oauth` is supplied.
1528
+ * For credential resolution (the auto chain env → `~/.kagura/
1529
+ * credentials.json` → `.kagura.json`), use `fromMcpUrl` — a bare
1530
+ * constructor deliberately does not read disk state.
1531
+ */
1532
+ apiKey?: string;
1533
+ /** REST API base URL without path (default: {@link DEFAULT_REST_BASE_URL}). */
1534
+ baseUrl?: string;
1535
+ /** Request timeout in milliseconds (default: 30000). */
1536
+ timeoutMs?: number;
1537
+ /**
1538
+ * Pre-built OAuth provider. `fromMcpUrl` passes one when the resolver
1539
+ * picked an OAuth profile; it injects a fresh access token per request.
1540
+ */
1541
+ oauth?: AuthProvider;
1542
+ /**
1543
+ * Provenance tag from `resolveAuth`; clients use it to flavor 403
1544
+ * hints (issue #115).
1545
+ */
1546
+ authSource?: AuthSource;
1547
+ /**
1548
+ * Workspace UUID associated with the credential source — hint display
1549
+ * only, never sent on the wire.
1550
+ */
1551
+ workspaceIdHint?: string | null;
1552
+ /** Fetch implementation override (for tests; default: globalThis.fetch). */
1553
+ fetch?: typeof globalThis.fetch;
1554
+ }
1555
+ interface FromMcpUrlOptions {
1556
+ /** Explicit Kagura API key. Skips the resolution chain. */
1557
+ apiKey?: string;
1558
+ /**
1559
+ * Explicit MCP URL. When omitted, the resolved credential source's
1560
+ * stored URL is used (default `https://memory.kagura-ai.com/mcp`).
1561
+ */
1562
+ mcpUrl?: string;
1563
+ /** Request timeout in milliseconds (default: 30000). */
1564
+ timeoutMs?: number;
1565
+ /** Named OAuth profile to load (overrides KAGURA_PROFILE and the file default). */
1566
+ profile?: string;
1567
+ /** Fetch implementation override (for tests; default: globalThis.fetch). */
1568
+ fetch?: typeof globalThis.fetch;
1569
+ /** Environment source override (for tests; default: process.env). */
1570
+ env?: Record<string, string | undefined>;
1571
+ /** Home directory override (for tests). */
1572
+ home?: string;
1573
+ }
1574
+ /**
1575
+ * Envelope returned by {@link KaguraRestClient.request} for 2xx responses.
1576
+ *
1577
+ * Beyond the `{status, headers, text}` triple, it carries the request
1578
+ * method and path so {@link KaguraRestClient.json} / `expectList` can name
1579
+ * the endpoint in shape-mismatch diagnostics (the Python port reads these
1580
+ * off `resp.request`; fetch's `Response` has no such back-pointer).
1581
+ */
1582
+ interface RestResponse {
1583
+ status: number;
1584
+ headers: Headers;
1585
+ text: string;
1586
+ method: HttpMethod;
1587
+ path: string;
1588
+ }
1589
+ /** Request payload context threaded to the 403 hook (subclass hints only). */
1590
+ interface RequestContext {
1591
+ requestJson: Record<string, unknown> | undefined;
1592
+ requestParams: Record<string, unknown> | undefined;
1593
+ }
1594
+ /**
1595
+ * Base class for the Kagura REST API clients.
1596
+ *
1597
+ * Subclasses add their domain methods on top of {@link request} and
1598
+ * override the `error*` builder hooks where their contract differs. The
1599
+ * default hooks implement the majority behavior:
1600
+ *
1601
+ * - 401 → {@link KaguraAuthError} with an OAuth-aware recovery hint
1602
+ * - 403 → the generic `HTTP 403: <detail>` mapping
1603
+ * - 404 → {@link KaguraNotFoundError} (server detail or "Not found")
1604
+ * - 429 → {@link KaguraQuotaError} with a tolerant `Retry-After`
1605
+ * - other statuses → {@link KaguraConnectionError}
1606
+ * - transport errors → {@link KaguraConnectionError}
1607
+ */
1608
+ declare class KaguraRestClient {
1609
+ readonly baseUrl: string;
1610
+ readonly timeoutMs: number;
1611
+ /** Supplies the Authorization header for every request (static or OAuth). */
1612
+ protected readonly auth: AuthProvider;
1613
+ /** Non-null exactly when constructed in OAuth mode (flavors the 401 hint). */
1614
+ protected readonly oauth: AuthProvider | null;
1615
+ /** Which resolution branch produced the credentials (403 hint flavoring). */
1616
+ protected readonly authSource: AuthSource | null;
1617
+ /** Workspace bound to the credential source — display only. */
1618
+ protected readonly workspaceIdHint: string | null;
1619
+ protected readonly fetchImpl: typeof globalThis.fetch;
1620
+ /**
1621
+ * Initialize with a static API key or a pre-built OAuth provider.
1622
+ *
1623
+ * @throws Error if neither `apiKey` nor `oauth` is given, or the base
1624
+ * URL is plain HTTP on a non-loopback host.
1625
+ */
1626
+ constructor(options?: KaguraRestClientOptions);
1627
+ /**
1628
+ * Create a client by resolving credentials from the SDK chain.
1629
+ *
1630
+ * Precedence: explicit `apiKey` > `KAGURA_API_KEY` env > OAuth profile
1631
+ * from `~/.kagura/credentials.json` > `.kagura.json`. The REST
1632
+ * `baseUrl` is derived from the resolved MCP URL (strips `/mcp` and any
1633
+ * `/mcp/w/{workspaceId}` suffix); a static key bakes the Bearer header
1634
+ * once, an OAuth profile installs an auto-refreshing `AuthProvider`.
1635
+ *
1636
+ * Declared with a polymorphic `this` so every subclass inherits a
1637
+ * factory returning its own type: `FilesClient.fromMcpUrl(...)` is a
1638
+ * `FilesClient`.
1639
+ */
1640
+ static fromMcpUrl<T extends typeof KaguraRestClient>(this: T, options?: FromMcpUrlOptions): InstanceType<T>;
1641
+ /**
1642
+ * Construct from a pre-resolved auth — internal CLI helper.
1643
+ *
1644
+ * Shared by {@link fromMcpUrl} (SDK entry) and CLI command runners,
1645
+ * which resolve once so apiKey and workspace can be paired from the
1646
+ * same credential source (#115).
1647
+ *
1648
+ * `workspaceIdHint` threads the workspace bound to a static apiKey into
1649
+ * the client for 403 hint display. On the OAuth branch the resolver
1650
+ * already carries `workspaceId`, so the hint is taken from there and
1651
+ * the option is ignored.
1652
+ */
1653
+ protected static fromResolvedAuth<T extends typeof KaguraRestClient>(this: T, resolved: ResolvedAuth, options?: {
1654
+ timeoutMs?: number;
1655
+ workspaceIdHint?: string | null;
1656
+ fetch?: typeof globalThis.fetch;
1657
+ }): InstanceType<T>;
1658
+ /** Release resources. (fetch has no persistent pool to close; kept for API parity.) */
1659
+ close(): Promise<void>;
1660
+ /**
1661
+ * Make an authenticated request with standard error mapping.
1662
+ *
1663
+ * Returns the {@link RestResponse} envelope for 2xx; throws the mapped
1664
+ * {@link KaguraError} for any other status and wraps transport/abort
1665
+ * failures in {@link KaguraConnectionError}.
1666
+ */
1667
+ protected request(method: HttpMethod, path: string, opts?: {
1668
+ json?: Record<string, unknown>;
1669
+ params?: Record<string, unknown>;
1670
+ extraHeaders?: Record<string, string>;
1671
+ }): Promise<RestResponse>;
1672
+ private safeText;
1673
+ /**
1674
+ * Build the Kagura error for a non-2xx response.
1675
+ *
1676
+ * Hooks RETURN the error rather than throwing it so {@link request}
1677
+ * owns the single throw site — one uniform chain and a compiler-checked
1678
+ * `KaguraError` contract on every hook.
1679
+ */
1680
+ protected mapStatusError(response: RestResponse, context: RequestContext): KaguraError;
1681
+ /** 401 → auth error with a recovery hint matching the auth mode. */
1682
+ protected error401(response: RestResponse): KaguraError;
1683
+ /**
1684
+ * 403 → generic mapping by default; clients with a richer story
1685
+ * (workspace hints, secret existence-hiding) override this.
1686
+ */
1687
+ protected error403(response: RestResponse, context: RequestContext): KaguraError;
1688
+ /** 429 → quota error with a tolerant `Retry-After` parse. */
1689
+ protected error429(response: RestResponse): KaguraError;
1690
+ /** Any other status → `HTTP <status>: <detail>` connection error. */
1691
+ protected genericError(response: RestResponse): KaguraError;
1692
+ /**
1693
+ * Parse a 2xx body as JSON, mapping garbage to a Kagura error.
1694
+ *
1695
+ * A proxy/CDN can 200 with an HTML maintenance page; that must not
1696
+ * surface as a raw `SyntaxError`.
1697
+ */
1698
+ protected json(response: RestResponse): unknown;
1699
+ /** Parse a 2xx body that the contract says is a JSON array. */
1700
+ protected expectList(response: RestResponse): unknown[];
1701
+ }
1702
+
1703
+ /**
1704
+ * REST client for Kagura Memory Cloud file uploads (port of files_client.py).
1705
+ *
1706
+ * Drives the 3-step file upload flow against memory-cloud:
1707
+ * 1. `POST /api/v1/files/reserve` — server returns a presigned PUT URL.
1708
+ * 2. `PUT` to R2 with body bytes and the `x-amz-checksum-sha256` header
1709
+ * (base64 of the raw sha256 digest), when the presign signed it.
1710
+ * 3. `POST /api/v1/files/{file_id}/confirm` — finalize the row.
1711
+ *
1712
+ * Plus `downloadUrl()`, `delete()` and `list()`. The R2 PUT is sent with a
1713
+ * plain fetch and NO Authorization header so the SDK's Bearer credential
1714
+ * cannot leak to the object store — the presigned URL carries its own
1715
+ * short-lived SigV4 signature.
1716
+ */
1717
+
1718
+ interface FilesClientOptions extends KaguraRestClientOptions {
1719
+ /** R2 PUT timeout in ms (default 300000 — 5 min for large files). */
1720
+ uploadTimeoutMs?: number;
1721
+ }
1722
+ interface UploadOptions {
1723
+ /**
1724
+ * Target context (workspace) UUID. Mapped to the backend's
1725
+ * `workspace_id` field on the wire.
1726
+ */
1727
+ contextId: string;
1728
+ /**
1729
+ * File contents. A string is treated as a filesystem path (read fully
1730
+ * into memory); a `Uint8Array` is used directly.
1731
+ */
1732
+ source: string | Uint8Array;
1733
+ /** Required when `source` is bytes; defaults to the path basename otherwise. */
1734
+ filename?: string;
1735
+ /** MIME type; falls back to an extension guess then `application/octet-stream`. */
1736
+ contentType?: string;
1737
+ /**
1738
+ * Optional owning context to bind the file to for access control
1739
+ * (server v0.41.0+). Sent as the wire `context_id` field — distinct
1740
+ * from `contextId` above, which maps to `workspace_id`.
1741
+ */
1742
+ bindingContextId?: string;
1743
+ }
1744
+ declare class FilesClient extends KaguraRestClient {
1745
+ private readonly uploadTimeoutMs;
1746
+ constructor(options?: FilesClientOptions);
1747
+ /**
1748
+ * Upload a file to Kagura Memory Cloud, driving reserve → presigned PUT
1749
+ * → confirm. Returns the finalized {@link FileObject}.
1750
+ *
1751
+ * When the file already exists with the same sha256 in the workspace,
1752
+ * the server returns 409 and this surfaces the existing FileObject
1753
+ * (dedup happy-path) rather than throwing.
1754
+ *
1755
+ * @throws Error if `source` is bytes and `filename` is not provided.
1756
+ * @throws KaguraIntegrityError if R2 rejected the body sha256 binding.
1757
+ */
1758
+ upload(options: UploadOptions): Promise<FileObject>;
1759
+ /** Return a short-lived presigned GET URL for `fileId`. */
1760
+ downloadUrl(fileId: string, options: {
1761
+ contextId: string;
1762
+ }): Promise<string>;
1763
+ /** Soft-delete a file by id (server hard-deletes after retention). */
1764
+ delete(fileId: string, options: {
1765
+ contextId: string;
1766
+ }): Promise<void>;
1767
+ /** List uploaded files in a workspace, newest first. */
1768
+ list(options: {
1769
+ contextId: string;
1770
+ /** Maximum files to return (1-500, default 50). */
1771
+ limit?: number;
1772
+ /** Forward-compatible pagination cursor (ignored by the current server). */
1773
+ cursor?: string;
1774
+ }): Promise<FileListResponse>;
1775
+ /**
1776
+ * PUT `body` to the presigned R2 URL with checksum binding. Sends
1777
+ * `x-amz-checksum-sha256` (base64 of the raw digest) only when the
1778
+ * presign signed it; a 400 from the store → {@link KaguraIntegrityError}.
1779
+ */
1780
+ private putToObjectStore;
1781
+ /**
1782
+ * 403 → a workspace-mismatch hint (issue #115): surface the credential
1783
+ * source and requested workspace prefix without leaking the api_key.
1784
+ */
1785
+ protected error403(response: RestResponse, context: RequestContext): KaguraError;
1786
+ /** Stash the raw non-2xx body so the 409 dedup path can recover `existing_file`. */
1787
+ protected genericError(response: RestResponse): KaguraError;
1788
+ }
1789
+
1790
+ /**
1791
+ * REST API client for Kagura Memory Cloud Resource Tokens (port of
1792
+ * resource_client.py).
1793
+ *
1794
+ * Handles two authentication modes:
1795
+ * - Token CRUD: `Authorization: Bearer <api_key>` (set once in constructor)
1796
+ * - Event ingestion: `X-Resource-API-Key` (passed per-call, never stored)
1797
+ *
1798
+ * All methods may throw:
1799
+ * - {@link KaguraAuthError}: Authentication failed (401)
1800
+ * - {@link KaguraNotFoundError}: Resource not found (404)
1801
+ * - {@link KaguraConnectionError}: Connection or HTTP error
1802
+ * - {@link KaguraQuotaError}: Quota exceeded (429)
1803
+ */
1804
+
1805
+ /**
1806
+ * Message surfaced when `setupResource` is called on an OAuth-resolved
1807
+ * client. Defined at module scope so tests can assert against the stable
1808
+ * constant instead of pinning a substring of the rendered output.
1809
+ *
1810
+ * The hint MUST point at a credential source that outranks OAuth in the
1811
+ * resolver chain (`env > OAuth profile > .kagura.json`). Suggesting
1812
+ * `.kagura.json` is misleading — it ranks BELOW OAuth and would still
1813
+ * be skipped while the OAuth profile is present.
1814
+ */
1815
+ declare const SETUP_OAUTH_NOT_SUPPORTED_MSG: string;
1816
+ interface CreateTokenOptions {
1817
+ /** Resource identifier this token is scoped to. */
1818
+ resourceId: string;
1819
+ /** Human-readable description. */
1820
+ description?: string | null;
1821
+ /** Event ingestion quota per hour (1-10000, default 1000). */
1822
+ quotaEventsPerHour?: number;
1823
+ }
1824
+ interface ListTokensOptions {
1825
+ /** Filter by resource ID. */
1826
+ resourceId?: string | null;
1827
+ /** Number of tokens per page (1-100, default 50). */
1828
+ limit?: number;
1829
+ /** Starting offset for pagination (default 0). */
1830
+ offset?: number;
1831
+ }
1832
+ interface UpdateTokenOptions {
1833
+ /** Updated description. */
1834
+ description?: string | null;
1835
+ /** Updated quota (1-10000). */
1836
+ quotaEventsPerHour?: number | null;
1837
+ }
1838
+ interface ResourceSetupOptions {
1839
+ /** Resource identifier for data ingestion. */
1840
+ resourceId: string;
1841
+ /** Context name (defaults to resourceId server-side). */
1842
+ contextName?: string;
1843
+ /** Context summary. */
1844
+ summary?: string;
1845
+ /** Token description. */
1846
+ description?: string;
1847
+ /** Token quota (1-10000, default 1000). */
1848
+ quotaEventsPerHour?: number;
1849
+ }
1850
+ /**
1851
+ * A single event to ingest (camelCase input for the wire-model
1852
+ * `ResourceEventRequest`). Serialized per-field to the snake_case wire
1853
+ * shape; unset/null optional fields are omitted, matching the Python
1854
+ * `model_dump(exclude_none=True)` semantics (`eventMetadata` defaults to
1855
+ * `{}` and is always sent).
1856
+ */
1857
+ interface ResourceEventInput {
1858
+ op: "upsert" | "delete";
1859
+ /** Document ID (1-255 chars). */
1860
+ docId: string;
1861
+ /** Document version (minimum 1). */
1862
+ version?: number | null;
1863
+ payload?: Record<string, unknown> | null;
1864
+ /** Idempotency key (1-255 chars). */
1865
+ idempotencyKey?: string | null;
1866
+ eventMetadata?: Record<string, unknown>;
1867
+ /** Importance score (0.0-1.0). */
1868
+ importance?: number | null;
1869
+ }
1870
+ interface ListResourceEventsOptions {
1871
+ /** Maximum events per page (1-100, default 50). */
1872
+ limit?: number;
1873
+ /** Opaque pagination cursor from a prior `next_cursor`. */
1874
+ cursor?: string | null;
1875
+ /** Filter by operation (`upsert` or `delete`). */
1876
+ op?: "upsert" | "delete" | null;
1877
+ /** Filter by document ID. */
1878
+ docId?: string | null;
1879
+ /** Filter by document version. */
1880
+ version?: number | null;
1881
+ /**
1882
+ * Return only events with `created_at` at or after this time
1883
+ * (inclusive). A `Date` is serialized to ISO 8601 UTC; a string is
1884
+ * passed through as-is (supply ISO 8601).
1885
+ */
1886
+ since?: Date | string | null;
1887
+ }
1888
+ /**
1889
+ * REST API client for Kagura Memory Cloud Resource Tokens.
1890
+ *
1891
+ * Extends {@link KaguraRestClient} with the resource-token wire contract;
1892
+ * the base's default error hooks already implement this client's mapping
1893
+ * (429 → {@link KaguraQuotaError} with `retryAfter`), so no hooks are
1894
+ * overridden here.
1895
+ */
1896
+ declare class ResourceClient extends KaguraRestClient {
1897
+ /**
1898
+ * Original MCP URL — `null` until {@link fromResolvedAuth} stamps it.
1899
+ * {@link setupResource} needs the ORIGINAL MCP URL, which the REST
1900
+ * `baseUrl` no longer carries.
1901
+ */
1902
+ private mcpUrlValue;
1903
+ /** MCP URL captured by `fromMcpUrl` (null for bare construction). */
1904
+ get mcpUrl(): string | null;
1905
+ /**
1906
+ * Construct from a pre-resolved auth, stamping the MCP URL.
1907
+ *
1908
+ * `setupResource()` needs the ORIGINAL MCP URL to build its MCP
1909
+ * session — the resolved auth always carries one, whether sourced from
1910
+ * the OAuth profile or the priority-4 config.
1911
+ */
1912
+ protected static fromResolvedAuth<T extends typeof KaguraRestClient>(this: T, resolved: ResolvedAuth, options?: {
1913
+ timeoutMs?: number;
1914
+ workspaceIdHint?: string | null;
1915
+ fetch?: typeof globalThis.fetch;
1916
+ }): InstanceType<T>;
1917
+ /**
1918
+ * Create a new resource token.
1919
+ *
1920
+ * @returns Created token including plaintext token (shown only once).
1921
+ */
1922
+ createToken(options: CreateTokenOptions): Promise<ResourceTokenCreateResponse>;
1923
+ /**
1924
+ * List resource tokens with optional filtering.
1925
+ *
1926
+ * @returns Paginated (`limit`/`offset`) list of resource tokens.
1927
+ */
1928
+ listTokens(options?: ListTokensOptions): Promise<PaginatedResourceTokensResponse>;
1929
+ /**
1930
+ * Update a resource token's metadata. Only fields that are set are
1931
+ * sent on the wire.
1932
+ *
1933
+ * @param tokenId Token database ID.
1934
+ * @returns Updated token metadata.
1935
+ */
1936
+ updateToken(tokenId: number, options?: UpdateTokenOptions): Promise<ResourceTokenResponse>;
1937
+ /**
1938
+ * Revoke (soft-delete) a resource token.
1939
+ *
1940
+ * @param tokenId Token database ID.
1941
+ */
1942
+ revokeToken(tokenId: number): Promise<void>;
1943
+ /**
1944
+ * Atomically set up a resource for data ingestion (server v0.14+).
1945
+ *
1946
+ * Calls the server-side atomic `setup_resource` MCP tool which creates
1947
+ * Context + Resource entity + token in a single transaction. On
1948
+ * failure, no orphan Context rows are left on the server. Requires the
1949
+ * client to be created via `fromMcpUrl()`.
1950
+ *
1951
+ * @returns ResourceSetupResponse with plaintext token (shown only once).
1952
+ * @throws Error if the client was not created via `fromMcpUrl()`, or
1953
+ * was constructed via the OAuth resolution path (`setupResource`
1954
+ * currently requires a static apiKey — see
1955
+ * {@link SETUP_OAUTH_NOT_SUPPORTED_MSG}).
1956
+ * @throws KaguraAuthError if the Authorization header is missing or
1957
+ * malformed in the static path.
1958
+ *
1959
+ * Note: Idempotency for repeated calls with the same `resourceId` is
1960
+ * not guaranteed; server-side behavior may evolve. Avoid retrying
1961
+ * setup for an existing `resourceId` without first verifying state.
1962
+ */
1963
+ setupResource(options: ResourceSetupOptions): Promise<ResourceSetupResponse>;
1964
+ /**
1965
+ * Get impact statistics for a resource.
1966
+ *
1967
+ * @returns Resource impact stats (token_count, memory_count, schema version).
1968
+ */
1969
+ getResourceImpact(resourceId: string): Promise<ResourceImpactResponse>;
1970
+ /**
1971
+ * List all resources in the caller's workspace (server v0.14+).
1972
+ *
1973
+ * Returns workspace-scoped resources with aggregated stats
1974
+ * (token_count, memory_count, current_schema_version, ...). The
1975
+ * endpoint is currently non-paginated; the server caps a workspace at
1976
+ * well under 50 resources by design.
1977
+ *
1978
+ * Workspace owners only — non-owners receive 403.
1979
+ */
1980
+ listResources(): Promise<ResourceListResponse>;
1981
+ /**
1982
+ * Get indexer state and recent ingest events for a resource.
1983
+ *
1984
+ * `state` is `null` when the indexer has never run for this resource —
1985
+ * a normal 200 response, distinct from a 404. `recent_events` is
1986
+ * server-capped at 5.
1987
+ *
1988
+ * @throws KaguraNotFoundError Resource slug does not exist in the
1989
+ * caller's workspace (404; cross-workspace probe protection).
1990
+ */
1991
+ getIndexerStatus(resourceId: string): Promise<IndexerStatusResponse>;
1992
+ /**
1993
+ * Get field definitions for a resource.
1994
+ *
1995
+ * @param schemaVersion Specific schema version to retrieve; omit for
1996
+ * the latest version.
1997
+ * @returns Resource schema with field definitions, or `null` if no
1998
+ * schema is registered for the resource.
1999
+ */
2000
+ getResourceSchema(resourceId: string, schemaVersion?: number | null): Promise<ResourceSchemaResponse | null>;
2001
+ /**
2002
+ * List ingested events for a resource (server v0.15+).
2003
+ *
2004
+ * Mirrors `GET /api/v1/resources/{resource_id}/events`. Results are
2005
+ * cursor-paginated: pass the returned `next_cursor` back as `cursor`
2006
+ * to fetch the next page (`next_cursor` is `null` on the last page).
2007
+ * Note this method uses `limit`/`cursor` pagination, unlike
2008
+ * {@link listTokens} which uses `limit`/`offset`.
2009
+ *
2010
+ * Uses Bearer auth (workspace read), not the `X-Resource-API-Key`
2011
+ * ingestion credential. An unknown `resourceId` returns an empty page
2012
+ * (`events=[]`, `next_cursor=null`) rather than a 404 — observed
2013
+ * against memory-cloud production.
2014
+ *
2015
+ * @throws KaguraNotFoundError The server returned 404 for this
2016
+ * resource (cross-workspace probe protection); applies only if the
2017
+ * server does respond with 404.
2018
+ */
2019
+ listResourceEvents(resourceId: string, options?: ListResourceEventsOptions): Promise<ResourceEventsListResponse>;
2020
+ /**
2021
+ * Ingest a single resource event.
2022
+ *
2023
+ * @param resourceApiKey Resource API key (`X-Resource-API-Key`
2024
+ * header) — sent per-call, never stored on the client.
2025
+ * @returns Ingestion result with `event_id`.
2026
+ */
2027
+ ingestEvent(resourceId: string, resourceApiKey: string, event: ResourceEventInput): Promise<ResourceEventResponse>;
2028
+ /**
2029
+ * Ingest a batch of resource events (1-100; the server validates the
2030
+ * bound).
2031
+ *
2032
+ * @param resourceApiKey Resource API key (`X-Resource-API-Key`
2033
+ * header) — sent per-call, never stored on the client.
2034
+ * @returns Batch ingestion result with created/failed counts.
2035
+ */
2036
+ ingestEvents(resourceId: string, resourceApiKey: string, events: ResourceEventInput[]): Promise<ResourceEventBatchResponse>;
2037
+ }
2038
+
2039
+ /**
2040
+ * REST client for workspace member & invitation management (#225) —
2041
+ * port of workspace_client.py.
2042
+ *
2043
+ * Owner-key operational tooling: memory-cloud v0.42.0 gates every endpoint
2044
+ * here at workspace-OWNER role for programmatic principals and rejects
2045
+ * OAuth Bearer tokens outright ("Use a workspace-owner API key"). The web
2046
+ * UI (session auth) keeps its own per-endpoint role semantics — this
2047
+ * client only ever sees the programmatic contract.
2048
+ *
2049
+ * Construction, credential resolution, lifecycle, and the base error
2050
+ * mapping live in {@link KaguraRestClient} (#229); this module keeps only
2051
+ * the workspace-specific wire contract: the owner-key 403 hint and the
2052
+ * detail-carrying 429 quota mapping.
2053
+ */
2054
+
2055
+ declare const VALID_ASSIGNABLE_ROLES: readonly ["member", "admin", "viewer"];
2056
+ declare const VALID_INVITE_EXPIRES: readonly [7, 30, 90, 365];
2057
+ /** Options for {@link WorkspaceClient.createInvitation}. */
2058
+ interface CreateInvitationOptions {
2059
+ /** `member` | `admin` | `viewer` (default: `"member"`). */
2060
+ role?: string;
2061
+ /**
2062
+ * Context grant — required (min 1) for member/viewer invitations,
2063
+ * ignored for admin. Sent on the wire as `allowed_context_ids`.
2064
+ */
2065
+ allowedContextIds?: string[];
2066
+ /**
2067
+ * One of 7/30/90/365 (sent as `expires_in_days`), or omit for a
2068
+ * never-expiring invitation.
2069
+ */
2070
+ expiresInDays?: number;
2071
+ }
2072
+ /** Options for {@link WorkspaceClient.listInvitations}. */
2073
+ interface ListInvitationsOptions {
2074
+ /** Include already-accepted invitations (default: false). */
2075
+ includeAccepted?: boolean;
2076
+ }
2077
+ /**
2078
+ * REST API client for workspace member / invitation management.
2079
+ *
2080
+ * Requires the workspace OWNER's API key when called programmatically
2081
+ * (memory-cloud v0.42.0+). OAuth profiles are rejected by the server on
2082
+ * this surface — resolve a static owner key (`KAGURA_API_KEY` env or
2083
+ * `.kagura.json`) instead.
2084
+ *
2085
+ * All methods may reject with:
2086
+ * - `KaguraAuthError` — authentication failed (401)
2087
+ * - `KaguraConnectionError` — access denied (403 — non-owner key, OAuth
2088
+ * token, or deployment kill-switch; the message says which) or any
2089
+ * other HTTP/connection error
2090
+ * - `KaguraNotFoundError` — workspace/member/invitation not found (404).
2091
+ * Also returned for a workspace-scoped key used against a different
2092
+ * workspace (uniform 404, memory-cloud #963) — a 404 here does NOT
2093
+ * prove the resource is absent.
2094
+ * - `KaguraQuotaError` — member quota or rate limit exceeded (429)
2095
+ */
2096
+ declare class WorkspaceClient extends KaguraRestClient {
2097
+ /**
2098
+ * List workspace members (owner key required).
2099
+ *
2100
+ * Rows are ordered owner→viewer then by join date and include
2101
+ * `user_name`/`user_email` when the member has logged in.
2102
+ */
2103
+ listMembers(workspaceId: string): Promise<WorkspaceMember[]>;
2104
+ /**
2105
+ * Add an already-registered user to the workspace.
2106
+ *
2107
+ * The server does NOT validate that `userId` exists (v0.42.0) — a typo
2108
+ * creates a dangling membership row that lists with null name/email.
2109
+ * Prefer {@link createInvitation} for onboarding; use this only with a
2110
+ * user_id copied from a trusted source. Duplicate members are rejected
2111
+ * with 422.
2112
+ */
2113
+ addMember(workspaceId: string, userId: string, role?: string): Promise<WorkspaceMember>;
2114
+ /** Change a member's role (member/admin/viewer only). */
2115
+ updateMemberRole(workspaceId: string, userId: string, role: string): Promise<WorkspaceMember>;
2116
+ /** Remove a member from the workspace (server returns 204). */
2117
+ removeMember(workspaceId: string, userId: string): Promise<void>;
2118
+ /**
2119
+ * Invite a not-yet-registered user by email.
2120
+ *
2121
+ * The returned invitation carries `token`/`invitation_url` — the only
2122
+ * response that ever exposes them to programmatic callers; treat them
2123
+ * as join credentials.
2124
+ *
2125
+ * @param workspaceId Target workspace UUID.
2126
+ * @param email Invitee email (must match their Google account).
2127
+ * @param options Role, context grant, and expiry preset.
2128
+ */
2129
+ createInvitation(workspaceId: string, email: string, options?: CreateInvitationOptions): Promise<WorkspaceInvitation>;
2130
+ /**
2131
+ * List invitations. `token`/`invitation_url` arrive as null for
2132
+ * programmatic callers (server-side token hygiene, #1164).
2133
+ */
2134
+ listInvitations(workspaceId: string, options?: ListInvitationsOptions): Promise<WorkspaceInvitation[]>;
2135
+ /** Revoke a pending invitation (server returns 200 `{"success": true}`). */
2136
+ revokeInvitation(workspaceId: string, invitationId: number): Promise<void>;
2137
+ /**
2138
+ * Mint an API key for ANOTHER member (owner key required).
2139
+ *
2140
+ * Privilege-downgrade provisioning only: the server 403s self-targets
2141
+ * ("An owner key cannot mint keys for itself") and owner/admin targets
2142
+ * — mint for member/viewer service identities. `expiresDays` is
2143
+ * required by the server for owner-provisioned mints (never-expiring
2144
+ * CI keys are not allowed). The returned `plaintext_key` is shown
2145
+ * exactly once — owner-provisioned keys are force-hidden at creation,
2146
+ * so no later call returns it.
2147
+ */
2148
+ mintMemberKey(workspaceId: string, userId: string, name: string, expiresDays: number): Promise<MemberAPIKey>;
2149
+ /**
2150
+ * List a member's API keys — metadata only.
2151
+ *
2152
+ * The server wraps the rows in a `MemberCredentialsResponse` envelope
2153
+ * (`api_keys` + `target_user_role`) and always nulls `plaintext_key`
2154
+ * for programmatic callers.
2155
+ */
2156
+ listMemberKeys(workspaceId: string, userId: string): Promise<MemberAPIKey[]>;
2157
+ /**
2158
+ * Revoke a member's API key.
2159
+ *
2160
+ * Owner-provisioned revocations are SOFT server-side (`revoked_at`
2161
+ * set, row retained for forensics); success is 200 with a status body,
2162
+ * and an already-revoked key surfaces as a uniform 404.
2163
+ */
2164
+ revokeMemberKey(workspaceId: string, userId: string, keyId: number): Promise<void>;
2165
+ private validateRole;
2166
+ /**
2167
+ * Build the 403 message, appending the owner-key hint only when useful.
2168
+ *
2169
+ * v0.42.0 sends purpose-built 403 messages on this surface (OAuth
2170
+ * rejection, deployment kill-switch, plan gate, self-role-change,
2171
+ * key/workspace mismatch) — those pass through untouched. Only the
2172
+ * deliberately uniform denial gets the owner-key hint, because that is
2173
+ * the one a non-owner static key actually hits.
2174
+ */
2175
+ private format403;
2176
+ protected error403(response: RestResponse, _context: RequestContext): KaguraError;
2177
+ protected error429(response: RestResponse): KaguraError;
2178
+ }
2179
+
2180
+ /**
2181
+ * Credential resolution shared by REST/MCP clients in this SDK (port of
2182
+ * _auth.py).
2183
+ *
2184
+ * Centralizes the precedence chain — explicit arg > `KAGURA_API_KEY` env >
2185
+ * OAuth profile in `~/.kagura/credentials.json` > `.kagura.json` config —
2186
+ * in one module so every client resolves credentials identically.
2187
+ *
2188
+ * Returns one of two result types (see `types.ts`):
2189
+ *
2190
+ * - `StaticAuthResult` — long-lived API key, baked into the client's
2191
+ * `Authorization` header at construction.
2192
+ * - `OAuthAuthResult` — a `KaguraOAuth` AuthProvider that injects a fresh
2193
+ * access token per request and coordinates refresh via a process-wide
2194
+ * mutex.
2195
+ *
2196
+ * This module imports only from `auth/credentials`, `config`, and
2197
+ * `errors` — never from `http`. The reverse direction (`http` importing
2198
+ * `resolve`) must also be avoided so the dependency stays one-way.
2199
+ */
2200
+
2201
+ declare const DEFAULT_MCP_URL = "https://memory.kagura-ai.com/mcp";
2202
+ interface ResolveAuthOptions {
2203
+ apiKey?: string | null;
2204
+ mcpUrl?: string | null;
2205
+ profile?: string | null;
2206
+ /** Pre-loaded `.kagura.json`; skips the priority-4 disk read when set. */
2207
+ config?: KaguraConfig | null;
2208
+ /** Environment source (default: process.env). */
2209
+ env?: Record<string, string | undefined>;
2210
+ /** Home directory for `~/.kagura/credentials.json` (default: os.homedir()). */
2211
+ home?: string;
2212
+ }
2213
+ /**
2214
+ * Pick a credential source per the documented precedence chain:
2215
+ *
2216
+ * 1. Explicit `apiKey` argument (non-whitespace) — wins absolutely.
2217
+ * 2. `KAGURA_API_KEY` env var, with mcpUrl fallback
2218
+ * `mcpUrl arg > KAGURA_MCP_URL > DEFAULT_MCP_URL`.
2219
+ * 3. OAuth profile from credentials.json:
2220
+ * `profile arg > KAGURA_PROFILE > default_profile`. An explicitly named
2221
+ * profile that is missing raises rather than falling through (silently
2222
+ * authenticating with the wrong account is the bug class prevented).
2223
+ * 4. Legacy `.kagura.json` (pre-loaded via `options.config` or read from
2224
+ * disk), with the same whitespace-stripped api_key check.
2225
+ *
2226
+ * Empty / whitespace-only api_keys are treated the same as absent at every
2227
+ * step — sending `Authorization: Bearer ` would always 401 and is never
2228
+ * what the caller intended.
2229
+ *
2230
+ * @throws KaguraAuthError when no source produces credentials.
2231
+ */
2232
+ declare function resolveAuth(options?: ResolveAuthOptions): ResolvedAuth;
2233
+
2234
+ export { type AnalysisResult, type Artifact, type AuthProvider, type AuthSource, type ContextDetail, type ContextInfo, type ContextStats, type CostBreakdown, type CreateContextOptions, type CreateInvitationOptions, type CreateTokenOptions, DEFAULT_MCP_URL, DEFAULT_REST_BASE_URL, type DeliveryMode, type DuplicateMemoryInfo, type DuplicatePair, type DuplicatesResponse, type Edge, type EmbeddingModel, type EmbeddingModelsResponse, type EmbeddingStatus, type ExploredMemory, type FailedMemoryInfo, type FieldDefinition, type FileDownloadUrlResponse, type FileListResponse, type FileObject, type FileReserveResponse, FilesClient, type FilesClientOptions, type FromMcpUrlOptions, type HttpMethod, type IndexerJobStatus, type IndexerSkippedReason, type IndexerState, type IndexerStateMetrics, type IndexerStatusResponse, type IngestErrorRecord, type IngestResult, KaguraAuthDeniedError, KaguraAuthError, KaguraAuthExpiredError, KaguraClient, type KaguraClientOptions, type KaguraConfig, KaguraConnectionError, KaguraContextError, KaguraError, KaguraFetchError, KaguraIngestError, KaguraIntegrityError, KaguraLLMError, KaguraNotFoundError, KaguraQuotaError, KaguraRateLimitError, KaguraRestClient, type KaguraRestClientOptions, type LLMUsage, type ListInvitationsOptions, type ListMemoriesOptions, type ListResourceEventsOptions, type ListTagsOptions, type ListTagsResponse, type ListTokensOptions, type LoadConfigOptions, MIN_SERVER_VERSION, type MemberAPIKey, type Memory, type MemoryInfo, type MemoryListItem, type MemoryListResponse, type MemoryStatItem, type MemoryStatsResponse, type MemoryToStore, type Message, type OAuthAuthResult, type PaginatedResourceTokensResponse, type ProcessResult, type RecallOptions, type RecallQuery, type RememberOptions, type ResolveAuthOptions, type ResolvedAuth, ResourceClient, type ResourceEventBatchRequest, type ResourceEventBatchResponse, type ResourceEventInput, type ResourceEventItem, type ResourceEventRecord, type ResourceEventRequest, type ResourceEventResponse, type ResourceEventsListResponse, type ResourceImpactResponse, type ResourceListItem, type ResourceListResponse, type ResourceSchemaResponse, type ResourceSetupOptions, type ResourceSetupResponse, type ResourceTokenCreate, type ResourceTokenCreateResponse, type ResourceTokenResponse, type ResourceTokenUpdate, type RollbackResult, type RollbackSummary, SDK_VERSION, SETUP_OAUTH_NOT_SUPPORTED_MSG, type SearchConfig, type SearchMode, type ServerFeatures, type ServerInfo, type Session, type SetupResourceOptions, type SleepAction, type SleepReport, type SleepReportDetail, type SleepRunStatus, type SourceType, type StaticAuthResult, type StaticSource, type TagInfo, type ToolResult, type UpdateContextOptions, type UpdateMemoryOptions, type UpdateSearchConfigOptions, type UpdateTokenOptions, type UploadOptions, type UsageInfo, type UsageQuota, type UsageQuotaLimitOnly, VALID_ASSIGNABLE_ROLES, VALID_INVITE_EXPIRES, WorkspaceClient, type WorkspaceInfo, type WorkspaceInvitation, type WorkspaceMember, loadConfig, resolveAuth };