@apifuse/provider-sdk 2.2.0-beta.60 → 2.2.0-beta.62

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 (85) hide show
  1. package/AUTHORING.md +17 -16
  2. package/CHANGELOG.md +8 -0
  3. package/bin/apifuse-dev.ts +5 -7
  4. package/bin/apifuse-pack-types.ts +26 -0
  5. package/bin/apifuse-perf.ts +4 -6
  6. package/bin/apifuse-record.ts +4 -7
  7. package/bin/apifuse-submit-check.ts +2 -2
  8. package/dist/define.d.ts +3 -2
  9. package/dist/define.js +1 -1
  10. package/dist/dev.js +3 -1
  11. package/dist/engine.d.ts +7 -6
  12. package/dist/engine.js +3 -4
  13. package/dist/error-resolution.js +21 -4
  14. package/dist/errors.d.ts +3 -0
  15. package/dist/errors.js +9 -0
  16. package/dist/handle-meta.d.ts +55 -0
  17. package/dist/handle-meta.js +57 -0
  18. package/dist/handle.d.ts +208 -0
  19. package/dist/handle.js +299 -0
  20. package/dist/i18n/catalog.js +21 -1
  21. package/dist/index.d.ts +7 -4
  22. package/dist/index.js +6 -3
  23. package/dist/lint.d.ts +3 -0
  24. package/dist/lint.js +372 -47
  25. package/dist/provider.d.ts +5 -3
  26. package/dist/provider.js +4 -2
  27. package/dist/runtime/handle-wordlist.d.ts +43 -0
  28. package/dist/runtime/{choice-wordlist.js → handle-wordlist.js} +127 -9
  29. package/dist/runtime/handle.d.ts +71 -0
  30. package/dist/runtime/handle.js +900 -0
  31. package/dist/runtime/http-telemetry-binding.d.ts +10 -0
  32. package/dist/runtime/http-telemetry-binding.js +152 -0
  33. package/dist/runtime/http-telemetry-guard.d.ts +6 -0
  34. package/dist/runtime/http-telemetry-guard.js +150 -0
  35. package/dist/runtime/http-telemetry.d.ts +104 -0
  36. package/dist/runtime/http-telemetry.js +190 -0
  37. package/dist/runtime/http.d.ts +31 -0
  38. package/dist/runtime/http.js +222 -146
  39. package/dist/runtime/native-network.d.ts +10 -1
  40. package/dist/runtime/native-network.js +230 -29
  41. package/dist/runtime/native-telemetry.d.ts +142 -0
  42. package/dist/runtime/native-telemetry.js +231 -0
  43. package/dist/runtime/state.d.ts +4 -1
  44. package/dist/runtime/state.js +32 -17
  45. package/dist/server/index.d.ts +3 -0
  46. package/dist/server/index.js +2 -0
  47. package/dist/server/sensitive-values.d.ts +1 -1
  48. package/dist/server/sensitive-values.js +0 -3
  49. package/dist/server/serve-implementation.d.ts +6 -11
  50. package/dist/server/serve-implementation.js +119 -52
  51. package/dist/testing/run.js +10 -7
  52. package/dist/types.d.ts +4 -107
  53. package/package.json +1 -1
  54. package/src/define.ts +4 -3
  55. package/src/dev.ts +3 -1
  56. package/src/engine.ts +5 -6
  57. package/src/error-resolution.ts +21 -4
  58. package/src/errors.ts +13 -0
  59. package/src/handle-meta.ts +93 -0
  60. package/src/handle.ts +612 -0
  61. package/src/i18n/catalog.ts +23 -1
  62. package/src/index.ts +45 -13
  63. package/src/lint.ts +437 -55
  64. package/src/provider.ts +19 -20
  65. package/src/runtime/{choice-wordlist.ts → handle-wordlist.ts} +130 -9
  66. package/src/runtime/handle.ts +1172 -0
  67. package/src/runtime/http-telemetry-binding.ts +162 -0
  68. package/src/runtime/http-telemetry-guard.ts +155 -0
  69. package/src/runtime/http-telemetry.ts +292 -0
  70. package/src/runtime/http.ts +295 -173
  71. package/src/runtime/native-network.ts +281 -33
  72. package/src/runtime/native-telemetry.ts +366 -0
  73. package/src/runtime/state.ts +44 -16
  74. package/src/server/index.ts +30 -0
  75. package/src/server/sensitive-values.ts +0 -3
  76. package/src/server/serve-implementation.ts +127 -89
  77. package/src/testing/run.ts +11 -7
  78. package/src/types.ts +4 -137
  79. package/dist/choice-token.d.ts +0 -24
  80. package/dist/choice-token.js +0 -74
  81. package/dist/runtime/choice-wordlist.d.ts +0 -9
  82. package/dist/runtime/choice.d.ts +0 -27
  83. package/dist/runtime/choice.js +0 -801
  84. package/src/choice-token.ts +0 -165
  85. package/src/runtime/choice.ts +0 -1197
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Shared, dependency-free definitions for LLM-friendly handles (ADR-0012).
3
+ *
4
+ * Kept separate from the runtime so schema helpers, lint, and the runtime can
5
+ * agree on the JSON Schema meta key and the declaration shape without importing
6
+ * each other.
7
+ */
8
+
9
+ /** JSON Schema meta key placed on every schema field created by `kind.field()`. */
10
+ export const APIFUSE_HANDLE_META_KEY = "x-apifuse-handle" as const;
11
+
12
+ export type HandleKindType = "cursor" | "draft";
13
+ export type HandleAccess = "bound" | "public";
14
+
15
+ /**
16
+ * Operation key(s) that issue a handle. A single string is the common case; a
17
+ * list names every operation whose output carries the field (for example
18
+ * `search-address` and `reverse-geocode` both issuing `location_token`).
19
+ */
20
+ export type HandleIssuedBy = string | readonly string[];
21
+
22
+ /** Value stored under {@link APIFUSE_HANDLE_META_KEY} on a handle field. */
23
+ export interface HandleFieldMeta {
24
+ readonly kind: string;
25
+ readonly type: HandleKindType;
26
+ readonly fieldName: string;
27
+ readonly issuedBy?: HandleIssuedBy;
28
+ }
29
+
30
+ /**
31
+ * Structural view of a handle kind as seen by the provider declaration
32
+ * (`handle: [WaitingDraft, PageCursor]`), lint, and the registry. The runtime
33
+ * kinds returned by `defineCursor` / `defineDraft` satisfy this shape.
34
+ */
35
+ export interface HandleKindDeclaration {
36
+ readonly name: string;
37
+ readonly type: HandleKindType;
38
+ readonly fieldName: string;
39
+ readonly access: HandleAccess;
40
+ readonly issuedBy?: HandleIssuedBy;
41
+ }
42
+
43
+ /** Kind names are lowercase letters only so they never fuse with the word body. */
44
+ export const HANDLE_KIND_NAME_PATTERN = /^[a-z]{2,12}$/;
45
+
46
+ /** True for a single operation key or a non-empty list of operation keys. */
47
+ export function isHandleIssuedBy(value: unknown): value is HandleIssuedBy {
48
+ if (typeof value === "string") return true;
49
+ return (
50
+ Array.isArray(value) && value.length > 0 && value.every((entry) => typeof entry === "string")
51
+ );
52
+ }
53
+
54
+ /** Normalizes `issuedBy` to a list of operation keys (empty when undefined). */
55
+ export function handleIssuerList(issuedBy: HandleIssuedBy | undefined): readonly string[] {
56
+ if (issuedBy === undefined) return [];
57
+ return typeof issuedBy === "string" ? [issuedBy] : issuedBy;
58
+ }
59
+
60
+ /**
61
+ * Renders the issuing operation(s) as inline code for error and description
62
+ * text: `` `a` ``, `` `a` or `b` ``, `` `a`, `b`, or `c` ``. Undefined when no
63
+ * issuer is declared.
64
+ */
65
+ export function formatHandleIssuers(issuedBy: HandleIssuedBy | undefined): string | undefined {
66
+ const issuers = handleIssuerList(issuedBy).map((operation) => `\`${operation}\``);
67
+ if (issuers.length === 0) return undefined;
68
+ if (issuers.length === 1) return issuers[0];
69
+ if (issuers.length === 2) return `${issuers[0]} or ${issuers[1]}`;
70
+ return `${issuers.slice(0, -1).join(", ")}, or ${issuers[issuers.length - 1]}`;
71
+ }
72
+
73
+ export function isHandleFieldMeta(value: unknown): value is HandleFieldMeta {
74
+ if (typeof value !== "object" || value === null) return false;
75
+ const record = value as Record<string, unknown>;
76
+ return (
77
+ typeof record.kind === "string" &&
78
+ (record.type === "cursor" || record.type === "draft") &&
79
+ typeof record.fieldName === "string" &&
80
+ (record.issuedBy === undefined || isHandleIssuedBy(record.issuedBy))
81
+ );
82
+ }
83
+
84
+ /**
85
+ * The SDK-owned description `kind.field()` emits. Lint exempts a handle field
86
+ * from `describeKey` only while its description is exactly this text; a
87
+ * provider override re-enters the localization rules.
88
+ */
89
+ export function handleFieldDescription(meta: Pick<HandleFieldMeta, "issuedBy">): string {
90
+ const issuers = formatHandleIssuers(meta.issuedBy);
91
+ const origin = issuers ? ` issued by ${issuers}` : "";
92
+ return `Opaque handle${origin}. Copy it exactly as returned; do not edit or shorten it.`;
93
+ }
package/src/handle.ts ADDED
@@ -0,0 +1,612 @@
1
+ /**
2
+ * LLM-friendly handles (ADR-0012): authoring API.
3
+ *
4
+ * A handle is a short string an LLM copies from one tool output into a later
5
+ * tool input. It is a lookup key to server state, never a carrier of encrypted
6
+ * payload. This module defines handle *kinds* (`defineCursor`, `defineDraft`),
7
+ * the schema helper `kind.field()`, the plain-value chooser `pick()`, and
8
+ * `HandleError`. The runtime (`ctx.handle`) lives in `runtime/handle.ts`.
9
+ */
10
+ import { type ZodString, type ZodType, z } from "zod";
11
+ import {
12
+ brandHandleError,
13
+ hasHandleErrorBrand,
14
+ ProviderError,
15
+ type ProviderErrorOptions,
16
+ } from "./errors.js";
17
+ import {
18
+ APIFUSE_HANDLE_META_KEY,
19
+ formatHandleIssuers,
20
+ handleFieldDescription,
21
+ HANDLE_KIND_NAME_PATTERN,
22
+ type HandleAccess,
23
+ type HandleFieldMeta,
24
+ type HandleIssuedBy,
25
+ type HandleKindDeclaration,
26
+ type HandleKindType,
27
+ isHandleIssuedBy,
28
+ } from "./handle-meta.js";
29
+ import type { ProviderErrorCategory } from "./observability.js";
30
+ import {
31
+ BOUND_HANDLE_WORD_COUNT,
32
+ HIGH_PUBLIC_HANDLE_WORD_COUNT,
33
+ PUBLIC_HANDLE_WORD_COUNT,
34
+ } from "./runtime/handle-wordlist.js";
35
+ import type { ProviderStateDurationString } from "./types.js";
36
+
37
+ export type {
38
+ HandleAccess,
39
+ HandleFieldMeta,
40
+ HandleIssuedBy,
41
+ HandleKindDeclaration,
42
+ HandleKindType,
43
+ };
44
+
45
+ /** Public kinds whose (max) ttl exceeds this are issued with five words (auto-high). */
46
+ const AUTO_HIGH_TTL_MS = 3_600_000;
47
+ const DEFAULT_BOUND_MAX_ENTRIES = 200;
48
+ const DEFAULT_CURSOR_MAX_VALUE_BYTES = 16_000;
49
+ const DEFAULT_DRAFT_MAX_VALUE_BYTES = 64_000;
50
+ const DEFAULT_RESULT_TTL: ProviderStateDurationString = "24h";
51
+
52
+ export type HandleStrength = "standard" | "high";
53
+
54
+ /** Words issued per handle: 2 for bound kinds, 4 for public, 5 for high-strength public. */
55
+ export type HandleWordCount = 2 | 4 | 5;
56
+
57
+ export interface HandleKindBase<TSchema extends ZodType = ZodType> extends HandleKindDeclaration {
58
+ /**
59
+ * Zod schema validated on `create`/`update`. Writes accept its *input* type
60
+ * (`InputOf`); stored records and callbacks carry its *output* type (`DataOf`).
61
+ */
62
+ readonly schema: TSchema;
63
+ /** Live-entry quota of the kind's namespace (per connection for bound kinds). */
64
+ readonly maxEntries: number;
65
+ /** Maximum JSON-encoded record size in bytes. */
66
+ readonly maxValueBytes: number;
67
+ /** Number of words the runtime issues for this kind. */
68
+ readonly wordCount: HandleWordCount;
69
+ /**
70
+ * Schema for the handle field, usable in output and input positions. Carries
71
+ * the `x-apifuse-handle` meta and an SDK-owned English description.
72
+ */
73
+ field(): ZodString;
74
+ }
75
+
76
+ export interface CursorKind<TSchema extends ZodType = ZodType> extends HandleKindBase<TSchema> {
77
+ readonly type: "cursor";
78
+ readonly ttl: ProviderStateDurationString;
79
+ readonly ttlMs: number;
80
+ readonly strength: HandleStrength;
81
+ }
82
+
83
+ export interface DraftKind<
84
+ TSchema extends ZodType = ZodType,
85
+ TResultSchema extends ZodType | undefined = ZodType | undefined,
86
+ > extends HandleKindBase<TSchema> {
87
+ readonly type: "draft";
88
+ /** `"bound"` (default): connection-scoped, 2 words. `"public"`: provider-scoped, 4-5 words. */
89
+ readonly access: HandleAccess;
90
+ /** Public only; `"high"` forces 5 words. Always `"standard"` for bound drafts. */
91
+ readonly strength: HandleStrength;
92
+ readonly ttl: {
93
+ readonly idle: ProviderStateDurationString;
94
+ readonly max: ProviderStateDurationString;
95
+ };
96
+ readonly idleTtlMs: number;
97
+ readonly maxTtlMs: number;
98
+ readonly resultTtl: ProviderStateDurationString;
99
+ readonly resultTtlMs: number;
100
+ /** Optional schema describing the commit result; type-level only at runtime. */
101
+ readonly result: TResultSchema | undefined;
102
+ }
103
+
104
+ // `any` here is variance-only: a concrete `CursorKind<{ page: number }>` must be
105
+ // assignable to the union without callers spelling out the data type.
106
+ export type HandleKind = CursorKind<any> | DraftKind<any, any>;
107
+
108
+ /** Stored record data type (schema output); what `read`, `update`, and `commit` callbacks receive. */
109
+ export type DataOf<K extends HandleKind> = z.output<K["schema"]>;
110
+ /** What `create` and `update` accept (schema input); differs from `DataOf` when the schema transforms or defaults. */
111
+ export type InputOf<K extends HandleKind> = z.input<K["schema"]>;
112
+ export type ResultOf<K extends HandleKind> =
113
+ K extends DraftKind<any, infer R> ? (R extends ZodType ? z.output<R> : unknown) : never;
114
+
115
+ export type HandleStatus = "active" | "committing" | "committed";
116
+
117
+ export interface HandleRecord<K extends HandleKind> {
118
+ /** Canonical handle string (`<kind>_<word>-<word>...`). */
119
+ readonly handle: string;
120
+ readonly kind: string;
121
+ readonly status: HandleStatus;
122
+ readonly data: DataOf<K>;
123
+ readonly result?: ResultOf<K>;
124
+ readonly createdAt: string;
125
+ readonly expiresAt: string;
126
+ }
127
+
128
+ export interface HandleCommitResult<K extends HandleKind> {
129
+ readonly status: "committed" | "replayed";
130
+ readonly handle: string;
131
+ readonly result: ResultOf<K>;
132
+ }
133
+
134
+ export interface HandleContext {
135
+ /** Validates `data` with `kind.schema`, stores it, and returns the canonical handle. */
136
+ create<K extends HandleKind>(kind: K, data: InputOf<K>): Promise<string>;
137
+ /**
138
+ * Same as `create` but returns the full record (`handle`, `status`, `data`,
139
+ * `createdAt`, `expiresAt`) so a provider can expose `expires_at` without
140
+ * recomputing ttl math. `create` is the string-returning shortcut.
141
+ */
142
+ createRecord<K extends HandleKind>(kind: K, data: InputOf<K>): Promise<HandleRecord<K>>;
143
+ /** Tolerantly parses `handle`, loads the record; drafts get their idle TTL touched. */
144
+ read<K extends HandleKind>(kind: K, handle: string): Promise<HandleRecord<K>>;
145
+ /** CAS update of an active draft (3 retries) with sliding TTL. */
146
+ update<K extends DraftKind>(
147
+ kind: K,
148
+ handle: string,
149
+ updater: (data: DataOf<K>) => InputOf<K> | Promise<InputOf<K>>,
150
+ ): Promise<HandleRecord<K>>;
151
+ /** One-shot commit with result replay; see runtime docs for the state machine. */
152
+ commit<K extends DraftKind>(
153
+ kind: K,
154
+ handle: string,
155
+ work: (data: DataOf<K>) => Promise<ResultOf<K>>,
156
+ ): Promise<HandleCommitResult<K>>;
157
+ /** Deletes the record; idempotent. */
158
+ discard<K extends HandleKind>(kind: K, handle: string): Promise<void>;
159
+ }
160
+
161
+ export type HandleOperation = "create" | "read" | "update" | "commit" | "discard";
162
+
163
+ export type HandleTelemetryOutcome =
164
+ | "success"
165
+ | "not_found"
166
+ | "expired"
167
+ | "invalid"
168
+ | "kind_mismatch"
169
+ | "busy"
170
+ | "replayed"
171
+ | "error";
172
+
173
+ /** Allowlisted metadata only; handle values, data, and results are never included. */
174
+ export interface HandleTelemetryEvent {
175
+ readonly providerId: string;
176
+ readonly kind: string;
177
+ readonly type: HandleKindType;
178
+ readonly operation: HandleOperation;
179
+ readonly outcome: HandleTelemetryOutcome;
180
+ /** `"none"` or the sorted normalization classes joined by `+`. */
181
+ readonly normalization: string;
182
+ readonly words: number;
183
+ }
184
+
185
+ // ---------------------------------------------------------------------------
186
+ // Errors
187
+ // ---------------------------------------------------------------------------
188
+
189
+ export type HandleErrorCode =
190
+ | "HANDLE_INVALID"
191
+ | "HANDLE_NOT_FOUND"
192
+ | "HANDLE_EXPIRED"
193
+ | "HANDLE_KIND_MISMATCH"
194
+ | "HANDLE_BUSY"
195
+ | "HANDLE_COMMITTED"
196
+ | "HANDLE_CONNECTION_REQUIRED"
197
+ | "HANDLE_STORAGE_UNAVAILABLE"
198
+ | "HANDLE_TOO_LARGE"
199
+ | "HANDLE_INVALID_DATA"
200
+ | "PICK_NOT_OFFERED";
201
+
202
+ const HANDLE_ERROR_DEFAULTS: Record<
203
+ HandleErrorCode,
204
+ { readonly category: ProviderErrorCategory; readonly retryable: boolean }
205
+ > = {
206
+ HANDLE_INVALID: { category: "input_validation", retryable: false },
207
+ HANDLE_NOT_FOUND: { category: "input_validation", retryable: false },
208
+ HANDLE_EXPIRED: { category: "input_validation", retryable: false },
209
+ HANDLE_KIND_MISMATCH: { category: "input_validation", retryable: false },
210
+ HANDLE_BUSY: { category: "internal_error", retryable: true },
211
+ HANDLE_COMMITTED: { category: "input_validation", retryable: false },
212
+ HANDLE_CONNECTION_REQUIRED: { category: "internal_error", retryable: false },
213
+ HANDLE_STORAGE_UNAVAILABLE: { category: "internal_error", retryable: false },
214
+ HANDLE_TOO_LARGE: { category: "internal_error", retryable: false },
215
+ HANDLE_INVALID_DATA: { category: "internal_error", retryable: false },
216
+ PICK_NOT_OFFERED: { category: "input_validation", retryable: false },
217
+ };
218
+
219
+ export type HandleErrorOptions = Omit<ProviderErrorOptions, "code"> & {
220
+ /** Kind name the error relates to, when known. */
221
+ readonly kind?: string;
222
+ };
223
+
224
+ export class HandleError extends ProviderError {
225
+ readonly handleCode: HandleErrorCode;
226
+ readonly kind?: string;
227
+
228
+ constructor(code: HandleErrorCode, message: string, options: HandleErrorOptions = {}) {
229
+ const { kind, ...rest } = options;
230
+ const defaults = HANDLE_ERROR_DEFAULTS[code];
231
+ super(message, {
232
+ category: defaults.category,
233
+ retryable: defaults.retryable,
234
+ ...rest,
235
+ code,
236
+ });
237
+ this.name = "HandleError";
238
+ this.handleCode = code;
239
+ this.kind = kind;
240
+ brandHandleError(this);
241
+ }
242
+
243
+ override get code(): HandleErrorCode {
244
+ return this.handleCode;
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Recognizes handle errors across duplicate SDK module copies (packaged CLI
250
+ * `src/*` runtime vs provider `dist/*` import), where `instanceof` splits.
251
+ */
252
+ export function isHandleError(value: unknown): value is HandleError {
253
+ return value instanceof HandleError || hasHandleErrorBrand(value);
254
+ }
255
+
256
+ /**
257
+ * Standard recovery sentence appended to every handle error message so the LLM
258
+ * knows the next action without provider-specific wording.
259
+ */
260
+ export function handleRecoverySentence(kind: {
261
+ readonly fieldName: string;
262
+ readonly issuedBy?: HandleIssuedBy;
263
+ }): string {
264
+ const issuers = formatHandleIssuers(kind.issuedBy);
265
+ if (issuers) {
266
+ return `Call ${issuers} again and pass the new \`${kind.fieldName}\` exactly as returned.`;
267
+ }
268
+ return `Request a new \`${kind.fieldName}\` and pass it exactly as returned.`;
269
+ }
270
+
271
+ // ---------------------------------------------------------------------------
272
+ // Durations
273
+ // ---------------------------------------------------------------------------
274
+
275
+ const SHORT_DURATION_PATTERN = /^(\d+)(ms|s|m|h|d)$/;
276
+ const ISO_DURATION_PATTERN = /^PT(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?$/;
277
+
278
+ /** Parses a `ProviderStateDurationString` to milliseconds; throws on invalid or non-positive input. */
279
+ export function parseHandleDurationMs(value: ProviderStateDurationString, label: string): number {
280
+ const short = SHORT_DURATION_PATTERN.exec(value);
281
+ let ms: number | undefined;
282
+ if (short) {
283
+ const amount = Number(short[1]);
284
+ const unit = short[2];
285
+ const multiplier =
286
+ unit === "ms"
287
+ ? 1
288
+ : unit === "s"
289
+ ? 1_000
290
+ : unit === "m"
291
+ ? 60_000
292
+ : unit === "h"
293
+ ? 3_600_000
294
+ : 86_400_000;
295
+ ms = amount * multiplier;
296
+ } else {
297
+ const iso = ISO_DURATION_PATTERN.exec(value);
298
+ if (iso && (iso[1] !== undefined || iso[2] !== undefined || iso[3] !== undefined)) {
299
+ ms =
300
+ Number(iso[1] ?? 0) * 3_600_000 +
301
+ Number(iso[2] ?? 0) * 60_000 +
302
+ Number(iso[3] ?? 0) * 1_000;
303
+ }
304
+ }
305
+ if (ms === undefined || !Number.isFinite(ms) || ms <= 0) {
306
+ throw new Error(
307
+ `Handle kind ${label} must be a positive duration such as "10m", "2h", or "PT30M" (received ${JSON.stringify(value)}).`,
308
+ );
309
+ }
310
+ return Math.floor(ms);
311
+ }
312
+
313
+ // ---------------------------------------------------------------------------
314
+ // Kind definitions
315
+ // ---------------------------------------------------------------------------
316
+
317
+ export interface DefineCursorOptions<TSchema extends ZodType> {
318
+ /** Kind name, `/^[a-z]{2,12}$/`; becomes the handle prefix. */
319
+ readonly name: string;
320
+ /** Schema property key carrying the handle. Default `${name}_token`. */
321
+ readonly fieldName?: string;
322
+ readonly schema: TSchema;
323
+ readonly ttl: ProviderStateDurationString;
324
+ /** `"bound"` (default): connection-scoped, 2 words. `"public"`: provider-scoped, 4-5 words. */
325
+ readonly access?: HandleAccess;
326
+ /** Required when public. Bound default 200 per connection. */
327
+ readonly maxEntries?: number;
328
+ /** Default 16,000. */
329
+ readonly maxValueBytes?: number;
330
+ /** Public only; `"high"` forces 5 words. Auto-high when ttl > 1h. */
331
+ readonly strength?: HandleStrength;
332
+ /** Operation key(s) that issue this handle; used in error text and lint. */
333
+ readonly issuedBy?: HandleIssuedBy;
334
+ }
335
+
336
+ export interface DefineDraftOptions<
337
+ TSchema extends ZodType,
338
+ TResultSchema extends ZodType | undefined,
339
+ > {
340
+ readonly name: string;
341
+ readonly fieldName?: string;
342
+ readonly schema: TSchema;
343
+ /** Optional schema of the commit result (type-level). */
344
+ readonly result?: TResultSchema;
345
+ readonly ttl: {
346
+ readonly idle: ProviderStateDurationString;
347
+ readonly max: ProviderStateDurationString;
348
+ };
349
+ /** How long a committed record stays for replay. Default "24h". */
350
+ readonly resultTtl?: ProviderStateDurationString;
351
+ /**
352
+ * `"bound"` (default): connection-scoped, 2 words. `"public"`: provider-scoped
353
+ * draft for connectionless providers (`auth: none`), 4-5 words, `maxEntries`
354
+ * required; every lookup failure collapses to `HANDLE_INVALID`.
355
+ */
356
+ readonly access?: HandleAccess;
357
+ /** Required when public. Bound default 200 per connection. */
358
+ readonly maxEntries?: number;
359
+ /** Default 64,000. */
360
+ readonly maxValueBytes?: number;
361
+ /** Public only; `"high"` forces 5 words. Auto-high when ttl.max > 1h. */
362
+ readonly strength?: HandleStrength;
363
+ /** Operation key(s) that issue this handle; used in error text and lint. */
364
+ readonly issuedBy?: HandleIssuedBy;
365
+ }
366
+
367
+ function assertKindName(name: unknown, define: string): asserts name is string {
368
+ if (typeof name !== "string" || !HANDLE_KIND_NAME_PATTERN.test(name)) {
369
+ throw new Error(
370
+ `${define}: kind name must match ${HANDLE_KIND_NAME_PATTERN} (2-12 lowercase letters, no digits or separators) so it never fuses with the word body; received ${JSON.stringify(name)}.`,
371
+ );
372
+ }
373
+ }
374
+
375
+ function assertFieldName(fieldName: string, define: string): void {
376
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(fieldName)) {
377
+ throw new Error(
378
+ `${define}: fieldName must be a plain identifier usable as a schema property key; received ${JSON.stringify(fieldName)}.`,
379
+ );
380
+ }
381
+ }
382
+
383
+ function assertPositiveInteger(value: number, label: string, define: string): void {
384
+ if (!Number.isInteger(value) || value <= 0) {
385
+ throw new Error(`${define}: ${label} must be a positive integer; received ${String(value)}.`);
386
+ }
387
+ }
388
+
389
+ function assertAccess(value: unknown, define: string): asserts value is HandleAccess {
390
+ if (value !== "bound" && value !== "public") {
391
+ throw new Error(`${define}: access must be "bound" or "public"; received ${String(value)}.`);
392
+ }
393
+ }
394
+
395
+ function assertStrength(value: unknown, define: string): asserts value is HandleStrength {
396
+ if (value !== "standard" && value !== "high") {
397
+ throw new Error(`${define}: strength must be "standard" or "high"; received ${String(value)}.`);
398
+ }
399
+ }
400
+
401
+ /** Validates `issuedBy` and returns a frozen copy for lists; `undefined` stays undefined. */
402
+ function normalizeIssuedBy(
403
+ value: unknown,
404
+ define: string,
405
+ name: string,
406
+ ): HandleIssuedBy | undefined {
407
+ if (value === undefined) return undefined;
408
+ if (!isHandleIssuedBy(value) || (typeof value === "string" ? value.length === 0 : false)) {
409
+ throw new Error(
410
+ `${define}: "${name}" issuedBy must be an operation key or a non-empty list of operation keys; received ${JSON.stringify(value)}.`,
411
+ );
412
+ }
413
+ if (typeof value === "string") return value;
414
+ if (value.some((operation) => operation.length === 0)) {
415
+ throw new Error(`${define}: "${name}" issuedBy must not contain empty operation keys.`);
416
+ }
417
+ return Object.freeze([...value]);
418
+ }
419
+
420
+ /** Word count for a kind: 2 bound; public 4, or 5 when high strength or the lifetime exceeds 1h. */
421
+ function wordCountFor(
422
+ access: HandleAccess,
423
+ strength: HandleStrength,
424
+ lifetimeMs: number,
425
+ ): HandleWordCount {
426
+ if (access === "bound") return BOUND_HANDLE_WORD_COUNT;
427
+ return strength === "high" || lifetimeMs > AUTO_HIGH_TTL_MS
428
+ ? HIGH_PUBLIC_HANDLE_WORD_COUNT
429
+ : PUBLIC_HANDLE_WORD_COUNT;
430
+ }
431
+
432
+ function createHandleField(meta: HandleFieldMeta): ZodString {
433
+ const described = z.string().min(1).describe(handleFieldDescription(meta));
434
+ // zod v4 `.meta()` replaces the registry entry, so carry the description over.
435
+ const existing = described.meta() ?? {};
436
+ return described.meta({ ...existing, [APIFUSE_HANDLE_META_KEY]: meta });
437
+ }
438
+
439
+ /** Defines an immutable cursor kind (pagination, offered option lists). */
440
+ export function defineCursor<TSchema extends ZodType>(
441
+ options: DefineCursorOptions<TSchema>,
442
+ ): CursorKind<TSchema> {
443
+ const define = "defineCursor";
444
+ assertKindName(options.name, define);
445
+ const fieldName = options.fieldName ?? `${options.name}_token`;
446
+ assertFieldName(fieldName, define);
447
+ const access: unknown = options.access ?? "bound";
448
+ assertAccess(access, define);
449
+ const ttlMs = parseHandleDurationMs(options.ttl, `"${options.name}" ttl`);
450
+ const strength: unknown = options.strength ?? "standard";
451
+ assertStrength(strength, define);
452
+ const issuedBy = normalizeIssuedBy(options.issuedBy, define, options.name);
453
+ if (access === "public" && options.maxEntries === undefined) {
454
+ throw new Error(
455
+ `${define}: public cursor "${options.name}" must declare maxEntries (provider-wide live-entry quota).`,
456
+ );
457
+ }
458
+ const maxEntries = options.maxEntries ?? DEFAULT_BOUND_MAX_ENTRIES;
459
+ assertPositiveInteger(maxEntries, "maxEntries", define);
460
+ const maxValueBytes = options.maxValueBytes ?? DEFAULT_CURSOR_MAX_VALUE_BYTES;
461
+ assertPositiveInteger(maxValueBytes, "maxValueBytes", define);
462
+ const wordCount = wordCountFor(access, strength, ttlMs);
463
+ const meta: HandleFieldMeta = {
464
+ kind: options.name,
465
+ type: "cursor",
466
+ fieldName,
467
+ ...(issuedBy ? { issuedBy } : {}),
468
+ };
469
+ return Object.freeze({
470
+ name: options.name,
471
+ type: "cursor",
472
+ fieldName,
473
+ access,
474
+ issuedBy,
475
+ schema: options.schema,
476
+ ttl: options.ttl,
477
+ ttlMs,
478
+ strength,
479
+ maxEntries,
480
+ maxValueBytes,
481
+ wordCount,
482
+ field: () => createHandleField(meta),
483
+ });
484
+ }
485
+
486
+ /**
487
+ * Defines a mutable draft kind (multi-turn forms with one-shot commit). Bound
488
+ * by default; `access: "public"` opts a connectionless provider into a
489
+ * provider-scoped draft under the public guessing analysis (ADR-0012 D3).
490
+ */
491
+ export function defineDraft<
492
+ TSchema extends ZodType,
493
+ TResultSchema extends ZodType | undefined = undefined,
494
+ >(options: DefineDraftOptions<TSchema, TResultSchema>): DraftKind<TSchema, TResultSchema> {
495
+ const define = "defineDraft";
496
+ assertKindName(options.name, define);
497
+ const fieldName = options.fieldName ?? `${options.name}_token`;
498
+ assertFieldName(fieldName, define);
499
+ if (!options.ttl || typeof options.ttl !== "object") {
500
+ throw new Error(`${define}: draft "${options.name}" ttl must be { idle, max }.`);
501
+ }
502
+ const idleTtlMs = parseHandleDurationMs(options.ttl.idle, `"${options.name}" ttl.idle`);
503
+ const maxTtlMs = parseHandleDurationMs(options.ttl.max, `"${options.name}" ttl.max`);
504
+ if (idleTtlMs > maxTtlMs) {
505
+ throw new Error(
506
+ `${define}: draft "${options.name}" ttl.idle (${idleTtlMs}ms) must not exceed ttl.max (${maxTtlMs}ms).`,
507
+ );
508
+ }
509
+ const resultTtl = options.resultTtl ?? DEFAULT_RESULT_TTL;
510
+ const resultTtlMs = parseHandleDurationMs(resultTtl, `"${options.name}" resultTtl`);
511
+ const access: unknown = options.access ?? "bound";
512
+ assertAccess(access, define);
513
+ const strength: unknown = options.strength ?? "standard";
514
+ assertStrength(strength, define);
515
+ if (access === "bound" && strength !== "standard") {
516
+ throw new Error(
517
+ `${define}: draft "${options.name}" strength applies to public drafts only; bound drafts are always two words.`,
518
+ );
519
+ }
520
+ const issuedBy = normalizeIssuedBy(options.issuedBy, define, options.name);
521
+ if (access === "public" && options.maxEntries === undefined) {
522
+ throw new Error(
523
+ `${define}: public draft "${options.name}" must declare maxEntries (provider-wide live-entry quota).`,
524
+ );
525
+ }
526
+ const maxEntries = options.maxEntries ?? DEFAULT_BOUND_MAX_ENTRIES;
527
+ assertPositiveInteger(maxEntries, "maxEntries", define);
528
+ const maxValueBytes = options.maxValueBytes ?? DEFAULT_DRAFT_MAX_VALUE_BYTES;
529
+ assertPositiveInteger(maxValueBytes, "maxValueBytes", define);
530
+ // A public draft's guessable lifetime is its hard `max` ttl (idle only shortens it).
531
+ const wordCount = wordCountFor(access, strength, maxTtlMs);
532
+ const meta: HandleFieldMeta = {
533
+ kind: options.name,
534
+ type: "draft",
535
+ fieldName,
536
+ ...(issuedBy ? { issuedBy } : {}),
537
+ };
538
+ return Object.freeze({
539
+ name: options.name,
540
+ type: "draft",
541
+ fieldName,
542
+ access,
543
+ strength,
544
+ issuedBy,
545
+ schema: options.schema,
546
+ result: options.result,
547
+ ttl: options.ttl,
548
+ idleTtlMs,
549
+ maxTtlMs,
550
+ resultTtl,
551
+ resultTtlMs,
552
+ maxEntries,
553
+ maxValueBytes,
554
+ wordCount,
555
+ field: () => createHandleField(meta),
556
+ });
557
+ }
558
+
559
+ export function isDraftKind(kind: HandleKind): kind is DraftKind<any, any> {
560
+ return kind.type === "draft";
561
+ }
562
+
563
+ export function isCursorKind(kind: HandleKind): kind is CursorKind<any> {
564
+ return kind.type === "cursor";
565
+ }
566
+
567
+ // ---------------------------------------------------------------------------
568
+ // pick
569
+ // ---------------------------------------------------------------------------
570
+
571
+ export interface PickOptions<T> {
572
+ /** Input field name, used in the error message. */
573
+ readonly field: string;
574
+ /** Item property compared against `value`. Default = `field`. */
575
+ readonly by?: keyof T & string;
576
+ /** Operation(s) that listed the items; used in the error message when known. */
577
+ readonly issuedBy?: HandleIssuedBy;
578
+ }
579
+
580
+ /**
581
+ * Chooses one offered item by a plain value the LLM copied from the offer.
582
+ * Exact match first, then a unique case-insensitive trimmed match; otherwise
583
+ * `PICK_NOT_OFFERED` with the allowed values so the LLM can self-correct. The
584
+ * server holds the offer, so a fabricated value fails here instead of reaching
585
+ * upstream. This is the "one handle per offer + plain picks" half of ADR-0012.
586
+ */
587
+ export function pick<T extends Record<string, unknown>>(
588
+ items: readonly T[],
589
+ value: string,
590
+ options: PickOptions<T>,
591
+ ): T {
592
+ const by = options.by ?? options.field;
593
+ const keyOf = (item: T): string => {
594
+ const raw = item[by];
595
+ return typeof raw === "string" ? raw : String(raw);
596
+ };
597
+ const exact = items.find((item) => keyOf(item) === value);
598
+ if (exact) return exact;
599
+ const folded = value.trim().toLowerCase();
600
+ const loose = items.filter((item) => keyOf(item).trim().toLowerCase() === folded);
601
+ if (loose.length === 1) return loose[0]!;
602
+ const allowed = items.map(keyOf);
603
+ const issuers = formatHandleIssuers(options.issuedBy);
604
+ const listed = issuers
605
+ ? ` Use the values exactly as listed by ${issuers}.`
606
+ : " Use the values exactly as listed.";
607
+ throw new HandleError(
608
+ "PICK_NOT_OFFERED",
609
+ `\`${options.field}\` must be one of: ${allowed.join(", ")}.${listed}`,
610
+ { details: { field: options.field, allowed } },
611
+ );
612
+ }