@sess.si/sdk 0.1.0-rc.7 → 0.1.0-rc.8

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 (57) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +41 -0
  3. package/dist/ask.d.ts +20 -8
  4. package/dist/ask.d.ts.map +1 -1
  5. package/dist/ask.js +43 -8
  6. package/dist/ask.js.map +1 -1
  7. package/dist/cli/verify.d.ts +1 -1
  8. package/dist/cli/verify.d.ts.map +1 -1
  9. package/dist/cli/verify.js +49 -3
  10. package/dist/cli/verify.js.map +1 -1
  11. package/dist/errors.d.ts +18 -0
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/errors.js +22 -1
  14. package/dist/errors.js.map +1 -1
  15. package/dist/generated/openapi.d.ts +489 -42
  16. package/dist/generated/openapi.d.ts.map +1 -1
  17. package/dist/internal/decode.d.ts.map +1 -1
  18. package/dist/internal/decode.js +37 -0
  19. package/dist/internal/decode.js.map +1 -1
  20. package/dist/polling.d.ts +4 -3
  21. package/dist/polling.d.ts.map +1 -1
  22. package/dist/polling.js +64 -18
  23. package/dist/polling.js.map +1 -1
  24. package/dist/receipts/index.d.ts +3 -1
  25. package/dist/receipts/index.d.ts.map +1 -1
  26. package/dist/receipts/index.js +2 -1
  27. package/dist/receipts/index.js.map +1 -1
  28. package/dist/receipts/renderers.d.ts +58 -0
  29. package/dist/receipts/renderers.d.ts.map +1 -0
  30. package/dist/receipts/renderers.js +154 -0
  31. package/dist/receipts/renderers.js.map +1 -0
  32. package/dist/receipts/resource.d.ts.map +1 -1
  33. package/dist/receipts/resource.js +27 -0
  34. package/dist/receipts/resource.js.map +1 -1
  35. package/dist/receipts/verify.d.ts +24 -1
  36. package/dist/receipts/verify.d.ts.map +1 -1
  37. package/dist/receipts/verify.js +63 -17
  38. package/dist/receipts/verify.js.map +1 -1
  39. package/dist/transport.d.ts.map +1 -1
  40. package/dist/transport.js +27 -2
  41. package/dist/transport.js.map +1 -1
  42. package/dist/types.d.ts +76 -7
  43. package/dist/types.d.ts.map +1 -1
  44. package/dist/types.js.map +1 -1
  45. package/package.json +1 -1
  46. package/src/ask.ts +63 -16
  47. package/src/cli/verify.ts +61 -3
  48. package/src/errors.ts +31 -0
  49. package/src/generated/openapi.ts +489 -42
  50. package/src/internal/decode.ts +29 -0
  51. package/src/polling.ts +70 -18
  52. package/src/receipts/index.ts +3 -1
  53. package/src/receipts/renderers.ts +220 -0
  54. package/src/receipts/resource.ts +37 -0
  55. package/src/receipts/verify.ts +108 -22
  56. package/src/transport.ts +35 -2
  57. package/src/types.ts +75 -4
package/src/ask.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { inspect } from 'node:util';
3
- import { SessError } from './errors.js';
3
+ import { SessError, lengthMessage } from './errors.js';
4
4
  import { canonicalJson } from './receipts/json.js';
5
5
  import type { ReceiptResource } from './receipts/resource.js';
6
6
  import type { Sessions } from './sessions.js';
@@ -19,7 +19,7 @@ import { withSignal } from './internal/time.js';
19
19
  interface AskFieldBase {
20
20
  /** Key of this field in the answer: `^[a-z][a-z0-9_]{0,63}$`. */
21
21
  readonly name: string;
22
- /** Human-facing label, 1–200 characters. */
22
+ /** What the field asks for: short, a few words; at most 60. Example: `Refund amount` */
23
23
  readonly label: string;
24
24
  /** Default `true`, except boolean fields (default `false`). */
25
25
  readonly required?: boolean;
@@ -40,22 +40,31 @@ export type AskField =
40
40
  | (AskFieldBase & { readonly type: 'boolean'; readonly default?: boolean })
41
41
  | (AskFieldBase & {
42
42
  readonly type: 'choice';
43
+ /** 1–100 choices. The words shown for one choice: short; at most 60. Example: `Next Monday` */
43
44
  readonly options: readonly [string, ...string[]];
44
45
  readonly default?: string;
45
46
  })
46
47
  | (AskFieldBase & {
47
48
  readonly type: 'multi_choice';
49
+ /** 1–100 choices. The words shown for one choice: short; at most 60. Example: `Next Monday` */
48
50
  readonly options: readonly [string, ...string[]];
49
51
  readonly default?: readonly string[];
50
52
  });
51
53
 
52
- /** A question plus typed fields: the same shape as the MCP `sess_ask` tool input. */
54
+ /**
55
+ * A question plus typed fields: the same shape as the MCP `sess_ask` tool input. Lengths are in
56
+ * Unicode code points and are never truncated: a value over its limit throws a `SessError` whose
57
+ * `field`, `limit` and `length` say which value to shorten and to what.
58
+ */
53
59
  export interface AskInput<F extends readonly AskField[] = readonly AskField[]> {
54
- /** Shown as the page title, 1–200 characters. */
60
+ /**
61
+ * The page's heading: a question or a task, about 40 characters; at most 80.
62
+ * Examples: `Approve the refund?`, `Pick a delivery date`
63
+ */
55
64
  readonly question: string;
56
- /** Optional plain-text context shown above the fields, 1–4000 characters. */
65
+ /** Optional plain-text context shown above the fields, at most 4,000 characters. */
57
66
  readonly details?: string;
58
- /** Submit button label, default `Send`. */
67
+ /** A button: a verb, 1–3 words; at most 24. Default `Send`. Examples: `Approve`, `Send refund` */
59
68
  readonly submit_label?: string;
60
69
  /** One to twelve fields with unique names. */
61
70
  readonly fields: F;
@@ -117,9 +126,12 @@ export interface AskHandle<T> {
117
126
  /** The Surface revision of the question, for recovery through the advanced API. */
118
127
  readonly revision: number;
119
128
  /**
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.
129
+ * When the link stops taking answers (`action_expires_at`, ISO 8601), as created. On a link of
130
+ * 20 hours or less the person may ask for more time, which moves it forward up to a fixed
131
+ * horizon; while the link is lapsed (past it, still extendable) `answer()` keeps waiting. An
132
+ * answer accepted before the end is still returned after it; with none, `answer()` ends with
133
+ * `wait_ended` code `LINK_EXPIRED` once the link has expired. Null only from a runtime that
134
+ * does not report it.
123
135
  */
124
136
  readonly expiresAt: string | null;
125
137
  /**
@@ -131,7 +143,22 @@ export interface AskHandle<T> {
131
143
 
132
144
  /** The runtime byte limit for one stored interaction. */
133
145
  const SURFACE_LIMIT_BYTES = 131_072;
134
- const LIMITS = Object.freeze({ fields: 12, options: 100, depth: 8, textMax: 4000 });
146
+ /**
147
+ * Sess's limits, in Unicode code points (the runtime checks the same numbers; nothing is ever
148
+ * truncated): the question (title) 80, details (a text component) 4,000, the submit button 24,
149
+ * field labels and options 60.
150
+ */
151
+ const LIMITS = Object.freeze({
152
+ fields: 12,
153
+ options: 100,
154
+ depth: 8,
155
+ textMax: 4000,
156
+ question: 80,
157
+ details: 4000,
158
+ submitLabel: 24,
159
+ label: 60,
160
+ option: 60,
161
+ });
135
162
  const TYPES = ['text', 'number', 'integer', 'boolean', 'choice', 'multi_choice'] as const;
136
163
  type AskType = (typeof TYPES)[number];
137
164
  const FIELD_NAME = /^[a-z][a-z0-9_]{0,63}$/;
@@ -168,6 +195,24 @@ function invalid(path: string, problem: string): never {
168
195
  outcome: 'not_sent',
169
196
  });
170
197
  }
198
+ /** `fields[0].label` → `/fields/0/label`: the JSON pointer of an input path. */
199
+ function pointer(path: string): string {
200
+ return `/${path
201
+ .replace(/\[(\d+)\]/g, '.$1')
202
+ .split('.')
203
+ .join('/')}`;
204
+ }
205
+ function tooLong(path: string, limit: number, length: number): never {
206
+ // The value itself never enters the message: only its pointer, the limit and its length, in
207
+ // Sess's own sentences.
208
+ throw new SessError('configuration', lengthMessage(pointer(path), limit, length), {
209
+ code: 'INVALID_QUESTION',
210
+ outcome: 'not_sent',
211
+ field: pointer(path),
212
+ limit,
213
+ length,
214
+ });
215
+ }
171
216
  function safeKey(key: string): string {
172
217
  return /^[A-Za-z0-9_]{1,40}$/.test(key) ? key : '?';
173
218
  }
@@ -221,7 +266,8 @@ function text(value: Json | undefined, path: string, max: number): string {
221
266
  if (typeof value !== 'string') return invalid(path, 'must be a string');
222
267
  if (!value.isWellFormed()) invalid(path, 'must be well-formed Unicode');
223
268
  const length = codePoints(value);
224
- if (length < 1 || length > max) invalid(path, `must be 1–${max} characters`);
269
+ if (length > max) tooLong(path, max, length);
270
+ if (length < 1) invalid(path, `must be 1–${max} characters`);
225
271
  if (!/\S/.test(value)) invalid(path, 'must not be blank');
226
272
  if (CONTROL.test(value)) invalid(path, 'contains control or bidirectional override characters');
227
273
  return value;
@@ -272,7 +318,7 @@ function compileField(raw: Json, path: string, names: Set<string>) {
272
318
  const name = f.name;
273
319
  if (names.has(name)) invalid(`${path}.name`, 'duplicates another field name');
274
320
  names.add(name);
275
- const label = text(f.label, `${path}.label`, 200);
321
+ const label = text(f.label, `${path}.label`, LIMITS.label);
276
322
  const type = f.type as AskType;
277
323
  if (!TYPES.includes(type)) invalid(`${path}.type`, `must be one of ${TYPES.join(', ')}`);
278
324
  const choice = type === 'choice' || type === 'multi_choice';
@@ -316,7 +362,7 @@ function compileField(raw: Json, path: string, names: Set<string>) {
316
362
  const options = f.options;
317
363
  if (!Array.isArray(options) || options.length < 1 || options.length > LIMITS.options)
318
364
  invalid(`${path}.options`, `must list 1–${LIMITS.options} options`);
319
- const values = options.map((option, i) => text(option, `${path}.options[${i}]`, 200));
365
+ const values = options.map((option, i) => text(option, `${path}.options[${i}]`, LIMITS.option));
320
366
  if (new Set(values).size !== values.length) invalid(`${path}.options`, 'must be unique');
321
367
  compiled.options = Object.freeze([...values]);
322
368
  schema =
@@ -355,9 +401,10 @@ export function compileAsk(input: unknown): CompiledAsk {
355
401
  expiresIn < LINK_LIFETIME_FLOOR_SECONDS)
356
402
  )
357
403
  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);
404
+ const title = text(a.question, 'question', LIMITS.question);
405
+ const details = a.details === undefined ? undefined : text(a.details, 'details', LIMITS.details);
406
+ const submit =
407
+ a.submit_label === undefined ? 'Send' : text(a.submit_label, 'submit_label', LIMITS.submitLabel);
361
408
  const fields = a.fields;
362
409
  if (!Array.isArray(fields) || fields.length < 1 || fields.length > LIMITS.fields)
363
410
  invalid('fields', `must contain 1–${LIMITS.fields} fields`);
package/src/cli/verify.ts CHANGED
@@ -9,7 +9,8 @@ import {
9
9
  type DecisionBundleVerification,
10
10
  type ExpectedBundleContext,
11
11
  } from '../receipts/bundle.js';
12
- import { validateKeySet } from '../receipts/verify.js';
12
+ import { BUNDLED_RENDERER_IDENTITIES } from '../receipts/renderers.js';
13
+ import { validateKeySet, verifyRendererIdentities } from '../receipts/verify.js';
13
14
 
14
15
  /** Exit codes: valid, invalid bundle, usage or file error. */
15
16
  export const EXIT = Object.freeze({ valid: 0, invalid: 1, usage: 2 });
@@ -17,6 +18,7 @@ export const EXIT = Object.freeze({ valid: 0, invalid: 1, usage: 2 });
17
18
  /** A bundle file larger than this is not read (the bundle bound itself is 1 MiB canonical). */
18
19
  const MAX_BUNDLE_FILE_BYTES = 16 * 1024 * 1024;
19
20
  const MAX_KEYS_FILE_BYTES = 1024 * 1024;
21
+ const MAX_RENDERERS_FILE_BYTES = 64 * 1024;
20
22
 
21
23
  export interface CliIo {
22
24
  stdout: (text: string) => void;
@@ -40,6 +42,11 @@ Expected context (optional; only what you pass is checked):
40
42
  --revision <n> the Surface revision
41
43
  --action <id> the action ID
42
44
 
45
+ Renderer identity (optional):
46
+ --renderers <file> the issuer's signed renderer list you obtained yourself
47
+ (<issuer>/.well-known/sess-renderer-identities.json); also checks that the
48
+ receipt's renderer identity is one this release knows or one on that list
49
+
43
50
  Other:
44
51
  --now <time> check at this RFC 3339 time instead of now
45
52
  --json print the full result as JSON
@@ -60,6 +67,7 @@ const STRING_OPTIONS = [
60
67
  'revision',
61
68
  'action',
62
69
  'now',
70
+ 'renderers',
63
71
  ] as const;
64
72
 
65
73
  const RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;
@@ -103,6 +111,7 @@ interface Parsed {
103
111
  file: string;
104
112
  issuer: string;
105
113
  keysPath: string;
114
+ renderersPath: string | undefined;
106
115
  context: ExpectedBundleContext | undefined;
107
116
  now: Date | undefined;
108
117
  json: boolean;
@@ -177,6 +186,7 @@ function parse(argv: readonly string[]): Parsed | 'help' {
177
186
  file,
178
187
  issuer,
179
188
  keysPath,
189
+ renderersPath: str('renderers'),
180
190
  context: Object.keys(context).length > 0 ? context : undefined,
181
191
  now,
182
192
  json: values.json === true,
@@ -201,9 +211,16 @@ const REASON_TEXT: Record<string, string> = {
201
211
  surface_mismatch: 'the disclosed Surface is not the one the receipt signed',
202
212
  input_mismatch: 'the disclosed input is not the one the receipt signed',
203
213
  context_mismatch: 'the decision is not the one you expected',
214
+ renderer: 'the receipt names a renderer identity that is neither known nor on the signed list',
204
215
  };
205
216
 
206
- function summary(r: DecisionBundleVerification): string {
217
+ /** With --renderers: the receipt's renderer identity and whether it is known or listed. */
218
+ interface RendererCheck {
219
+ identity: string | null;
220
+ status: 'listed' | 'unlisted' | 'not_checked';
221
+ }
222
+
223
+ function summary(r: DecisionBundleVerification, renderer?: RendererCheck): string {
207
224
  const lines: string[] = [];
208
225
  const row = (label: string, value: string) => lines.push(` ${label.padEnd(11)} ${value}`);
209
226
  const context =
@@ -225,11 +242,13 @@ function summary(r: DecisionBundleVerification): string {
225
242
  row('Context', context);
226
243
  row('Purpose', r.application_purpose);
227
244
  row('Expires', safe(c.expires_at));
245
+ if (renderer) row('Renderer', `${safe(c.surface.renderer_version)} (listed)`);
228
246
  } else {
229
247
  lines.push(`Invalid decision bundle: ${r.reason}`);
230
248
  lines.push(` ${REASON_TEXT[r.reason ?? ''] ?? ''}`);
231
249
  row('Content', r.content);
232
250
  row('Context', context);
251
+ if (renderer?.identity) row('Renderer', `${safe(renderer.identity)} (${renderer.status})`);
233
252
  }
234
253
  row('Checked at', r.checked_at);
235
254
  return `${lines.join('\n')}\n`;
@@ -267,6 +286,27 @@ export async function runCli(argv: readonly string[], io: CliIo): Promise<number
267
286
  'the --keys file must be a JWK Set of public Ed25519 keys with unique kids (private keys are refused)',
268
287
  );
269
288
  }
289
+ // Decision 0009 Amendment 13: the issuer's signed renderer list, trusted only through its
290
+ // signature under the keys above.
291
+ let listed: readonly string[] | undefined;
292
+ if (parsed.renderersPath !== undefined) {
293
+ const listJson = parseJson(
294
+ await readBounded(parsed.renderersPath, MAX_RENDERERS_FILE_BYTES, 'the --renderers file'),
295
+ );
296
+ try {
297
+ if (!listJson.ok) throw new Error('not JSON');
298
+ listed = (
299
+ await verifyRendererIdentities(listJson.value as never, {
300
+ issuer: parsed.issuer,
301
+ keys: trustedKeys,
302
+ })
303
+ ).identities.map((i) => i.renderer_version);
304
+ } catch {
305
+ throw new UsageError(
306
+ "the --renderers file must be the issuer's renderer list, signed with the keys you trust",
307
+ );
308
+ }
309
+ }
270
310
  const bundleBytes = await readBounded(parsed.file, MAX_BUNDLE_FILE_BYTES, 'the bundle file');
271
311
  const bundleJson = parseJson(bundleBytes);
272
312
  let result: DecisionBundleVerification;
@@ -281,7 +321,25 @@ export async function runCli(argv: readonly string[], io: CliIo): Promise<number
281
321
  } catch {
282
322
  throw new UsageError('invalid verification options');
283
323
  }
284
- io.stdout(parsed.json ? safeJson(result) : summary(result));
324
+ let renderer: RendererCheck | undefined;
325
+ if (listed !== undefined) {
326
+ const identity = result.receipt?.surface.renderer_version ?? null;
327
+ renderer =
328
+ identity === null
329
+ ? { identity, status: 'not_checked' }
330
+ : {
331
+ identity,
332
+ status:
333
+ BUNDLED_RENDERER_IDENTITIES.includes(identity) || listed.includes(identity)
334
+ ? 'listed'
335
+ : 'unlisted',
336
+ };
337
+ if (renderer.status === 'unlisted')
338
+ result = { ...result, valid: false, reason: 'renderer' as DecisionBundleVerification['reason'] };
339
+ }
340
+ io.stdout(
341
+ parsed.json ? safeJson(renderer ? { ...result, renderer } : result) : summary(result, renderer),
342
+ );
285
343
  return result.valid ? EXIT.valid : EXIT.invalid;
286
344
  } catch (e) {
287
345
  const message = e instanceof UsageError ? e.message : 'unexpected error';
package/src/errors.ts CHANGED
@@ -24,6 +24,12 @@ export interface SessErrorDetails {
24
24
  retryAfterMs?: number;
25
25
  sessionId?: string;
26
26
  revision?: number;
27
+ /** With a length error: a JSON pointer to the value that is too long, e.g. `/interaction/title`. */
28
+ field?: string;
29
+ /** With a length error: the most the value may have, in Unicode code points. */
30
+ limit?: number;
31
+ /** With a length error: the value's actual length, in Unicode code points. */
32
+ length?: number;
27
33
  }
28
34
  const recovery = new WeakMap<SessError, Readonly<CreateSessionResponse>>();
29
35
 
@@ -41,6 +47,16 @@ export class SessError extends Error {
41
47
  readonly retryAfterMs?: number;
42
48
  readonly sessionId?: string;
43
49
  readonly revision?: number;
50
+ /**
51
+ * Set only when a value is too long (a 400 INVALID_SCHEMA from Sess, or INVALID_QUESTION from
52
+ * `ask`): a JSON pointer to it, e.g. `/interaction/title`. Nothing is ever truncated: shorten
53
+ * the value to at most `limit` characters and send again.
54
+ */
55
+ readonly field?: string;
56
+ /** With `field`: the most the value may have, in Unicode code points (e.g. title 80). */
57
+ readonly limit?: number;
58
+ /** With `field`: the value's actual length, in Unicode code points. */
59
+ readonly length?: number;
44
60
 
45
61
  constructor(kind: SessErrorKind, message: string, details: SessErrorDetails = {}) {
46
62
  super(message);
@@ -68,6 +84,9 @@ export class SessError extends Error {
68
84
  outcome,
69
85
  idempotencyKey,
70
86
  retryAfterMs,
87
+ field,
88
+ limit,
89
+ length,
71
90
  } = this;
72
91
  return {
73
92
  name,
@@ -82,6 +101,9 @@ export class SessError extends Error {
82
101
  outcome,
83
102
  idempotencyKey,
84
103
  retryAfterMs,
104
+ field,
105
+ limit,
106
+ length,
85
107
  };
86
108
  }
87
109
 
@@ -90,6 +112,15 @@ export class SessError extends Error {
90
112
  }
91
113
  }
92
114
 
115
+ /** Internal: the one-line fix every length error carries (field, limit, actual length, fix). */
116
+ export function lengthMessage(field: string, limit: number, length: number): string {
117
+ // The same sentences as Sess's 400 INVALID_SCHEMA (`field` is a JSON pointer); the title (the
118
+ // `sess.ask()` question) has its own.
119
+ if (field === '/interaction/title' || field === '/question')
120
+ return `The title can be at most ${limit} characters. Keep it to a short heading, about 40.`;
121
+ return `${field} is ${length} characters; the limit is ${limit}. Shorten it to at most ${limit} characters.`;
122
+ }
123
+
93
124
  /** Internal: keep private creation capabilities out of inspection and serialization. */
94
125
  export function attachRecovery(error: SessError, value: CreateSessionResponse): void {
95
126
  recovery.set(error, Object.freeze({ ...value }));