kagura-memory 0.2.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -9,85 +9,6 @@
9
9
  * Fields that carry a default in the Python models (including `None`
10
10
  * defaults) are optional here — servers may omit them.
11
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
12
  /** An embedding model available on the server. */
92
13
  interface EmbeddingModel {
93
14
  name: string;
@@ -597,6 +518,54 @@ interface Edge {
597
518
  /** ISO 8601 datetime string. */
598
519
  last_updated?: string | null;
599
520
  }
521
+ /**
522
+ * A geographic point attached to a memory under `details.location`.
523
+ *
524
+ * This is what makes a memory reachable from `recallNearby()`. Any memory
525
+ * type can carry one; the server validates the shape.
526
+ *
527
+ * `lat`/`lon` are typed `number` deliberately: argument coercion does not
528
+ * recurse into `details`, so string-typed numerics (`"35.68"`) are rejected
529
+ * server-side with HTTP 422 rather than silently parsed.
530
+ *
531
+ * Caveat: `updateMemory()` / PATCH replace `details` wholesale. Resend
532
+ * `location` when updating details, or the memory silently drops off the
533
+ * spatial axis.
534
+ */
535
+ interface MemoryLocation {
536
+ /** Latitude in decimal degrees (-90..90). */
537
+ lat: number;
538
+ /** Longitude in decimal degrees (-180..180). */
539
+ lon: number;
540
+ /** Short human label, e.g. a place name. */
541
+ label?: string;
542
+ /** Free-form descriptive text about the place. */
543
+ text?: string;
544
+ }
545
+ /**
546
+ * One entry in a `recall_nearby` result list, ordered nearest first.
547
+ *
548
+ * `details` is the memory's full details object; when the memory was
549
+ * stored with a location it contains `location: MemoryLocation`.
550
+ */
551
+ interface NearbyMemory {
552
+ memory_id: string;
553
+ summary: string;
554
+ type: string;
555
+ details?: Record<string, unknown> | null;
556
+ /** Great-circle distance from the query point, in meters. */
557
+ distance_m: number;
558
+ }
559
+ /** Response from `recall_nearby`: memories near a point, nearest first. */
560
+ interface RecallNearbyResponse {
561
+ status: string;
562
+ results: NearbyMemory[];
563
+ context_id: string;
564
+ context_name: string;
565
+ context_display_name?: string | null;
566
+ context_is_private?: boolean;
567
+ context_is_locked?: boolean;
568
+ }
600
569
  /**
601
570
  * A tag with its usage count and last-used timestamp.
602
571
  *
@@ -1062,10 +1031,26 @@ interface RememberOptions {
1062
1031
  sourceType?: SourceType;
1063
1032
  /** Why the memory exists and how to use it (max 2000 chars). */
1064
1033
  contextSummary?: string;
1065
- /** Structured details JSON, stored as-is. */
1034
+ /**
1035
+ * Structured details JSON, stored as-is.
1036
+ *
1037
+ * A `location: {@link MemoryLocation}` here is what makes the memory
1038
+ * reachable from {@link recallNearby}. `lat`/`lon` must be JSON numbers —
1039
+ * argument coercion does not recurse into `details`, so string-typed
1040
+ * numerics are rejected server-side with HTTP 422.
1041
+ */
1066
1042
  details?: Record<string, unknown>;
1067
1043
  /** Open-ended context metadata JSON. */
1068
1044
  context?: Record<string, unknown>;
1045
+ /**
1046
+ * UUID of an existing memory this one replaces.
1047
+ *
1048
+ * Creates a supersede edge: the old memory is shadowed out of default
1049
+ * recall but stays restorable and reachable via
1050
+ * `recall({ includeSuperseded: true })` and {@link explore}. Prefer this
1051
+ * over {@link forget} + `remember`, which destroys the history.
1052
+ */
1053
+ supersedes?: string;
1069
1054
  /**
1070
1055
  * When the memory is surfaced. `"on_recall"` (default) leaves it to
1071
1056
  * probabilistic recall; `"always"` pins it so every loadPinned call
@@ -1105,6 +1090,14 @@ interface UpdateMemoryOptions {
1105
1090
  importance?: number;
1106
1091
  tags?: string[];
1107
1092
  contextSummary?: string;
1093
+ /**
1094
+ * Structured details JSON. **Replaces `details` wholesale** — the server
1095
+ * does not deep-merge. Round-trip any keys you want to keep (notably
1096
+ * `location`, see {@link MemoryLocation}) or they are silently dropped.
1097
+ *
1098
+ * Omitted from the request when `undefined`; pass `{}` to clear.
1099
+ */
1100
+ details?: Record<string, unknown>;
1108
1101
  /** `"always"` pins, `"on_recall"` unpins; omit to leave unchanged. */
1109
1102
  deliveryMode?: DeliveryMode;
1110
1103
  }
@@ -1156,6 +1149,16 @@ interface ListTagsOptions {
1156
1149
  sort?: "count" | "recent" | "alpha";
1157
1150
  /** Case-insensitive prefix filter (max 200 chars). */
1158
1151
  prefix?: string;
1152
+ /**
1153
+ * Multi-tag AND drill-down: restrict the vocabulary to memories whose
1154
+ * tags contain **all** of these values (`tags @> with_tags`), and exclude
1155
+ * these values from the returned tags.
1156
+ *
1157
+ * Combine with `prefix` for server-side faceted browsing — one call per
1158
+ * drill-down level, no local index. An empty array is a no-op filter and
1159
+ * is not sent.
1160
+ */
1161
+ withTags?: string[];
1159
1162
  }
1160
1163
  interface ListMemoriesOptions {
1161
1164
  /** Context UUID; omit for the caller's cross-context view. */
@@ -1332,6 +1335,38 @@ declare class KaguraClient {
1332
1335
  /** Maximum results (default 20, server max 100). */
1333
1336
  k?: number;
1334
1337
  }): Promise<ToolResult>;
1338
+ /**
1339
+ * List memories near a geographic point, nearest first, each carrying
1340
+ * `distance_m`. The WHERE axis — a deterministic spatial query over
1341
+ * stored `details.location` coordinates, not semantic search (use
1342
+ * {@link recall} for topic search). Mirrors {@link recallUpcoming}.
1343
+ *
1344
+ * Store a location with
1345
+ * `remember({ details: { location: { lat, lon, label } } })`; see
1346
+ * {@link MemoryLocation}. Any memory type can carry one.
1347
+ *
1348
+ * Note: {@link updateMemory} replaces `details` wholesale, so resend
1349
+ * `location` when updating details or the memory drops off this axis.
1350
+ *
1351
+ * `radiusM` is clamped server-side to [1, 1_000_000]; it is forwarded
1352
+ * unchanged rather than pre-clamped here, so the server stays the single
1353
+ * authority on the bound.
1354
+ *
1355
+ * @throws Error if `lat`/`lon` are not finite numbers in range. The
1356
+ * server rejects these with HTTP 422; failing locally turns the common
1357
+ * swapped-lat/lon mistake into an immediate, named error.
1358
+ */
1359
+ recallNearby(options: {
1360
+ contextId: string;
1361
+ /** Query latitude (-90..90). */
1362
+ lat: number;
1363
+ /** Query longitude (-180..180). */
1364
+ lon: number;
1365
+ /** Search radius in meters (default 1000). */
1366
+ radiusM?: number;
1367
+ /** Maximum results (default 20; the server clamps to 1-100). */
1368
+ k?: number;
1369
+ }): Promise<RecallNearbyResponse>;
1335
1370
  /**
1336
1371
  * Deterministically load a context's pinned (`delivery_mode="always"`)
1337
1372
  * memories — the complete, unranked pinned set on every call.
@@ -1845,7 +1880,7 @@ declare class KaguraIngestError extends KaguraError {
1845
1880
  * Package version string, shared across client modules (User-Agent, MCP
1846
1881
  * clientInfo). Kept in sync with package.json by the release process.
1847
1882
  */
1848
- declare const SDK_VERSION = "0.1.0";
1883
+ declare const SDK_VERSION = "0.5.0";
1849
1884
 
1850
1885
  /**
1851
1886
  * Auth contracts shared by the credential resolver and the HTTP clients.
@@ -2667,4 +2702,482 @@ interface ResolveAuthOptions {
2667
2702
  */
2668
2703
  declare function resolveAuth(options?: ResolveAuthOptions): ResolvedAuth;
2669
2704
 
2670
- export { type Agent, type AgentBinding, type AgentBindingScopeOptions, type AgentBootstrapAgent, type AgentBootstrapBinding, type AgentBootstrapComponent, type AgentBootstrapComponentName, type AgentBootstrapCorrelation, type AgentBootstrapResponse, type AgentEnforcementMode, type AgentStatus, type AgentWritePolicy, AgentsClient, type AnalysisResult, type Artifact, type AuthProvider, type AuthSource, type BindAgentContextOptions, 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 GetAgentBootstrapOptions, 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 RegisterAgentOptions, 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 UpdateAgentBindingOptions, type UpdateAgentOptions, 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 };
2705
+ /**
2706
+ * Persistent OAuth credentials for the Kagura SDK (port of
2707
+ * auth/credentials.py).
2708
+ *
2709
+ * This module owns three responsibilities:
2710
+ *
2711
+ * 1. The `OAuthCredentials` / `CredentialsFile` shapes and their JSON
2712
+ * (de)serialization. The on-disk format at `~/.kagura/credentials.json`
2713
+ * is SHARED with the Python CLI — keys stay snake_case on disk
2714
+ * (`default_profile`, `profiles`, `access_token`, ...), timestamps are
2715
+ * Z-suffixed UTC ISO-8601.
2716
+ * 2. Atomic, mode-0600 read/write of the credentials file with a mode-0700
2717
+ * parent directory (permissions are best-effort where the platform,
2718
+ * e.g. Windows/NTFS, does not honor POSIX bits).
2719
+ * 3. A process-wide cache (`getSharedState`) so concurrent clients pointing
2720
+ * at the same credentials file share a single in-process mutex, ensuring
2721
+ * only one `/oauth/token/` refresh fires per cycle even when many client
2722
+ * instances run side by side.
2723
+ *
2724
+ * Multi-process coordination is handled in two layers: the in-process
2725
+ * `AsyncMutex` coalesces refreshes *within* a process, and the
2726
+ * cross-process lock in `filelock.ts` (acquired inside the refresh path)
2727
+ * re-reads the on-disk token after locking and skips the `/oauth/token/`
2728
+ * round-trip when another process already rotated it.
2729
+ */
2730
+
2731
+ /**
2732
+ * Refresh `accessToken` when within this many seconds of `expiresAt`.
2733
+ *
2734
+ * Default of 5 minutes mirrors common OAuth2 client conventions and gives
2735
+ * enough headroom for a slow refresh round-trip.
2736
+ */
2737
+ declare const REFRESH_SKEW_SEC = 300;
2738
+ /**
2739
+ * Default location of the credentials file: `~/.kagura/credentials.json`.
2740
+ * Tests pass an explicit `home`/path instead of touching the real one.
2741
+ */
2742
+ declare function defaultCredentialsPath(home?: string): string;
2743
+ /** A single profile's OAuth2 credentials (camelCase in memory, snake_case on disk). */
2744
+ interface OAuthCredentials {
2745
+ server: string;
2746
+ mcpUrl: string;
2747
+ clientId: string;
2748
+ accessToken: string;
2749
+ refreshToken: string;
2750
+ tokenType: string;
2751
+ expiresAt: Date;
2752
+ scope: string;
2753
+ workspaceId: string;
2754
+ workspaceName: string;
2755
+ userEmail: string;
2756
+ issuedAt: Date;
2757
+ }
2758
+ /** True when `accessToken` is past `expiresAt - skewSeconds`. */
2759
+ declare function isExpired(creds: OAuthCredentials, skewSeconds?: number): boolean;
2760
+ /**
2761
+ * Return a copy of `creds` with the rotated token fields applied.
2762
+ *
2763
+ * `refreshToken` is rotated when the server returns a new one (RFC 6749
2764
+ * §10.4 recommended) — pass `null`/omit to preserve the stored one.
2765
+ * `scope` is updated when the server narrows or widens the grant.
2766
+ */
2767
+ declare function withRefreshed(creds: OAuthCredentials, fields: {
2768
+ accessToken: string;
2769
+ refreshToken?: string | null;
2770
+ expiresAt: Date;
2771
+ scope?: string | null;
2772
+ }): OAuthCredentials;
2773
+ /** Top-level wrapper for `~/.kagura/credentials.json`. */
2774
+ interface CredentialsFile {
2775
+ version: number;
2776
+ defaultProfile: string;
2777
+ profiles: Record<string, OAuthCredentials>;
2778
+ }
2779
+ declare function emptyCredentialsFile(): CredentialsFile;
2780
+ /** Return the named profile, or the default, or `null` if missing. */
2781
+ declare function getProfile(cf: CredentialsFile, name?: string | null): OAuthCredentials | null;
2782
+ /** Insert or replace a profile. The first profile becomes default. */
2783
+ declare function setProfile(cf: CredentialsFile, name: string, creds: OAuthCredentials): void;
2784
+ /** Remove a profile in memory if present; repoints a deleted default. */
2785
+ declare function removeProfile(cf: CredentialsFile, name: string): void;
2786
+ /**
2787
+ * Read and parse the credentials file.
2788
+ *
2789
+ * Returns an empty `CredentialsFile` when the file is missing, unreadable,
2790
+ * or malformed — the caller can distinguish "no profile" via
2791
+ * `getProfile(cf) === null`. On a present file, parent directory and file
2792
+ * permissions are coerced to 0700/0600 (best-effort).
2793
+ */
2794
+ declare function loadCredentialsFile(credentialsPath?: string): CredentialsFile;
2795
+ /** Atomically persist a `CredentialsFile` to disk. */
2796
+ declare function saveCredentialsFile(cf: CredentialsFile, credentialsPath?: string): void;
2797
+ /**
2798
+ * Load, mutate one profile, and atomically save back.
2799
+ *
2800
+ * The read-modify-write is wrapped in the cross-process lock from
2801
+ * `filelock.ts` so concurrent writers in *different* processes cannot lose
2802
+ * an update. The lock is on a sibling `credentials.json.lock`, not the
2803
+ * file itself, so it never races the atomic rename in
2804
+ * `saveCredentialsFile`.
2805
+ */
2806
+ declare function updateProfile(profileName: string, creds: OAuthCredentials, credentialsPath?: string): Promise<void>;
2807
+ /**
2808
+ * Set `default_profile` to an existing profile (backs `kagura auth use`).
2809
+ *
2810
+ * Unlike `setProfile`'s implicit first-wins promotion, this is a
2811
+ * *deliberate* default selection, wrapped in the same cross-process lock as
2812
+ * `updateProfile` so a concurrent refresh/login cannot clobber it.
2813
+ *
2814
+ * @throws Error if `profileName` is not an existing profile — selecting a
2815
+ * non-existent default would silently break resolution. (Python raises
2816
+ * `KeyError` here; a plain `Error` is the TS equivalent.)
2817
+ */
2818
+ declare function setDefaultProfile(profileName: string, credentialsPath?: string): Promise<void>;
2819
+ /**
2820
+ * Remove a profile and save. No-op if the profile is absent.
2821
+ *
2822
+ * The read-modify-write is wrapped in the cross-process lock so a logout
2823
+ * (delete) racing a concurrent token refresh (update) in a sibling process
2824
+ * cannot clobber a freshly written token. The absent-profile early return
2825
+ * runs *inside* the lock so the membership check and the save observe one
2826
+ * consistent snapshot (no TOCTOU).
2827
+ */
2828
+ declare function deleteProfile(profileName: string, credentialsPath?: string): Promise<void>;
2829
+ /**
2830
+ * Remove the entire credentials file (`kagura auth logout --all`).
2831
+ *
2832
+ * Missing file is treated as success — logout is idempotent.
2833
+ */
2834
+ declare function deleteCredentialsFile(credentialsPath?: string): void;
2835
+ /**
2836
+ * Minimal promise-chaining mutex — the `asyncio.Lock` equivalent.
2837
+ *
2838
+ * `runExclusive` calls are serialized in arrival order; a rejection inside
2839
+ * one critical section does not poison the chain for later callers.
2840
+ */
2841
+ declare class AsyncMutex {
2842
+ private tail;
2843
+ runExclusive<T>(fn: () => T | Promise<T>): Promise<T>;
2844
+ }
2845
+ /**
2846
+ * Mutable per-(path, profile) state shared across clients.
2847
+ *
2848
+ * The `mutex` is shared across **all profiles in the same file** — not
2849
+ * per-(path, profile) — so two profiles refreshing concurrently can't both
2850
+ * read-modify-write the file and clobber each other's update.
2851
+ */
2852
+ interface SharedCredentialsState {
2853
+ credentials: OAuthCredentials;
2854
+ profileName: string;
2855
+ /** Resolved absolute path of the credentials file. */
2856
+ path: string;
2857
+ mutex: AsyncMutex;
2858
+ }
2859
+ /**
2860
+ * `AuthProvider` that supplies the current access token as a Bearer header.
2861
+ *
2862
+ * Holds a reference to a shared `SharedCredentialsState`, so concurrent
2863
+ * client instances pointing at the same credentials file all coalesce
2864
+ * refresh calls through a single in-process mutex. When the access token
2865
+ * is within `REFRESH_SKEW_SEC` of expiry the mutex is acquired, the
2866
+ * refresh runs once, and every other in-flight `getAuthHeader` call waits
2867
+ * and then sees the rotated token.
2868
+ *
2869
+ * (The Python SDK expresses this as an `httpx.Auth` subclass; with `fetch`
2870
+ * there is no request-hook layer, so clients ask for a fresh header value
2871
+ * before each request instead.)
2872
+ */
2873
+ declare class KaguraOAuth implements AuthProvider {
2874
+ private readonly state;
2875
+ private readonly fetchImpl;
2876
+ constructor(state: SharedCredentialsState, options?: {
2877
+ fetch?: typeof globalThis.fetch;
2878
+ });
2879
+ /**
2880
+ * Return `Bearer <access_token>`, refreshing first when the token is
2881
+ * within the skew window.
2882
+ */
2883
+ getAuthHeader(): Promise<string>;
2884
+ /**
2885
+ * Refresh the access token if it's within the skew window.
2886
+ *
2887
+ * The mutex is held across the entire read-check-refresh-persist
2888
+ * sequence so a second caller waiting on it will find the token already
2889
+ * rotated when it acquires.
2890
+ */
2891
+ private maybeRefresh;
2892
+ /**
2893
+ * Unconditionally refresh the access token, ignoring the skew window.
2894
+ *
2895
+ * Used on an upstream 401: the token was rejected server-side (rotated /
2896
+ * revoked out-of-band) even though it is not yet within the skew window.
2897
+ * The same in-process mutex serializes this with skew-driven refreshes.
2898
+ * Cross-process dedup is handled in `refreshLocked` via the
2899
+ * rejected-token identity check.
2900
+ */
2901
+ forceRefresh(options?: {
2902
+ scope?: string;
2903
+ }): Promise<void>;
2904
+ /**
2905
+ * Refresh `/oauth/token/` once across all processes. Caller holds the
2906
+ * in-process mutex.
2907
+ *
2908
+ * After acquiring the cross-process file lock, re-read the credentials
2909
+ * from disk and **skip the network call when another process already
2910
+ * rotated the token** — "skip" means "adopt the on-disk result", never
2911
+ * "leave the stale in-memory token in place".
2912
+ *
2913
+ * `expectedStaleToken` governs the "already rotated?" predicate:
2914
+ * `null` (skew path) → skip when the on-disk token is no longer within
2915
+ * the skew window. A token string (401 path) → skip only when the
2916
+ * on-disk token *differs* from the rejected one (a 401 is independent of
2917
+ * `expiresAt`).
2918
+ */
2919
+ private refreshLocked;
2920
+ /** Whether `disk` shows another process already produced a usable token. */
2921
+ private alreadyRotated;
2922
+ /** Hit `/oauth/token/` from `base` and persist. Caller holds both locks. */
2923
+ private networkRefreshAndSave;
2924
+ }
2925
+
2926
+ /**
2927
+ * OAuth2 RFC 8628 device authorization grant — stateless async helpers
2928
+ * (port of auth/device_flow.py).
2929
+ *
2930
+ * Pure-function API: every entry point takes the server base URL plus the
2931
+ * relevant parameters and returns a plain object. No CLI, no terminal IO,
2932
+ * no global state.
2933
+ *
2934
+ * The Python SDK constructs a dedicated unauthenticated `httpx.AsyncClient`
2935
+ * so the SDK's `Authorization: Bearer` header cannot leak into `/oauth/*`
2936
+ * requests (device-flow uses `client_id` body-parameter authentication, RFC
2937
+ * 8628 §3.1 `token_endpoint_auth_method='none'`). With `fetch` there is no
2938
+ * client object; the same isolation holds because each request here sets
2939
+ * its own headers and never an `Authorization` header. The `fetch`
2940
+ * implementation is injectable on every function so tests can stub HTTP.
2941
+ */
2942
+ /** The pre-registered public client ID seeded by memory-cloud #624. */
2943
+ declare const DEFAULT_CLIENT_ID = "kagura-cli";
2944
+ declare const DEVICE_FLOW_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
2945
+ declare const REFRESH_TOKEN_GRANT_TYPE = "refresh_token";
2946
+ /** RFC 8628 §3.2 device authorization response. */
2947
+ interface DeviceAuthorizationResponse {
2948
+ deviceCode: string;
2949
+ userCode: string;
2950
+ verificationUri: string;
2951
+ verificationUriComplete: string;
2952
+ expiresIn: number;
2953
+ /** Polling interval in seconds. */
2954
+ interval: number;
2955
+ /** = now + expiresIn. */
2956
+ expiresAt: Date;
2957
+ }
2958
+ /**
2959
+ * RFC 8628 §3.5 / RFC 6749 §5.1 successful token response.
2960
+ *
2961
+ * `expiresAt` is computed once at receipt time so a paused or suspended
2962
+ * laptop never sees a negative TTL after wake.
2963
+ */
2964
+ interface TokenResponse {
2965
+ accessToken: string;
2966
+ refreshToken: string;
2967
+ tokenType: string;
2968
+ expiresAt: Date;
2969
+ scope: string;
2970
+ userEmail: string;
2971
+ workspaceId: string;
2972
+ workspaceName: string;
2973
+ }
2974
+ /** Common HTTP knobs: injectable `fetch` so tests can stub the transport. */
2975
+ interface OAuthHttpOptions {
2976
+ fetch?: typeof globalThis.fetch;
2977
+ }
2978
+ /**
2979
+ * POST `{server}/api/v1/oauth/device/authorize` and parse the response.
2980
+ *
2981
+ * memory-cloud's device/authorize accepts JSON, unlike the /oauth/token/ +
2982
+ * /oauth/revoke endpoints which take application/x-www-form-urlencoded.
2983
+ */
2984
+ declare function authorizeDevice(server: string, options?: OAuthHttpOptions & {
2985
+ clientId?: string;
2986
+ scope?: string;
2987
+ }): Promise<DeviceAuthorizationResponse>;
2988
+ interface PollForTokenOptions extends OAuthHttpOptions {
2989
+ clientId: string;
2990
+ deviceCode: string;
2991
+ /** RFC 8628 polling interval in seconds. */
2992
+ interval: number;
2993
+ expiresAt: Date;
2994
+ /**
2995
+ * Injectable sleep (milliseconds) so tests can supply a no-op or
2996
+ * counter-based stub without waiting real seconds.
2997
+ */
2998
+ sleep?: (ms: number) => Promise<void>;
2999
+ }
3000
+ /**
3001
+ * Poll `{server}/api/v1/oauth/token/` until the user approves or denies.
3002
+ *
3003
+ * The first poll fires immediately (no initial sleep) so a fast approval
3004
+ * never waits a whole interval; sleeps only happen between retries after
3005
+ * `authorization_pending` / `slow_down`.
3006
+ *
3007
+ * @throws KaguraAuthDeniedError user clicked "Deny" at the consent screen
3008
+ * (server returns `access_denied`).
3009
+ * @throws KaguraAuthExpiredError the `device_code` lifetime elapsed without
3010
+ * approval (server returns `expired_token`, or `expiresAt` passed locally).
3011
+ * @throws KaguraAuthError any other OAuth error or unexpected response.
3012
+ * @throws KaguraConnectionError network failure during polling.
3013
+ */
3014
+ declare function pollForToken(server: string, options: PollForTokenOptions): Promise<TokenResponse>;
3015
+ interface RefreshAccessTokenOptions extends OAuthHttpOptions {
3016
+ clientId: string;
3017
+ refreshToken: string;
3018
+ scope?: string | null;
3019
+ }
3020
+ /**
3021
+ * POST `{server}/api/v1/oauth/token/` with `grant_type=refresh_token`.
3022
+ *
3023
+ * When `scope` is supplied, the server may reject the call with
3024
+ * `insufficient_scope` / `invalid_scope` if the grant doesn't cover it.
3025
+ *
3026
+ * @throws KaguraAuthExpiredError refresh token is invalid or expired
3027
+ * (server returns `invalid_grant`).
3028
+ * @throws KaguraAuthError any other OAuth error.
3029
+ * @throws KaguraConnectionError network failure.
3030
+ */
3031
+ declare function refreshAccessToken(server: string, options: RefreshAccessTokenOptions): Promise<TokenResponse>;
3032
+ /**
3033
+ * POST `{server}/api/v1/oauth/revoke`. Best-effort — never throws.
3034
+ *
3035
+ * Returns `true` on success, `false` on any failure. The caller
3036
+ * (`kagura auth logout`) deletes the local profile regardless of the
3037
+ * return value, on the principle that local logout must succeed even when
3038
+ * the server is unreachable.
3039
+ */
3040
+ declare function revokeToken(server: string, options: OAuthHttpOptions & {
3041
+ token: string;
3042
+ clientId?: string;
3043
+ }): Promise<boolean>;
3044
+
3045
+ /**
3046
+ * Interactive OAuth login — the one step the SDK could not do on its own.
3047
+ *
3048
+ * `deviceFlow.ts` provides the stateless RFC 8628 primitives and
3049
+ * `credentials.ts` the Python-CLI-compatible store; this module is the thin
3050
+ * orchestrator that joins them: authorize → hand the user code to the host
3051
+ * app → poll → persist. It is what lets a TypeScript-only consumer (an
3052
+ * Electron app, a CLI of its own) obtain credentials instead of requiring
3053
+ * the user to install and run the Python `kagura auth login` first.
3054
+ *
3055
+ * Deliberately still no terminal IO and no browser launching: `onUserCode`
3056
+ * hands the code and verification URI back to the caller, which owns how it
3057
+ * is displayed. The only side effect is the credentials file write.
3058
+ */
3059
+
3060
+ /**
3061
+ * Scope requested when `login()` is called without one.
3062
+ *
3063
+ * Read **and** write, matching the Python CLI's `kagura auth login`
3064
+ * default. The credentials file is shared between both SDKs, so a profile
3065
+ * must not end up with different authority depending on which one wrote
3066
+ * it. Opt down with `scope: READ_ONLY_SCOPE` — the CLI's `--read-only`.
3067
+ */
3068
+ declare const DEFAULT_SCOPE = "memory:read memory:write";
3069
+ /** Read-only scope; the Python CLI's `--read-only`. */
3070
+ declare const READ_ONLY_SCOPE = "memory:read";
3071
+ interface LoginOptions {
3072
+ /**
3073
+ * MCP endpoint to log into. The OAuth endpoints are derived from it, and
3074
+ * both URLs are stored on the profile so the pair can never drift apart.
3075
+ *
3076
+ * Resolution mirrors the Python CLI's `--server` chain: this option,
3077
+ * then `KAGURA_MCP_URL`, then {@link DEFAULT_MCP_URL}. Plain HTTP is
3078
+ * rejected for non-loopback hosts — the flow carries a bearer token.
3079
+ */
3080
+ mcpUrl?: string;
3081
+ /** Environment source override (for tests; default: `process.env`). */
3082
+ env?: Record<string, string | undefined>;
3083
+ /** OAuth client ID (default {@link DEFAULT_CLIENT_ID}). */
3084
+ clientId?: string;
3085
+ /**
3086
+ * Requested scope. Defaults to {@link DEFAULT_SCOPE} (read + write), the
3087
+ * same default as the Python CLI's `kagura auth login`. Pass
3088
+ * {@link READ_ONLY_SCOPE} for the CLI's `--read-only` behaviour.
3089
+ */
3090
+ scope?: string;
3091
+ /** Profile name to store under (default `"default"`). */
3092
+ profile?: string;
3093
+ /** Credentials file path (default `~/.kagura/credentials.json`). */
3094
+ credentialsPath?: string;
3095
+ /**
3096
+ * Make this profile the default even when others already exist.
3097
+ *
3098
+ * Off by default: the first profile ever written is promoted
3099
+ * automatically, so adding a second one leaves the user's existing
3100
+ * default alone unless they ask for the switch.
3101
+ */
3102
+ setAsDefault?: boolean;
3103
+ /**
3104
+ * Called once with the device-authorization response before polling
3105
+ * starts — display `userCode` and `verificationUri` (or open
3106
+ * `verificationUriComplete`) here.
3107
+ *
3108
+ * Awaited, and a throw aborts the login before any polling or disk
3109
+ * write, so a host app that cannot show the code fails fast.
3110
+ */
3111
+ onUserCode?: (auth: DeviceAuthorizationResponse) => void | Promise<void>;
3112
+ /** Injectable fetch (tests / custom agents). */
3113
+ fetch?: typeof globalThis.fetch;
3114
+ /** Injectable sleep in milliseconds, used between polls. */
3115
+ sleep?: (ms: number) => Promise<void>;
3116
+ }
3117
+ /**
3118
+ * Run the full device-authorization login and persist the result.
3119
+ *
3120
+ * @returns the credentials that were written.
3121
+ * @throws KaguraAuthDeniedError the user denied at the consent screen.
3122
+ * @throws KaguraAuthExpiredError the device code expired before approval.
3123
+ * @throws KaguraAuthError propagated from the device-flow primitives on a
3124
+ * protocol/response failure.
3125
+ * @throws KaguraConnectionError the server was unreachable.
3126
+ *
3127
+ * Nothing is written unless the token exchange succeeds, so a failed login
3128
+ * never disturbs an existing profile. A response with no `refresh_token`
3129
+ * warns and still persists (matching the Python CLI); check the returned
3130
+ * `refreshToken` if the caller needs to react.
3131
+ */
3132
+ declare function login(options?: LoginOptions): Promise<OAuthCredentials>;
3133
+
3134
+ /**
3135
+ * Explicit credential refresh — the `kagura auth refresh` counterpart.
3136
+ *
3137
+ * Auto-refresh already happens inside {@link KaguraOAuth} as tokens near
3138
+ * expiry, so this is for the cases that skew-driven rotation cannot cover:
3139
+ * a token revoked out-of-band (rejected server-side while still outside
3140
+ * the skew window), a deliberate scope change, or a pre-flight refresh
3141
+ * before a long batch.
3142
+ *
3143
+ * Like `login()`, this owns no terminal IO — the device-flow fallback
3144
+ * hands the user code back through `onUserCode`.
3145
+ */
3146
+
3147
+ interface RefreshOptions {
3148
+ /** Profile to refresh (default: the file's default profile). */
3149
+ profile?: string;
3150
+ /** Credentials file path (default `~/.kagura/credentials.json`). */
3151
+ credentialsPath?: string;
3152
+ /**
3153
+ * Request a different scope.
3154
+ *
3155
+ * Narrowing goes through the refresh grant silently. Widening needs
3156
+ * fresh consent, so a server rejection triggers a full device flow —
3157
+ * see {@link RefreshOptions.onUserCode}.
3158
+ */
3159
+ scope?: string;
3160
+ /**
3161
+ * Called with the device-authorization response when a scope widening
3162
+ * forces re-consent. Required in practice for that path: without it the
3163
+ * user is never shown the code, and polling times out.
3164
+ */
3165
+ onUserCode?: (auth: DeviceAuthorizationResponse) => void | Promise<void>;
3166
+ /** Injectable fetch (tests / custom agents). */
3167
+ fetch?: typeof globalThis.fetch;
3168
+ /** Injectable sleep in milliseconds, used between device-flow polls. */
3169
+ sleep?: (ms: number) => Promise<void>;
3170
+ }
3171
+ /**
3172
+ * Refresh a stored profile's access token and persist the result.
3173
+ *
3174
+ * @returns the credentials that were written.
3175
+ * @throws Error if the named profile does not exist.
3176
+ * @throws KaguraAuthExpiredError the refresh token is no longer valid —
3177
+ * the stored profile is left untouched so it can still be inspected.
3178
+ * @throws KaguraAuthError other protocol/response failures.
3179
+ * @throws KaguraConnectionError the server was unreachable.
3180
+ */
3181
+ declare function refresh(options?: RefreshOptions): Promise<OAuthCredentials>;
3182
+
3183
+ export { type Agent, type AgentBinding, type AgentBindingScopeOptions, type AgentBootstrapAgent, type AgentBootstrapBinding, type AgentBootstrapComponent, type AgentBootstrapComponentName, type AgentBootstrapCorrelation, type AgentBootstrapResponse, type AgentEnforcementMode, type AgentStatus, type AgentWritePolicy, AgentsClient, type AuthProvider, type AuthSource, type BindAgentContextOptions, type ContextDetail, type ContextInfo, type ContextStats, type CostBreakdown, type CreateContextOptions, type CreateInvitationOptions, type CreateTokenOptions, type CredentialsFile, DEFAULT_CLIENT_ID, DEFAULT_MCP_URL, DEFAULT_REST_BASE_URL, DEFAULT_SCOPE, DEVICE_FLOW_GRANT_TYPE, type DeliveryMode, type DeviceAuthorizationResponse, type DuplicateMemoryInfo, type DuplicatePair, type DuplicatesResponse, type Edge, type EmbeddingModel, type EmbeddingModelsResponse, type EmbeddingStatus, type FailedMemoryInfo, type FieldDefinition, type FileDownloadUrlResponse, type FileListResponse, type FileObject, type FileReserveResponse, FilesClient, type FilesClientOptions, type FromMcpUrlOptions, type GetAgentBootstrapOptions, 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, KaguraOAuth, KaguraQuotaError, KaguraRateLimitError, KaguraRestClient, type KaguraRestClientOptions, type ListInvitationsOptions, type ListMemoriesOptions, type ListResourceEventsOptions, type ListTagsOptions, type ListTagsResponse, type ListTokensOptions, type LoadConfigOptions, type LoginOptions, MIN_SERVER_VERSION, type MemberAPIKey, type MemoryListItem, type MemoryListResponse, type MemoryLocation, type MemoryStatItem, type MemoryStatsResponse, type NearbyMemory, type OAuthAuthResult, type OAuthCredentials, type OAuthHttpOptions, type PaginatedResourceTokensResponse, type PollForTokenOptions, READ_ONLY_SCOPE, REFRESH_SKEW_SEC, REFRESH_TOKEN_GRANT_TYPE, type RecallNearbyResponse, type RecallOptions, type RefreshAccessTokenOptions, type RefreshOptions, type RegisterAgentOptions, 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 SetupResourceOptions, type SharedCredentialsState, type SleepAction, type SleepReport, type SleepReportDetail, type SleepRunStatus, type SourceType, type StaticAuthResult, type StaticSource, type TagInfo, type TokenResponse, type ToolResult, type UpdateAgentBindingOptions, type UpdateAgentOptions, 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, authorizeDevice, defaultCredentialsPath, deleteCredentialsFile, deleteProfile, emptyCredentialsFile, getProfile, isExpired, loadConfig, loadCredentialsFile, login, pollForToken, refresh, refreshAccessToken, removeProfile, resolveAuth, revokeToken, saveCredentialsFile, setDefaultProfile, setProfile, updateProfile, withRefreshed };