@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,208 @@
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 { ProviderError, type ProviderErrorOptions } from "./errors.js";
12
+ import { type HandleAccess, type HandleFieldMeta, type HandleIssuedBy, type HandleKindDeclaration, type HandleKindType } from "./handle-meta.js";
13
+ import type { ProviderStateDurationString } from "./types.js";
14
+ export type { HandleAccess, HandleFieldMeta, HandleIssuedBy, HandleKindDeclaration, HandleKindType, };
15
+ export type HandleStrength = "standard" | "high";
16
+ /** Words issued per handle: 2 for bound kinds, 4 for public, 5 for high-strength public. */
17
+ export type HandleWordCount = 2 | 4 | 5;
18
+ export interface HandleKindBase<TSchema extends ZodType = ZodType> extends HandleKindDeclaration {
19
+ /**
20
+ * Zod schema validated on `create`/`update`. Writes accept its *input* type
21
+ * (`InputOf`); stored records and callbacks carry its *output* type (`DataOf`).
22
+ */
23
+ readonly schema: TSchema;
24
+ /** Live-entry quota of the kind's namespace (per connection for bound kinds). */
25
+ readonly maxEntries: number;
26
+ /** Maximum JSON-encoded record size in bytes. */
27
+ readonly maxValueBytes: number;
28
+ /** Number of words the runtime issues for this kind. */
29
+ readonly wordCount: HandleWordCount;
30
+ /**
31
+ * Schema for the handle field, usable in output and input positions. Carries
32
+ * the `x-apifuse-handle` meta and an SDK-owned English description.
33
+ */
34
+ field(): ZodString;
35
+ }
36
+ export interface CursorKind<TSchema extends ZodType = ZodType> extends HandleKindBase<TSchema> {
37
+ readonly type: "cursor";
38
+ readonly ttl: ProviderStateDurationString;
39
+ readonly ttlMs: number;
40
+ readonly strength: HandleStrength;
41
+ }
42
+ export interface DraftKind<TSchema extends ZodType = ZodType, TResultSchema extends ZodType | undefined = ZodType | undefined> extends HandleKindBase<TSchema> {
43
+ readonly type: "draft";
44
+ /** `"bound"` (default): connection-scoped, 2 words. `"public"`: provider-scoped, 4-5 words. */
45
+ readonly access: HandleAccess;
46
+ /** Public only; `"high"` forces 5 words. Always `"standard"` for bound drafts. */
47
+ readonly strength: HandleStrength;
48
+ readonly ttl: {
49
+ readonly idle: ProviderStateDurationString;
50
+ readonly max: ProviderStateDurationString;
51
+ };
52
+ readonly idleTtlMs: number;
53
+ readonly maxTtlMs: number;
54
+ readonly resultTtl: ProviderStateDurationString;
55
+ readonly resultTtlMs: number;
56
+ /** Optional schema describing the commit result; type-level only at runtime. */
57
+ readonly result: TResultSchema | undefined;
58
+ }
59
+ export type HandleKind = CursorKind<any> | DraftKind<any, any>;
60
+ /** Stored record data type (schema output); what `read`, `update`, and `commit` callbacks receive. */
61
+ export type DataOf<K extends HandleKind> = z.output<K["schema"]>;
62
+ /** What `create` and `update` accept (schema input); differs from `DataOf` when the schema transforms or defaults. */
63
+ export type InputOf<K extends HandleKind> = z.input<K["schema"]>;
64
+ export type ResultOf<K extends HandleKind> = K extends DraftKind<any, infer R> ? (R extends ZodType ? z.output<R> : unknown) : never;
65
+ export type HandleStatus = "active" | "committing" | "committed";
66
+ export interface HandleRecord<K extends HandleKind> {
67
+ /** Canonical handle string (`<kind>_<word>-<word>...`). */
68
+ readonly handle: string;
69
+ readonly kind: string;
70
+ readonly status: HandleStatus;
71
+ readonly data: DataOf<K>;
72
+ readonly result?: ResultOf<K>;
73
+ readonly createdAt: string;
74
+ readonly expiresAt: string;
75
+ }
76
+ export interface HandleCommitResult<K extends HandleKind> {
77
+ readonly status: "committed" | "replayed";
78
+ readonly handle: string;
79
+ readonly result: ResultOf<K>;
80
+ }
81
+ export interface HandleContext {
82
+ /** Validates `data` with `kind.schema`, stores it, and returns the canonical handle. */
83
+ create<K extends HandleKind>(kind: K, data: InputOf<K>): Promise<string>;
84
+ /**
85
+ * Same as `create` but returns the full record (`handle`, `status`, `data`,
86
+ * `createdAt`, `expiresAt`) so a provider can expose `expires_at` without
87
+ * recomputing ttl math. `create` is the string-returning shortcut.
88
+ */
89
+ createRecord<K extends HandleKind>(kind: K, data: InputOf<K>): Promise<HandleRecord<K>>;
90
+ /** Tolerantly parses `handle`, loads the record; drafts get their idle TTL touched. */
91
+ read<K extends HandleKind>(kind: K, handle: string): Promise<HandleRecord<K>>;
92
+ /** CAS update of an active draft (3 retries) with sliding TTL. */
93
+ update<K extends DraftKind>(kind: K, handle: string, updater: (data: DataOf<K>) => InputOf<K> | Promise<InputOf<K>>): Promise<HandleRecord<K>>;
94
+ /** One-shot commit with result replay; see runtime docs for the state machine. */
95
+ commit<K extends DraftKind>(kind: K, handle: string, work: (data: DataOf<K>) => Promise<ResultOf<K>>): Promise<HandleCommitResult<K>>;
96
+ /** Deletes the record; idempotent. */
97
+ discard<K extends HandleKind>(kind: K, handle: string): Promise<void>;
98
+ }
99
+ export type HandleOperation = "create" | "read" | "update" | "commit" | "discard";
100
+ export type HandleTelemetryOutcome = "success" | "not_found" | "expired" | "invalid" | "kind_mismatch" | "busy" | "replayed" | "error";
101
+ /** Allowlisted metadata only; handle values, data, and results are never included. */
102
+ export interface HandleTelemetryEvent {
103
+ readonly providerId: string;
104
+ readonly kind: string;
105
+ readonly type: HandleKindType;
106
+ readonly operation: HandleOperation;
107
+ readonly outcome: HandleTelemetryOutcome;
108
+ /** `"none"` or the sorted normalization classes joined by `+`. */
109
+ readonly normalization: string;
110
+ readonly words: number;
111
+ }
112
+ export type HandleErrorCode = "HANDLE_INVALID" | "HANDLE_NOT_FOUND" | "HANDLE_EXPIRED" | "HANDLE_KIND_MISMATCH" | "HANDLE_BUSY" | "HANDLE_COMMITTED" | "HANDLE_CONNECTION_REQUIRED" | "HANDLE_STORAGE_UNAVAILABLE" | "HANDLE_TOO_LARGE" | "HANDLE_INVALID_DATA" | "PICK_NOT_OFFERED";
113
+ export type HandleErrorOptions = Omit<ProviderErrorOptions, "code"> & {
114
+ /** Kind name the error relates to, when known. */
115
+ readonly kind?: string;
116
+ };
117
+ export declare class HandleError extends ProviderError {
118
+ readonly handleCode: HandleErrorCode;
119
+ readonly kind?: string;
120
+ constructor(code: HandleErrorCode, message: string, options?: HandleErrorOptions);
121
+ get code(): HandleErrorCode;
122
+ }
123
+ /**
124
+ * Recognizes handle errors across duplicate SDK module copies (packaged CLI
125
+ * `src/*` runtime vs provider `dist/*` import), where `instanceof` splits.
126
+ */
127
+ export declare function isHandleError(value: unknown): value is HandleError;
128
+ /**
129
+ * Standard recovery sentence appended to every handle error message so the LLM
130
+ * knows the next action without provider-specific wording.
131
+ */
132
+ export declare function handleRecoverySentence(kind: {
133
+ readonly fieldName: string;
134
+ readonly issuedBy?: HandleIssuedBy;
135
+ }): string;
136
+ /** Parses a `ProviderStateDurationString` to milliseconds; throws on invalid or non-positive input. */
137
+ export declare function parseHandleDurationMs(value: ProviderStateDurationString, label: string): number;
138
+ export interface DefineCursorOptions<TSchema extends ZodType> {
139
+ /** Kind name, `/^[a-z]{2,12}$/`; becomes the handle prefix. */
140
+ readonly name: string;
141
+ /** Schema property key carrying the handle. Default `${name}_token`. */
142
+ readonly fieldName?: string;
143
+ readonly schema: TSchema;
144
+ readonly ttl: ProviderStateDurationString;
145
+ /** `"bound"` (default): connection-scoped, 2 words. `"public"`: provider-scoped, 4-5 words. */
146
+ readonly access?: HandleAccess;
147
+ /** Required when public. Bound default 200 per connection. */
148
+ readonly maxEntries?: number;
149
+ /** Default 16,000. */
150
+ readonly maxValueBytes?: number;
151
+ /** Public only; `"high"` forces 5 words. Auto-high when ttl > 1h. */
152
+ readonly strength?: HandleStrength;
153
+ /** Operation key(s) that issue this handle; used in error text and lint. */
154
+ readonly issuedBy?: HandleIssuedBy;
155
+ }
156
+ export interface DefineDraftOptions<TSchema extends ZodType, TResultSchema extends ZodType | undefined> {
157
+ readonly name: string;
158
+ readonly fieldName?: string;
159
+ readonly schema: TSchema;
160
+ /** Optional schema of the commit result (type-level). */
161
+ readonly result?: TResultSchema;
162
+ readonly ttl: {
163
+ readonly idle: ProviderStateDurationString;
164
+ readonly max: ProviderStateDurationString;
165
+ };
166
+ /** How long a committed record stays for replay. Default "24h". */
167
+ readonly resultTtl?: ProviderStateDurationString;
168
+ /**
169
+ * `"bound"` (default): connection-scoped, 2 words. `"public"`: provider-scoped
170
+ * draft for connectionless providers (`auth: none`), 4-5 words, `maxEntries`
171
+ * required; every lookup failure collapses to `HANDLE_INVALID`.
172
+ */
173
+ readonly access?: HandleAccess;
174
+ /** Required when public. Bound default 200 per connection. */
175
+ readonly maxEntries?: number;
176
+ /** Default 64,000. */
177
+ readonly maxValueBytes?: number;
178
+ /** Public only; `"high"` forces 5 words. Auto-high when ttl.max > 1h. */
179
+ readonly strength?: HandleStrength;
180
+ /** Operation key(s) that issue this handle; used in error text and lint. */
181
+ readonly issuedBy?: HandleIssuedBy;
182
+ }
183
+ /** Defines an immutable cursor kind (pagination, offered option lists). */
184
+ export declare function defineCursor<TSchema extends ZodType>(options: DefineCursorOptions<TSchema>): CursorKind<TSchema>;
185
+ /**
186
+ * Defines a mutable draft kind (multi-turn forms with one-shot commit). Bound
187
+ * by default; `access: "public"` opts a connectionless provider into a
188
+ * provider-scoped draft under the public guessing analysis (ADR-0012 D3).
189
+ */
190
+ export declare function defineDraft<TSchema extends ZodType, TResultSchema extends ZodType | undefined = undefined>(options: DefineDraftOptions<TSchema, TResultSchema>): DraftKind<TSchema, TResultSchema>;
191
+ export declare function isDraftKind(kind: HandleKind): kind is DraftKind<any, any>;
192
+ export declare function isCursorKind(kind: HandleKind): kind is CursorKind<any>;
193
+ export interface PickOptions<T> {
194
+ /** Input field name, used in the error message. */
195
+ readonly field: string;
196
+ /** Item property compared against `value`. Default = `field`. */
197
+ readonly by?: keyof T & string;
198
+ /** Operation(s) that listed the items; used in the error message when known. */
199
+ readonly issuedBy?: HandleIssuedBy;
200
+ }
201
+ /**
202
+ * Chooses one offered item by a plain value the LLM copied from the offer.
203
+ * Exact match first, then a unique case-insensitive trimmed match; otherwise
204
+ * `PICK_NOT_OFFERED` with the allowed values so the LLM can self-correct. The
205
+ * server holds the offer, so a fabricated value fails here instead of reaching
206
+ * upstream. This is the "one handle per offer + plain picks" half of ADR-0012.
207
+ */
208
+ export declare function pick<T extends Record<string, unknown>>(items: readonly T[], value: string, options: PickOptions<T>): T;
package/dist/handle.js ADDED
@@ -0,0 +1,299 @@
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 { z } from "zod";
11
+ import { brandHandleError, hasHandleErrorBrand, ProviderError, } from "./errors.js";
12
+ import { APIFUSE_HANDLE_META_KEY, formatHandleIssuers, handleFieldDescription, HANDLE_KIND_NAME_PATTERN, isHandleIssuedBy, } from "./handle-meta.js";
13
+ import { BOUND_HANDLE_WORD_COUNT, HIGH_PUBLIC_HANDLE_WORD_COUNT, PUBLIC_HANDLE_WORD_COUNT, } from "./runtime/handle-wordlist.js";
14
+ /** Public kinds whose (max) ttl exceeds this are issued with five words (auto-high). */
15
+ const AUTO_HIGH_TTL_MS = 3_600_000;
16
+ const DEFAULT_BOUND_MAX_ENTRIES = 200;
17
+ const DEFAULT_CURSOR_MAX_VALUE_BYTES = 16_000;
18
+ const DEFAULT_DRAFT_MAX_VALUE_BYTES = 64_000;
19
+ const DEFAULT_RESULT_TTL = "24h";
20
+ const HANDLE_ERROR_DEFAULTS = {
21
+ HANDLE_INVALID: { category: "input_validation", retryable: false },
22
+ HANDLE_NOT_FOUND: { category: "input_validation", retryable: false },
23
+ HANDLE_EXPIRED: { category: "input_validation", retryable: false },
24
+ HANDLE_KIND_MISMATCH: { category: "input_validation", retryable: false },
25
+ HANDLE_BUSY: { category: "internal_error", retryable: true },
26
+ HANDLE_COMMITTED: { category: "input_validation", retryable: false },
27
+ HANDLE_CONNECTION_REQUIRED: { category: "internal_error", retryable: false },
28
+ HANDLE_STORAGE_UNAVAILABLE: { category: "internal_error", retryable: false },
29
+ HANDLE_TOO_LARGE: { category: "internal_error", retryable: false },
30
+ HANDLE_INVALID_DATA: { category: "internal_error", retryable: false },
31
+ PICK_NOT_OFFERED: { category: "input_validation", retryable: false },
32
+ };
33
+ export class HandleError extends ProviderError {
34
+ handleCode;
35
+ kind;
36
+ constructor(code, message, options = {}) {
37
+ const { kind, ...rest } = options;
38
+ const defaults = HANDLE_ERROR_DEFAULTS[code];
39
+ super(message, {
40
+ category: defaults.category,
41
+ retryable: defaults.retryable,
42
+ ...rest,
43
+ code,
44
+ });
45
+ this.name = "HandleError";
46
+ this.handleCode = code;
47
+ this.kind = kind;
48
+ brandHandleError(this);
49
+ }
50
+ get code() {
51
+ return this.handleCode;
52
+ }
53
+ }
54
+ /**
55
+ * Recognizes handle errors across duplicate SDK module copies (packaged CLI
56
+ * `src/*` runtime vs provider `dist/*` import), where `instanceof` splits.
57
+ */
58
+ export function isHandleError(value) {
59
+ return value instanceof HandleError || hasHandleErrorBrand(value);
60
+ }
61
+ /**
62
+ * Standard recovery sentence appended to every handle error message so the LLM
63
+ * knows the next action without provider-specific wording.
64
+ */
65
+ export function handleRecoverySentence(kind) {
66
+ const issuers = formatHandleIssuers(kind.issuedBy);
67
+ if (issuers) {
68
+ return `Call ${issuers} again and pass the new \`${kind.fieldName}\` exactly as returned.`;
69
+ }
70
+ return `Request a new \`${kind.fieldName}\` and pass it exactly as returned.`;
71
+ }
72
+ // ---------------------------------------------------------------------------
73
+ // Durations
74
+ // ---------------------------------------------------------------------------
75
+ const SHORT_DURATION_PATTERN = /^(\d+)(ms|s|m|h|d)$/;
76
+ const ISO_DURATION_PATTERN = /^PT(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?$/;
77
+ /** Parses a `ProviderStateDurationString` to milliseconds; throws on invalid or non-positive input. */
78
+ export function parseHandleDurationMs(value, label) {
79
+ const short = SHORT_DURATION_PATTERN.exec(value);
80
+ let ms;
81
+ if (short) {
82
+ const amount = Number(short[1]);
83
+ const unit = short[2];
84
+ const multiplier = unit === "ms"
85
+ ? 1
86
+ : unit === "s"
87
+ ? 1_000
88
+ : unit === "m"
89
+ ? 60_000
90
+ : unit === "h"
91
+ ? 3_600_000
92
+ : 86_400_000;
93
+ ms = amount * multiplier;
94
+ }
95
+ else {
96
+ const iso = ISO_DURATION_PATTERN.exec(value);
97
+ if (iso && (iso[1] !== undefined || iso[2] !== undefined || iso[3] !== undefined)) {
98
+ ms =
99
+ Number(iso[1] ?? 0) * 3_600_000 +
100
+ Number(iso[2] ?? 0) * 60_000 +
101
+ Number(iso[3] ?? 0) * 1_000;
102
+ }
103
+ }
104
+ if (ms === undefined || !Number.isFinite(ms) || ms <= 0) {
105
+ throw new Error(`Handle kind ${label} must be a positive duration such as "10m", "2h", or "PT30M" (received ${JSON.stringify(value)}).`);
106
+ }
107
+ return Math.floor(ms);
108
+ }
109
+ function assertKindName(name, define) {
110
+ if (typeof name !== "string" || !HANDLE_KIND_NAME_PATTERN.test(name)) {
111
+ throw new Error(`${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)}.`);
112
+ }
113
+ }
114
+ function assertFieldName(fieldName, define) {
115
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(fieldName)) {
116
+ throw new Error(`${define}: fieldName must be a plain identifier usable as a schema property key; received ${JSON.stringify(fieldName)}.`);
117
+ }
118
+ }
119
+ function assertPositiveInteger(value, label, define) {
120
+ if (!Number.isInteger(value) || value <= 0) {
121
+ throw new Error(`${define}: ${label} must be a positive integer; received ${String(value)}.`);
122
+ }
123
+ }
124
+ function assertAccess(value, define) {
125
+ if (value !== "bound" && value !== "public") {
126
+ throw new Error(`${define}: access must be "bound" or "public"; received ${String(value)}.`);
127
+ }
128
+ }
129
+ function assertStrength(value, define) {
130
+ if (value !== "standard" && value !== "high") {
131
+ throw new Error(`${define}: strength must be "standard" or "high"; received ${String(value)}.`);
132
+ }
133
+ }
134
+ /** Validates `issuedBy` and returns a frozen copy for lists; `undefined` stays undefined. */
135
+ function normalizeIssuedBy(value, define, name) {
136
+ if (value === undefined)
137
+ return undefined;
138
+ if (!isHandleIssuedBy(value) || (typeof value === "string" ? value.length === 0 : false)) {
139
+ throw new Error(`${define}: "${name}" issuedBy must be an operation key or a non-empty list of operation keys; received ${JSON.stringify(value)}.`);
140
+ }
141
+ if (typeof value === "string")
142
+ return value;
143
+ if (value.some((operation) => operation.length === 0)) {
144
+ throw new Error(`${define}: "${name}" issuedBy must not contain empty operation keys.`);
145
+ }
146
+ return Object.freeze([...value]);
147
+ }
148
+ /** Word count for a kind: 2 bound; public 4, or 5 when high strength or the lifetime exceeds 1h. */
149
+ function wordCountFor(access, strength, lifetimeMs) {
150
+ if (access === "bound")
151
+ return BOUND_HANDLE_WORD_COUNT;
152
+ return strength === "high" || lifetimeMs > AUTO_HIGH_TTL_MS
153
+ ? HIGH_PUBLIC_HANDLE_WORD_COUNT
154
+ : PUBLIC_HANDLE_WORD_COUNT;
155
+ }
156
+ function createHandleField(meta) {
157
+ const described = z.string().min(1).describe(handleFieldDescription(meta));
158
+ // zod v4 `.meta()` replaces the registry entry, so carry the description over.
159
+ const existing = described.meta() ?? {};
160
+ return described.meta({ ...existing, [APIFUSE_HANDLE_META_KEY]: meta });
161
+ }
162
+ /** Defines an immutable cursor kind (pagination, offered option lists). */
163
+ export function defineCursor(options) {
164
+ const define = "defineCursor";
165
+ assertKindName(options.name, define);
166
+ const fieldName = options.fieldName ?? `${options.name}_token`;
167
+ assertFieldName(fieldName, define);
168
+ const access = options.access ?? "bound";
169
+ assertAccess(access, define);
170
+ const ttlMs = parseHandleDurationMs(options.ttl, `"${options.name}" ttl`);
171
+ const strength = options.strength ?? "standard";
172
+ assertStrength(strength, define);
173
+ const issuedBy = normalizeIssuedBy(options.issuedBy, define, options.name);
174
+ if (access === "public" && options.maxEntries === undefined) {
175
+ throw new Error(`${define}: public cursor "${options.name}" must declare maxEntries (provider-wide live-entry quota).`);
176
+ }
177
+ const maxEntries = options.maxEntries ?? DEFAULT_BOUND_MAX_ENTRIES;
178
+ assertPositiveInteger(maxEntries, "maxEntries", define);
179
+ const maxValueBytes = options.maxValueBytes ?? DEFAULT_CURSOR_MAX_VALUE_BYTES;
180
+ assertPositiveInteger(maxValueBytes, "maxValueBytes", define);
181
+ const wordCount = wordCountFor(access, strength, ttlMs);
182
+ const meta = {
183
+ kind: options.name,
184
+ type: "cursor",
185
+ fieldName,
186
+ ...(issuedBy ? { issuedBy } : {}),
187
+ };
188
+ return Object.freeze({
189
+ name: options.name,
190
+ type: "cursor",
191
+ fieldName,
192
+ access,
193
+ issuedBy,
194
+ schema: options.schema,
195
+ ttl: options.ttl,
196
+ ttlMs,
197
+ strength,
198
+ maxEntries,
199
+ maxValueBytes,
200
+ wordCount,
201
+ field: () => createHandleField(meta),
202
+ });
203
+ }
204
+ /**
205
+ * Defines a mutable draft kind (multi-turn forms with one-shot commit). Bound
206
+ * by default; `access: "public"` opts a connectionless provider into a
207
+ * provider-scoped draft under the public guessing analysis (ADR-0012 D3).
208
+ */
209
+ export function defineDraft(options) {
210
+ const define = "defineDraft";
211
+ assertKindName(options.name, define);
212
+ const fieldName = options.fieldName ?? `${options.name}_token`;
213
+ assertFieldName(fieldName, define);
214
+ if (!options.ttl || typeof options.ttl !== "object") {
215
+ throw new Error(`${define}: draft "${options.name}" ttl must be { idle, max }.`);
216
+ }
217
+ const idleTtlMs = parseHandleDurationMs(options.ttl.idle, `"${options.name}" ttl.idle`);
218
+ const maxTtlMs = parseHandleDurationMs(options.ttl.max, `"${options.name}" ttl.max`);
219
+ if (idleTtlMs > maxTtlMs) {
220
+ throw new Error(`${define}: draft "${options.name}" ttl.idle (${idleTtlMs}ms) must not exceed ttl.max (${maxTtlMs}ms).`);
221
+ }
222
+ const resultTtl = options.resultTtl ?? DEFAULT_RESULT_TTL;
223
+ const resultTtlMs = parseHandleDurationMs(resultTtl, `"${options.name}" resultTtl`);
224
+ const access = options.access ?? "bound";
225
+ assertAccess(access, define);
226
+ const strength = options.strength ?? "standard";
227
+ assertStrength(strength, define);
228
+ if (access === "bound" && strength !== "standard") {
229
+ throw new Error(`${define}: draft "${options.name}" strength applies to public drafts only; bound drafts are always two words.`);
230
+ }
231
+ const issuedBy = normalizeIssuedBy(options.issuedBy, define, options.name);
232
+ if (access === "public" && options.maxEntries === undefined) {
233
+ throw new Error(`${define}: public draft "${options.name}" must declare maxEntries (provider-wide live-entry quota).`);
234
+ }
235
+ const maxEntries = options.maxEntries ?? DEFAULT_BOUND_MAX_ENTRIES;
236
+ assertPositiveInteger(maxEntries, "maxEntries", define);
237
+ const maxValueBytes = options.maxValueBytes ?? DEFAULT_DRAFT_MAX_VALUE_BYTES;
238
+ assertPositiveInteger(maxValueBytes, "maxValueBytes", define);
239
+ // A public draft's guessable lifetime is its hard `max` ttl (idle only shortens it).
240
+ const wordCount = wordCountFor(access, strength, maxTtlMs);
241
+ const meta = {
242
+ kind: options.name,
243
+ type: "draft",
244
+ fieldName,
245
+ ...(issuedBy ? { issuedBy } : {}),
246
+ };
247
+ return Object.freeze({
248
+ name: options.name,
249
+ type: "draft",
250
+ fieldName,
251
+ access,
252
+ strength,
253
+ issuedBy,
254
+ schema: options.schema,
255
+ result: options.result,
256
+ ttl: options.ttl,
257
+ idleTtlMs,
258
+ maxTtlMs,
259
+ resultTtl,
260
+ resultTtlMs,
261
+ maxEntries,
262
+ maxValueBytes,
263
+ wordCount,
264
+ field: () => createHandleField(meta),
265
+ });
266
+ }
267
+ export function isDraftKind(kind) {
268
+ return kind.type === "draft";
269
+ }
270
+ export function isCursorKind(kind) {
271
+ return kind.type === "cursor";
272
+ }
273
+ /**
274
+ * Chooses one offered item by a plain value the LLM copied from the offer.
275
+ * Exact match first, then a unique case-insensitive trimmed match; otherwise
276
+ * `PICK_NOT_OFFERED` with the allowed values so the LLM can self-correct. The
277
+ * server holds the offer, so a fabricated value fails here instead of reaching
278
+ * upstream. This is the "one handle per offer + plain picks" half of ADR-0012.
279
+ */
280
+ export function pick(items, value, options) {
281
+ const by = options.by ?? options.field;
282
+ const keyOf = (item) => {
283
+ const raw = item[by];
284
+ return typeof raw === "string" ? raw : String(raw);
285
+ };
286
+ const exact = items.find((item) => keyOf(item) === value);
287
+ if (exact)
288
+ return exact;
289
+ const folded = value.trim().toLowerCase();
290
+ const loose = items.filter((item) => keyOf(item).trim().toLowerCase() === folded);
291
+ if (loose.length === 1)
292
+ return loose[0];
293
+ const allowed = items.map(keyOf);
294
+ const issuers = formatHandleIssuers(options.issuedBy);
295
+ const listed = issuers
296
+ ? ` Use the values exactly as listed by ${issuers}.`
297
+ : " Use the values exactly as listed.";
298
+ throw new HandleError("PICK_NOT_OFFERED", `\`${options.field}\` must be one of: ${allowed.join(", ")}.${listed}`, { details: { field: options.field, allowed } });
299
+ }
@@ -100,6 +100,26 @@ export function localizeAuthTurn(turn, options) {
100
100
  : {}),
101
101
  };
102
102
  }
103
+ /**
104
+ * Markers that indicate a locale value was scaffolded but never translated.
105
+ *
106
+ * ASCII tokens are matched case-sensitively as whole `\w` tokens so ordinary
107
+ * prose such as "todo list" or identifiers like "TBDx" are not flagged. Locale
108
+ * tags such as `[ko]` are matched literally (the brackets are the boundary), and
109
+ * the Korean/Japanese phrases are matched as-is since CJK text has no `\b`.
110
+ */
111
+ const PROVIDER_LOCALE_PLACEHOLDER_PATTERNS = [
112
+ /\b(?:TODO|FIXME|TBD|TRANSLATE)\b/,
113
+ /\[(?:en|ko|ja)\]/i,
114
+ /번역\s*필요/,
115
+ /翻訳が必要/,
116
+ ];
117
+ function isProviderLocalePlaceholderText(text) {
118
+ if (text.trim().length === 0) {
119
+ return true;
120
+ }
121
+ return PROVIDER_LOCALE_PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(text));
122
+ }
103
123
  export function validateProviderLocaleCatalogs(options) {
104
124
  const issues = [];
105
125
  const uniqueKeys = Array.from(new Set(options.requiredKeys.map((key) => {
@@ -138,7 +158,7 @@ export function validateProviderLocaleCatalogs(options) {
138
158
  continue;
139
159
  }
140
160
  for (const text of Array.isArray(value) ? value : [value]) {
141
- if (text.trim().length === 0 || /\bTODO\b/i.test(text)) {
161
+ if (isProviderLocalePlaceholderText(text)) {
142
162
  issues.push({
143
163
  locale,
144
164
  key,
package/dist/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  export * from "./auth.js";
2
2
  export * from "./ceremonies/index.js";
3
- export * from "./choice-token.js";
4
3
  export type { ApiFuseConfig, BrowserConfig, ProxyCacheStatus, ProxyProtocol, ProxyResolutionOptions, ProxyResolutionSource, ProxyUserAgentSource, ProxyVendorName, ResolvedProxyConfig, SessionConfig, SmartproxyAllocatorBodyClass, } from "./config/loader.js";
5
4
  export { defineConfig, loadApiFuseConfig, resolveProxy } from "./config/loader.js";
6
5
  export { canonicalJson, digestProviderContract, extractProviderContract, type JsonPrimitive, type JsonValue, PROVIDER_CONTRACT_SCHEMA_VERSION, type ProviderContractOperation, type ProviderContractSnapshot, } from "./contract.js";
@@ -20,7 +19,9 @@ export * from "./recipes/rest-api.js";
20
19
  export { createFlowContext, createScratchpad } from "./runtime/auth-flow.js";
21
20
  export type { BrowserClientOptions } from "./runtime/browser.js";
22
21
  export { APIFUSE__CACHE__KEY_PEPPER_ENV, createBypassProviderCache, createProviderCache, type ProviderCacheOptions, } from "./runtime/cache.js";
23
- export { type CreateProviderChoiceContextOptions, createProviderChoiceContext, createTestProviderChoiceContext, PROVIDER_RUNTIME_CHOICE_TOKEN_MASTER_SECRET_ENV, } from "./runtime/choice.js";
22
+ export * from "./handle.js";
23
+ export { APIFUSE_HANDLE_META_KEY, HANDLE_KIND_NAME_PATTERN, handleFieldDescription, isHandleFieldMeta, } from "./handle-meta.js";
24
+ export { type CreateHandleContextOptions, type CreateTestHandleContextOptions, createHandleContext, createTestHandleContext, type HandleNormalizationClass, type NormalizedHandle, normalizeHandle, } from "./runtime/handle.js";
24
25
  export { type CreateCredentialContextOptions, createCredentialContext, } from "./runtime/credential.js";
25
26
  export { createEnvContext } from "./runtime/env.js";
26
27
  export { executeOperation } from "./runtime/executor.js";
@@ -41,7 +42,7 @@ export { createUnsupportedResolverClient } from "./runtime/resolver-shared.js";
41
42
  export type { ResolverRuntimeOptions } from "./runtime/resolver.js";
42
43
  export type { ResolverPaidUsageContext, ResolverVendorTransport, ResolverVendorUnavailableReason, } from "./runtime/resolver-vendors/types.js";
43
44
  export { assertRequiredSecretsPresent, listMissingRequiredSecrets, MISSING_SECRET_CODE, } from "./runtime/secrets.js";
44
- export { createUnsupportedProviderRuntimeState, UnsupportedProviderStateError, } from "./runtime/state.js";
45
+ export { createMemoryProviderRuntimeState, createUnsupportedProviderRuntimeState, UnsupportedProviderStateError, } from "./runtime/state.js";
45
46
  export { APIFUSE__OCR__API_KEY_ENV, APIFUSE__OCR__BACKEND_ENV, APIFUSE__OCR__BASE_URL_ENV, APIFUSE__OCR__CLOUDFLARE_API_TOKEN_ENV, APIFUSE__OCR__MODEL_ENV, CLOUDFLARE_ACCOUNT_ID_ENV, CLOUDFLARE_WORKERS_AI_OCR_BACKEND, createCloudflareWorkersAiOcrClient, createOcrClientFromEnv, createOpenAiCompatibleOcrClient, createUnsupportedOcrClient, DEFAULT_CLOUDFLARE_WORKERS_AI_OCR_MODEL, extractCaptchaCandidates, OPENAI_COMPATIBLE_OCR_BACKEND, } from "./runtime/ocr.js";
46
47
  export { APIFUSE__STT__BACKEND_ENV, APIFUSE__STT__CLOUDFLARE_API_TOKEN_ENV, APIFUSE__STT__MODEL_ENV, createSttClientFromEnv, createUnsupportedSttClient, extractVerificationCode, resolveSttPrompt, } from "./runtime/stt.js";
47
48
  export { type CreateTraceContextOptions, createTraceContext, type Span, type TraceContext, } from "./runtime/trace.js";
@@ -50,9 +51,11 @@ export { APIFUSE_CONTENT_PROVENANCE_META_KEY, APIFUSE_CONTENT_TRUST_META_KEY, AP
50
51
  export { createServerApp, createServerAppAsync, ERROR_OBSERVABILITY_HEADER, type ProviderErrorCauseFrame, type ServeOptions, serve, } from "./server/serve.js";
51
52
  export { DEFAULT_STEALTH_BROWSER, DEFAULT_STEALTH_OS, getStealthProfile, listStealthProfiles, } from "./stealth/profiles.js";
52
53
  export * from "./stream.js";
53
- export type { ApiFuseResponse, AuthConfig, AuthContext, AuthFlowDefinition, AuthFlowInputHandler, AuthFlowStartHandler, AuthMode, AuthTurn, Bcp47Locale, BrowserCookie, BrowserEngine, BrowserOptions, BrowserResourceBody, BrowserResourceDecision, BrowserResourceMethod, BrowserResourcePolicy, BrowserResourceRequest, BrowserResourceRoute, ChallengeSolution, ConnectionMode, ContextDeclaration, CookieJar, ContextScratchpad, CredentialContext, CredentialDeclaration, E164PhoneNumber, EnvContext, FlowContext, FlowContextStore, HealthCheckAssertionContext, HealthCheckCase, HealthCheckCaseResult, HealthCheckSuite, HealthCheckUnsupported, HealthJourneyDefinition, HealthJourneyEventContext, HealthJourneyGatewayContext, HealthJourneyJournalContext, HealthJourneyManualTriggerPolicy, HealthJourneyRunContext, HealthJourneyRunResult, HealthJourneySchedule, HealthScheduleRandomization, HealthJourneySmsContext, HealthJourneyStep, HttpClient, HttpMethod, HttpRedirectFailureReason, HttpRedirectPolicy, HttpRedirectPolicyMode, HttpResponse, HttpRetryOptions, HttpRetrySummary, HttpStreamResponse, IanaTimeZone, InferSchemaOutput, Iso3166Alpha2CountryCode, Iso4217CurrencyCode, Iso8601Duration, NativeContext, NativeNetworkClient, NativeNetworkCloseReason, NativeNetworkConnection, NativeNetworkConnectInput, NativeNetworkConnectOptions, NativeNetworkDynamicGrantOptions, NativeNetworkEgressGrant, NativeProviderConfig, NativeProxyDrainHandler, NativeProxyEgressInfo, NativeProxyExpiringEvent, NativeProxyExpiringReason, NativeTcpDynamicEgressRule, NativeTcpEgressGrant, NativeTcpEgressRule, NativeTcpPortRange, NativeTcpTlsMode, NativeTlsConnectOptions, OcrCaptchaCandidate, OcrCaptchaOptions, OcrCaptchaResult, OcrContext, OcrImageInput, OcrRecognizeRequest, OcrResult, OcrWarning, OperationApprovalPolicy, OperationContractMetadata, OperationDefinition, OperationDeprecationMetadata, OperationExample, OperationErrorCode, ProviderErrorStatus, OperationHandlerResult, OperationLifecycle, OperationObservabilityConfig, OperationObservabilitySensitiveConfig, OperationRelationships, OperationRiskClass, OperationSensitivePath, OperationTransport, OperationTransportKind, ProbeInterval, ProviderAccessConfig, ProviderAccessVisibility, ProviderCache, ProviderCacheGetOrSetOptions, ProviderCacheKeyOptions, ProviderCacheLookupMeta, ProviderCacheResponseMeta, ProviderCacheResult, ProviderChoiceBindingOptions, ProviderChoiceConsumeMode, ProviderChoiceConsumeResult, ProviderChoiceContext, ProviderChoiceExplicitParseResult, ProviderChoiceIssueOptions, ProviderChoiceParseOptions, ProviderChallenge, ProviderChallengeKind, ProviderContext, ProviderContextFor, ProviderDefinition, ProviderDeploymentOverrides, ProviderFileRef, ProviderFilesContext, ProviderHealthMonitorConfig, ProviderHealthProbeConfig, ProviderLocale, ProviderLocaleKey, ProviderLocaleKeyInput, ProviderLogoProfile, ProviderLogoSource, ProviderMeta, ProviderOcrConfig, ProviderProxyConfig, ProviderProxyMode, ProviderProxyPolicy, ProxiedOAuthConfig, ProviderProxyProvider, ProviderProxySessionAffinity, ProviderPublicConnectionMode, ProviderPublicProfile, ProviderReviewed, ProviderResolvedFile, ProviderResolverConfig, ProviderResolverVendor, ProviderRuntimeTarget, ProviderRuntimeState, ProviderSecretDeclaration, ProviderStealthConfig, ProviderStateDurationString, ProviderStateNamespace, ProviderStreamEvent, ProviderSttConfig, ProviderSttMode, ProviderSupportLevel, RequestOptions, RedirectRunReason, ResolverContext, Rfc3339Instant, SchemaLike, SmsOrigin, SmsOtpExtractionPattern, SmsOtpMatcherDefinition, SseMessage, StandardSchemaV1, StateCasResult, StateNamespaceOptions, StateNamespaceScope, StateValue, StateWriteOptions, StealthClient, StealthBrowser, StealthChallengeClassification, StealthCookieStore, StealthCookieStoreV1, StealthFetchOptions, StealthPlatform, StealthProfile, StealthProfileDescriptor, StealthProfileSelection, StealthOS, StealthRedirectHop, StealthRedirectRunOptions, StealthRedirectRunResult, StealthResponse, StealthSession, StealthSessionCookies, SttAudioInput, SttContext, SttPromptPolicy, SttSegment, SttTranscribeMode, SttTranscribeRequest, SttTranscript, SttUnsupportedOptionPolicy, SttUsage, SttVerificationCodeOptions, SttWarning, TraceConfig, TraceSpan, VerificationCodeCandidate, VerificationCodeCandidateSource, VerificationCodeExtractionResult, } from "./types.js";
54
+ export type { ApiFuseResponse, AuthConfig, AuthContext, AuthFlowDefinition, AuthFlowInputHandler, AuthFlowStartHandler, AuthMode, AuthTurn, Bcp47Locale, BrowserCookie, BrowserEngine, BrowserOptions, BrowserResourceBody, BrowserResourceDecision, BrowserResourceMethod, BrowserResourcePolicy, BrowserResourceRequest, BrowserResourceRoute, ChallengeSolution, ConnectionMode, ContextDeclaration, CookieJar, ContextScratchpad, CredentialContext, CredentialDeclaration, E164PhoneNumber, EnvContext, FlowContext, FlowContextStore, HealthCheckAssertionContext, HealthCheckCase, HealthCheckCaseResult, HealthCheckSuite, HealthCheckUnsupported, HealthJourneyDefinition, HealthJourneyEventContext, HealthJourneyGatewayContext, HealthJourneyJournalContext, HealthJourneyManualTriggerPolicy, HealthJourneyRunContext, HealthJourneyRunResult, HealthJourneySchedule, HealthScheduleRandomization, HealthJourneySmsContext, HealthJourneyStep, HttpClient, HttpMethod, HttpRedirectFailureReason, HttpRedirectPolicy, HttpRedirectPolicyMode, HttpResponse, HttpRetryOptions, HttpRetrySummary, HttpStreamResponse, IanaTimeZone, InferSchemaOutput, Iso3166Alpha2CountryCode, Iso4217CurrencyCode, Iso8601Duration, NativeContext, NativeNetworkClient, NativeNetworkCloseReason, NativeNetworkConnection, NativeNetworkConnectInput, NativeNetworkConnectOptions, NativeNetworkDynamicGrantOptions, NativeNetworkEgressGrant, NativeProviderConfig, NativeProxyDrainHandler, NativeProxyEgressInfo, NativeProxyExpiringEvent, NativeProxyExpiringReason, NativeTcpDynamicEgressRule, NativeTcpEgressGrant, NativeTcpEgressRule, NativeTcpPortRange, NativeTcpTlsMode, NativeTlsConnectOptions, OcrCaptchaCandidate, OcrCaptchaOptions, OcrCaptchaResult, OcrContext, OcrImageInput, OcrRecognizeRequest, OcrResult, OcrWarning, OperationApprovalPolicy, OperationContractMetadata, OperationDefinition, OperationDeprecationMetadata, OperationExample, OperationErrorCode, ProviderErrorStatus, OperationHandlerResult, OperationLifecycle, OperationObservabilityConfig, OperationObservabilitySensitiveConfig, OperationRelationships, OperationRiskClass, OperationSensitivePath, OperationTransport, OperationTransportKind, ProbeInterval, ProviderAccessConfig, ProviderAccessVisibility, ProviderCache, ProviderCacheGetOrSetOptions, ProviderCacheKeyOptions, ProviderCacheLookupMeta, ProviderCacheResponseMeta, ProviderCacheResult, ProviderChallenge, ProviderChallengeKind, ProviderContext, ProviderContextFor, ProviderDefinition, ProviderDeploymentOverrides, ProviderFileRef, ProviderFilesContext, ProviderHealthMonitorConfig, ProviderHealthProbeConfig, ProviderLocale, ProviderLocaleKey, ProviderLocaleKeyInput, ProviderLogoProfile, ProviderLogoSource, ProviderMeta, ProviderOcrConfig, ProviderProxyConfig, ProviderProxyMode, ProviderProxyPolicy, ProxiedOAuthConfig, ProviderProxyProvider, ProviderProxySessionAffinity, ProviderPublicConnectionMode, ProviderPublicProfile, ProviderReviewed, ProviderResolvedFile, ProviderResolverConfig, ProviderResolverVendor, ProviderRuntimeTarget, ProviderRuntimeState, ProviderSecretDeclaration, ProviderStealthConfig, ProviderStateDurationString, ProviderStateNamespace, ProviderStreamEvent, ProviderSttConfig, ProviderSttMode, ProviderSupportLevel, RequestOptions, RedirectRunReason, ResolverContext, Rfc3339Instant, SchemaLike, SmsOrigin, SmsOtpExtractionPattern, SmsOtpMatcherDefinition, SseMessage, StandardSchemaV1, StateCasResult, StateNamespaceOptions, StateNamespaceScope, StateValue, StateWriteOptions, StealthClient, StealthBrowser, StealthChallengeClassification, StealthCookieStore, StealthCookieStoreV1, StealthFetchOptions, StealthPlatform, StealthProfile, StealthProfileDescriptor, StealthProfileSelection, StealthOS, StealthRedirectHop, StealthRedirectRunOptions, StealthRedirectRunResult, StealthResponse, StealthSession, StealthSessionCookies, SttAudioInput, SttContext, SttPromptPolicy, SttSegment, SttTranscribeMode, SttTranscribeRequest, SttTranscript, SttUnsupportedOptionPolicy, SttUsage, SttVerificationCodeOptions, SttWarning, TraceConfig, TraceSpan, VerificationCodeCandidate, VerificationCodeCandidateSource, VerificationCodeExtractionResult, } from "./types.js";
54
55
  export { DEFAULT_OPERATION_TRANSPORT, HttpRetryAfterPolicy, HttpRetryDelayStrategy, HttpRetryJitter, HttpRetryPreset, HttpRetryUnsafeMethodPolicy, PROBE_INTERVALS, STREAM_CHUNK_BYTES_MAX, STREAM_CHUNK_BYTES_MIN, STREAM_HEARTBEAT_MS_MAX, STREAM_HEARTBEAT_MS_MIN, STREAM_IDLE_TIMEOUT_MS_MAX, STREAM_IDLE_TIMEOUT_MS_MIN, STREAM_MAX_DURATION_MS_MAX, STREAM_MAX_DURATION_MS_MIN, } from "./types.js";
55
56
  export * from "./utils/date.js";
56
57
  export * from "./utils/parse.js";
57
58
  export * from "./utils/text.js";
58
59
  export * from "./utils/transform.js";
60
+ export { HttpTelemetryCollector, type HttpTelemetrySink, type HttpTelemetryRequestSink, type HttpAttemptTelemetryEvent, type HttpAttemptSample, type HttpTelemetryErrorCode, type HttpTelemetryRetryPayload, type HttpTelemetryLogPayload, type HttpTelemetryHeaderPayload, } from "./runtime/http-telemetry.js";
61
+ export { NativeTelemetryCollector, type NativeAttemptSample, type NativeConnectTelemetryEvent, type NativeLifecycleTelemetryEvent, type NativeTelemetryDiagnostics, type NativeTelemetryErrorCode, type NativeTelemetryHeaderPayload, type NativeTelemetryKind, type NativeTelemetryLifecycleKind, type NativeTelemetryLogPayload, type NativeTelemetryOutcome, type NativeTelemetrySink, type NativeTelemetryVendorSkipReason, type NativeVendorSkipTelemetryEvent, } from "./runtime/native-telemetry.js";
package/dist/index.js CHANGED
@@ -1,7 +1,6 @@
1
1
  // @apifuse/provider-sdk
2
2
  export * from "./auth.js";
3
3
  export * from "./ceremonies/index.js";
4
- export * from "./choice-token.js";
5
4
  export { defineConfig, loadApiFuseConfig, resolveProxy } from "./config/loader.js";
6
5
  export { canonicalJson, digestProviderContract, extractProviderContract, PROVIDER_CONTRACT_SCHEMA_VERSION, } from "./contract.js";
7
6
  export { centered, delayed, defineHealthJourney, defineOperation, defineProvider, defineSmsOtpMatcher, defineStreamOperation, every, } from "./define.js";
@@ -17,7 +16,9 @@ export * from "./recipes/gov-api.js";
17
16
  export * from "./recipes/rest-api.js";
18
17
  export { createFlowContext, createScratchpad } from "./runtime/auth-flow.js";
19
18
  export { APIFUSE__CACHE__KEY_PEPPER_ENV, createBypassProviderCache, createProviderCache, } from "./runtime/cache.js";
20
- export { createProviderChoiceContext, createTestProviderChoiceContext, PROVIDER_RUNTIME_CHOICE_TOKEN_MASTER_SECRET_ENV, } from "./runtime/choice.js";
19
+ export * from "./handle.js";
20
+ export { APIFUSE_HANDLE_META_KEY, HANDLE_KIND_NAME_PATTERN, handleFieldDescription, isHandleFieldMeta, } from "./handle-meta.js";
21
+ export { createHandleContext, createTestHandleContext, normalizeHandle, } from "./runtime/handle.js";
21
22
  export { createCredentialContext, } from "./runtime/credential.js";
22
23
  export { createEnvContext } from "./runtime/env.js";
23
24
  export { executeOperation } from "./runtime/executor.js";
@@ -32,7 +33,7 @@ export { ResolverTelemetryCollector, } from "./runtime/resolver-telemetry.js";
32
33
  export { APIFUSE__CDP_POOL__URL, APIFUSE__RESOLVER__2CAPTCHA__API_KEY, APIFUSE__RESOLVER__CAPMONSTER__API_KEY, APIFUSE__RESOLVER__CAPSOLVER__API_KEY, APIFUSE__RESOLVER__HYPERSOLUTIONS__API_KEY, APIFUSE__RESOLVER__TIMEOUT_MS, DEFAULT_RESOLVER_TIMEOUT_MS, } from "./runtime/resolver-config.js";
33
34
  export { createUnsupportedResolverClient } from "./runtime/resolver-shared.js";
34
35
  export { assertRequiredSecretsPresent, listMissingRequiredSecrets, MISSING_SECRET_CODE, } from "./runtime/secrets.js";
35
- export { createUnsupportedProviderRuntimeState, UnsupportedProviderStateError, } from "./runtime/state.js";
36
+ export { createMemoryProviderRuntimeState, createUnsupportedProviderRuntimeState, UnsupportedProviderStateError, } from "./runtime/state.js";
36
37
  export { APIFUSE__OCR__API_KEY_ENV, APIFUSE__OCR__BACKEND_ENV, APIFUSE__OCR__BASE_URL_ENV, APIFUSE__OCR__CLOUDFLARE_API_TOKEN_ENV, APIFUSE__OCR__MODEL_ENV, CLOUDFLARE_ACCOUNT_ID_ENV, CLOUDFLARE_WORKERS_AI_OCR_BACKEND, createCloudflareWorkersAiOcrClient, createOcrClientFromEnv, createOpenAiCompatibleOcrClient, createUnsupportedOcrClient, DEFAULT_CLOUDFLARE_WORKERS_AI_OCR_MODEL, extractCaptchaCandidates, OPENAI_COMPATIBLE_OCR_BACKEND, } from "./runtime/ocr.js";
37
38
  export { APIFUSE__STT__BACKEND_ENV, APIFUSE__STT__CLOUDFLARE_API_TOKEN_ENV, APIFUSE__STT__MODEL_ENV, createSttClientFromEnv, createUnsupportedSttClient, extractVerificationCode, resolveSttPrompt, } from "./runtime/stt.js";
38
39
  export { createTraceContext, } from "./runtime/trace.js";
@@ -45,3 +46,5 @@ export * from "./utils/date.js";
45
46
  export * from "./utils/parse.js";
46
47
  export * from "./utils/text.js";
47
48
  export * from "./utils/transform.js";
49
+ export { HttpTelemetryCollector, } from "./runtime/http-telemetry.js";
50
+ export { NativeTelemetryCollector, } from "./runtime/native-telemetry.js";
package/dist/lint.d.ts CHANGED
@@ -80,6 +80,9 @@ export declare function lintProvider(provider: {
80
80
  contract?: ProviderContractMetaLike;
81
81
  };
82
82
  reviewed?: string;
83
+ /** Declared handle kinds (ADR-0012); read structurally, see readHandleKindDeclarations. */
84
+ handle?: unknown;
85
+ state?: unknown;
83
86
  }, options?: ProviderLintOptions): LintDiagnostic[];
84
87
  /** Internal detailed result used by the CLI to render suppression audits. */
85
88
  export declare function lintProviderWithInformation(provider: Parameters<typeof lintProvider>[0], options?: ProviderLintOptions): ProviderLintResult;