@opendatalabs/vana-sdk 3.18.1 → 3.19.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,355 @@
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 401
28
+ * (the Personal Server keeps sessions in memory and forgets them when it
29
+ * restarts).
30
+ *
31
+ * @category Protocol
32
+ */
33
+ import { z } from "zod";
34
+ import type { DataFileEnvelope } from "./data-file.js";
35
+ import { type WriteTransportRetryOptions } from "./write-request.js";
36
+ import { type ResolveWriteSignerOptions, type WriteSignerSource } from "./write-signer.js";
37
+ /** Path the question routes are mounted at. */
38
+ export declare const DERIVATIVE_QUESTIONS_PATH = "/v1/derivatives/questions";
39
+ /** The most source scopes one question may read. */
40
+ export declare const MAX_QUESTION_SOURCE_SCOPES = 16;
41
+ /** The longest question text the Personal Server accepts. */
42
+ export declare const MAX_QUESTION_CHARS = 8000;
43
+ /** The longest model id the Personal Server accepts. */
44
+ export declare const MAX_QUESTION_MODEL_CHARS = 128;
45
+ /** How long {@link waitForQuestion} polls before giving up. */
46
+ export declare const DEFAULT_QUESTION_TIMEOUT_MS = 120000;
47
+ /** How long {@link waitForQuestion} waits between polls. */
48
+ export declare const DEFAULT_QUESTION_POLL_INTERVAL_MS = 2000;
49
+ /** Every state a question can be in. */
50
+ export declare const QUESTION_STATUSES: readonly ["pending", "ready", "failed", "stale"];
51
+ /**
52
+ * `pending` (never computed) -> `ready` | `failed`; a source change or an
53
+ * explicit recompute puts a computed question back to `stale`, which
54
+ * settles as `ready` or `failed` again.
55
+ */
56
+ export declare const QuestionStatusSchema: z.ZodEnum<{
57
+ pending: "pending";
58
+ ready: "ready";
59
+ failed: "failed";
60
+ stale: "stale";
61
+ }>;
62
+ /** @see {@link QuestionStatusSchema} */
63
+ export type QuestionStatus = z.infer<typeof QuestionStatusSchema>;
64
+ /** Who registered the question: the owner, or a builder under a grant. */
65
+ export declare const QuestionRegisteredBySchema: z.ZodUnion<readonly [z.ZodObject<{
66
+ kind: z.ZodLiteral<"owner">;
67
+ }, z.core.$strip>, z.ZodObject<{
68
+ kind: z.ZodLiteral<"builder">;
69
+ builder: z.ZodString;
70
+ grantId: z.ZodString;
71
+ }, z.core.$strip>]>;
72
+ /** @see {@link QuestionRegisteredBySchema} */
73
+ export type QuestionRegisteredBy = z.infer<typeof QuestionRegisteredBySchema>;
74
+ /**
75
+ * A question registration as the Personal Server reports it (the answer of
76
+ * register, get and list).
77
+ */
78
+ export declare const DerivativeQuestionSchema: z.ZodObject<{
79
+ questionId: z.ZodString;
80
+ derivedScope: z.ZodString;
81
+ sourceScopes: z.ZodArray<z.ZodString>;
82
+ question: z.ZodString;
83
+ model: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
84
+ registeredBy: z.ZodUnion<readonly [z.ZodObject<{
85
+ kind: z.ZodLiteral<"owner">;
86
+ }, z.core.$strip>, z.ZodObject<{
87
+ kind: z.ZodLiteral<"builder">;
88
+ builder: z.ZodString;
89
+ grantId: z.ZodString;
90
+ }, z.core.$strip>]>;
91
+ status: z.ZodEnum<{
92
+ pending: "pending";
93
+ ready: "ready";
94
+ failed: "failed";
95
+ stale: "stale";
96
+ }>;
97
+ error: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
98
+ createdAt: z.ZodString;
99
+ updatedAt: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
100
+ lastComputedAt: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
101
+ derivedVersion: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodNumber>>, z.ZodTransform<number | null, number | null | undefined>>;
102
+ derivedCollectedAt: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
103
+ }, z.core.$strip>;
104
+ /** @see {@link DerivativeQuestionSchema} */
105
+ export type DerivativeQuestion = z.infer<typeof DerivativeQuestionSchema>;
106
+ /** The 202 answer of a recompute request. */
107
+ export declare const QuestionRecomputeResultSchema: z.ZodObject<{
108
+ questionId: z.ZodString;
109
+ derivedScope: z.ZodString;
110
+ status: z.ZodEnum<{
111
+ pending: "pending";
112
+ ready: "ready";
113
+ failed: "failed";
114
+ stale: "stale";
115
+ }>;
116
+ }, z.core.$strip>;
117
+ /** @see {@link QuestionRecomputeResultSchema} */
118
+ export type QuestionRecomputeResult = z.infer<typeof QuestionRecomputeResultSchema>;
119
+ /** The answer of a delete request. */
120
+ export declare const QuestionDeleteResultSchema: z.ZodObject<{
121
+ questionId: z.ZodString;
122
+ deleted: z.ZodLiteral<true>;
123
+ }, z.core.$strip>;
124
+ /** @see {@link QuestionDeleteResultSchema} */
125
+ export type QuestionDeleteResult = z.infer<typeof QuestionDeleteResultSchema>;
126
+ /**
127
+ * Connection, credential and transport shared by every question call.
128
+ *
129
+ * @remarks
130
+ * The write session is opened on demand and reused for every later call
131
+ * made with the same `signer` object, Personal Server, audience, grant and
132
+ * `fetch`; a 401 re-opens it once and replays the call.
133
+ */
134
+ export interface DerivativeQuestionAuthParams extends ResolveWriteSignerOptions {
135
+ /** Personal Server origin, e.g. `https://ps.example.com`. */
136
+ personalServerUrl: string;
137
+ /** Builder key: a viem `LocalAccount`, `WalletClient`, or `{ signMessage }`. */
138
+ signer: WriteSignerSource;
139
+ /**
140
+ * The grant the call runs under. It must carry `write:<derivedScope>`, a
141
+ * bare read entry for the derived scope, and a bare read entry for every
142
+ * source scope.
143
+ */
144
+ grantId: string;
145
+ /** Web3Signed audience; defaults to `personalServerUrl`. */
146
+ audience?: string;
147
+ /** `fetch` to use; defaults to `globalThis.fetch`. */
148
+ fetch?: typeof fetch;
149
+ /** Extra request headers. */
150
+ headers?: HeadersInit;
151
+ retry?: WriteTransportRetryOptions;
152
+ /** Aborts the request (and, for {@link waitForQuestion}, the polling). */
153
+ signal?: AbortSignal;
154
+ }
155
+ export interface RegisterQuestionParams extends DerivativeQuestionAuthParams {
156
+ /**
157
+ * The scope the answer is written into. Must not share its first
158
+ * dot-segment with any source scope, so put derivatives in the app's own
159
+ * namespace.
160
+ */
161
+ derivedScope: string;
162
+ /**
163
+ * The scopes the question reads: 1 to
164
+ * {@link MAX_QUESTION_SOURCE_SCOPES} distinct scopes, none of them the
165
+ * derived scope. They do not have to hold data yet: the question computes
166
+ * once they do.
167
+ */
168
+ sourceScopes: readonly string[];
169
+ /** The prompt, 1 to {@link MAX_QUESTION_CHARS} characters. */
170
+ question: string;
171
+ /** Model id override; omitted = the Personal Server's default model. */
172
+ model?: string;
173
+ }
174
+ export interface GetQuestionParams extends DerivativeQuestionAuthParams {
175
+ questionId: string;
176
+ }
177
+ export interface ListQuestionsParams extends DerivativeQuestionAuthParams {
178
+ /**
179
+ * The derived scope to list. A builder must name one (it may only see its
180
+ * own questions on a scope it may write); the unfiltered list is the
181
+ * owner's.
182
+ */
183
+ derivedScope: string;
184
+ }
185
+ export interface RecomputeQuestionParams extends DerivativeQuestionAuthParams {
186
+ questionId: string;
187
+ }
188
+ export interface DeleteQuestionParams extends DerivativeQuestionAuthParams {
189
+ questionId: string;
190
+ }
191
+ export interface WaitForQuestionParams extends DerivativeQuestionAuthParams {
192
+ questionId: string;
193
+ /** Give up after this long (default {@link DEFAULT_QUESTION_TIMEOUT_MS}). */
194
+ timeoutMs?: number;
195
+ /** Wait between polls (default {@link DEFAULT_QUESTION_POLL_INTERVAL_MS}). */
196
+ pollIntervalMs?: number;
197
+ }
198
+ export interface AskPersonalServerParams extends RegisterQuestionParams {
199
+ timeoutMs?: number;
200
+ pollIntervalMs?: number;
201
+ }
202
+ /** {@link askPersonalServer}'s answer. */
203
+ export interface AskPersonalServerResult {
204
+ /** The settled registration (`status` is `ready`). */
205
+ registration: DerivativeQuestion;
206
+ /** The derived record the Personal Server wrote and the builder just read. */
207
+ record: DataFileEnvelope;
208
+ }
209
+ /**
210
+ * Register a standing question over the owner's source scopes.
211
+ *
212
+ * @remarks
213
+ * Sends `POST /v1/derivatives/questions`. The registration comes back
214
+ * `pending` and the first compute is scheduled immediately; poll it with
215
+ * {@link waitForQuestion}, then read `derivedScope`.
216
+ *
217
+ * @example
218
+ * ```typescript
219
+ * const registered = await registerQuestion({
220
+ * personalServerUrl: "https://ps.example.com",
221
+ * signer,
222
+ * grantId,
223
+ * derivedScope: "coach.weekly",
224
+ * sourceScopes: ["oura.sleep", "chatgpt.conversations"],
225
+ * question: "How did my sleep relate to my mood this week?",
226
+ * });
227
+ * ```
228
+ * @returns The registration, `status: "pending"`.
229
+ * @throws {WriteRequestError} Before sending: a missing grant, a bad scope
230
+ * list, an over-long question, a derived scope under a source's namespace.
231
+ * @throws {DerivativeSourceNotGrantedError} 403: a source scope is not
232
+ * read-granted to the builder (`details.scopes`).
233
+ * @throws {DerivativeCycleError} 409: the question would make the derived
234
+ * scope a transitive source of itself.
235
+ * @throws {DerivativeQuestionInvalidError} 400 from the server.
236
+ * @throws {DerivativeComputeUnavailableError} 503: no compute layer.
237
+ * @throws {WriteForbiddenError} 403: the grant does not authorize writing
238
+ * the derived scope.
239
+ */
240
+ export declare function registerQuestion(params: RegisterQuestionParams): Promise<DerivativeQuestion>;
241
+ /**
242
+ * Read one question's current state.
243
+ *
244
+ * @remarks
245
+ * Sends `GET /v1/derivatives/questions/:id`. A builder only sees questions
246
+ * it registered itself; anything else is a 404.
247
+ *
248
+ * @returns The registration, including `status`, `lastComputedAt`,
249
+ * `derivedVersion` and (when it failed) `error`.
250
+ * @throws {DerivativeQuestionNotFoundError} 404: unknown id, or not this
251
+ * builder's question.
252
+ */
253
+ export declare function getQuestion(params: GetQuestionParams): Promise<DerivativeQuestion>;
254
+ /**
255
+ * List the questions this builder registered on a derived scope.
256
+ *
257
+ * @remarks
258
+ * Sends `GET /v1/derivatives/questions?derivedScope=...`. The scope is
259
+ * required for a builder: it is what the call is authorized against. Note
260
+ * that the query string is outside the signed proof, which covers the path.
261
+ *
262
+ * @returns The registrations, newest state included.
263
+ */
264
+ export declare function listQuestions(params: ListQuestionsParams): Promise<DerivativeQuestion[]>;
265
+ /**
266
+ * Ask the Personal Server to recompute a question now.
267
+ *
268
+ * @remarks
269
+ * Sends `POST /v1/derivatives/questions/:id/recompute`, which answers 202
270
+ * and schedules the compute immediately instead of after the usual quiet
271
+ * period. Use it to retry a `failed` question; a source change recomputes on
272
+ * its own.
273
+ *
274
+ * @returns `{ questionId, derivedScope, status }` with the status the
275
+ * question was put into (`pending` when it had never computed, else
276
+ * `stale`).
277
+ */
278
+ export declare function recomputeQuestion(params: RecomputeQuestionParams): Promise<QuestionRecomputeResult>;
279
+ /**
280
+ * Delete a question registration.
281
+ *
282
+ * @remarks
283
+ * Sends `DELETE /v1/derivatives/questions/:id`. The question stops
284
+ * recomputing; the derived records it already wrote are left alone (delete
285
+ * those through the data-point deletion path).
286
+ *
287
+ * @returns `{ questionId, deleted: true }`.
288
+ */
289
+ export declare function deleteQuestion(params: DeleteQuestionParams): Promise<QuestionDeleteResult>;
290
+ /**
291
+ * Poll a question until it settles.
292
+ *
293
+ * @remarks
294
+ * Calls {@link getQuestion} every `pollIntervalMs` until `status` is `ready`
295
+ * or `failed` and returns that state; a `failed` question is returned, not
296
+ * thrown, so the caller can read `error` and decide whether to
297
+ * {@link recomputeQuestion}. All polls share the one write session and each
298
+ * signs its own proof.
299
+ *
300
+ * @example
301
+ * ```typescript
302
+ * const settled = await waitForQuestion({
303
+ * personalServerUrl,
304
+ * signer,
305
+ * grantId,
306
+ * questionId: registered.questionId,
307
+ * timeoutMs: 60_000,
308
+ * });
309
+ * if (settled.status === "ready") {
310
+ * // read derivedScope
311
+ * }
312
+ * ```
313
+ * @returns The settled registration (`ready` or `failed`).
314
+ * @throws {DerivativeQuestionTimeoutError} The question had not settled
315
+ * within `timeoutMs`; it keeps computing on the server.
316
+ * @throws Whatever {@link getQuestion} throws, and the `signal`'s abort
317
+ * reason when the caller aborts.
318
+ */
319
+ export declare function waitForQuestion(params: WaitForQuestionParams): Promise<DerivativeQuestion>;
320
+ /**
321
+ * Register a question, wait for it, and read the answer: the whole builder
322
+ * loop in one call.
323
+ *
324
+ * @remarks
325
+ * {@link registerQuestion} + {@link waitForQuestion} +
326
+ * {@link readPersonalServerData} on the derived scope, which is why the
327
+ * grant needs a bare read entry for `derivedScope` on top of
328
+ * `write:<derivedScope>` and the source reads. The read is the plain
329
+ * Web3Signed one; when the grant is priced, settle the 402 yourself with the
330
+ * escrow-aware read from `@opendatalabs/vana-sdk/server` and use
331
+ * {@link registerQuestion} and {@link waitForQuestion} directly.
332
+ *
333
+ * A question registered this way keeps recomputing after the call returns:
334
+ * every later change to a source scope refreshes the derived record, and the
335
+ * builder can read it again without registering anything.
336
+ *
337
+ * @example
338
+ * ```typescript
339
+ * const { registration, record } = await askPersonalServer({
340
+ * personalServerUrl: "https://ps.example.com",
341
+ * signer,
342
+ * grantId,
343
+ * derivedScope: "coach.weekly",
344
+ * sourceScopes: ["oura.sleep"],
345
+ * question: "How did my sleep trend this week?",
346
+ * });
347
+ * console.log(record.data.answer, registration.questionId);
348
+ * ```
349
+ * @returns The settled registration and the derived record.
350
+ * @throws {DerivativeQuestionFailedError} The question settled as `failed`
351
+ * (`details.error` is the server's reason).
352
+ * @throws Everything {@link registerQuestion}, {@link waitForQuestion} and
353
+ * the read path throw.
354
+ */
355
+ export declare function askPersonalServer(params: AskPersonalServerParams): Promise<AskPersonalServerResult>;