@ragable/sdk 0.7.6 → 0.7.7

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
@@ -76,11 +76,6 @@ type ColumnValue<D extends RagableDatabase, T extends RagableTableNames<D>, C ex
76
76
  declare function bindFetch(custom?: typeof fetch): typeof fetch;
77
77
  /** Hosted Ragable HTTP API base (`…/api`) — used by all SDK clients (not configurable). */
78
78
  declare const DEFAULT_RAGABLE_API_BASE = "https://ragable-341305259977.asia-southeast1.run.app/api";
79
- interface RagableClientOptions {
80
- apiKey: string;
81
- fetch?: typeof fetch;
82
- headers?: HeadersInit;
83
- }
84
79
  type RequestOptions = Omit<RequestInit, "body"> & {
85
80
  body?: unknown;
86
81
  };
@@ -124,116 +119,20 @@ declare class RagableTimeoutError extends RagableSdkError {
124
119
  toJSON(): Record<string, unknown>;
125
120
  }
126
121
  declare function extractErrorMessage(payload: unknown, fallback: string): string;
127
- declare class RagableRequestClient {
128
- private readonly apiKey;
129
- private readonly baseUrl;
130
- private readonly fetchImpl;
131
- private readonly defaultHeaders;
132
- constructor(options: RagableClientOptions);
133
- toUrl(path: string): string;
134
- request<T>(path: string, options?: RequestOptions): Promise<T>;
135
- /**
136
- * Low-level fetch with API key and JSON body encoding. Caller handles status and body.
137
- */
138
- rawFetch(path: string, options?: RequestOptions): Promise<Response>;
139
- private parseResponseBody;
140
- }
141
122
 
142
- interface ShiftIndex {
143
- id: string;
144
- name: string;
145
- description: string | null;
146
- dimensions: number;
147
- embeddingModel: string;
148
- status: string;
149
- entryCount?: number;
150
- createdAt: string;
151
- updatedAt: string;
152
- }
153
- interface ShiftEntry {
154
- id: string;
155
- content: string;
156
- metadata: unknown;
157
- chunkIndex: number;
158
- createdAt: string;
159
- }
160
- interface ShiftSearchResult {
123
+ interface AgentChatMessage {
124
+ role: "user" | "assistant";
161
125
  content: string;
162
- score: number;
163
- metadata: unknown;
164
126
  }
165
- interface ShiftCreateIndexParams {
166
- name: string;
167
- description?: string;
168
- dimensions?: number;
169
- embeddingModel?: string;
170
- }
171
- interface ShiftUpdateIndexParams {
172
- name?: string;
173
- description?: string;
174
- }
175
- interface ShiftAddDocumentParams {
176
- content: string;
177
- metadata?: Record<string, unknown>;
178
- chunkSize?: number;
179
- chunkOverlap?: number;
180
- }
181
- type ShiftUploadableFile = Blob | ArrayBuffer | Uint8Array;
182
- interface ShiftUploadFileParams {
183
- file: ShiftUploadableFile;
184
- fileName?: string;
185
- contentType?: string;
186
- metadata?: Record<string, unknown>;
187
- chunkSize?: number;
188
- chunkOverlap?: number;
189
- }
190
- interface ShiftListEntriesParams {
191
- take?: number;
192
- skip?: number;
193
- }
194
- interface ShiftSearchParams {
195
- query: string;
196
- topK?: number;
197
- }
198
- interface ShiftIngestResponse {
199
- chunksCreated: number;
200
- entries: string[];
201
- extractedText?: string;
202
- message?: string;
203
- }
204
- interface ShiftListEntriesResponse {
205
- entries: ShiftEntry[];
206
- total: number;
207
- }
208
- declare class ShiftClient {
209
- private readonly client;
210
- readonly indexes: {
211
- list: () => Promise<{
212
- indexes: ShiftIndex[];
213
- }>;
214
- create: (params: ShiftCreateIndexParams) => Promise<ShiftIndex>;
215
- get: (indexId: string) => Promise<ShiftIndex>;
216
- update: (indexId: string, params: ShiftUpdateIndexParams) => Promise<ShiftIndex>;
217
- delete: (indexId: string) => Promise<{
218
- success: true;
219
- }>;
220
- };
221
- readonly documents: {
222
- create: (indexId: string, params: ShiftAddDocumentParams) => Promise<ShiftIngestResponse>;
223
- upload: (indexId: string, params: ShiftUploadFileParams) => Promise<ShiftIngestResponse>;
224
- };
225
- readonly entries: {
226
- list: (indexId: string, params?: ShiftListEntriesParams) => Promise<ShiftListEntriesResponse>;
227
- delete: (indexId: string, entryId: string) => Promise<{
228
- success: true;
229
- }>;
230
- };
231
- constructor(client: RagableRequestClient);
232
- search(indexId: string, params: ShiftSearchParams): Promise<{
233
- results: ShiftSearchResult[];
234
- }>;
127
+ interface AgentChatParams {
128
+ message: string;
129
+ history?: AgentChatMessage[];
130
+ /** Passed to `fetch` — aborts the HTTP request and SSE body. */
131
+ signal?: AbortSignal;
235
132
  }
236
-
133
+ type AgentStreamEvent = Record<string, unknown> & {
134
+ type: string;
135
+ };
237
136
  /**
238
137
  * First SSE frame for website project agents (`POST …/agents/:name/chat/stream`).
239
138
  */
@@ -477,61 +376,6 @@ declare function finalizeAgentChatUiTurn(segments: AgentChatUiSegment[], done: A
477
376
  */
478
377
  declare function runAgentChatStreamForUi(source: AsyncIterable<AgentStreamEvent>, handlers?: AgentChatStreamUiHandlers, options?: RunAgentChatStreamOptions): Promise<AgentChatUiStreamResult>;
479
378
 
480
- interface AgentSummary {
481
- id: string;
482
- name: string;
483
- description: string | null;
484
- active: boolean;
485
- createdAt: string;
486
- updatedAt: string;
487
- }
488
- interface AgentChatMessage {
489
- role: "user" | "assistant";
490
- content: string;
491
- }
492
- interface AgentChatParams {
493
- message: string;
494
- history?: AgentChatMessage[];
495
- /** Passed to `fetch` — aborts the HTTP request and SSE body. */
496
- signal?: AbortSignal;
497
- }
498
- /** Mirrors backend ExecutionResult JSON shape (traces are opaque in the SDK). */
499
- interface AgentChatResult {
500
- response: string;
501
- traces: unknown[];
502
- totalDurationMs: number;
503
- httpResponse?: unknown;
504
- }
505
- /**
506
- * Loose SSE event from POST /v1/agents/:id/chat/stream — narrows with `type` at runtime.
507
- */
508
- type AgentStreamEvent = Record<string, unknown> & {
509
- type: string;
510
- };
511
- declare class AgentsClient {
512
- private readonly client;
513
- constructor(client: RagableRequestClient);
514
- list(): Promise<{
515
- agents: AgentSummary[];
516
- }>;
517
- get(agentId: string): Promise<AgentSummary>;
518
- chat(agentId: string, params: AgentChatParams): Promise<AgentChatResult>;
519
- /**
520
- * Stream agent execution as SSE (`data: {json}` lines). Yields parsed JSON objects.
521
- */
522
- chatStream(agentId: string, params: AgentChatParams): AsyncGenerator<AgentStreamEvent, void, undefined>;
523
- /**
524
- * Stream an agent turn with callbacks; returns the final `done` payload plus streamed text.
525
- * Prefer this over manual iteration when building chat UIs against the server API key client.
526
- */
527
- runChatStream(agentId: string, params: AgentChatParams, handlers?: AgentChatStreamHandlers): Promise<AgentChatStreamResult>;
528
- /**
529
- * Stream with dashboard-style `AgentChat` ergonomics: {@link AgentChatStreamUiHandlers.onSegments}
530
- * / `onStreamingText` for live UI; returns a persisted-shaped assistant message on `done`.
531
- */
532
- runChatUi(agentId: string, params: AgentChatParams, handlers?: AgentChatStreamUiHandlers): Promise<AgentChatUiStreamResult>;
533
- }
534
-
535
379
  /** @deprecated Kept for backward compat with `database.query()`. Not used by PostgREST path. */
536
380
  interface BrowserSqlExecParams {
537
381
  databaseInstanceId: string;
@@ -1098,6 +942,191 @@ declare class Transport {
1098
942
  }
1099
943
  declare function parseTransportResponse<T>(response: Response): Promise<T>;
1100
944
 
945
+ /**
946
+ * Vercel AI SDK–style stream part types, used by both `client.ai.streamText`
947
+ * (Fireworks chunks via the Ragable proxy) and `client.agents.run` (existing
948
+ * agent SSE events). Keep this module zero-dep so it can be re-exported from
949
+ * the SDK entrypoint without dragging in agent/browser code.
950
+ */
951
+ type FinishReason = "stop" | "length" | "tool-calls" | "content-filter" | "error" | "unknown";
952
+ interface TokenUsage {
953
+ promptTokens: number;
954
+ completionTokens: number;
955
+ totalTokens: number;
956
+ /** Prompt-cache read tokens reported by the upstream provider, when available. */
957
+ cachedPromptTokens?: number;
958
+ }
959
+ type StreamPart = {
960
+ type: "text-delta";
961
+ textDelta: string;
962
+ } | {
963
+ type: "reasoning";
964
+ textDelta: string;
965
+ } | {
966
+ type: "tool-call";
967
+ toolCallId: string;
968
+ toolName: string;
969
+ args: unknown;
970
+ } | {
971
+ type: "tool-result";
972
+ toolCallId: string;
973
+ toolName: string;
974
+ result: unknown;
975
+ durationMs?: number;
976
+ } | {
977
+ type: "finish";
978
+ finishReason: FinishReason;
979
+ usage: TokenUsage;
980
+ } | {
981
+ type: "error";
982
+ error: unknown;
983
+ };
984
+ interface Message {
985
+ role: "system" | "user" | "assistant";
986
+ content: string;
987
+ }
988
+ /**
989
+ * OpenAI/Fireworks SSE chunk shape, only the fields we actually consume.
990
+ * Kept as a local type so we don't depend on backend internals.
991
+ */
992
+ interface OpenAiStreamChunk {
993
+ choices?: Array<{
994
+ delta?: {
995
+ content?: string | null;
996
+ reasoning_content?: string | null;
997
+ reasoning?: string | null;
998
+ tool_calls?: Array<{
999
+ index?: number;
1000
+ id?: string | null;
1001
+ type?: string;
1002
+ function?: {
1003
+ name?: string | null;
1004
+ arguments?: string | null;
1005
+ };
1006
+ }>;
1007
+ };
1008
+ finish_reason?: string | null;
1009
+ }>;
1010
+ usage?: {
1011
+ prompt_tokens?: number;
1012
+ completion_tokens?: number;
1013
+ total_tokens?: number;
1014
+ prompt_tokens_details?: {
1015
+ cached_tokens?: number;
1016
+ };
1017
+ cache_read_input_tokens?: number;
1018
+ };
1019
+ error?: {
1020
+ code?: number;
1021
+ message?: string;
1022
+ };
1023
+ }
1024
+ /**
1025
+ * Accumulator for partial tool-call function arguments streamed across
1026
+ * multiple chunks (Fireworks streams the `arguments` JSON token-by-token).
1027
+ */
1028
+ interface ToolCallAccumulator {
1029
+ byIndex: Map<number, {
1030
+ id: string;
1031
+ name: string;
1032
+ argsBuffer: string;
1033
+ emitted: boolean;
1034
+ }>;
1035
+ }
1036
+ /**
1037
+ * Map a single Fireworks/OpenAI chunk into zero or more StreamParts.
1038
+ * Tool calls are buffered until their `arguments` JSON is parseable, then
1039
+ * emitted as a single `tool-call` part — same convention as Vercel AI SDK.
1040
+ */
1041
+ declare function mapFireworksChunk(chunk: OpenAiStreamChunk, acc: ToolCallAccumulator): StreamPart[];
1042
+ /**
1043
+ * Minimal shape of an `AgentStreamEvent` from `agent-stream.ts`. Inlined to
1044
+ * keep this module zero-import.
1045
+ */
1046
+ interface AgentStreamLikeEvent {
1047
+ type: string;
1048
+ [k: string]: unknown;
1049
+ }
1050
+ /**
1051
+ * Map an existing agent SSE event (`token`, `reasoning_token`, `tool:call`,
1052
+ * `tool:result`, `done`) into a StreamPart, or `null` for events that don't
1053
+ * map (`ping`, `agent:info`, `node:*`).
1054
+ */
1055
+ declare function mapAgentEvent(event: AgentStreamLikeEvent): StreamPart | null;
1056
+
1057
+ /**
1058
+ * Vercel AI SDK–style raw inference for `@ragable/sdk`. Routes through the
1059
+ * Ragable backend's Fireworks proxy
1060
+ * (`POST /public/organizations/:id/websites/:websiteId/inference/stream`)
1061
+ * so callers don't need a provider API key and credit usage is tracked
1062
+ * against the website's organization.
1063
+ */
1064
+
1065
+ interface StreamTextParams {
1066
+ model: string;
1067
+ messages: Message[];
1068
+ system?: string;
1069
+ temperature?: number;
1070
+ maxTokens?: number;
1071
+ topP?: number;
1072
+ reasoningEffort?: "none" | "low" | "medium" | "high";
1073
+ signal?: AbortSignal;
1074
+ }
1075
+ interface ToolCallRecord {
1076
+ toolCallId: string;
1077
+ toolName: string;
1078
+ args: unknown;
1079
+ }
1080
+ interface StreamTextResult {
1081
+ /** Stream of text deltas only. Same content as `fullStream.filter(p => p.type === "text-delta")`. */
1082
+ textStream: AsyncIterable<string>;
1083
+ /** Full event stream — text deltas, reasoning, tool calls, finish, error. */
1084
+ fullStream: AsyncIterable<StreamPart>;
1085
+ /** Resolves to the concatenation of all `text-delta` parts once the stream finishes. */
1086
+ text: Promise<string>;
1087
+ /** Resolves to the concatenation of all `reasoning` parts. */
1088
+ reasoning: Promise<string>;
1089
+ /** Resolves to token usage from the final chunk (zeros if not reported). */
1090
+ usage: Promise<TokenUsage>;
1091
+ /** Resolves to the upstream finish reason. */
1092
+ finishReason: Promise<FinishReason>;
1093
+ /** Resolves to the list of tool calls extracted from this turn. */
1094
+ toolCalls: Promise<ToolCallRecord[]>;
1095
+ }
1096
+ interface GenerateTextResult {
1097
+ text: string;
1098
+ reasoning: string;
1099
+ usage: TokenUsage;
1100
+ finishReason: FinishReason;
1101
+ toolCalls: ToolCallRecord[];
1102
+ }
1103
+ /**
1104
+ * Build the JSON body for the inference proxy. Public so tests can assert it.
1105
+ */
1106
+ declare function buildInferenceRequestBody(params: StreamTextParams): Record<string, unknown>;
1107
+ /**
1108
+ * Build a `StreamTextResult` from a pre-existing async iterable of StreamParts.
1109
+ * Used by `client.agents.run()` to share the same DX as `client.ai.streamText`.
1110
+ */
1111
+ declare function createStreamResultFromParts(source: AsyncIterable<StreamPart>): StreamTextResult;
1112
+ interface AiClientOptions {
1113
+ organizationId: string;
1114
+ websiteId?: string;
1115
+ fetch?: typeof fetch;
1116
+ headers?: HeadersInit;
1117
+ /** API base override; defaults to the shared SDK base. */
1118
+ apiBase: string;
1119
+ }
1120
+ declare class RagableBrowserAiClient {
1121
+ private readonly options;
1122
+ private readonly fetchImpl;
1123
+ constructor(options: AiClientOptions);
1124
+ private requireWebsiteId;
1125
+ private buildContext;
1126
+ streamText(params: StreamTextParams): StreamTextResult;
1127
+ generateText(params: StreamTextParams): Promise<GenerateTextResult>;
1128
+ }
1129
+
1101
1130
  /** Canonical browser/server API base (`…/api`, no trailing slash). */
1102
1131
  declare function normalizeBrowserApiBase(): string;
1103
1132
  type BrowserDataAuthMode = "user" | "publicAnon" | "admin";
@@ -1674,10 +1703,33 @@ declare class RagableBrowserAgentsClient {
1674
1703
  private requestJson;
1675
1704
  /** @deprecated Prefer `chatStreamByName(agentName, params)` for project-local `/agents/*.json` agents. */
1676
1705
  chatStream(agentId: string, params: AgentPublicChatParams): AsyncGenerator<AgentStreamEvent, void, undefined>;
1706
+ /**
1707
+ * Stream a project agent defined in `agents/*.json` using the same result
1708
+ * shape as `client.ai.streamText`. Preferred over {@link chatStreamByName}
1709
+ * and {@link runChatStreamByName} — those remain for back-compat only.
1710
+ *
1711
+ * ```ts
1712
+ * const { textStream, text } = client.agents.run("support", {
1713
+ * messages: [{ role: "user", content: "I can't log in" }],
1714
+ * });
1715
+ * for await (const delta of textStream) process.stdout.write(delta);
1716
+ * console.log(await text);
1717
+ * ```
1718
+ */
1719
+ run(agentName: string, params: {
1720
+ messages: Message[];
1721
+ signal?: AbortSignal;
1722
+ }): StreamTextResult;
1723
+ private runStreamParts;
1724
+ /**
1725
+ * @deprecated Use {@link run} for new code. This method is kept for
1726
+ * back-compat with the original chat-stream DX.
1727
+ */
1677
1728
  chatStreamByName(agentName: string, params: AgentChatParams): AsyncGenerator<AgentStreamEvent, void, undefined>;
1678
1729
  /**
1679
- * Stream a project agent (`/agents/*.json`) with callbacks; returns the final `done` payload
1680
- * plus streamed assistant text. Prefer this over manual `for await` when building chat UIs.
1730
+ * @deprecated Use {@link run} for new code. Returns the legacy callback-based
1731
+ * result type leaking server internals; the new Vercel-style API exposes
1732
+ * `textStream` / `fullStream` / promises for `text`, `usage`, `finishReason`.
1681
1733
  */
1682
1734
  runChatStreamByName(agentName: string, params: AgentChatParams, handlers?: AgentChatStreamHandlers): Promise<AgentChatStreamResult>;
1683
1735
  /**
@@ -1711,6 +1763,7 @@ interface AgentPublicChatParams extends AgentChatParams {
1711
1763
  }
1712
1764
  declare class RagableBrowser<Database extends RagableDatabase = DefaultRagableDatabase, AuthUser extends object = DefaultAuthUser> {
1713
1765
  readonly agents: RagableBrowserAgentsClient;
1766
+ readonly ai: RagableBrowserAiClient;
1714
1767
  readonly auth: RagableBrowserAuthClient<AuthUser>;
1715
1768
  readonly database: RagableBrowserDatabaseClient<Database>;
1716
1769
  readonly db: RagableBrowserDatabaseClient<Database>;
@@ -1737,366 +1790,6 @@ declare function parseSseDataLine(line: string): SseJsonEvent | null;
1737
1790
  */
1738
1791
  declare function readSseStream(body: ReadableStream<Uint8Array>): AsyncGenerator<SseJsonEvent, void, undefined>;
1739
1792
 
1740
- /** Minimal client surface for {@link createRagPipeline} (implemented by {@link Ragable}). */
1741
- interface RagClientForPipeline {
1742
- shift: {
1743
- documents: {
1744
- create: (indexId: string, params: ShiftAddDocumentParams) => Promise<ShiftIngestResponse>;
1745
- upload: (indexId: string, params: ShiftUploadFileParams) => Promise<ShiftIngestResponse>;
1746
- };
1747
- search: (indexId: string, params: ShiftSearchParams) => Promise<{
1748
- results: ShiftSearchResult[];
1749
- }>;
1750
- };
1751
- }
1752
- interface FormatContextOptions {
1753
- /** Prepended before numbered passages (default: "Relevant passages:\\n") */
1754
- header?: string;
1755
- /** Joiner between passages (default: "\\n\\n") */
1756
- separator?: string;
1757
- /** Omit results with similarity score below this (default: no filter) */
1758
- minScore?: number;
1759
- /** Truncate total context string to this UTF-16 length (default: no limit) */
1760
- maxChars?: number;
1761
- /** Include similarity score in each block (default: false) */
1762
- includeScores?: boolean;
1763
- }
1764
- interface RagPipelineOptions {
1765
- indexId: string;
1766
- }
1767
- type RetrieveParams = ShiftSearchParams & {
1768
- format?: FormatContextOptions;
1769
- };
1770
- interface RagPipeline {
1771
- readonly indexId: string;
1772
- ingestText(params: ShiftAddDocumentParams): Promise<ShiftIngestResponse>;
1773
- ingestFile(params: ShiftUploadFileParams): Promise<ShiftIngestResponse>;
1774
- search(params: ShiftSearchParams): Promise<{
1775
- results: ShiftSearchResult[];
1776
- }>;
1777
- retrieve(params: RetrieveParams): Promise<{
1778
- results: ShiftSearchResult[];
1779
- context: string;
1780
- }>;
1781
- }
1782
- /**
1783
- * Turn vector search hits into a single block of text for system prompts or RAG user messages.
1784
- */
1785
- declare function formatRetrievalContext(results: ShiftSearchResult[], options?: FormatContextOptions): string;
1786
- /**
1787
- * High-level RAG helpers bound to one Shift index: ingest, search, retrieve with prompt-ready context.
1788
- */
1789
- declare function createRagPipeline(client: RagClientForPipeline, options: RagPipelineOptions): RagPipeline;
1790
-
1791
- interface StorageBucket {
1792
- id: string;
1793
- name: string;
1794
- organizationId: string;
1795
- status: string;
1796
- createdAt: string;
1797
- updatedAt: string;
1798
- }
1799
- interface StorageBucketItem {
1800
- type: "file" | "folder";
1801
- path: string;
1802
- name: string;
1803
- /** File size in bytes (files only). */
1804
- size?: string | null;
1805
- contentType?: string | null;
1806
- updated?: string | null;
1807
- generation?: string | null;
1808
- }
1809
- interface StorageListContentsResult {
1810
- bucket: string;
1811
- prefix: string;
1812
- items: StorageBucketItem[];
1813
- nextPageToken: string | null;
1814
- }
1815
- interface StorageListBucketsParams {
1816
- /** Filter by name substring. */
1817
- q?: string;
1818
- status?: string;
1819
- sort?: string;
1820
- }
1821
- interface StorageListContentsParams {
1822
- /** Folder prefix to list inside (e.g. `"reports/"`). */
1823
- prefix?: string;
1824
- /** Path delimiter — defaults to `"/"` on the server. */
1825
- delimiter?: string;
1826
- maxResults?: number;
1827
- pageToken?: string;
1828
- }
1829
- type StorageUploadableFile = Blob | ArrayBuffer | Uint8Array;
1830
- interface StorageUploadParams {
1831
- /** Target path inside the bucket (e.g. `"reports/jan.pdf"`). */
1832
- objectPath: string;
1833
- file: StorageUploadableFile;
1834
- /** Optional filename hint for content-type detection. */
1835
- fileName?: string;
1836
- contentType?: string;
1837
- /** HTTP `Cache-Control` header stored with the object. */
1838
- cacheControl?: string;
1839
- }
1840
- interface StorageUploadResult {
1841
- success: true;
1842
- path: string;
1843
- size: string | null;
1844
- contentType: string | null;
1845
- generation: string | null;
1846
- updated: string | null;
1847
- }
1848
- interface StorageDownloadParams {
1849
- objectPath: string;
1850
- /** When `true`, the response includes `text` if the file fits in `maxTextBytes`. */
1851
- asText?: boolean;
1852
- /** Maximum bytes to decode as text (default 1 MB, max 5 MB). */
1853
- maxTextBytes?: number;
1854
- }
1855
- interface StorageDownloadResult {
1856
- path: string;
1857
- size: string | null;
1858
- contentType: string | null;
1859
- updated: string | null;
1860
- generation: string | null;
1861
- /** Always `"base64"`. */
1862
- encoding: string;
1863
- /** Full file contents encoded as base64. */
1864
- contentsBase64: string;
1865
- /** UTF-8 decoded text when `asText: true` and size ≤ `maxTextBytes`. */
1866
- text: string | null;
1867
- textIncluded: boolean;
1868
- }
1869
- interface StorageObjectMetadata {
1870
- name: string;
1871
- bucket: string;
1872
- contentType: string | null;
1873
- size: string | null;
1874
- updated: string | null;
1875
- generation: string | null;
1876
- metadata?: Record<string, string>;
1877
- [key: string]: unknown;
1878
- }
1879
- interface StorageUpdateMetadataParams {
1880
- objectPath: string;
1881
- contentType?: string;
1882
- cacheControl?: string;
1883
- metadata?: Record<string, string>;
1884
- }
1885
- interface StorageCopyMoveParams {
1886
- sourcePath: string;
1887
- destinationPath: string;
1888
- }
1889
- interface StorageBulkDeleteResult {
1890
- success: boolean;
1891
- totalRequested: number;
1892
- uniquePaths: number;
1893
- deleted: string[];
1894
- errors: Array<{
1895
- path: string;
1896
- error: string;
1897
- }>;
1898
- }
1899
- interface StorageSignedUploadUrlParams {
1900
- objectPath: string;
1901
- /** Expiry in seconds — clamped to [60, 3600] by the server. Default 900. */
1902
- expiresInSeconds?: number;
1903
- contentType?: string;
1904
- }
1905
- interface StorageSignedUploadUrlResult {
1906
- url: string;
1907
- method: string;
1908
- expiresInSeconds: number;
1909
- objectPath: string;
1910
- }
1911
- interface StorageSignedDownloadUrlParams {
1912
- objectPath: string;
1913
- /** Expiry in seconds — clamped to [60, 86400] by the server. Default 900. */
1914
- expiresInSeconds?: number;
1915
- }
1916
- interface StorageSignedDownloadUrlResult {
1917
- url: string;
1918
- method: string;
1919
- expiresInSeconds: number;
1920
- objectPath: string;
1921
- }
1922
- interface StorageBucketCorsEntry {
1923
- origin?: string[];
1924
- method?: string[];
1925
- responseHeader?: string[];
1926
- maxAgeSeconds?: number;
1927
- }
1928
- interface StorageBucketSettings {
1929
- id: string;
1930
- logicalName: string;
1931
- gcpBucketName: string;
1932
- location: string | null;
1933
- storageClass: string | null;
1934
- labels: Record<string, string>;
1935
- versioningEnabled: boolean;
1936
- publicAccessPrevention: string | null;
1937
- uniformBucketLevelAccessEnabled: boolean;
1938
- cors: StorageBucketCorsEntry[];
1939
- retentionPolicy: unknown;
1940
- lifecycleRules: unknown[];
1941
- updated: string | null;
1942
- }
1943
- interface StorageUpdateBucketSettingsParams {
1944
- labels?: Record<string, string>;
1945
- storageClass?: string;
1946
- versioningEnabled?: boolean;
1947
- publicAccessPrevention?: "inherited" | "enforced";
1948
- uniformBucketLevelAccessEnabled?: boolean;
1949
- cors?: StorageBucketCorsEntry[];
1950
- }
1951
- /**
1952
- * Object/file operations scoped to a single bucket.
1953
- * Obtained via {@link StorageClient.from}.
1954
- *
1955
- * @example
1956
- * const bucket = ragable.storage.from("bucket-id");
1957
- *
1958
- * // Upload a file
1959
- * await bucket.upload({ objectPath: "data/report.pdf", file: pdfBlob });
1960
- *
1961
- * // Download and read as text
1962
- * const { text } = await bucket.download({ objectPath: "data/notes.txt", asText: true });
1963
- *
1964
- * // Generate a short-lived public download link
1965
- * const { url } = await bucket.getSignedDownloadUrl({ objectPath: "data/report.pdf" });
1966
- */
1967
- interface StorageBucketClient {
1968
- /** List objects and sub-folders inside this bucket (optionally under a prefix). */
1969
- list(params?: StorageListContentsParams): Promise<StorageListContentsResult>;
1970
- /** Create an empty folder placeholder (GCS folder marker). */
1971
- createFolder(folderPath: string): Promise<{
1972
- success: true;
1973
- folderPath: string;
1974
- }>;
1975
- /** Delete a folder and all objects under it. */
1976
- deleteFolder(folderPath: string): Promise<{
1977
- success: true;
1978
- folderPath: string;
1979
- }>;
1980
- /** Upload a file to the specified `objectPath`. */
1981
- upload(params: StorageUploadParams): Promise<StorageUploadResult>;
1982
- /** Delete a single object. */
1983
- delete(objectPath: string): Promise<{
1984
- success: true;
1985
- path: string;
1986
- }>;
1987
- /** Delete up to 1 000 objects in one call. */
1988
- bulkDelete(objectPaths: string[]): Promise<StorageBulkDeleteResult>;
1989
- /** Retrieve GCS metadata for an object. */
1990
- getMetadata(objectPath: string): Promise<StorageObjectMetadata>;
1991
- /** Update `contentType`, `cacheControl`, or custom `metadata` for an object. */
1992
- updateMetadata(params: StorageUpdateMetadataParams): Promise<StorageObjectMetadata>;
1993
- /**
1994
- * Download an object. Contents are always returned as `contentsBase64`.
1995
- * Pass `asText: true` to also receive a decoded `text` field (≤ maxTextBytes).
1996
- */
1997
- download(params: StorageDownloadParams): Promise<StorageDownloadResult>;
1998
- /** Copy an object to a new path inside the same bucket. */
1999
- copy(params: StorageCopyMoveParams): Promise<{
2000
- success: true;
2001
- sourcePath: string;
2002
- destinationPath: string;
2003
- }>;
2004
- /** Move (rename) an object inside the same bucket. */
2005
- move(params: StorageCopyMoveParams): Promise<{
2006
- success: true;
2007
- sourcePath: string;
2008
- destinationPath: string;
2009
- }>;
2010
- /**
2011
- * Generate a signed URL for direct client-side PUT upload (bypasses your server).
2012
- * Use this when a website needs to upload large files directly to GCS.
2013
- */
2014
- getSignedUploadUrl(params: StorageSignedUploadUrlParams): Promise<StorageSignedUploadUrlResult>;
2015
- /**
2016
- * Generate a signed URL for direct client-side download.
2017
- * Useful for serving private files without proxying through your server.
2018
- */
2019
- getSignedDownloadUrl(params: StorageSignedDownloadUrlParams): Promise<StorageSignedDownloadUrlResult>;
2020
- /** Retrieve GCS-level settings for this bucket (CORS, versioning, storage class …). */
2021
- getSettings(): Promise<StorageBucketSettings>;
2022
- /** Update GCS-level settings for this bucket. */
2023
- updateSettings(params: StorageUpdateBucketSettingsParams): Promise<StorageBucketSettings>;
2024
- }
2025
- /**
2026
- * Server-side storage client — access via `ragable.storage`.
2027
- *
2028
- * Manages GCS-backed storage buckets for your organisation and exposes typed
2029
- * helpers for every object-storage operation websites need for durable storage.
2030
- *
2031
- * ```ts
2032
- * import { createClient } from "@ragable/sdk";
2033
- *
2034
- * const ragable = createClient({ apiKey: process.env.RAGABLE_API_KEY! });
2035
- *
2036
- * // ── Bucket management ───────────────────────────────────────────────────
2037
- * const buckets = await ragable.storage.buckets.list();
2038
- * const bucket = await ragable.storage.buckets.create("my-website-assets");
2039
- *
2040
- * // ── Object operations (via .from()) ─────────────────────────────────────
2041
- * const b = ragable.storage.from(bucket.id);
2042
- *
2043
- * await b.upload({ objectPath: "pages/index.html", file: htmlBlob, contentType: "text/html" });
2044
- * const { text } = await b.download({ objectPath: "pages/index.html", asText: true });
2045
- *
2046
- * // ── Signed URLs for client-side direct upload/download ──────────────────
2047
- * const { url } = await b.getSignedUploadUrl({ objectPath: "uploads/photo.jpg", contentType: "image/jpeg" });
2048
- * ```
2049
- */
2050
- declare class StorageClient {
2051
- private readonly client;
2052
- /**
2053
- * Bucket-level CRUD — list, create and delete buckets for this organisation.
2054
- */
2055
- readonly buckets: {
2056
- /**
2057
- * List all managed storage buckets.
2058
- *
2059
- * @param params Optional filter / sort params (`q`, `status`, `sort`).
2060
- */
2061
- list(params?: StorageListBucketsParams): Promise<StorageBucket[]>;
2062
- /**
2063
- * Create a new managed GCS bucket.
2064
- *
2065
- * The `name` must be lowercase alphanumeric + dashes, max 63 chars.
2066
- */
2067
- create(name: string): Promise<StorageBucket>;
2068
- /**
2069
- * Permanently delete a bucket and **all** its contents.
2070
- *
2071
- * @param bucketId The Ragable bucket ID (not the raw GCS bucket name).
2072
- */
2073
- delete(bucketId: string): Promise<{
2074
- success: true;
2075
- }>;
2076
- };
2077
- constructor(client: RagableRequestClient);
2078
- /**
2079
- * Returns a {@link StorageBucketClient} scoped to the given bucket ID.
2080
- *
2081
- * All object operations (upload, download, list, copy, move, signed URLs, …)
2082
- * are performed through the returned client.
2083
- *
2084
- * @param bucketId The Ragable bucket ID obtained from `buckets.list()` or `buckets.create()`.
2085
- */
2086
- from(bucketId: string): StorageBucketClient;
2087
- }
2088
-
2089
- declare class Ragable {
2090
- readonly shift: ShiftClient;
2091
- readonly agents: AgentsClient;
2092
- readonly storage: StorageClient;
2093
- readonly infrastructure: {
2094
- shift: ShiftClient;
2095
- };
2096
- constructor(options: RagableClientOptions);
2097
- }
2098
- declare function createClient(options: RagableClientOptions): Ragable;
2099
1793
  declare function createClient<Database extends RagableDatabase = DefaultRagableDatabase, AuthUser extends object = DefaultAuthUser>(options: RagableBrowserClientOptions): RagableBrowser<Database, AuthUser>;
2100
- declare function createRagableServerClient(options: RagableClientOptions): Ragable;
2101
1794
 
2102
- export { type AgentChatMessage, type AgentChatParams, type AgentChatResult, type AgentChatStreamDonePayload, type AgentChatStreamHandlers, type AgentChatStreamResult, type AgentChatStreamUiHandlers, type AgentChatUiAssistantMessage, type AgentChatUiSegment, type AgentChatUiStreamResult, type AgentConversation, type AgentConversationMessage, type AgentConversationSubscription, type AgentPublicChatParams, type AgentStreamAgentInfoEvent, type AgentStreamEvent, type AgentSummary, AgentsClient, AuthBroadcastChannel, type AuthBroadcastMessage, type AuthChangeEvent, type AuthOptions, type AuthSession, type AuthSignUpCredentials, type AuthUpdateUserAttributes, type AuthUserMetadata, type BrowserAuthSession, type BrowserAuthTokens, BrowserCollectionApi, type BrowserCollectionDefinition, type BrowserCollectionFactory, type BrowserCollectionFindParams, type BrowserCollectionRecord, type BrowserCollections, type BrowserDataAuthMode, type BrowserRealtimeNotification, type BrowserRealtimeStatus, type BrowserRealtimeSubscribeParams, type BrowserRealtimeSubscription, type BrowserSqlExecParams, type BrowserSqlExecResult, type BrowserSqlQueryParams, type BrowserSqlQueryResult, type CollectionReturnMode, type CollectionRowData, type CollectionRowWithMeta, type CollectionWhere, type ColumnName, type ColumnValue, CookieStorageAdapter, DEFAULT_RAGABLE_API_BASE, type DefaultAuthUser, type DefaultRagableDatabase, type FormatContextOptions, type HttpMethod, type Json, LocalStorageAdapter, MemoryStorageAdapter, type PostgRESTFetch, type PostgRESTFetchParams, PostgrestDeleteReturningBuilder, PostgrestDeleteRootBuilder, PostgrestInsertReturningBuilder, PostgrestInsertRootBuilder, PostgrestInsertSdkErrorReturning, PostgrestInsertSdkErrorRoot, type PostgrestResult, PostgrestSelectBuilder, PostgrestTableApi, PostgrestUpdateReturningBuilder, PostgrestUpdateRootBuilder, type PostgrestUpsertOptions, PostgrestUpsertReturningBuilder, PostgrestUpsertRootBuilder, type RagClientForPipeline, type RagPipeline, type RagPipelineOptions, Ragable, RagableAbortError, RagableAuth, type RagableAuthConfig, RagableBrowser, RagableBrowserAgentsClient, RagableBrowserAuthClient, type RagableBrowserClientOptions, RagableBrowserDatabaseClient, type RagableClientOptions, type RagableDatabase, RagableError, RagableNetworkError, RagableRequestClient, type RagableResult, RagableSdkError, type RagableTableDefinition, type RagableTableNames, RagableTimeoutError, type RequestOptions, type RetrieveParams, type RetryOptions, type RunAgentChatStreamOptions, type RunQuery, type SessionStorage, SessionStorageAdapter, type ShiftAddDocumentParams, ShiftClient, type ShiftCreateIndexParams, type ShiftEntry, type ShiftIndex, type ShiftIngestResponse, type ShiftListEntriesParams, type ShiftListEntriesResponse, type ShiftSearchParams, type ShiftSearchResult, type ShiftUpdateIndexParams, type ShiftUploadFileParams, type ShiftUploadableFile, type SseJsonEvent, type StorageBucket, type StorageBucketClient, type StorageBucketCorsEntry, type StorageBucketItem, type StorageBucketSettings, type StorageBulkDeleteResult, StorageClient, type StorageCopyMoveParams, type StorageDownloadParams, type StorageDownloadResult, type StorageListBucketsParams, type StorageListContentsParams, type StorageListContentsResult, type StorageObjectMetadata, type StorageSignedDownloadUrlParams, type StorageSignedDownloadUrlResult, type StorageSignedUploadUrlParams, type StorageSignedUploadUrlResult, type StorageUpdateBucketSettingsParams, type StorageUpdateMetadataParams, type StorageUploadParams, type StorageUploadResult, type StorageUploadableFile, type SupabaseCompatSession, type TableInsertRow, type TableRow, type TableUpdatePatch, type Tables, type TablesInsert, type TablesUpdate, Transport, type TransportOptions, type TransportRequest, type WhereInput, type WhereOperatorObject, asPostgrestResponse, assertPostgrestSuccess, bindFetch, collectAssistantTextFromUiSegments, collectionRecordToRowWithMeta, collectionRecordsToRowWithMeta, createBrowserClient, createClient, createRagPipeline, createRagableBrowserClient, createRagableServerClient, detectStorage, effectiveDataAuth, extractErrorMessage, finalizeAgentChatUiTurn, foldAgentStreamIntoUiSegments, formatPostgrestError, formatRetrievalContext, formatSdkError, generateIdempotencyKey, isIncompleteAgentStreamError, normalizeBrowserApiBase, parseAgentStreamAgentInfo, parseAgentStreamDone, parseSseDataLine, parseTransportResponse, readSseStream, runAgentChatStream, runAgentChatStreamForUi, runAgentChatStreamLenient, toRagableResult, unwrapPostgrest };
1795
+ export { type AgentChatMessage, type AgentChatParams, type AgentChatStreamDonePayload, type AgentChatStreamHandlers, type AgentChatStreamResult, type AgentChatStreamUiHandlers, type AgentChatUiAssistantMessage, type AgentChatUiSegment, type AgentChatUiStreamResult, type AgentConversation, type AgentConversationMessage, type AgentConversationSubscription, type AgentPublicChatParams, type AgentStreamAgentInfoEvent, type AgentStreamEvent, AuthBroadcastChannel, type AuthBroadcastMessage, type AuthChangeEvent, type AuthOptions, type AuthSession, type AuthSignUpCredentials, type AuthUpdateUserAttributes, type AuthUserMetadata, type BrowserAuthSession, type BrowserAuthTokens, BrowserCollectionApi, type BrowserCollectionDefinition, type BrowserCollectionFactory, type BrowserCollectionFindParams, type BrowserCollectionRecord, type BrowserCollections, type BrowserDataAuthMode, type BrowserRealtimeNotification, type BrowserRealtimeStatus, type BrowserRealtimeSubscribeParams, type BrowserRealtimeSubscription, type BrowserSqlExecParams, type BrowserSqlExecResult, type BrowserSqlQueryParams, type BrowserSqlQueryResult, BrowserStorageBucketClient, type BrowserStorageBulkDeleteResult, type BrowserStorageDownloadResult, type BrowserStorageItem, type BrowserStorageListResult, type BrowserStorageSignedUrlResult, type BrowserStorageUploadResult, type CollectionReturnMode, type CollectionRowData, type CollectionRowWithMeta, type CollectionWhere, type ColumnName, type ColumnValue, CookieStorageAdapter, DEFAULT_RAGABLE_API_BASE, type DefaultAuthUser, type DefaultRagableDatabase, type FinishReason, type GenerateTextResult, type HttpMethod, type Json, LocalStorageAdapter, MemoryStorageAdapter, type Message, type PostgRESTFetch, type PostgRESTFetchParams, PostgrestDeleteReturningBuilder, PostgrestDeleteRootBuilder, PostgrestInsertReturningBuilder, PostgrestInsertRootBuilder, PostgrestInsertSdkErrorReturning, PostgrestInsertSdkErrorRoot, type PostgrestResult, PostgrestSelectBuilder, PostgrestTableApi, PostgrestUpdateReturningBuilder, PostgrestUpdateRootBuilder, type PostgrestUpsertOptions, PostgrestUpsertReturningBuilder, PostgrestUpsertRootBuilder, RagableAbortError, RagableAuth, type RagableAuthConfig, RagableBrowser, RagableBrowserAgentsClient, RagableBrowserAiClient, RagableBrowserAuthClient, type RagableBrowserClientOptions, RagableBrowserDatabaseClient, RagableBrowserStorageClient, type RagableDatabase, RagableError, RagableNetworkError, type RagableResult, RagableSdkError, type RagableTableDefinition, type RagableTableNames, RagableTimeoutError, type RequestOptions, type RetryOptions, type RunAgentChatStreamOptions, type RunQuery, type SessionStorage, SessionStorageAdapter, type SseJsonEvent, type StreamPart, type StreamTextParams, type StreamTextResult, type SupabaseCompatSession, type TableInsertRow, type TableRow, type TableUpdatePatch, type Tables, type TablesInsert, type TablesUpdate, type TokenUsage, type ToolCallRecord, Transport, type TransportOptions, type TransportRequest, type WhereInput, type WhereOperatorObject, asPostgrestResponse, assertPostgrestSuccess, bindFetch, buildInferenceRequestBody, collectAssistantTextFromUiSegments, collectionRecordToRowWithMeta, collectionRecordsToRowWithMeta, createBrowserClient, createClient, createRagableBrowserClient, createStreamResultFromParts, detectStorage, effectiveDataAuth, extractErrorMessage, finalizeAgentChatUiTurn, foldAgentStreamIntoUiSegments, formatPostgrestError, formatSdkError, generateIdempotencyKey, isIncompleteAgentStreamError, mapAgentEvent, mapFireworksChunk, normalizeBrowserApiBase, parseAgentStreamAgentInfo, parseAgentStreamDone, parseSseDataLine, parseTransportResponse, readSseStream, runAgentChatStream, runAgentChatStreamForUi, runAgentChatStreamLenient, toRagableResult, unwrapPostgrest };