@sess.si/sdk 0.1.0-rc.5 → 0.1.0-rc.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.
Files changed (56) hide show
  1. package/CHANGELOG.md +43 -1
  2. package/NOTICE +18 -0
  3. package/README.md +72 -19
  4. package/dist/ask.d.ts +150 -0
  5. package/dist/ask.d.ts.map +1 -0
  6. package/dist/ask.js +465 -0
  7. package/dist/ask.js.map +1 -0
  8. package/dist/client.d.ts +8 -0
  9. package/dist/client.d.ts.map +1 -1
  10. package/dist/client.js +10 -0
  11. package/dist/client.js.map +1 -1
  12. package/dist/generated/openapi.d.ts +6461 -1009
  13. package/dist/generated/openapi.d.ts.map +1 -1
  14. package/dist/index.d.ts +1 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/internal/decode.d.ts.map +1 -1
  18. package/dist/internal/decode.js +4 -1
  19. package/dist/internal/decode.js.map +1 -1
  20. package/dist/polling.d.ts +8 -0
  21. package/dist/polling.d.ts.map +1 -1
  22. package/dist/polling.js +32 -1
  23. package/dist/polling.js.map +1 -1
  24. package/dist/qr/encoder.d.ts +11 -0
  25. package/dist/qr/encoder.d.ts.map +1 -0
  26. package/dist/qr/encoder.js +344 -0
  27. package/dist/qr/encoder.js.map +1 -0
  28. package/dist/qr/index.d.ts +56 -0
  29. package/dist/qr/index.d.ts.map +1 -0
  30. package/dist/qr/index.js +151 -0
  31. package/dist/qr/index.js.map +1 -0
  32. package/dist/sessions.d.ts.map +1 -1
  33. package/dist/sessions.js +7 -0
  34. package/dist/sessions.js.map +1 -1
  35. package/dist/transport.d.ts +2 -0
  36. package/dist/transport.d.ts.map +1 -1
  37. package/dist/transport.js +11 -2
  38. package/dist/transport.js.map +1 -1
  39. package/dist/types.d.ts +11 -0
  40. package/dist/types.d.ts.map +1 -1
  41. package/dist/types.js.map +1 -1
  42. package/dist/webhooks/index.js +1 -1
  43. package/dist/webhooks/index.js.map +1 -1
  44. package/package.json +6 -2
  45. package/src/ask.ts +636 -0
  46. package/src/client.ts +14 -0
  47. package/src/generated/openapi.ts +6724 -1163
  48. package/src/index.ts +1 -0
  49. package/src/internal/decode.ts +3 -1
  50. package/src/polling.ts +45 -1
  51. package/src/qr/encoder.ts +345 -0
  52. package/src/qr/index.ts +203 -0
  53. package/src/sessions.ts +11 -0
  54. package/src/transport.ts +11 -2
  55. package/src/types.ts +14 -1
  56. package/src/webhooks/index.ts +1 -1
package/src/ask.ts ADDED
@@ -0,0 +1,636 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { inspect } from 'node:util';
3
+ import { SessError } from './errors.js';
4
+ import { canonicalJson } from './receipts/json.js';
5
+ import type { ReceiptResource } from './receipts/resource.js';
6
+ import type { Sessions } from './sessions.js';
7
+ import { isInteractiveSession } from './types.js';
8
+ import type {
9
+ AcceptedResponse,
10
+ FieldSchema,
11
+ InteractiveInteraction,
12
+ InteractiveSession,
13
+ RequestOptions,
14
+ SurfaceComponent,
15
+ VersionedResult,
16
+ } from './types.js';
17
+ import { withSignal } from './internal/time.js';
18
+
19
+ interface AskFieldBase {
20
+ /** Key of this field in the answer: `^[a-z][a-z0-9_]{0,63}$`. */
21
+ readonly name: string;
22
+ /** Human-facing label, 1–200 characters. */
23
+ readonly label: string;
24
+ /** Default `true`, except boolean fields (default `false`). */
25
+ readonly required?: boolean;
26
+ }
27
+ /**
28
+ * One simple field of a single question. Each kind compiles to the ordinary interactive field
29
+ * with the runtime names, limits and schema semantics. `default` is a proposal the person can
30
+ * correct; it must itself be a valid value.
31
+ */
32
+ export type AskField =
33
+ | (AskFieldBase & { readonly type: 'text'; readonly multiline?: boolean; readonly default?: string })
34
+ | (AskFieldBase & {
35
+ readonly type: 'number' | 'integer';
36
+ readonly minimum?: number;
37
+ readonly maximum?: number;
38
+ readonly default?: number;
39
+ })
40
+ | (AskFieldBase & { readonly type: 'boolean'; readonly default?: boolean })
41
+ | (AskFieldBase & {
42
+ readonly type: 'choice';
43
+ readonly options: readonly [string, ...string[]];
44
+ readonly default?: string;
45
+ })
46
+ | (AskFieldBase & {
47
+ readonly type: 'multi_choice';
48
+ readonly options: readonly [string, ...string[]];
49
+ readonly default?: readonly string[];
50
+ });
51
+
52
+ /** A question plus typed fields: the same shape as the MCP `sess_ask` tool input. */
53
+ export interface AskInput<F extends readonly AskField[] = readonly AskField[]> {
54
+ /** Shown as the page title, 1–200 characters. */
55
+ readonly question: string;
56
+ /** Optional plain-text context shown above the fields, 1–4000 characters. */
57
+ readonly details?: string;
58
+ /** Submit button label, default `Send`. */
59
+ readonly submit_label?: string;
60
+ /** One to twelve fields with unique names. */
61
+ readonly fields: F;
62
+ /**
63
+ * Advanced: how long the link stays open, in whole seconds from creation: from 30 up to your
64
+ * plan's link lifetime (Sess checks the ceiling). Absent: the plan's lifetime.
65
+ */
66
+ readonly expires_in?: number;
67
+ }
68
+
69
+ type AskValue<T> = T extends { type: 'text' }
70
+ ? string
71
+ : T extends { type: 'number' | 'integer' }
72
+ ? number
73
+ : T extends { type: 'boolean' }
74
+ ? boolean
75
+ : T extends { type: 'choice'; options: readonly (infer O extends string)[] }
76
+ ? O
77
+ : T extends { type: 'multi_choice'; options: readonly (infer O extends string)[] }
78
+ ? readonly O[]
79
+ : never;
80
+ /** A checkbox and a multiple choice always have a value; other fields only when required. */
81
+ type AlwaysPresent<T> = T extends { type: 'boolean' | 'multi_choice' }
82
+ ? true
83
+ : T extends { required: false }
84
+ ? false
85
+ : T extends { required: true }
86
+ ? true
87
+ : T extends { required: boolean }
88
+ ? false
89
+ : true;
90
+ type Simplify<T> = { [K in keyof T]: T[K] } & {};
91
+ /** The verified answer type inferred from the field definitions (and checked at runtime). */
92
+ export type AskAnswer<F extends readonly AskField[]> = Simplify<
93
+ {
94
+ readonly [P in F[number] as AlwaysPresent<P> extends true ? P['name'] : never]: AskValue<P>;
95
+ } & {
96
+ readonly [P in F[number] as AlwaysPresent<P> extends true ? never : P['name']]?: AskValue<P>;
97
+ }
98
+ >;
99
+
100
+ export interface AskOptions extends RequestOptions {
101
+ /** Trusted expected receipt audience for this question; defaults to the client configuration. */
102
+ expectedWorkspaceId?: string;
103
+ }
104
+ export interface AskAnswerOptions {
105
+ /** Total local wait for the person, default ten minutes. Ending it never closes the Session. */
106
+ timeoutMs?: number;
107
+ /** Polling interval, default 1,500 ms plus jitter, minimum 1,000 ms. */
108
+ intervalMs?: number;
109
+ /** Ends the local wait of this call only. */
110
+ signal?: AbortSignal;
111
+ }
112
+ /** One question: its private link now, its verified answer later. */
113
+ export interface AskHandle<T> {
114
+ /** Private bearer link for the person. Deliver it only to them; keep it out of logs. */
115
+ readonly link: string;
116
+ readonly sessionId: string;
117
+ /** The Surface revision of the question, for recovery through the advanced API. */
118
+ readonly revision: number;
119
+ /**
120
+ * When the link stops taking answers (`action_expires_at`, ISO 8601). Nothing moves it. An
121
+ * answer accepted before it is still returned after it; with none, `answer()` ends with
122
+ * `wait_ended` code `LINK_EXPIRED`. Null only from a runtime that does not report it.
123
+ */
124
+ readonly expiresAt: string | null;
125
+ /**
126
+ * Waits for the answer, verifies its signed receipt and exact bindings, checks that it is still
127
+ * the current step, completes (closes) the Session, then returns the typed answer.
128
+ */
129
+ answer(options?: AskAnswerOptions): Promise<T>;
130
+ }
131
+
132
+ /** The runtime byte limit for one stored interaction. */
133
+ const SURFACE_LIMIT_BYTES = 131_072;
134
+ const LIMITS = Object.freeze({ fields: 12, options: 100, depth: 8, textMax: 4000 });
135
+ const TYPES = ['text', 'number', 'integer', 'boolean', 'choice', 'multi_choice'] as const;
136
+ type AskType = (typeof TYPES)[number];
137
+ const FIELD_NAME = /^[a-z][a-z0-9_]{0,63}$/;
138
+ const RESERVED = new Set(['__proto__', 'constructor', 'prototype']);
139
+ // Plain text: no C0/C1 controls other than tab and newline, no bidirectional overrides.
140
+ const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f‪-‮⁦-⁩]/;
141
+
142
+ /** Internal compiled field: what an accepted answer is checked against. */
143
+ interface CompiledField {
144
+ name: string;
145
+ type: AskType;
146
+ required: boolean;
147
+ options?: readonly string[];
148
+ minimum?: number;
149
+ maximum?: number;
150
+ }
151
+ export interface CompiledAsk {
152
+ interaction: InteractiveInteraction;
153
+ fields: readonly CompiledField[];
154
+ /** The link lifetime in seconds, when the question set one. */
155
+ expiresIn?: number;
156
+ }
157
+
158
+ /** The shortest link lifetime Sess accepts, in seconds (the ceiling is the plan's). */
159
+ export const LINK_LIFETIME_FLOOR_SECONDS = 30;
160
+
161
+ type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
162
+ type JsonObject = { [key: string]: Json };
163
+
164
+ function invalid(path: string, problem: string): never {
165
+ // Paths and problems only: caller values never enter the message.
166
+ throw new SessError('configuration', `Invalid question: ${path} ${problem}.`, {
167
+ code: 'INVALID_QUESTION',
168
+ outcome: 'not_sent',
169
+ });
170
+ }
171
+ function safeKey(key: string): string {
172
+ return /^[A-Za-z0-9_]{1,40}$/.test(key) ? key : '?';
173
+ }
174
+
175
+ /** Detached copy of plain JSON data: no accessors, symbols, special objects or deep nesting. */
176
+ function plain(value: unknown, path: string, depth = 0): Json {
177
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
178
+ if (typeof value === 'number') {
179
+ if (!Number.isFinite(value)) invalid(path, 'must be a finite number');
180
+ return value;
181
+ }
182
+ if (typeof value !== 'object') return invalid(path, 'must be JSON data');
183
+ if (depth >= LIMITS.depth) invalid(path, 'is nested too deeply');
184
+ if (Array.isArray(value)) {
185
+ if (Object.getPrototypeOf(value) !== Array.prototype) invalid(path, 'must be a plain array');
186
+ const out: Json[] = [];
187
+ for (let i = 0; i < value.length; i++) {
188
+ const descriptor = Object.getOwnPropertyDescriptor(value, i);
189
+ if (!descriptor || !('value' in descriptor)) invalid(`${path}[${i}]`, 'must be a plain element');
190
+ out.push(plain(descriptor.value, `${path}[${i}]`, depth + 1));
191
+ }
192
+ return out;
193
+ }
194
+ const prototype = Object.getPrototypeOf(value);
195
+ if (prototype !== Object.prototype && prototype !== null) invalid(path, 'must be a plain object');
196
+ if (Object.getOwnPropertySymbols(value).length) invalid(path, 'must not have symbol keys');
197
+ const out: JsonObject = {};
198
+ for (const key of Object.getOwnPropertyNames(value)) {
199
+ if (RESERVED.has(key)) invalid(path, 'has a reserved key');
200
+ const descriptor = Object.getOwnPropertyDescriptor(value, key)!;
201
+ if (!('value' in descriptor) || !descriptor.enumerable) invalid(path, 'must have plain data properties');
202
+ // An optional property given as undefined is omitted, as in request serialization.
203
+ if (descriptor.value === undefined) continue;
204
+ out[key] = plain(descriptor.value, path ? `${path}.${safeKey(key)}` : safeKey(key), depth + 1);
205
+ }
206
+ return out;
207
+ }
208
+
209
+ function object(value: Json | undefined, path: string): JsonObject {
210
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
211
+ return invalid(path, 'must be an object');
212
+ return value;
213
+ }
214
+ function closed(value: JsonObject, path: string, allowed: readonly string[], required: readonly string[]) {
215
+ for (const key of Object.keys(value))
216
+ if (!allowed.includes(key)) invalid(path, `has an unsupported property "${safeKey(key)}"`);
217
+ for (const key of required) if (!Object.hasOwn(value, key)) invalid(path, `needs "${key}"`);
218
+ }
219
+ const codePoints = (value: string) => [...value].length;
220
+ function text(value: Json | undefined, path: string, max: number): string {
221
+ if (typeof value !== 'string') return invalid(path, 'must be a string');
222
+ if (!value.isWellFormed()) invalid(path, 'must be well-formed Unicode');
223
+ const length = codePoints(value);
224
+ if (length < 1 || length > max) invalid(path, `must be 1–${max} characters`);
225
+ if (!/\S/.test(value)) invalid(path, 'must not be blank');
226
+ if (CONTROL.test(value)) invalid(path, 'contains control or bidirectional override characters');
227
+ return value;
228
+ }
229
+ function finite(value: Json | undefined, path: string): number {
230
+ if (typeof value !== 'number' || !Number.isFinite(value)) return invalid(path, 'must be a finite number');
231
+ return value;
232
+ }
233
+
234
+ /** Whether `value` is valid for the field: a proposal before creation or an accepted value after. */
235
+ function validValue(field: CompiledField, value: unknown): boolean {
236
+ switch (field.type) {
237
+ case 'text':
238
+ // The runtime bounds a string field without maxLength to 4000 code points.
239
+ return typeof value === 'string' && value.isWellFormed() && codePoints(value) <= LIMITS.textMax;
240
+ case 'number':
241
+ case 'integer':
242
+ return (
243
+ typeof value === 'number' &&
244
+ Number.isFinite(value) &&
245
+ (field.type === 'number' || Number.isInteger(value)) &&
246
+ (field.minimum === undefined || value >= field.minimum) &&
247
+ (field.maximum === undefined || value <= field.maximum)
248
+ );
249
+ case 'boolean':
250
+ return typeof value === 'boolean';
251
+ case 'choice':
252
+ return typeof value === 'string' && field.options!.includes(value);
253
+ case 'multi_choice':
254
+ return (
255
+ Array.isArray(value) &&
256
+ value.every((item) => typeof item === 'string' && field.options!.includes(item)) &&
257
+ new Set(value).size === value.length
258
+ );
259
+ }
260
+ }
261
+
262
+ function compileField(raw: Json, path: string, names: Set<string>) {
263
+ const f = object(raw, path);
264
+ closed(
265
+ f,
266
+ path,
267
+ ['name', 'label', 'type', 'required', 'options', 'default', 'multiline', 'minimum', 'maximum'],
268
+ ['name', 'label', 'type'],
269
+ );
270
+ if (typeof f.name !== 'string' || !FIELD_NAME.test(f.name) || RESERVED.has(f.name))
271
+ invalid(`${path}.name`, 'must match ^[a-z][a-z0-9_]{0,63}$');
272
+ const name = f.name;
273
+ if (names.has(name)) invalid(`${path}.name`, 'duplicates another field name');
274
+ names.add(name);
275
+ const label = text(f.label, `${path}.label`, 200);
276
+ const type = f.type as AskType;
277
+ if (!TYPES.includes(type)) invalid(`${path}.type`, `must be one of ${TYPES.join(', ')}`);
278
+ const choice = type === 'choice' || type === 'multi_choice';
279
+ if (choice !== (f.options !== undefined))
280
+ invalid(
281
+ `${path}.options`,
282
+ choice ? 'is required for choice fields' : 'is only allowed for choice fields',
283
+ );
284
+ if (f.multiline !== undefined && type !== 'text') invalid(`${path}.multiline`, 'is only allowed for text');
285
+ if ((f.minimum !== undefined || f.maximum !== undefined) && type !== 'number' && type !== 'integer')
286
+ invalid(path, 'minimum/maximum are only allowed for number and integer');
287
+ for (const key of ['required', 'multiline'] as const)
288
+ if (f[key] !== undefined && typeof f[key] !== 'boolean') invalid(`${path}.${key}`, 'must be a boolean');
289
+ const required = f.required === undefined ? type !== 'boolean' : f.required === true;
290
+ const compiled: CompiledField = { name, type, required };
291
+ let schema: FieldSchema;
292
+ switch (type) {
293
+ case 'text':
294
+ schema = { type: 'string' };
295
+ break;
296
+ case 'number':
297
+ case 'integer': {
298
+ const minimum = f.minimum === undefined ? undefined : finite(f.minimum, `${path}.minimum`);
299
+ const maximum = f.maximum === undefined ? undefined : finite(f.maximum, `${path}.maximum`);
300
+ if (minimum !== undefined && maximum !== undefined && minimum > maximum)
301
+ invalid(`${path}.minimum`, 'must not exceed maximum');
302
+ if (minimum !== undefined) compiled.minimum = minimum;
303
+ if (maximum !== undefined) compiled.maximum = maximum;
304
+ schema = {
305
+ type,
306
+ ...(minimum !== undefined ? { minimum } : {}),
307
+ ...(maximum !== undefined ? { maximum } : {}),
308
+ };
309
+ break;
310
+ }
311
+ case 'boolean':
312
+ schema = { type: 'boolean' };
313
+ break;
314
+ case 'choice':
315
+ case 'multi_choice': {
316
+ const options = f.options;
317
+ if (!Array.isArray(options) || options.length < 1 || options.length > LIMITS.options)
318
+ invalid(`${path}.options`, `must list 1–${LIMITS.options} options`);
319
+ const values = options.map((option, i) => text(option, `${path}.options[${i}]`, 200));
320
+ if (new Set(values).size !== values.length) invalid(`${path}.options`, 'must be unique');
321
+ compiled.options = Object.freeze([...values]);
322
+ schema =
323
+ type === 'choice'
324
+ ? { type: 'string', enum: values }
325
+ : { type: 'array', items: { type: 'string', enum: [...values] }, uniqueItems: true };
326
+ break;
327
+ }
328
+ }
329
+ if (f.default !== undefined && !validValue(compiled, f.default))
330
+ invalid(`${path}.default`, 'is not a valid value for this field');
331
+ const component: SurfaceComponent = {
332
+ type: 'field',
333
+ name,
334
+ label,
335
+ required,
336
+ schema,
337
+ ...(f.multiline !== undefined ? { multiline: f.multiline as boolean } : {}),
338
+ ...(f.default !== undefined ? { value: f.default } : {}),
339
+ };
340
+ return { component, compiled: Object.freeze(compiled) };
341
+ }
342
+
343
+ /**
344
+ * The one deterministic simple-field compiler: validates a question locally, without network,
345
+ * credential or clock access, and expands it into the ordinary interactive Surface.
346
+ */
347
+ export function compileAsk(input: unknown): CompiledAsk {
348
+ const a = object(plain(input, ''), 'input');
349
+ closed(a, 'input', ['question', 'details', 'fields', 'submit_label', 'expires_in'], ['question', 'fields']);
350
+ const expiresIn = a.expires_in;
351
+ if (
352
+ expiresIn !== undefined &&
353
+ (typeof expiresIn !== 'number' ||
354
+ !Number.isSafeInteger(expiresIn) ||
355
+ expiresIn < LINK_LIFETIME_FLOOR_SECONDS)
356
+ )
357
+ invalid('expires_in', `must be a whole number of seconds, at least ${LINK_LIFETIME_FLOOR_SECONDS}`);
358
+ const title = text(a.question, 'question', 200);
359
+ const details = a.details === undefined ? undefined : text(a.details, 'details', 4000);
360
+ const submit = a.submit_label === undefined ? 'Send' : text(a.submit_label, 'submit_label', 200);
361
+ const fields = a.fields;
362
+ if (!Array.isArray(fields) || fields.length < 1 || fields.length > LIMITS.fields)
363
+ invalid('fields', `must contain 1–${LIMITS.fields} fields`);
364
+ const components: SurfaceComponent[] = [];
365
+ if (details !== undefined) components.push({ type: 'text', text: details });
366
+ const names = new Set<string>();
367
+ const compiled: CompiledField[] = [];
368
+ fields.forEach((field, i) => {
369
+ const result = compileField(field, `fields[${i}]`, names);
370
+ components.push(result.component);
371
+ compiled.push(result.compiled);
372
+ });
373
+ const interaction: InteractiveInteraction = {
374
+ mode: 'interactive',
375
+ title,
376
+ source: { kind: 'sess_surface', components },
377
+ actions: [{ id: 'submit', label: submit, intent: 'submit' }],
378
+ };
379
+ if (Buffer.byteLength(JSON.stringify(interaction), 'utf8') > SURFACE_LIMIT_BYTES)
380
+ invalid('input', `exceeds the ${SURFACE_LIMIT_BYTES}-byte Surface limit`);
381
+ return {
382
+ interaction,
383
+ fields: Object.freeze(compiled),
384
+ ...(expiresIn !== undefined ? { expiresIn: expiresIn as number } : {}),
385
+ };
386
+ }
387
+
388
+ /**
389
+ * Checks verified answer data against the compiled fields and returns a frozen copy in field
390
+ * order. It follows the runtime decoding: a checkbox is always present, a multiple choice is
391
+ * always a list, and an empty optional value is absent.
392
+ */
393
+ export function checkAnswer(
394
+ fields: readonly CompiledField[],
395
+ data: unknown,
396
+ ): Readonly<Record<string, unknown>> {
397
+ const mismatch = () =>
398
+ new SessError('protocol', 'The verified answer does not match the question’s fields.', {
399
+ code: 'INVALID_RESPONSE',
400
+ });
401
+ if (data === null || typeof data !== 'object' || Array.isArray(data)) throw mismatch();
402
+ const source = data as Record<string, unknown>;
403
+ const known = new Set(fields.map((f) => f.name));
404
+ for (const key of Object.keys(source)) if (!known.has(key)) throw mismatch();
405
+ const out: Record<string, unknown> = {};
406
+ for (const field of fields) {
407
+ if (!Object.hasOwn(source, field.name)) {
408
+ if (field.required || field.type === 'boolean' || field.type === 'multi_choice') throw mismatch();
409
+ continue;
410
+ }
411
+ const value = source[field.name];
412
+ if (!validValue(field, value) || value === '') throw mismatch();
413
+ out[field.name] = Array.isArray(value) ? Object.freeze([...value]) : value;
414
+ }
415
+ return Object.freeze(out);
416
+ }
417
+
418
+ /** The replay identity of the completion, saved before its first dispatch. */
419
+ interface Completion {
420
+ eventId: string;
421
+ ifMatch: string;
422
+ idempotencyKey: string;
423
+ uncertain: boolean;
424
+ }
425
+
426
+ class Handle<T> implements AskHandle<T> {
427
+ readonly sessionId: string;
428
+ readonly revision: number;
429
+ readonly expiresAt: string | null;
430
+ #link: string;
431
+ #sessions: Sessions;
432
+ #receipts: ReceiptResource;
433
+ #expectedWorkspaceId: string | undefined;
434
+ #fields: readonly CompiledField[];
435
+ #surface: string;
436
+ #result: { value: T } | undefined;
437
+ #settling: Promise<T> | undefined;
438
+ #completion: Completion | undefined;
439
+
440
+ constructor(context: {
441
+ sessionId: string;
442
+ revision: number;
443
+ expiresAt: string | null;
444
+ link: string;
445
+ sessions: Sessions;
446
+ receipts: ReceiptResource;
447
+ expectedWorkspaceId: string | undefined;
448
+ compiled: CompiledAsk;
449
+ }) {
450
+ this.sessionId = context.sessionId;
451
+ this.revision = context.revision;
452
+ this.expiresAt = context.expiresAt;
453
+ this.#link = context.link;
454
+ this.#sessions = context.sessions;
455
+ this.#receipts = context.receipts;
456
+ this.#expectedWorkspaceId = context.expectedWorkspaceId;
457
+ this.#fields = context.compiled.fields;
458
+ // The runtime stores the interaction with its only response policy.
459
+ this.#surface = canonicalJson({ ...context.compiled.interaction, response_policy: 'first' });
460
+ this.answer = this.answer.bind(this);
461
+ Object.freeze(this);
462
+ }
463
+
464
+ get link(): string {
465
+ return this.#link;
466
+ }
467
+
468
+ async answer(options: AskAnswerOptions = {}): Promise<T> {
469
+ if (!options || typeof options !== 'object')
470
+ throw new SessError('configuration', 'answer options must be an object.', { outcome: 'not_sent' });
471
+ const { timeoutMs, intervalMs, signal } = options;
472
+ if (this.#result) return this.#result.value;
473
+ const waited = await this.#sessions.waitForResponse(this.sessionId, {
474
+ revision: this.revision,
475
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
476
+ ...(intervalMs !== undefined ? { intervalMs } : {}),
477
+ ...(signal !== undefined ? { signal } : {}),
478
+ });
479
+ // Another call may have settled this handle during the wait.
480
+ const settled = this.#result as { value: T } | undefined;
481
+ if (settled) return settled.value;
482
+ // One logical settlement per handle, shared by concurrent callers. It is not bound to the
483
+ // signal of any caller: an abort ends only that local wait.
484
+ this.#settling ??= this.#settle(waited.response).finally(() => {
485
+ this.#settling = undefined;
486
+ });
487
+ if (!signal) return this.#settling;
488
+ try {
489
+ return await withSignal(this.#settling, signal);
490
+ } catch (error) {
491
+ if (signal.aborted)
492
+ throw new SessError('aborted', 'Waiting for the answer was aborted. The Session remains available.', {
493
+ sessionId: this.sessionId,
494
+ revision: this.revision,
495
+ });
496
+ throw error;
497
+ }
498
+ }
499
+
500
+ async #settle(accepted: AcceptedResponse): Promise<T> {
501
+ const verified = await this.#receipts.verifyResponse({
502
+ sessionId: this.sessionId,
503
+ response: accepted,
504
+ ...(this.#expectedWorkspaceId !== undefined ? { expectedWorkspaceId: this.#expectedWorkspaceId } : {}),
505
+ });
506
+ const response = verified.response;
507
+ if (
508
+ response.event_id !== accepted.event_id ||
509
+ response.revision !== this.revision ||
510
+ response.action_id !== 'submit' ||
511
+ verified.surface.id !== this.sessionId ||
512
+ verified.surface.revision !== this.revision ||
513
+ canonicalJson(verified.surface.interaction) !== this.#surface
514
+ )
515
+ throw new SessError('receipt_verification', 'The verified answer is not bound to this question.', {
516
+ code: 'RECORD_BINDING_MISMATCH',
517
+ });
518
+ const value = checkAnswer(this.#fields, response.data) as T;
519
+ await this.#complete(response.event_id);
520
+ this.#result = { value };
521
+ return value;
522
+ }
523
+
524
+ /** Completed at exactly this revision and still retaining exactly this accepted event. */
525
+ #completedHere(session: InteractiveSession, eventId: string): boolean {
526
+ return (
527
+ session.status === 'completed' &&
528
+ session.revision === this.revision &&
529
+ session.responses.some((r) => r.event_id === eventId && r.revision === this.revision)
530
+ );
531
+ }
532
+
533
+ async #complete(eventId: string): Promise<void> {
534
+ if (this.#completion && this.#completion.eventId !== eventId)
535
+ throw new SessError('receipt_verification', 'A different answer was already used for this question.', {
536
+ code: 'RECORD_BINDING_MISMATCH',
537
+ });
538
+ // Currentness after verification: a historically valid answer alone does not allow progression.
539
+ const current = await this.#sessions.retrieve(this.sessionId);
540
+ const session = current.data;
541
+ if (!isInteractiveSession(session))
542
+ throw this.#ended('NOT_INTERACTIVE', 'A display Session has no accepted human responses.');
543
+ if (this.#completedHere(session, eventId)) return;
544
+ const retained = session.responses.some((r) => r.event_id === eventId && r.revision === this.revision);
545
+ if (!retained || session.revision !== this.revision || session.status !== 'responded')
546
+ throw this.#ended('REVISION_SUPERSEDED', 'The answered revision is no longer the current step.');
547
+ // Saved before the first dispatch and replayed after any uncertainty: never a fresh identity.
548
+ this.#completion ??= {
549
+ eventId,
550
+ ifMatch: current.meta.etag,
551
+ idempotencyKey: `sess-ask:${randomUUID()}`,
552
+ uncertain: false,
553
+ };
554
+ const pending = this.#completion;
555
+ let result: VersionedResult<InteractiveSession>;
556
+ try {
557
+ result = await this.#sessions.complete(this.sessionId, {
558
+ ifMatch: pending.ifMatch,
559
+ idempotencyKey: pending.idempotencyKey,
560
+ });
561
+ } catch (error) {
562
+ if (error instanceof SessError && error.code === 'SESSION_COMPLETED') {
563
+ // Already completed: confirmed only by reading it back at this revision with this event.
564
+ const readback = await this.#sessions.retrieve(this.sessionId);
565
+ if (isInteractiveSession(readback.data) && this.#completedHere(readback.data, eventId)) return;
566
+ throw error;
567
+ }
568
+ // A definite rejection of an identity that was never uncertain wrote nothing; anything else
569
+ // keeps the identity for an exact replay on the next call.
570
+ if (error instanceof SessError && error.outcome === 'rejected' && !pending.uncertain)
571
+ this.#completion = undefined;
572
+ else pending.uncertain = true;
573
+ throw error;
574
+ }
575
+ if (!this.#completedHere(result.data, eventId)) {
576
+ pending.uncertain = true;
577
+ throw new SessError('protocol', 'Completion was not confirmed at the answered revision.', {
578
+ code: 'INVALID_RESPONSE',
579
+ operation: 'sessions.complete',
580
+ outcome: 'unknown',
581
+ });
582
+ }
583
+ }
584
+
585
+ #ended(code: string, message: string): SessError {
586
+ return new SessError('wait_ended', message, { code, sessionId: this.sessionId, revision: this.revision });
587
+ }
588
+
589
+ /** The private link is omitted from serialization and inspection. */
590
+ toJSON(): object {
591
+ return { sessionId: this.sessionId, revision: this.revision };
592
+ }
593
+
594
+ [inspect.custom](): object {
595
+ return this.toJSON();
596
+ }
597
+ }
598
+
599
+ /** Validates locally, creates once (the link is available before any wait) and returns the handle. */
600
+ export async function ask<T>(
601
+ sessions: Sessions,
602
+ receipts: ReceiptResource,
603
+ input: unknown,
604
+ options: AskOptions = {},
605
+ ): Promise<AskHandle<T>> {
606
+ const compiled = compileAsk(input);
607
+ if (!options || typeof options !== 'object')
608
+ throw new SessError('configuration', 'ask options must be an object.', { outcome: 'not_sent' });
609
+ const { expectedWorkspaceId, ...requestOptions } = options;
610
+ if (
611
+ expectedWorkspaceId !== undefined &&
612
+ (typeof expectedWorkspaceId !== 'string' || !/^[A-Za-z0-9_:-]{1,128}$/.test(expectedWorkspaceId))
613
+ )
614
+ throw new SessError('configuration', 'expectedWorkspaceId must be a trusted workspace identifier.', {
615
+ outcome: 'not_sent',
616
+ });
617
+ // Creation carries the whole interaction and is attempted once. An uncertain outcome surfaces as
618
+ // the unknown_outcome error of the client and is never retried here.
619
+ const created = await sessions.create(
620
+ {
621
+ interaction: compiled.interaction,
622
+ ...(compiled.expiresIn !== undefined ? { expires_in: compiled.expiresIn } : {}),
623
+ },
624
+ requestOptions,
625
+ );
626
+ return new Handle<T>({
627
+ sessionId: created.data.id,
628
+ revision: created.data.revision,
629
+ expiresAt: typeof created.data.action_expires_at === 'string' ? created.data.action_expires_at : null,
630
+ link: created.data.human_url,
631
+ sessions,
632
+ receipts,
633
+ expectedWorkspaceId,
634
+ compiled,
635
+ });
636
+ }
package/src/client.ts CHANGED
@@ -3,6 +3,7 @@ import { Transport } from './transport.js';
3
3
  import { Sessions } from './sessions.js';
4
4
  import { WebhookResource } from './webhook-resource.js';
5
5
  import { createReceiptResource } from './receipts/resource.js';
6
+ import { ask, type AskAnswer, type AskField, type AskHandle, type AskInput, type AskOptions } from './ask.js';
6
7
 
7
8
  /** Server-side client. Construction has no network or installation side effects. */
8
9
  export class Sess {
@@ -38,4 +39,17 @@ export class Sess {
38
39
  });
39
40
  Object.freeze(this);
40
41
  }
42
+
43
+ /**
44
+ * Asks one question with simple typed fields. Invalid input fails before credential lookup or
45
+ * network access. The Session is created once with the whole interaction, and the returned
46
+ * handle carries the private link before any wait. `answer()` verifies the answer, checks that it
47
+ * is still current, completes the Session and returns the typed values.
48
+ */
49
+ ask<const F extends readonly AskField[]>(
50
+ input: AskInput<F>,
51
+ options?: AskOptions,
52
+ ): Promise<AskHandle<AskAnswer<F>>> {
53
+ return ask<AskAnswer<F>>(this.sessions, this.receipts, input, options);
54
+ }
41
55
  }