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

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 (73) hide show
  1. package/AUTHORING.md +17 -16
  2. package/CHANGELOG.md +4 -0
  3. package/bin/apifuse-dev.ts +5 -7
  4. package/bin/apifuse-pack-types.ts +22 -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 +39 -0
  17. package/dist/handle-meta.js +29 -0
  18. package/dist/handle.d.ts +187 -0
  19. package/dist/handle.js +254 -0
  20. package/dist/i18n/catalog.js +21 -1
  21. package/dist/index.d.ts +4 -3
  22. package/dist/index.js +3 -2
  23. package/dist/lint.d.ts +3 -0
  24. package/dist/lint.js +352 -47
  25. package/dist/provider.d.ts +3 -3
  26. package/dist/provider.js +2 -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 +895 -0
  31. package/dist/runtime/native-network.d.ts +10 -1
  32. package/dist/runtime/native-network.js +230 -29
  33. package/dist/runtime/native-telemetry.d.ts +142 -0
  34. package/dist/runtime/native-telemetry.js +231 -0
  35. package/dist/runtime/state.d.ts +4 -1
  36. package/dist/runtime/state.js +32 -17
  37. package/dist/server/index.d.ts +1 -0
  38. package/dist/server/index.js +1 -0
  39. package/dist/server/sensitive-values.d.ts +1 -1
  40. package/dist/server/sensitive-values.js +0 -3
  41. package/dist/server/serve-implementation.d.ts +4 -11
  42. package/dist/server/serve-implementation.js +86 -18
  43. package/dist/testing/run.js +10 -7
  44. package/dist/types.d.ts +4 -107
  45. package/package.json +1 -1
  46. package/src/define.ts +4 -3
  47. package/src/dev.ts +3 -1
  48. package/src/engine.ts +5 -6
  49. package/src/error-resolution.ts +21 -4
  50. package/src/errors.ts +13 -0
  51. package/src/handle-meta.ts +58 -0
  52. package/src/handle.ts +529 -0
  53. package/src/i18n/catalog.ts +23 -1
  54. package/src/index.ts +26 -13
  55. package/src/lint.ts +414 -55
  56. package/src/provider.ts +9 -20
  57. package/src/runtime/{choice-wordlist.ts → handle-wordlist.ts} +130 -9
  58. package/src/runtime/handle.ts +1162 -0
  59. package/src/runtime/native-network.ts +281 -33
  60. package/src/runtime/native-telemetry.ts +366 -0
  61. package/src/runtime/state.ts +44 -16
  62. package/src/server/index.ts +17 -0
  63. package/src/server/sensitive-values.ts +0 -3
  64. package/src/server/serve-implementation.ts +87 -32
  65. package/src/testing/run.ts +11 -7
  66. package/src/types.ts +4 -137
  67. package/dist/choice-token.d.ts +0 -24
  68. package/dist/choice-token.js +0 -74
  69. package/dist/runtime/choice-wordlist.d.ts +0 -9
  70. package/dist/runtime/choice.d.ts +0 -27
  71. package/dist/runtime/choice.js +0 -801
  72. package/src/choice-token.ts +0 -165
  73. package/src/runtime/choice.ts +0 -1197
@@ -0,0 +1,187 @@
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 HandleKindDeclaration, type HandleKindType } from "./handle-meta.js";
13
+ import type { ProviderStateDurationString } from "./types.js";
14
+ export type { HandleAccess, HandleFieldMeta, 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
+ readonly access: "bound";
45
+ readonly ttl: {
46
+ readonly idle: ProviderStateDurationString;
47
+ readonly max: ProviderStateDurationString;
48
+ };
49
+ readonly idleTtlMs: number;
50
+ readonly maxTtlMs: number;
51
+ readonly resultTtl: ProviderStateDurationString;
52
+ readonly resultTtlMs: number;
53
+ /** Optional schema describing the commit result; type-level only at runtime. */
54
+ readonly result: TResultSchema | undefined;
55
+ readonly wordCount: 2;
56
+ }
57
+ export type HandleKind = CursorKind<any> | DraftKind<any, any>;
58
+ /** Stored record data type (schema output); what `read`, `update`, and `commit` callbacks receive. */
59
+ export type DataOf<K extends HandleKind> = z.output<K["schema"]>;
60
+ /** What `create` and `update` accept (schema input); differs from `DataOf` when the schema transforms or defaults. */
61
+ export type InputOf<K extends HandleKind> = z.input<K["schema"]>;
62
+ export type ResultOf<K extends HandleKind> = K extends DraftKind<any, infer R> ? (R extends ZodType ? z.output<R> : unknown) : never;
63
+ export type HandleStatus = "active" | "committing" | "committed";
64
+ export interface HandleRecord<K extends HandleKind> {
65
+ /** Canonical handle string (`<kind>_<word>-<word>...`). */
66
+ readonly handle: string;
67
+ readonly kind: string;
68
+ readonly status: HandleStatus;
69
+ readonly data: DataOf<K>;
70
+ readonly result?: ResultOf<K>;
71
+ readonly createdAt: string;
72
+ readonly expiresAt: string;
73
+ }
74
+ export interface HandleCommitResult<K extends HandleKind> {
75
+ readonly status: "committed" | "replayed";
76
+ readonly handle: string;
77
+ readonly result: ResultOf<K>;
78
+ }
79
+ export interface HandleContext {
80
+ /** Validates `data` with `kind.schema`, stores it, and returns the canonical handle. */
81
+ create<K extends HandleKind>(kind: K, data: InputOf<K>): Promise<string>;
82
+ /** Tolerantly parses `handle`, loads the record; drafts get their idle TTL touched. */
83
+ read<K extends HandleKind>(kind: K, handle: string): Promise<HandleRecord<K>>;
84
+ /** CAS update of an active draft (3 retries) with sliding TTL. */
85
+ update<K extends DraftKind>(kind: K, handle: string, updater: (data: DataOf<K>) => InputOf<K> | Promise<InputOf<K>>): Promise<HandleRecord<K>>;
86
+ /** One-shot commit with result replay; see runtime docs for the state machine. */
87
+ commit<K extends DraftKind>(kind: K, handle: string, work: (data: DataOf<K>) => Promise<ResultOf<K>>): Promise<HandleCommitResult<K>>;
88
+ /** Deletes the record; idempotent. */
89
+ discard<K extends HandleKind>(kind: K, handle: string): Promise<void>;
90
+ }
91
+ export type HandleOperation = "create" | "read" | "update" | "commit" | "discard";
92
+ export type HandleTelemetryOutcome = "success" | "not_found" | "expired" | "invalid" | "kind_mismatch" | "busy" | "replayed" | "error";
93
+ /** Allowlisted metadata only; handle values, data, and results are never included. */
94
+ export interface HandleTelemetryEvent {
95
+ readonly providerId: string;
96
+ readonly kind: string;
97
+ readonly type: HandleKindType;
98
+ readonly operation: HandleOperation;
99
+ readonly outcome: HandleTelemetryOutcome;
100
+ /** `"none"` or the sorted normalization classes joined by `+`. */
101
+ readonly normalization: string;
102
+ readonly words: number;
103
+ }
104
+ 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";
105
+ export type HandleErrorOptions = Omit<ProviderErrorOptions, "code"> & {
106
+ /** Kind name the error relates to, when known. */
107
+ readonly kind?: string;
108
+ };
109
+ export declare class HandleError extends ProviderError {
110
+ readonly handleCode: HandleErrorCode;
111
+ readonly kind?: string;
112
+ constructor(code: HandleErrorCode, message: string, options?: HandleErrorOptions);
113
+ get code(): HandleErrorCode;
114
+ }
115
+ /**
116
+ * Recognizes handle errors across duplicate SDK module copies (packaged CLI
117
+ * `src/*` runtime vs provider `dist/*` import), where `instanceof` splits.
118
+ */
119
+ export declare function isHandleError(value: unknown): value is HandleError;
120
+ /**
121
+ * Standard recovery sentence appended to every handle error message so the LLM
122
+ * knows the next action without provider-specific wording.
123
+ */
124
+ export declare function handleRecoverySentence(kind: {
125
+ readonly fieldName: string;
126
+ readonly issuedBy?: string;
127
+ }): string;
128
+ /** Parses a `ProviderStateDurationString` to milliseconds; throws on invalid or non-positive input. */
129
+ export declare function parseHandleDurationMs(value: ProviderStateDurationString, label: string): number;
130
+ export interface DefineCursorOptions<TSchema extends ZodType> {
131
+ /** Kind name, `/^[a-z]{2,12}$/`; becomes the handle prefix. */
132
+ readonly name: string;
133
+ /** Schema property key carrying the handle. Default `${name}_token`. */
134
+ readonly fieldName?: string;
135
+ readonly schema: TSchema;
136
+ readonly ttl: ProviderStateDurationString;
137
+ /** `"bound"` (default): connection-scoped, 2 words. `"public"`: provider-scoped, 4-5 words. */
138
+ readonly access?: HandleAccess;
139
+ /** Required when public. Bound default 200 per connection. */
140
+ readonly maxEntries?: number;
141
+ /** Default 16,000. */
142
+ readonly maxValueBytes?: number;
143
+ /** Public only; `"high"` forces 5 words. Auto-high when ttl > 1h. */
144
+ readonly strength?: HandleStrength;
145
+ /** Operation key that issues this handle; used in error text and lint. */
146
+ readonly issuedBy?: string;
147
+ }
148
+ export interface DefineDraftOptions<TSchema extends ZodType, TResultSchema extends ZodType | undefined> {
149
+ readonly name: string;
150
+ readonly fieldName?: string;
151
+ readonly schema: TSchema;
152
+ /** Optional schema of the commit result (type-level). */
153
+ readonly result?: TResultSchema;
154
+ readonly ttl: {
155
+ readonly idle: ProviderStateDurationString;
156
+ readonly max: ProviderStateDurationString;
157
+ };
158
+ /** How long a committed record stays for replay. Default "24h". */
159
+ readonly resultTtl?: ProviderStateDurationString;
160
+ /** Default 200 per connection. */
161
+ readonly maxEntries?: number;
162
+ /** Default 64,000. */
163
+ readonly maxValueBytes?: number;
164
+ readonly issuedBy?: string;
165
+ }
166
+ /** Defines an immutable cursor kind (pagination, offered option lists). */
167
+ export declare function defineCursor<TSchema extends ZodType>(options: DefineCursorOptions<TSchema>): CursorKind<TSchema>;
168
+ /** Defines a mutable, always-bound draft kind (multi-turn forms with one-shot commit). */
169
+ export declare function defineDraft<TSchema extends ZodType, TResultSchema extends ZodType | undefined = undefined>(options: DefineDraftOptions<TSchema, TResultSchema>): DraftKind<TSchema, TResultSchema>;
170
+ export declare function isDraftKind(kind: HandleKind): kind is DraftKind<any, any>;
171
+ export declare function isCursorKind(kind: HandleKind): kind is CursorKind<any>;
172
+ export interface PickOptions<T> {
173
+ /** Input field name, used in the error message. */
174
+ readonly field: string;
175
+ /** Item property compared against `value`. Default = `field`. */
176
+ readonly by?: keyof T & string;
177
+ /** Operation that listed the items; used in the error message when known. */
178
+ readonly issuedBy?: string;
179
+ }
180
+ /**
181
+ * Chooses one offered item by a plain value the LLM copied from the offer.
182
+ * Exact match first, then a unique case-insensitive trimmed match; otherwise
183
+ * `PICK_NOT_OFFERED` with the allowed values so the LLM can self-correct. The
184
+ * server holds the offer, so a fabricated value fails here instead of reaching
185
+ * upstream. This is the "one handle per offer + plain picks" half of ADR-0012.
186
+ */
187
+ 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,254 @@
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, handleFieldDescription, HANDLE_KIND_NAME_PATTERN, } 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 cursors whose 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
+ if (kind.issuedBy) {
67
+ return `Call \`${kind.issuedBy}\` again and pass the new \`${kind.fieldName}\` exactly as returned.`;
68
+ }
69
+ return `Request a new \`${kind.fieldName}\` and pass it exactly as returned.`;
70
+ }
71
+ // ---------------------------------------------------------------------------
72
+ // Durations
73
+ // ---------------------------------------------------------------------------
74
+ const SHORT_DURATION_PATTERN = /^(\d+)(ms|s|m|h|d)$/;
75
+ const ISO_DURATION_PATTERN = /^PT(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?$/;
76
+ /** Parses a `ProviderStateDurationString` to milliseconds; throws on invalid or non-positive input. */
77
+ export function parseHandleDurationMs(value, label) {
78
+ const short = SHORT_DURATION_PATTERN.exec(value);
79
+ let ms;
80
+ if (short) {
81
+ const amount = Number(short[1]);
82
+ const unit = short[2];
83
+ const multiplier = unit === "ms"
84
+ ? 1
85
+ : unit === "s"
86
+ ? 1_000
87
+ : unit === "m"
88
+ ? 60_000
89
+ : unit === "h"
90
+ ? 3_600_000
91
+ : 86_400_000;
92
+ ms = amount * multiplier;
93
+ }
94
+ else {
95
+ const iso = ISO_DURATION_PATTERN.exec(value);
96
+ if (iso && (iso[1] !== undefined || iso[2] !== undefined || iso[3] !== undefined)) {
97
+ ms =
98
+ Number(iso[1] ?? 0) * 3_600_000 +
99
+ Number(iso[2] ?? 0) * 60_000 +
100
+ Number(iso[3] ?? 0) * 1_000;
101
+ }
102
+ }
103
+ if (ms === undefined || !Number.isFinite(ms) || ms <= 0) {
104
+ throw new Error(`Handle kind ${label} must be a positive duration such as "10m", "2h", or "PT30M" (received ${JSON.stringify(value)}).`);
105
+ }
106
+ return Math.floor(ms);
107
+ }
108
+ function assertKindName(name, define) {
109
+ if (typeof name !== "string" || !HANDLE_KIND_NAME_PATTERN.test(name)) {
110
+ 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)}.`);
111
+ }
112
+ }
113
+ function assertFieldName(fieldName, define) {
114
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(fieldName)) {
115
+ throw new Error(`${define}: fieldName must be a plain identifier usable as a schema property key; received ${JSON.stringify(fieldName)}.`);
116
+ }
117
+ }
118
+ function assertPositiveInteger(value, label, define) {
119
+ if (!Number.isInteger(value) || value <= 0) {
120
+ throw new Error(`${define}: ${label} must be a positive integer; received ${String(value)}.`);
121
+ }
122
+ }
123
+ function createHandleField(meta) {
124
+ const described = z.string().min(1).describe(handleFieldDescription(meta));
125
+ // zod v4 `.meta()` replaces the registry entry, so carry the description over.
126
+ const existing = described.meta() ?? {};
127
+ return described.meta({ ...existing, [APIFUSE_HANDLE_META_KEY]: meta });
128
+ }
129
+ /** Defines an immutable cursor kind (pagination, offered option lists). */
130
+ export function defineCursor(options) {
131
+ const define = "defineCursor";
132
+ assertKindName(options.name, define);
133
+ const fieldName = options.fieldName ?? `${options.name}_token`;
134
+ assertFieldName(fieldName, define);
135
+ const access = options.access ?? "bound";
136
+ if (access !== "bound" && access !== "public") {
137
+ throw new Error(`${define}: access must be "bound" or "public"; received ${String(access)}.`);
138
+ }
139
+ const ttlMs = parseHandleDurationMs(options.ttl, `"${options.name}" ttl`);
140
+ const strength = options.strength ?? "standard";
141
+ if (strength !== "standard" && strength !== "high") {
142
+ throw new Error(`${define}: strength must be "standard" or "high"; received ${String(strength)}.`);
143
+ }
144
+ if (access === "public" && options.maxEntries === undefined) {
145
+ throw new Error(`${define}: public cursor "${options.name}" must declare maxEntries (provider-wide live-entry quota).`);
146
+ }
147
+ const maxEntries = options.maxEntries ?? DEFAULT_BOUND_MAX_ENTRIES;
148
+ assertPositiveInteger(maxEntries, "maxEntries", define);
149
+ const maxValueBytes = options.maxValueBytes ?? DEFAULT_CURSOR_MAX_VALUE_BYTES;
150
+ assertPositiveInteger(maxValueBytes, "maxValueBytes", define);
151
+ const wordCount = access === "bound"
152
+ ? BOUND_HANDLE_WORD_COUNT
153
+ : strength === "high" || ttlMs > AUTO_HIGH_TTL_MS
154
+ ? HIGH_PUBLIC_HANDLE_WORD_COUNT
155
+ : PUBLIC_HANDLE_WORD_COUNT;
156
+ const meta = {
157
+ kind: options.name,
158
+ type: "cursor",
159
+ fieldName,
160
+ ...(options.issuedBy ? { issuedBy: options.issuedBy } : {}),
161
+ };
162
+ return Object.freeze({
163
+ name: options.name,
164
+ type: "cursor",
165
+ fieldName,
166
+ access,
167
+ issuedBy: options.issuedBy,
168
+ schema: options.schema,
169
+ ttl: options.ttl,
170
+ ttlMs,
171
+ strength,
172
+ maxEntries,
173
+ maxValueBytes,
174
+ wordCount,
175
+ field: () => createHandleField(meta),
176
+ });
177
+ }
178
+ /** Defines a mutable, always-bound draft kind (multi-turn forms with one-shot commit). */
179
+ export function defineDraft(options) {
180
+ const define = "defineDraft";
181
+ assertKindName(options.name, define);
182
+ const fieldName = options.fieldName ?? `${options.name}_token`;
183
+ assertFieldName(fieldName, define);
184
+ if (!options.ttl || typeof options.ttl !== "object") {
185
+ throw new Error(`${define}: draft "${options.name}" ttl must be { idle, max }.`);
186
+ }
187
+ const idleTtlMs = parseHandleDurationMs(options.ttl.idle, `"${options.name}" ttl.idle`);
188
+ const maxTtlMs = parseHandleDurationMs(options.ttl.max, `"${options.name}" ttl.max`);
189
+ if (idleTtlMs > maxTtlMs) {
190
+ throw new Error(`${define}: draft "${options.name}" ttl.idle (${idleTtlMs}ms) must not exceed ttl.max (${maxTtlMs}ms).`);
191
+ }
192
+ const resultTtl = options.resultTtl ?? DEFAULT_RESULT_TTL;
193
+ const resultTtlMs = parseHandleDurationMs(resultTtl, `"${options.name}" resultTtl`);
194
+ const maxEntries = options.maxEntries ?? DEFAULT_BOUND_MAX_ENTRIES;
195
+ assertPositiveInteger(maxEntries, "maxEntries", define);
196
+ const maxValueBytes = options.maxValueBytes ?? DEFAULT_DRAFT_MAX_VALUE_BYTES;
197
+ assertPositiveInteger(maxValueBytes, "maxValueBytes", define);
198
+ const meta = {
199
+ kind: options.name,
200
+ type: "draft",
201
+ fieldName,
202
+ ...(options.issuedBy ? { issuedBy: options.issuedBy } : {}),
203
+ };
204
+ return Object.freeze({
205
+ name: options.name,
206
+ type: "draft",
207
+ fieldName,
208
+ access: "bound",
209
+ issuedBy: options.issuedBy,
210
+ schema: options.schema,
211
+ result: options.result,
212
+ ttl: options.ttl,
213
+ idleTtlMs,
214
+ maxTtlMs,
215
+ resultTtl,
216
+ resultTtlMs,
217
+ maxEntries,
218
+ maxValueBytes,
219
+ wordCount: BOUND_HANDLE_WORD_COUNT,
220
+ field: () => createHandleField(meta),
221
+ });
222
+ }
223
+ export function isDraftKind(kind) {
224
+ return kind.type === "draft";
225
+ }
226
+ export function isCursorKind(kind) {
227
+ return kind.type === "cursor";
228
+ }
229
+ /**
230
+ * Chooses one offered item by a plain value the LLM copied from the offer.
231
+ * Exact match first, then a unique case-insensitive trimmed match; otherwise
232
+ * `PICK_NOT_OFFERED` with the allowed values so the LLM can self-correct. The
233
+ * server holds the offer, so a fabricated value fails here instead of reaching
234
+ * upstream. This is the "one handle per offer + plain picks" half of ADR-0012.
235
+ */
236
+ export function pick(items, value, options) {
237
+ const by = options.by ?? options.field;
238
+ const keyOf = (item) => {
239
+ const raw = item[by];
240
+ return typeof raw === "string" ? raw : String(raw);
241
+ };
242
+ const exact = items.find((item) => keyOf(item) === value);
243
+ if (exact)
244
+ return exact;
245
+ const folded = value.trim().toLowerCase();
246
+ const loose = items.filter((item) => keyOf(item).trim().toLowerCase() === folded);
247
+ if (loose.length === 1)
248
+ return loose[0];
249
+ const allowed = items.map(keyOf);
250
+ const listed = options.issuedBy
251
+ ? ` Use the values exactly as listed by \`${options.issuedBy}\`.`
252
+ : " Use the values exactly as listed.";
253
+ throw new HandleError("PICK_NOT_OFFERED", `\`${options.field}\` must be one of: ${allowed.join(", ")}.${listed}`, { details: { field: options.field, allowed } });
254
+ }
@@ -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,8 @@ 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 { type CreateHandleContextOptions, type CreateTestHandleContextOptions, createHandleContext, createTestHandleContext, type HandleNormalizationClass, type NormalizedHandle, normalizeHandle, } from "./runtime/handle.js";
24
24
  export { type CreateCredentialContextOptions, createCredentialContext, } from "./runtime/credential.js";
25
25
  export { createEnvContext } from "./runtime/env.js";
26
26
  export { executeOperation } from "./runtime/executor.js";
@@ -50,9 +50,10 @@ export { APIFUSE_CONTENT_PROVENANCE_META_KEY, APIFUSE_CONTENT_TRUST_META_KEY, AP
50
50
  export { createServerApp, createServerAppAsync, ERROR_OBSERVABILITY_HEADER, type ProviderErrorCauseFrame, type ServeOptions, serve, } from "./server/serve.js";
51
51
  export { DEFAULT_STEALTH_BROWSER, DEFAULT_STEALTH_OS, getStealthProfile, listStealthProfiles, } from "./stealth/profiles.js";
52
52
  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";
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, 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
54
  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
55
  export * from "./utils/date.js";
56
56
  export * from "./utils/parse.js";
57
57
  export * from "./utils/text.js";
58
58
  export * from "./utils/transform.js";
59
+ 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,8 @@ 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 { createHandleContext, createTestHandleContext, normalizeHandle, } from "./runtime/handle.js";
21
21
  export { createCredentialContext, } from "./runtime/credential.js";
22
22
  export { createEnvContext } from "./runtime/env.js";
23
23
  export { executeOperation } from "./runtime/executor.js";
@@ -45,3 +45,4 @@ export * from "./utils/date.js";
45
45
  export * from "./utils/parse.js";
46
46
  export * from "./utils/text.js";
47
47
  export * from "./utils/transform.js";
48
+ 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;