@baseera/node 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,306 @@
1
+ import { VerifiedFinish, VerifyFinishRefusal, TenantPurgeRecord, SignalEntity, SignalData, KnowledgeMetadata, KnowledgeAccess, KnowledgeItemResult, KnowledgeItemStatusResponse, BaseeraWebhookEvent, WebhookSignatureFailure } from '@baseera/core';
2
+ export { BaseeraWebhookEvent, FINISH_WEBHOOK_EVENT_TYPE, FinishOverride, ImmersiveRecordFinishedData, ImmersiveRecordFinishedEvent, ImmersiveWebhookTrailEvent, KnowledgeAccess, KnowledgeItemEvent, KnowledgeItemEventData, KnowledgeItemResult, KnowledgeItemStatusResponse, KnowledgeMetadata, PROTOCOL_VERSION, SIGNAL_LIMITS, SignUserTokenOptions, SignalData, SignalEntity, SignalValue, TENANT_UPLOAD_TOKEN_DEFAULT_TTL_SECONDS, TENANT_UPLOAD_TOKEN_MAX_TTL_SECONDS, TenantPurgeRecord, USER_TOKEN_DEFAULT_TTL_SECONDS, USER_TOKEN_MAX_TTL_SECONDS, UserTokenClaims, UserTokenInput, VerifiedFinish, VerifyFinishRefusal, WEBHOOK_TOLERANCE_SECONDS, WebhookEvent, WebhookEventType, generateWebhookSecret, signUserToken } from '@baseera/core';
3
+
4
+ /** How long `verifyFinish` waits for the runtime before it gives up (and refuses). */
5
+ declare const VERIFY_FINISH_TIMEOUT_MS = 5000;
6
+ interface VerifyFinishOptions {
7
+ /** The receipt your browser got from Baseera and sent to your finish route (`fin_…`). */
8
+ receipt: string;
9
+ /** The record being finished. Must be the one the receipt was recorded for. */
10
+ entity: {
11
+ type: string;
12
+ ref: string;
13
+ };
14
+ /**
15
+ * The blocking checks YOUR server found open for this record, computed on the server from your own data. The
16
+ * receipt's override must cover every one of them, otherwise the result is `override_required`. Pass them
17
+ * whenever you can: the browser's own list of open checks is not something Baseera can vouch for.
18
+ */
19
+ openBlocking?: string[];
20
+ /** The agent's id (uuid), from the platform. */
21
+ agentId: string;
22
+ /** The agent's secret key (`sk_…`). Server only. It signs a fresh 60-second token per call and is never sent. */
23
+ secretKey: string;
24
+ /** The runtime's URL. */
25
+ baseUrl: string;
26
+ /** Replaces the global `fetch`, for tests. */
27
+ fetch?: typeof fetch;
28
+ }
29
+ /**
30
+ * `ok: true`: the finish was recorded, is unused, unexpired and for this record, and its override covers what
31
+ * your server passed. It is now used up. `ok: false`: do not finish. `unavailable` means Baseera could not be
32
+ * asked or its answer could not be trusted (network error, timeout, redirect, a non-200 status, a malformed body):
33
+ * treat it as a refusal and let the person retry.
34
+ */
35
+ type VerifyFinishResult = {
36
+ ok: true;
37
+ finish: VerifiedFinish;
38
+ } | {
39
+ ok: false;
40
+ code: VerifyFinishRefusal | "unavailable";
41
+ };
42
+ /**
43
+ * Call this in your finish route, before you change anything, with the receipt the browser sent.
44
+ *
45
+ * What it proves: Baseera recorded this finish first, for this record and agent, once, within 10 minutes, and any
46
+ * blocking checks that were open (as the browser reported them) plus the ones your server passes in are covered
47
+ * by a written override. What it does not prove: that the browser's check results were true. That is why your
48
+ * server should compute its own blocking checks and pass them as `openBlocking`.
49
+ *
50
+ * It fails closed: any error returns `{ ok: false, code: "unavailable" }`. It never throws and never logs the key or token.
51
+ */
52
+ declare function verifyFinish(options: VerifyFinishOptions): Promise<VerifyFinishResult>;
53
+
54
+ /** How long `purgeTenantKnowledge` waits for the runtime. A purge of a large tenant can take a while. */
55
+ declare const PURGE_TENANT_TIMEOUT_MS = 30000;
56
+ interface PurgeTenantKnowledgeOptions {
57
+ /** The tenant whose knowledge to delete: the same id you put in your users' tokens (`tenantId`). */
58
+ tenantId: string;
59
+ /** The agent's id (uuid), from the platform. The purge covers that agent's whole organization. */
60
+ agentId: string;
61
+ /** The agent's secret key (`sk_…`). Server only. It signs a fresh 60-second token per call and is never sent. */
62
+ secretKey: string;
63
+ /** The runtime's URL. */
64
+ baseUrl: string;
65
+ /** Replaces the global `fetch`, for tests. */
66
+ fetch?: typeof fetch;
67
+ }
68
+ /**
69
+ * `ok: true`: every source and chunk of the tenant is gone from search and `record` confirms it (counts and times,
70
+ * no content). The original files are removed from storage within a minute. `ok: false`: nothing is known to have
71
+ * been deleted; `unavailable` means Baseera could not be reached or its answer could not be trusted, so call again
72
+ * (a second purge of the same tenant is harmless).
73
+ */
74
+ type PurgeTenantKnowledgeResult = {
75
+ ok: true;
76
+ record: TenantPurgeRecord;
77
+ } | {
78
+ ok: false;
79
+ code: "invalid_server_token" | "invalid_request" | "unavailable";
80
+ };
81
+ /**
82
+ * Deletes everything a tenant has in the agent's organization's knowledge bases: sources, documents, chunks and
83
+ * embeddings. Platform-wide knowledge (no tenant) and other tenants are never touched. Call it from your server when
84
+ * a customer leaves or asks to be forgotten. It never throws and never logs the key or token.
85
+ */
86
+ declare function purgeTenantKnowledge(options: PurgeTenantKnowledgeOptions): Promise<PurgeTenantKnowledgeResult>;
87
+
88
+ /** How long one call to the runtime may take. */
89
+ declare const KB_REQUEST_TIMEOUT_MS = 30000;
90
+ /** How long uploading one file may take. */
91
+ declare const KB_UPLOAD_TIMEOUT_MS = 120000;
92
+ interface BaseeraOptions {
93
+ /** The agent's id (uuid), from the platform. */
94
+ agentId: string;
95
+ /** The agent's secret key (`sk_…`). Server only. It signs a fresh 60-second token per call and is never sent. */
96
+ secretKey: string;
97
+ /** The runtime's URL. */
98
+ baseUrl: string;
99
+ /** Replaces the global `fetch`, for tests. */
100
+ fetch?: typeof fetch;
101
+ }
102
+ /** A file to index: its bytes and name (the extension decides the type: .pdf, .docx, .md, .txt, .html, .csv). */
103
+ interface KbFile {
104
+ name: string;
105
+ data: Uint8Array | ArrayBuffer | Blob;
106
+ /** Defaults from the extension. */
107
+ mimeType?: string;
108
+ }
109
+ interface KbUpsertInput {
110
+ /** The knowledge base's id (uuid), from the console. It must belong to the agent's organization. */
111
+ knowledgeBase: string;
112
+ /** Your id for the item. Pushing the same one again replaces the old version; unchanged content isn't embedded again. */
113
+ externalId: string;
114
+ title: string;
115
+ /** Exactly one of `text`, `url` and `file`. */
116
+ text?: string;
117
+ /** An https address Baseera fetches (public hosts only): HTML, text, Markdown, CSV, PDF or DOCX. */
118
+ url?: string;
119
+ file?: KbFile;
120
+ /** At most 20 keys; values are strings (500), numbers, booleans or lists of at most 20 strings. Stored on every chunk. */
121
+ metadata?: KnowledgeMetadata;
122
+ /** Visible to this tenant only. Omit for knowledge shared by all your tenants. */
123
+ tenantId?: string;
124
+ /**
125
+ * Who may read it, for example `{ roles: ["staff"] }`: a user whose token (`role`, `claims`) does not satisfy every name never
126
+ * gets the item from a search, a citation or a source link. Omit to keep the item's current rules (none, for a new item);
127
+ * `null` removes them. Fails closed: a user without the claim sees nothing of it.
128
+ */
129
+ access?: KnowledgeAccess | null;
130
+ }
131
+ /** Why a whole call failed (not one item: those are `rejected` results). */
132
+ type KbFailureCode = "invalid_server_token" | "invalid_request" | "knowledge_base_not_found" | "message_too_large" | "rate_limited" | "idempotency_conflict" | "unavailable";
133
+ type KbFailure = {
134
+ ok: false;
135
+ code: KbFailureCode; /** Seconds, with `rate_limited`. */
136
+ retryAfter?: number;
137
+ };
138
+ type KbUpsertResult = {
139
+ ok: true;
140
+ item: KnowledgeItemResult;
141
+ } | KbFailure;
142
+ /** `results` has one entry per input, in order. On a failure it holds the items that were decided before it: the rest were not sent. */
143
+ type KbUpsertManyResult = {
144
+ ok: true;
145
+ results: KnowledgeItemResult[];
146
+ } | (KbFailure & {
147
+ results: KnowledgeItemResult[];
148
+ });
149
+ type KbDeleteResult = {
150
+ ok: true;
151
+ deleted: boolean;
152
+ } | KbFailure;
153
+ /** `not_found`: the knowledge base exists but the item does not. */
154
+ type KbStatusResult = {
155
+ ok: true;
156
+ status: KnowledgeItemStatusResponse;
157
+ } | KbFailure | {
158
+ ok: false;
159
+ code: "not_found";
160
+ };
161
+ /** What your upload route returns to the browser: the token and when it stops working. */
162
+ type KbTenantUploadTokenResult = {
163
+ ok: true;
164
+ token: string;
165
+ expiresAt: string;
166
+ } | {
167
+ ok: false;
168
+ code: "invalid_request";
169
+ };
170
+ /** What `signal` answers: stored (`duplicate: false`), already stored under that idempotency key (`duplicate: true`), or why not. */
171
+ type SignalResult = {
172
+ ok: true;
173
+ duplicate: boolean;
174
+ } | KbFailure;
175
+ interface SignalOptions {
176
+ /** Only the sessions of this tenant see the signal. Omit when the record is not tenant-specific. */
177
+ tenantId?: string;
178
+ /** Makes a retry safe: the same key with the same content is stored once. Use your own event id (a payment id). Default: a random one, so the SDK's own retry can't store it twice. */
179
+ idempotencyKey?: string;
180
+ }
181
+ interface Baseera {
182
+ /**
183
+ * Tells Baseera that something happened to a record while nobody had it open (a payment arrived, a carrier updated, a
184
+ * document was processed). The record's AI checks run again the next time it is opened, and see the signal as
185
+ * untrusted data. `data` is flat (strings up to 500 characters, numbers, booleans, null; 20 keys, 2 KB) and must hold no
186
+ * secrets. Server only: it needs your secret key. Never throws; a refused signal is `{ ok: false, code: "invalid_request" }`.
187
+ */
188
+ signal(entity: SignalEntity, name: string, data?: SignalData, options?: SignalOptions): Promise<SignalResult>;
189
+ kb: {
190
+ /**
191
+ * A token for `<BaseeraKnowledgeUpload>`: this user of this tenant may add documents to this knowledge base for
192
+ * `ttlSeconds` (default 300, at most 600). Authorize the user on YOUR server first. `{ ok: false }` for a missing field.
193
+ */
194
+ createTenantUploadToken(input: {
195
+ knowledgeBase: string;
196
+ tenantId: string;
197
+ userId: string;
198
+ ttlSeconds?: number;
199
+ }): Promise<KbTenantUploadTokenResult>;
200
+ upsert(input: KbUpsertInput): Promise<KbUpsertResult>;
201
+ upsertMany(inputs: readonly KbUpsertInput[]): Promise<KbUpsertManyResult>;
202
+ delete(input: {
203
+ knowledgeBase: string;
204
+ externalId: string;
205
+ tenantId?: string;
206
+ }): Promise<KbDeleteResult>;
207
+ /** Where an item stands: `queued`, `parsing`, `embedding`, `ready` or `failed` (and `errorCode`). */
208
+ status(input: {
209
+ knowledgeBase: string;
210
+ externalId: string;
211
+ tenantId?: string;
212
+ }): Promise<KbStatusResult>;
213
+ };
214
+ }
215
+ /**
216
+ * The server-side client for your agent: push knowledge from your own system.
217
+ *
218
+ * ```ts
219
+ * const baseera = createBaseera({ agentId, secretKey: process.env.BASEERA_SECRET_KEY!, baseUrl });
220
+ * await baseera.kb.upsert({ knowledgeBase, externalId: "policy-7", title: "Refund policy", text, metadata: { lang: "en" } });
221
+ * ```
222
+ * Nothing here throws and nothing logs a key or token: a failed call is `{ ok: false, code }`, a refused item is
223
+ * `{ status: "rejected", error }`. Call it from your server only.
224
+ */
225
+ declare function createBaseera(options: BaseeraOptions): Baseera;
226
+
227
+ interface TenantUploadTokenOptions {
228
+ /** The agent's id (uuid), from the platform. */
229
+ agentId: string;
230
+ /** The agent's secret key (`sk_…`). Server only. */
231
+ secretKey: string;
232
+ /** The knowledge base the user's uploads go to (its id, from the console). */
233
+ knowledgeBase: string;
234
+ /** The tenant that owns the uploads: the same id you put in this user's tokens (`tenantId`). */
235
+ tenantId: string;
236
+ /** The user who may upload. Their id is recorded when they delete one of their tenant's documents. */
237
+ userId: string;
238
+ /** Seconds the token stays valid: 1 to 600, default 300. */
239
+ ttlSeconds?: number;
240
+ /** For tests. */
241
+ now?: Date;
242
+ }
243
+ /**
244
+ * Signs the token `<BaseeraKnowledgeUpload>` needs, for one user of one tenant, on YOUR server, after YOUR check that this
245
+ * user may manage that tenant's documents. The browser sends it to Baseera; Baseera takes the knowledge base, tenant and
246
+ * user from it and from nowhere else, so the browser can't upload for another tenant. Call it from a route that only
247
+ * a signed-in admin of the tenant can reach; never in the browser. Throws a TypeError for a missing field.
248
+ *
249
+ * ```ts
250
+ * export async function POST() {
251
+ * const admin = await requireTenantAdmin(); // your own authorization
252
+ * const token = await signTenantUploadToken({ agentId, secretKey, knowledgeBase, tenantId: admin.orgId, userId: admin.id });
253
+ * return Response.json({ token });
254
+ * }
255
+ * ```
256
+ */
257
+ declare function signTenantUploadToken(options: TenantUploadTokenOptions): Promise<string>;
258
+
259
+ interface VerifyWebhookOptions {
260
+ /** Seconds either side of now a signature's timestamp may be (replay protection). Default 300. */
261
+ toleranceSec?: number;
262
+ /** For tests. */
263
+ now?: Date;
264
+ }
265
+ type VerifyWebhookResult = {
266
+ ok: true;
267
+ event: BaseeraWebhookEvent;
268
+ timestamp: number;
269
+ } | {
270
+ ok: false;
271
+ reason: WebhookSignatureFailure | "invalid_body";
272
+ };
273
+ /** Anything with a header getter and a body reader: a Fetch `Request` (Next.js route handlers, Hono, Deno, Bun, Workers). */
274
+ interface WebhookRequestLike {
275
+ headers: {
276
+ get(name: string): string | null;
277
+ };
278
+ text(): Promise<string>;
279
+ clone?(): WebhookRequestLike;
280
+ bodyUsed?: boolean;
281
+ }
282
+ /**
283
+ * Checks a webhook from Baseera and parses it. Two forms:
284
+ *
285
+ * ```ts
286
+ * // A Fetch Request (Next.js route handler, Hono, Workers, Bun, Deno): the body is read for you.
287
+ * export async function POST(request: Request) {
288
+ * const result = await verifyWebhook(request, process.env.BASEERA_WEBHOOK_SECRET!);
289
+ * if (!result.ok) return new Response(null, { status: 400 });
290
+ * if (result.event.type === "immersive.record.finished") await saveTrail(result.event.data);
291
+ * return new Response(null, { status: 200 });
292
+ * }
293
+ *
294
+ * // Node (Express, Fastify, ...): pass the RAW body (a string, or the Buffer a raw-body parser gives, before any JSON
295
+ * // parsing), the `Baseera-Signature` header and the secret.
296
+ * const result = await verifyWebhook(rawBody, req.headers["baseera-signature"], secret);
297
+ * ```
298
+ * The secret is the endpoint's `whsec_…` (shown once in the console). The comparison is constant time, a timestamp more than
299
+ * `toleranceSec` (default 300) from now is refused (replay), and a header with several `v1` values (a secret being rotated)
300
+ * passes when any one matches. Deliveries are retried, so ignore an event id you already handled (`result.event.id`, also the
301
+ * `Baseera-Event-Id` header). Never throws.
302
+ */
303
+ declare function verifyWebhook(request: WebhookRequestLike, secret: string, options?: VerifyWebhookOptions): Promise<VerifyWebhookResult>;
304
+ declare function verifyWebhook(rawBody: string | Uint8Array, signatureHeader: string | string[] | null | undefined, secret: string, options?: VerifyWebhookOptions): Promise<VerifyWebhookResult>;
305
+
306
+ export { type Baseera, type BaseeraOptions, KB_REQUEST_TIMEOUT_MS, KB_UPLOAD_TIMEOUT_MS, type KbDeleteResult, type KbFailure, type KbFailureCode, type KbFile, type KbStatusResult, type KbTenantUploadTokenResult, type KbUpsertInput, type KbUpsertManyResult, type KbUpsertResult, PURGE_TENANT_TIMEOUT_MS, type PurgeTenantKnowledgeOptions, type PurgeTenantKnowledgeResult, type SignalOptions, type SignalResult, type TenantUploadTokenOptions, VERIFY_FINISH_TIMEOUT_MS, type VerifyFinishOptions, type VerifyFinishResult, type VerifyWebhookOptions, type VerifyWebhookResult, type WebhookRequestLike, createBaseera, purgeTenantKnowledge, signTenantUploadToken, verifyFinish, verifyWebhook };