@opendatalabs/vana-sdk 3.18.1 → 3.19.1

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.
Files changed (37) hide show
  1. package/README.md +141 -0
  2. package/dist/auth/web3-signed-builder.cjs +3 -0
  3. package/dist/auth/web3-signed-builder.cjs.map +1 -1
  4. package/dist/auth/web3-signed-builder.d.ts +14 -0
  5. package/dist/auth/web3-signed-builder.js +3 -0
  6. package/dist/auth/web3-signed-builder.js.map +1 -1
  7. package/dist/errors.cjs +69 -0
  8. package/dist/errors.cjs.map +1 -1
  9. package/dist/errors.d.ts +117 -2
  10. package/dist/errors.js +60 -0
  11. package/dist/errors.js.map +1 -1
  12. package/dist/index.browser.d.ts +1 -0
  13. package/dist/index.browser.js +577 -29
  14. package/dist/index.browser.js.map +4 -4
  15. package/dist/index.node.cjs +605 -29
  16. package/dist/index.node.cjs.map +4 -4
  17. package/dist/index.node.d.ts +1 -0
  18. package/dist/index.node.js +577 -29
  19. package/dist/index.node.js.map +4 -4
  20. package/dist/protocol/derivative-questions.cjs +518 -0
  21. package/dist/protocol/derivative-questions.cjs.map +1 -0
  22. package/dist/protocol/derivative-questions.d.ts +396 -0
  23. package/dist/protocol/derivative-questions.js +507 -0
  24. package/dist/protocol/derivative-questions.js.map +1 -0
  25. package/dist/protocol/derivative-questions.test.d.ts +1 -0
  26. package/dist/protocol/personal-server-write.cjs +12 -108
  27. package/dist/protocol/personal-server-write.cjs.map +1 -1
  28. package/dist/protocol/personal-server-write.d.ts +2 -17
  29. package/dist/protocol/personal-server-write.js +7 -98
  30. package/dist/protocol/personal-server-write.js.map +1 -1
  31. package/dist/protocol/write-request.cjs +156 -0
  32. package/dist/protocol/write-request.cjs.map +1 -0
  33. package/dist/protocol/write-request.d.ts +75 -0
  34. package/dist/protocol/write-request.js +124 -0
  35. package/dist/protocol/write-request.js.map +1 -0
  36. package/dist/tests/mock-personal-server.d.ts +54 -0
  37. package/package.json +1 -1
@@ -0,0 +1,396 @@
1
+ /**
2
+ * Builder-side client for the Personal Server derivative question API.
3
+ *
4
+ * @remarks
5
+ * A question is a standing prompt over the owner's source scopes. The
6
+ * Personal Server answers it locally (the raw sources never leave the
7
+ * machine except through its inference call) and writes the answer into the
8
+ * derived scope as an ordinary derivative record, with lineage pointing at
9
+ * the sources. The builder then reads the derived scope with its normal read
10
+ * grant. Every source change re-runs the question, so a builder registers it
11
+ * once and keeps reading a scope that stays up to date.
12
+ *
13
+ * One grant carries the whole pipeline, and it needs all three of:
14
+ *
15
+ * - a bare read entry for every source scope (the answer exposes them, so
16
+ * the server refuses the registration otherwise:
17
+ * `DERIVATIVE_SOURCE_NOT_GRANTED`),
18
+ * - a bare read entry for the derived scope (to read the answer back),
19
+ * - `write:<derivedScope>` (the credential the question routes authorize
20
+ * against).
21
+ *
22
+ * Authentication is the Write API's, with no new credential: the write
23
+ * session bearer from {@link openWriteSession} plus a fresh, single-use
24
+ * `X-Vana-Write-Signature` Web3Signed proof over every request, carrying the
25
+ * grant id as a signed claim. These helpers own that: they open one session
26
+ * per `{ signer, Personal Server, grant }`, reuse it across calls, sign a new
27
+ * proof per request, and re-open the session once when a call comes back a
28
+ * 401 the session is responsible for (the Personal Server keeps sessions in
29
+ * memory and forgets them when it restarts; a 401 about the PROOF is
30
+ * surfaced as it is, since a new session would not change it).
31
+ *
32
+ * Two rules govern the proof on these routes, and both are the server's
33
+ * (`personal-server-ts` d91124d and later):
34
+ *
35
+ * - the signed `uri` claim covers the query string, not just the path,
36
+ * because `?derivedScope=` is what the list route authorizes against;
37
+ * - every call carries a fresh `nonce` claim, which becomes the server's
38
+ * replay key. Without one the whole proof is the key, so two identical
39
+ * polls signed inside the same second are refused as a replay.
40
+ *
41
+ * @category Protocol
42
+ */
43
+ import { z } from "zod";
44
+ import type { DataFileEnvelope } from "./data-file.js";
45
+ import { type WriteTransportRetryOptions } from "./write-request.js";
46
+ import { type ResolveWriteSignerOptions, type WriteSignerSource } from "./write-signer.js";
47
+ /** Path the question routes are mounted at. */
48
+ export declare const DERIVATIVE_QUESTIONS_PATH = "/v1/derivatives/questions";
49
+ /** The most source scopes one question may read. */
50
+ export declare const MAX_QUESTION_SOURCE_SCOPES = 16;
51
+ /** The longest question text the Personal Server accepts. */
52
+ export declare const MAX_QUESTION_CHARS = 8000;
53
+ /** The longest model id the Personal Server accepts. */
54
+ export declare const MAX_QUESTION_MODEL_CHARS = 128;
55
+ /** How long {@link waitForQuestion} polls before giving up. */
56
+ export declare const DEFAULT_QUESTION_TIMEOUT_MS = 120000;
57
+ /** How long {@link waitForQuestion} waits between polls. */
58
+ export declare const DEFAULT_QUESTION_POLL_INTERVAL_MS = 2000;
59
+ /** Every state a question can be in. */
60
+ export declare const QUESTION_STATUSES: readonly ["pending", "ready", "failed", "stale"];
61
+ /**
62
+ * `pending` (never computed) -> `ready` | `failed`; a source change or an
63
+ * explicit recompute puts a computed question back to `stale`, which
64
+ * settles as `ready` or `failed` again.
65
+ */
66
+ export declare const QuestionStatusSchema: z.ZodEnum<{
67
+ pending: "pending";
68
+ ready: "ready";
69
+ failed: "failed";
70
+ stale: "stale";
71
+ }>;
72
+ /** @see {@link QuestionStatusSchema} */
73
+ export type QuestionStatus = z.infer<typeof QuestionStatusSchema>;
74
+ /** Who registered the question: the owner, or a builder under a grant. */
75
+ export declare const QuestionRegisteredBySchema: z.ZodUnion<readonly [z.ZodObject<{
76
+ kind: z.ZodLiteral<"owner">;
77
+ }, z.core.$strip>, z.ZodObject<{
78
+ kind: z.ZodLiteral<"builder">;
79
+ builder: z.ZodString;
80
+ grantId: z.ZodString;
81
+ }, z.core.$strip>]>;
82
+ /** @see {@link QuestionRegisteredBySchema} */
83
+ export type QuestionRegisteredBy = z.infer<typeof QuestionRegisteredBySchema>;
84
+ /**
85
+ * A question registration as the Personal Server reports it (the answer of
86
+ * register, get and list).
87
+ */
88
+ export declare const DerivativeQuestionSchema: z.ZodObject<{
89
+ questionId: z.ZodString;
90
+ derivedScope: z.ZodString;
91
+ sourceScopes: z.ZodArray<z.ZodString>;
92
+ question: z.ZodString;
93
+ model: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
94
+ registeredBy: z.ZodUnion<readonly [z.ZodObject<{
95
+ kind: z.ZodLiteral<"owner">;
96
+ }, z.core.$strip>, z.ZodObject<{
97
+ kind: z.ZodLiteral<"builder">;
98
+ builder: z.ZodString;
99
+ grantId: z.ZodString;
100
+ }, z.core.$strip>]>;
101
+ status: z.ZodEnum<{
102
+ pending: "pending";
103
+ ready: "ready";
104
+ failed: "failed";
105
+ stale: "stale";
106
+ }>;
107
+ error: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
108
+ createdAt: z.ZodString;
109
+ updatedAt: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
110
+ lastComputedAt: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
111
+ derivedVersion: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodNumber>>, z.ZodTransform<number | null, number | null | undefined>>;
112
+ derivedCollectedAt: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
113
+ }, z.core.$strip>;
114
+ /** @see {@link DerivativeQuestionSchema} */
115
+ export type DerivativeQuestion = z.infer<typeof DerivativeQuestionSchema>;
116
+ /**
117
+ * The 202 answer of a recompute request: the same registration view every
118
+ * other question route answers, so a client needs one schema.
119
+ *
120
+ * @remarks
121
+ * Older Personal Servers answered only
122
+ * `{ questionId, derivedScope, status }` here. The full view is a superset
123
+ * of those three fields, so code reading them is unaffected, but the answer
124
+ * of a server before `personal-server-ts` d91124d no longer parses.
125
+ */
126
+ export declare const QuestionRecomputeResultSchema: z.ZodObject<{
127
+ questionId: z.ZodString;
128
+ derivedScope: z.ZodString;
129
+ sourceScopes: z.ZodArray<z.ZodString>;
130
+ question: z.ZodString;
131
+ model: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
132
+ registeredBy: z.ZodUnion<readonly [z.ZodObject<{
133
+ kind: z.ZodLiteral<"owner">;
134
+ }, z.core.$strip>, z.ZodObject<{
135
+ kind: z.ZodLiteral<"builder">;
136
+ builder: z.ZodString;
137
+ grantId: z.ZodString;
138
+ }, z.core.$strip>]>;
139
+ status: z.ZodEnum<{
140
+ pending: "pending";
141
+ ready: "ready";
142
+ failed: "failed";
143
+ stale: "stale";
144
+ }>;
145
+ error: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
146
+ createdAt: z.ZodString;
147
+ updatedAt: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
148
+ lastComputedAt: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
149
+ derivedVersion: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodNumber>>, z.ZodTransform<number | null, number | null | undefined>>;
150
+ derivedCollectedAt: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
151
+ }, z.core.$strip>;
152
+ /** @see {@link QuestionRecomputeResultSchema} */
153
+ export type QuestionRecomputeResult = DerivativeQuestion;
154
+ /** The answer of a delete request. */
155
+ export declare const QuestionDeleteResultSchema: z.ZodObject<{
156
+ questionId: z.ZodString;
157
+ deleted: z.ZodLiteral<true>;
158
+ }, z.core.$strip>;
159
+ /** @see {@link QuestionDeleteResultSchema} */
160
+ export type QuestionDeleteResult = z.infer<typeof QuestionDeleteResultSchema>;
161
+ /**
162
+ * Connection, credential and transport shared by every question call.
163
+ *
164
+ * @remarks
165
+ * The write session is opened on demand and reused for every later call
166
+ * made with the same `signer` object, Personal Server, audience, grant and
167
+ * `fetch`; a 401 re-opens it once and replays the call.
168
+ */
169
+ export interface DerivativeQuestionAuthParams extends ResolveWriteSignerOptions {
170
+ /** Personal Server origin, e.g. `https://ps.example.com`. */
171
+ personalServerUrl: string;
172
+ /** Builder key: a viem `LocalAccount`, `WalletClient`, or `{ signMessage }`. */
173
+ signer: WriteSignerSource;
174
+ /**
175
+ * The grant the call runs under. It must carry `write:<derivedScope>`, a
176
+ * bare read entry for the derived scope, and a bare read entry for every
177
+ * source scope.
178
+ */
179
+ grantId: string;
180
+ /** Web3Signed audience; defaults to `personalServerUrl`. */
181
+ audience?: string;
182
+ /** `fetch` to use; defaults to `globalThis.fetch`. */
183
+ fetch?: typeof fetch;
184
+ /** Extra request headers. */
185
+ headers?: HeadersInit;
186
+ retry?: WriteTransportRetryOptions;
187
+ /** Aborts the request (and, for {@link waitForQuestion}, the polling). */
188
+ signal?: AbortSignal;
189
+ }
190
+ export interface RegisterQuestionParams extends DerivativeQuestionAuthParams {
191
+ /**
192
+ * The scope the answer is written into. Must not share its first
193
+ * dot-segment with any source scope, so put derivatives in the app's own
194
+ * namespace.
195
+ */
196
+ derivedScope: string;
197
+ /**
198
+ * The scopes the question reads: 1 to
199
+ * {@link MAX_QUESTION_SOURCE_SCOPES} distinct scopes, none of them the
200
+ * derived scope. They do not have to hold data yet: the question computes
201
+ * once they do.
202
+ */
203
+ sourceScopes: readonly string[];
204
+ /** The prompt, 1 to {@link MAX_QUESTION_CHARS} characters. */
205
+ question: string;
206
+ /** Model id override; omitted = the Personal Server's default model. */
207
+ model?: string;
208
+ }
209
+ export interface GetQuestionParams extends DerivativeQuestionAuthParams {
210
+ questionId: string;
211
+ }
212
+ export interface ListQuestionsParams extends DerivativeQuestionAuthParams {
213
+ /**
214
+ * The derived scope to list. A builder must name one (it may only see its
215
+ * own questions on a scope it may write); the unfiltered list is the
216
+ * owner's.
217
+ */
218
+ derivedScope: string;
219
+ }
220
+ export interface RecomputeQuestionParams extends DerivativeQuestionAuthParams {
221
+ questionId: string;
222
+ }
223
+ export interface DeleteQuestionParams extends DerivativeQuestionAuthParams {
224
+ questionId: string;
225
+ }
226
+ export interface WaitForQuestionParams extends DerivativeQuestionAuthParams {
227
+ questionId: string;
228
+ /** Give up after this long (default {@link DEFAULT_QUESTION_TIMEOUT_MS}). */
229
+ timeoutMs?: number;
230
+ /** Wait between polls (default {@link DEFAULT_QUESTION_POLL_INTERVAL_MS}). */
231
+ pollIntervalMs?: number;
232
+ }
233
+ export interface AskPersonalServerParams extends RegisterQuestionParams {
234
+ timeoutMs?: number;
235
+ pollIntervalMs?: number;
236
+ }
237
+ /** {@link askPersonalServer}'s answer. */
238
+ export interface AskPersonalServerResult {
239
+ /** The settled registration (`status` is `ready`). */
240
+ registration: DerivativeQuestion;
241
+ /** The derived record the Personal Server wrote and the builder just read. */
242
+ record: DataFileEnvelope;
243
+ }
244
+ /**
245
+ * Register a standing question over the owner's source scopes.
246
+ *
247
+ * @remarks
248
+ * Sends `POST /v1/derivatives/questions`. The registration comes back
249
+ * `pending` and the first compute is scheduled immediately; poll it with
250
+ * {@link waitForQuestion}, then read `derivedScope`.
251
+ *
252
+ * @example
253
+ * ```typescript
254
+ * const registered = await registerQuestion({
255
+ * personalServerUrl: "https://ps.example.com",
256
+ * signer,
257
+ * grantId,
258
+ * derivedScope: "coach.weekly",
259
+ * sourceScopes: ["oura.sleep", "chatgpt.conversations"],
260
+ * question: "How did my sleep relate to my mood this week?",
261
+ * });
262
+ * ```
263
+ * @returns The registration, `status: "pending"`.
264
+ * @throws {WriteRequestError} Before sending: a missing grant, a bad scope
265
+ * list, an over-long question, a derived scope under a source's namespace.
266
+ * @throws {DerivativeSourceNotGrantedError} 403: a source scope is not
267
+ * read-granted to the builder (`details.scopes`).
268
+ * @throws {DerivativeCycleError} 409: the question would make the derived
269
+ * scope a transitive source of itself.
270
+ * @throws {DerivativeQuestionInvalidError} 400 from the server.
271
+ * @throws {DerivativeComputeUnavailableError} 503: no compute layer.
272
+ * @throws {WriteForbiddenError} 403: the grant does not authorize writing
273
+ * the derived scope.
274
+ */
275
+ export declare function registerQuestion(params: RegisterQuestionParams): Promise<DerivativeQuestion>;
276
+ /**
277
+ * Read one question's current state.
278
+ *
279
+ * @remarks
280
+ * Sends `GET /v1/derivatives/questions/:id`. A builder only sees questions
281
+ * it registered itself; anything else is a 404.
282
+ *
283
+ * @returns The registration, including `status`, `lastComputedAt`,
284
+ * `derivedVersion` and (when it failed) `error`.
285
+ * @throws {DerivativeQuestionNotFoundError} 404: unknown id, or not this
286
+ * builder's question.
287
+ */
288
+ export declare function getQuestion(params: GetQuestionParams): Promise<DerivativeQuestion>;
289
+ /**
290
+ * List the questions this builder registered on a derived scope.
291
+ *
292
+ * @remarks
293
+ * Sends `GET /v1/derivatives/questions?derivedScope=...`. The scope is
294
+ * required for a builder: it is what the call is authorized against, which
295
+ * is exactly why the signed proof commits to the query string as well as the
296
+ * path. The target is built once and used for both, so the signature and the
297
+ * request can never name different scopes.
298
+ *
299
+ * @returns The registrations, newest state included.
300
+ * @throws {DerivativeDerivedScopeRequiredError} 400
301
+ * `DERIVATIVE_DERIVED_SCOPE_REQUIRED` when the server saw no
302
+ * `?derivedScope=` (the SDK refuses an empty one before sending).
303
+ */
304
+ export declare function listQuestions(params: ListQuestionsParams): Promise<DerivativeQuestion[]>;
305
+ /**
306
+ * Ask the Personal Server to recompute a question now.
307
+ *
308
+ * @remarks
309
+ * Sends `POST /v1/derivatives/questions/:id/recompute`, which answers 202
310
+ * and schedules the compute immediately instead of after the usual quiet
311
+ * period. Use it to retry a `failed` question; a source change recomputes on
312
+ * its own.
313
+ *
314
+ * @returns The full registration view, with the status the question was put
315
+ * into (`pending` when it had never computed, else `stale`). Servers
316
+ * before `personal-server-ts` d91124d answered only
317
+ * `{ questionId, derivedScope, status }` here, which no longer parses.
318
+ */
319
+ export declare function recomputeQuestion(params: RecomputeQuestionParams): Promise<QuestionRecomputeResult>;
320
+ /**
321
+ * Delete a question registration.
322
+ *
323
+ * @remarks
324
+ * Sends `DELETE /v1/derivatives/questions/:id`. The question stops
325
+ * recomputing; the derived records it already wrote are left alone (delete
326
+ * those through the data-point deletion path).
327
+ *
328
+ * @returns `{ questionId, deleted: true }`.
329
+ */
330
+ export declare function deleteQuestion(params: DeleteQuestionParams): Promise<QuestionDeleteResult>;
331
+ /**
332
+ * Poll a question until it settles.
333
+ *
334
+ * @remarks
335
+ * Calls {@link getQuestion} every `pollIntervalMs` until `status` is `ready`
336
+ * or `failed` and returns that state; a `failed` question is returned, not
337
+ * thrown, so the caller can read `error` and decide whether to
338
+ * {@link recomputeQuestion}. All polls share the one write session and each
339
+ * signs its own proof.
340
+ *
341
+ * @example
342
+ * ```typescript
343
+ * const settled = await waitForQuestion({
344
+ * personalServerUrl,
345
+ * signer,
346
+ * grantId,
347
+ * questionId: registered.questionId,
348
+ * timeoutMs: 60_000,
349
+ * });
350
+ * if (settled.status === "ready") {
351
+ * // read derivedScope
352
+ * }
353
+ * ```
354
+ * @returns The settled registration (`ready` or `failed`).
355
+ * @throws {DerivativeQuestionTimeoutError} The question had not settled
356
+ * within `timeoutMs`; it keeps computing on the server.
357
+ * @throws Whatever {@link getQuestion} throws, and the `signal`'s abort
358
+ * reason when the caller aborts.
359
+ */
360
+ export declare function waitForQuestion(params: WaitForQuestionParams): Promise<DerivativeQuestion>;
361
+ /**
362
+ * Register a question, wait for it, and read the answer: the whole builder
363
+ * loop in one call.
364
+ *
365
+ * @remarks
366
+ * {@link registerQuestion} + {@link waitForQuestion} +
367
+ * {@link readPersonalServerData} on the derived scope, which is why the
368
+ * grant needs a bare read entry for `derivedScope` on top of
369
+ * `write:<derivedScope>` and the source reads. The read is the plain
370
+ * Web3Signed one; when the grant is priced, settle the 402 yourself with the
371
+ * escrow-aware read from `@opendatalabs/vana-sdk/server` and use
372
+ * {@link registerQuestion} and {@link waitForQuestion} directly.
373
+ *
374
+ * A question registered this way keeps recomputing after the call returns:
375
+ * every later change to a source scope refreshes the derived record, and the
376
+ * builder can read it again without registering anything.
377
+ *
378
+ * @example
379
+ * ```typescript
380
+ * const { registration, record } = await askPersonalServer({
381
+ * personalServerUrl: "https://ps.example.com",
382
+ * signer,
383
+ * grantId,
384
+ * derivedScope: "coach.weekly",
385
+ * sourceScopes: ["oura.sleep"],
386
+ * question: "How did my sleep trend this week?",
387
+ * });
388
+ * console.log(record.data.answer, registration.questionId);
389
+ * ```
390
+ * @returns The settled registration and the derived record.
391
+ * @throws {DerivativeQuestionFailedError} The question settled as `failed`
392
+ * (`details.error` is the server's reason).
393
+ * @throws Everything {@link registerQuestion}, {@link waitForQuestion} and
394
+ * the read path throw.
395
+ */
396
+ export declare function askPersonalServer(params: AskPersonalServerParams): Promise<AskPersonalServerResult>;