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