@apifuse/provider-sdk 2.2.0-beta.59 → 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 (124) hide show
  1. package/AUTHORING.md +33 -16
  2. package/CHANGELOG.md +8 -0
  3. package/bin/apifuse-dev.ts +7 -8
  4. package/bin/apifuse-pack-types.ts +22 -0
  5. package/bin/apifuse-perf.ts +45 -10
  6. package/bin/apifuse-record.ts +6 -8
  7. package/bin/apifuse-submit-check.ts +2 -2
  8. package/dist/config/loader.js +13 -12
  9. package/dist/define.d.ts +3 -2
  10. package/dist/define.js +1 -1
  11. package/dist/dev.js +3 -1
  12. package/dist/engine.d.ts +7 -6
  13. package/dist/engine.js +6 -6
  14. package/dist/error-resolution.js +21 -4
  15. package/dist/errors.d.ts +3 -0
  16. package/dist/errors.js +9 -0
  17. package/dist/handle-meta.d.ts +39 -0
  18. package/dist/handle-meta.js +29 -0
  19. package/dist/handle.d.ts +187 -0
  20. package/dist/handle.js +254 -0
  21. package/dist/i18n/catalog.js +21 -1
  22. package/dist/index.d.ts +6 -4
  23. package/dist/index.js +4 -3
  24. package/dist/lint.d.ts +3 -0
  25. package/dist/lint.js +388 -62
  26. package/dist/provider.d.ts +4 -4
  27. package/dist/provider.js +3 -3
  28. package/dist/runtime/browser.js +2 -1
  29. package/dist/runtime/cache.js +3 -2
  30. package/dist/runtime/diagnostic-env-values.d.ts +5 -0
  31. package/dist/runtime/diagnostic-env-values.js +57 -0
  32. package/dist/runtime/diagnostic-env.d.ts +11 -0
  33. package/dist/runtime/diagnostic-env.js +35 -0
  34. package/dist/runtime/diagnostic-redactor.d.ts +49 -0
  35. package/dist/runtime/diagnostic-redactor.js +569 -0
  36. package/dist/runtime/egress-lease.d.ts +2 -0
  37. package/dist/runtime/egress-lease.js +4 -1
  38. package/dist/runtime/env.js +2 -1
  39. package/dist/runtime/handle-wordlist.d.ts +43 -0
  40. package/dist/runtime/{choice-wordlist.js → handle-wordlist.js} +127 -9
  41. package/dist/runtime/handle.d.ts +71 -0
  42. package/dist/runtime/handle.js +895 -0
  43. package/dist/runtime/instrumentation.js +3 -0
  44. package/dist/runtime/native-network.d.ts +10 -1
  45. package/dist/runtime/native-network.js +230 -29
  46. package/dist/runtime/native-telemetry.d.ts +142 -0
  47. package/dist/runtime/native-telemetry.js +231 -0
  48. package/dist/runtime/ocr.js +2 -1
  49. package/dist/runtime/otlp.js +5 -4
  50. package/dist/runtime/proxy-nodemaven.js +3 -2
  51. package/dist/runtime/request-options.d.ts +7 -0
  52. package/dist/runtime/request-options.js +62 -22
  53. package/dist/runtime/resolver-vendors/browser.js +0 -1
  54. package/dist/runtime/resolver.js +3 -2
  55. package/dist/runtime/state.d.ts +4 -1
  56. package/dist/runtime/state.js +32 -17
  57. package/dist/runtime/stt.js +3 -2
  58. package/dist/runtime/trace.d.ts +5 -0
  59. package/dist/runtime/trace.js +115 -20
  60. package/dist/schema.d.ts +11 -0
  61. package/dist/schema.js +56 -2
  62. package/dist/server/index.d.ts +1 -0
  63. package/dist/server/index.js +1 -0
  64. package/dist/server/self-test-redaction.js +8 -33
  65. package/dist/server/sensitive-values.d.ts +26 -0
  66. package/dist/server/sensitive-values.js +128 -0
  67. package/dist/server/serve-implementation.d.ts +4 -11
  68. package/dist/server/serve-implementation.js +305 -96
  69. package/dist/server/trace-output.d.ts +2 -1
  70. package/dist/server/trace-output.js +46 -14
  71. package/dist/testing/run.js +10 -7
  72. package/dist/trace-sanitization.d.ts +4 -3
  73. package/dist/trace-sanitization.js +45 -22
  74. package/dist/types.d.ts +4 -107
  75. package/package.json +2 -1
  76. package/src/config/loader.ts +13 -12
  77. package/src/define.ts +4 -3
  78. package/src/dev.ts +3 -1
  79. package/src/engine.ts +8 -8
  80. package/src/error-resolution.ts +21 -4
  81. package/src/errors.ts +13 -0
  82. package/src/handle-meta.ts +58 -0
  83. package/src/handle.ts +529 -0
  84. package/src/i18n/catalog.ts +23 -1
  85. package/src/index.ts +28 -13
  86. package/src/lint.ts +456 -71
  87. package/src/provider.ts +10 -20
  88. package/src/runtime/browser.ts +2 -1
  89. package/src/runtime/cache.ts +3 -2
  90. package/src/runtime/diagnostic-env-values.ts +56 -0
  91. package/src/runtime/diagnostic-env.ts +55 -0
  92. package/src/runtime/diagnostic-redactor.ts +662 -0
  93. package/src/runtime/egress-lease.ts +6 -1
  94. package/src/runtime/env.ts +2 -1
  95. package/src/runtime/{choice-wordlist.ts → handle-wordlist.ts} +130 -9
  96. package/src/runtime/handle.ts +1162 -0
  97. package/src/runtime/instrumentation.ts +3 -0
  98. package/src/runtime/native-network.ts +281 -33
  99. package/src/runtime/native-telemetry.ts +366 -0
  100. package/src/runtime/ocr.ts +2 -1
  101. package/src/runtime/otlp.ts +5 -4
  102. package/src/runtime/proxy-nodemaven.ts +3 -2
  103. package/src/runtime/request-options.ts +76 -28
  104. package/src/runtime/resolver-vendors/browser.ts +0 -1
  105. package/src/runtime/resolver.ts +3 -2
  106. package/src/runtime/state.ts +44 -16
  107. package/src/runtime/stt.ts +3 -2
  108. package/src/runtime/trace.ts +168 -26
  109. package/src/schema.ts +63 -2
  110. package/src/server/index.ts +17 -0
  111. package/src/server/self-test-redaction.ts +10 -40
  112. package/src/server/sensitive-values.ts +197 -0
  113. package/src/server/serve-implementation.ts +388 -128
  114. package/src/server/trace-output.ts +77 -17
  115. package/src/testing/run.ts +11 -7
  116. package/src/trace-sanitization.ts +70 -23
  117. package/src/types.ts +4 -137
  118. package/dist/choice-token.d.ts +0 -24
  119. package/dist/choice-token.js +0 -74
  120. package/dist/runtime/choice-wordlist.d.ts +0 -9
  121. package/dist/runtime/choice.d.ts +0 -27
  122. package/dist/runtime/choice.js +0 -801
  123. package/src/choice-token.ts +0 -165
  124. package/src/runtime/choice.ts +0 -1197
package/src/errors.ts CHANGED
@@ -12,6 +12,7 @@ const PROVIDER_ERROR_BRAND_VALUE = 1;
12
12
  const SESSION_EXPIRED_BRAND = Symbol.for("@apifuse/provider-sdk/error-kind/session-expired@1");
13
13
  const TRANSPORT_BRAND = Symbol.for("@apifuse/provider-sdk/error-kind/transport@1");
14
14
  const VALIDATION_BRAND = Symbol.for("@apifuse/provider-sdk/error-kind/validation@1");
15
+ const HANDLE_BRAND = Symbol.for("@apifuse/provider-sdk/error-kind/handle@1");
15
16
 
16
17
  // Defines a non-enumerable, non-writable, non-configurable own data property.
17
18
  // Immutable + own means a guard can trust it via a single descriptor read
@@ -208,6 +209,18 @@ export function isTransportError(value: unknown): value is TransportError {
208
209
  return isProviderError(value) && hasOwnBrand(value, TRANSPORT_BRAND, true);
209
210
  }
210
211
 
212
+ /** Brands a handle error (ADR-0012) so `isHandleError` works across duplicate SDK module copies. */
213
+ export function brandHandleError(target: object): void {
214
+ defineErrorBrand(target, HANDLE_BRAND, true);
215
+ }
216
+
217
+ export function hasHandleErrorBrand(value: unknown): boolean {
218
+ return (
219
+ hasOwnBrand(value, PROVIDER_ERROR_BRAND, PROVIDER_ERROR_BRAND_VALUE) &&
220
+ hasOwnBrand(value, HANDLE_BRAND, true)
221
+ );
222
+ }
223
+
211
224
  export function isValidationError(value: unknown): value is ValidationError {
212
225
  return (
213
226
  isProviderError(value) &&
@@ -0,0 +1,58 @@
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
+ /** Value stored under {@link APIFUSE_HANDLE_META_KEY} on a handle field. */
16
+ export interface HandleFieldMeta {
17
+ readonly kind: string;
18
+ readonly type: HandleKindType;
19
+ readonly fieldName: string;
20
+ readonly issuedBy?: string;
21
+ }
22
+
23
+ /**
24
+ * Structural view of a handle kind as seen by the provider declaration
25
+ * (`handle: [WaitingDraft, PageCursor]`), lint, and the registry. The runtime
26
+ * kinds returned by `defineCursor` / `defineDraft` satisfy this shape.
27
+ */
28
+ export interface HandleKindDeclaration {
29
+ readonly name: string;
30
+ readonly type: HandleKindType;
31
+ readonly fieldName: string;
32
+ readonly access: HandleAccess;
33
+ readonly issuedBy?: string;
34
+ }
35
+
36
+ /** Kind names are lowercase letters only so they never fuse with the word body. */
37
+ export const HANDLE_KIND_NAME_PATTERN = /^[a-z]{2,12}$/;
38
+
39
+ export function isHandleFieldMeta(value: unknown): value is HandleFieldMeta {
40
+ if (typeof value !== "object" || value === null) return false;
41
+ const record = value as Record<string, unknown>;
42
+ return (
43
+ typeof record.kind === "string" &&
44
+ (record.type === "cursor" || record.type === "draft") &&
45
+ typeof record.fieldName === "string" &&
46
+ (record.issuedBy === undefined || typeof record.issuedBy === "string")
47
+ );
48
+ }
49
+
50
+ /**
51
+ * The SDK-owned description `kind.field()` emits. Lint exempts a handle field
52
+ * from `describeKey` only while its description is exactly this text; a
53
+ * provider override re-enters the localization rules.
54
+ */
55
+ export function handleFieldDescription(meta: Pick<HandleFieldMeta, "issuedBy">): string {
56
+ const origin = meta.issuedBy ? ` issued by \`${meta.issuedBy}\`` : "";
57
+ return `Opaque handle${origin}. Copy it exactly as returned; do not edit or shorten it.`;
58
+ }
package/src/handle.ts ADDED
@@ -0,0 +1,529 @@
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
+ handleFieldDescription,
20
+ HANDLE_KIND_NAME_PATTERN,
21
+ type HandleAccess,
22
+ type HandleFieldMeta,
23
+ type HandleKindDeclaration,
24
+ type HandleKindType,
25
+ } from "./handle-meta.js";
26
+ import type { ProviderErrorCategory } from "./observability.js";
27
+ import {
28
+ BOUND_HANDLE_WORD_COUNT,
29
+ HIGH_PUBLIC_HANDLE_WORD_COUNT,
30
+ PUBLIC_HANDLE_WORD_COUNT,
31
+ } from "./runtime/handle-wordlist.js";
32
+ import type { ProviderStateDurationString } from "./types.js";
33
+
34
+ export type { HandleAccess, HandleFieldMeta, HandleKindDeclaration, HandleKindType };
35
+
36
+ /** Public cursors whose ttl exceeds this are issued with five words (auto-high). */
37
+ const AUTO_HIGH_TTL_MS = 3_600_000;
38
+ const DEFAULT_BOUND_MAX_ENTRIES = 200;
39
+ const DEFAULT_CURSOR_MAX_VALUE_BYTES = 16_000;
40
+ const DEFAULT_DRAFT_MAX_VALUE_BYTES = 64_000;
41
+ const DEFAULT_RESULT_TTL: ProviderStateDurationString = "24h";
42
+
43
+ export type HandleStrength = "standard" | "high";
44
+
45
+ /** Words issued per handle: 2 for bound kinds, 4 for public, 5 for high-strength public. */
46
+ export type HandleWordCount = 2 | 4 | 5;
47
+
48
+ export interface HandleKindBase<TSchema extends ZodType = ZodType> extends HandleKindDeclaration {
49
+ /**
50
+ * Zod schema validated on `create`/`update`. Writes accept its *input* type
51
+ * (`InputOf`); stored records and callbacks carry its *output* type (`DataOf`).
52
+ */
53
+ readonly schema: TSchema;
54
+ /** Live-entry quota of the kind's namespace (per connection for bound kinds). */
55
+ readonly maxEntries: number;
56
+ /** Maximum JSON-encoded record size in bytes. */
57
+ readonly maxValueBytes: number;
58
+ /** Number of words the runtime issues for this kind. */
59
+ readonly wordCount: HandleWordCount;
60
+ /**
61
+ * Schema for the handle field, usable in output and input positions. Carries
62
+ * the `x-apifuse-handle` meta and an SDK-owned English description.
63
+ */
64
+ field(): ZodString;
65
+ }
66
+
67
+ export interface CursorKind<TSchema extends ZodType = ZodType> extends HandleKindBase<TSchema> {
68
+ readonly type: "cursor";
69
+ readonly ttl: ProviderStateDurationString;
70
+ readonly ttlMs: number;
71
+ readonly strength: HandleStrength;
72
+ }
73
+
74
+ export interface DraftKind<
75
+ TSchema extends ZodType = ZodType,
76
+ TResultSchema extends ZodType | undefined = ZodType | undefined,
77
+ > extends HandleKindBase<TSchema> {
78
+ readonly type: "draft";
79
+ readonly access: "bound";
80
+ readonly ttl: {
81
+ readonly idle: ProviderStateDurationString;
82
+ readonly max: ProviderStateDurationString;
83
+ };
84
+ readonly idleTtlMs: number;
85
+ readonly maxTtlMs: number;
86
+ readonly resultTtl: ProviderStateDurationString;
87
+ readonly resultTtlMs: number;
88
+ /** Optional schema describing the commit result; type-level only at runtime. */
89
+ readonly result: TResultSchema | undefined;
90
+ readonly wordCount: 2;
91
+ }
92
+
93
+ // `any` here is variance-only: a concrete `CursorKind<{ page: number }>` must be
94
+ // assignable to the union without callers spelling out the data type.
95
+ export type HandleKind = CursorKind<any> | DraftKind<any, any>;
96
+
97
+ /** Stored record data type (schema output); what `read`, `update`, and `commit` callbacks receive. */
98
+ export type DataOf<K extends HandleKind> = z.output<K["schema"]>;
99
+ /** What `create` and `update` accept (schema input); differs from `DataOf` when the schema transforms or defaults. */
100
+ export type InputOf<K extends HandleKind> = z.input<K["schema"]>;
101
+ export type ResultOf<K extends HandleKind> =
102
+ K extends DraftKind<any, infer R> ? (R extends ZodType ? z.output<R> : unknown) : never;
103
+
104
+ export type HandleStatus = "active" | "committing" | "committed";
105
+
106
+ export interface HandleRecord<K extends HandleKind> {
107
+ /** Canonical handle string (`<kind>_<word>-<word>...`). */
108
+ readonly handle: string;
109
+ readonly kind: string;
110
+ readonly status: HandleStatus;
111
+ readonly data: DataOf<K>;
112
+ readonly result?: ResultOf<K>;
113
+ readonly createdAt: string;
114
+ readonly expiresAt: string;
115
+ }
116
+
117
+ export interface HandleCommitResult<K extends HandleKind> {
118
+ readonly status: "committed" | "replayed";
119
+ readonly handle: string;
120
+ readonly result: ResultOf<K>;
121
+ }
122
+
123
+ export interface HandleContext {
124
+ /** Validates `data` with `kind.schema`, stores it, and returns the canonical handle. */
125
+ create<K extends HandleKind>(kind: K, data: InputOf<K>): Promise<string>;
126
+ /** Tolerantly parses `handle`, loads the record; drafts get their idle TTL touched. */
127
+ read<K extends HandleKind>(kind: K, handle: string): Promise<HandleRecord<K>>;
128
+ /** CAS update of an active draft (3 retries) with sliding TTL. */
129
+ update<K extends DraftKind>(
130
+ kind: K,
131
+ handle: string,
132
+ updater: (data: DataOf<K>) => InputOf<K> | Promise<InputOf<K>>,
133
+ ): Promise<HandleRecord<K>>;
134
+ /** One-shot commit with result replay; see runtime docs for the state machine. */
135
+ commit<K extends DraftKind>(
136
+ kind: K,
137
+ handle: string,
138
+ work: (data: DataOf<K>) => Promise<ResultOf<K>>,
139
+ ): Promise<HandleCommitResult<K>>;
140
+ /** Deletes the record; idempotent. */
141
+ discard<K extends HandleKind>(kind: K, handle: string): Promise<void>;
142
+ }
143
+
144
+ export type HandleOperation = "create" | "read" | "update" | "commit" | "discard";
145
+
146
+ export type HandleTelemetryOutcome =
147
+ | "success"
148
+ | "not_found"
149
+ | "expired"
150
+ | "invalid"
151
+ | "kind_mismatch"
152
+ | "busy"
153
+ | "replayed"
154
+ | "error";
155
+
156
+ /** Allowlisted metadata only; handle values, data, and results are never included. */
157
+ export interface HandleTelemetryEvent {
158
+ readonly providerId: string;
159
+ readonly kind: string;
160
+ readonly type: HandleKindType;
161
+ readonly operation: HandleOperation;
162
+ readonly outcome: HandleTelemetryOutcome;
163
+ /** `"none"` or the sorted normalization classes joined by `+`. */
164
+ readonly normalization: string;
165
+ readonly words: number;
166
+ }
167
+
168
+ // ---------------------------------------------------------------------------
169
+ // Errors
170
+ // ---------------------------------------------------------------------------
171
+
172
+ export type HandleErrorCode =
173
+ | "HANDLE_INVALID"
174
+ | "HANDLE_NOT_FOUND"
175
+ | "HANDLE_EXPIRED"
176
+ | "HANDLE_KIND_MISMATCH"
177
+ | "HANDLE_BUSY"
178
+ | "HANDLE_COMMITTED"
179
+ | "HANDLE_CONNECTION_REQUIRED"
180
+ | "HANDLE_STORAGE_UNAVAILABLE"
181
+ | "HANDLE_TOO_LARGE"
182
+ | "HANDLE_INVALID_DATA"
183
+ | "PICK_NOT_OFFERED";
184
+
185
+ const HANDLE_ERROR_DEFAULTS: Record<
186
+ HandleErrorCode,
187
+ { readonly category: ProviderErrorCategory; readonly retryable: boolean }
188
+ > = {
189
+ HANDLE_INVALID: { category: "input_validation", retryable: false },
190
+ HANDLE_NOT_FOUND: { category: "input_validation", retryable: false },
191
+ HANDLE_EXPIRED: { category: "input_validation", retryable: false },
192
+ HANDLE_KIND_MISMATCH: { category: "input_validation", retryable: false },
193
+ HANDLE_BUSY: { category: "internal_error", retryable: true },
194
+ HANDLE_COMMITTED: { category: "input_validation", retryable: false },
195
+ HANDLE_CONNECTION_REQUIRED: { category: "internal_error", retryable: false },
196
+ HANDLE_STORAGE_UNAVAILABLE: { category: "internal_error", retryable: false },
197
+ HANDLE_TOO_LARGE: { category: "internal_error", retryable: false },
198
+ HANDLE_INVALID_DATA: { category: "internal_error", retryable: false },
199
+ PICK_NOT_OFFERED: { category: "input_validation", retryable: false },
200
+ };
201
+
202
+ export type HandleErrorOptions = Omit<ProviderErrorOptions, "code"> & {
203
+ /** Kind name the error relates to, when known. */
204
+ readonly kind?: string;
205
+ };
206
+
207
+ export class HandleError extends ProviderError {
208
+ readonly handleCode: HandleErrorCode;
209
+ readonly kind?: string;
210
+
211
+ constructor(code: HandleErrorCode, message: string, options: HandleErrorOptions = {}) {
212
+ const { kind, ...rest } = options;
213
+ const defaults = HANDLE_ERROR_DEFAULTS[code];
214
+ super(message, {
215
+ category: defaults.category,
216
+ retryable: defaults.retryable,
217
+ ...rest,
218
+ code,
219
+ });
220
+ this.name = "HandleError";
221
+ this.handleCode = code;
222
+ this.kind = kind;
223
+ brandHandleError(this);
224
+ }
225
+
226
+ override get code(): HandleErrorCode {
227
+ return this.handleCode;
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Recognizes handle errors across duplicate SDK module copies (packaged CLI
233
+ * `src/*` runtime vs provider `dist/*` import), where `instanceof` splits.
234
+ */
235
+ export function isHandleError(value: unknown): value is HandleError {
236
+ return value instanceof HandleError || hasHandleErrorBrand(value);
237
+ }
238
+
239
+ /**
240
+ * Standard recovery sentence appended to every handle error message so the LLM
241
+ * knows the next action without provider-specific wording.
242
+ */
243
+ export function handleRecoverySentence(kind: {
244
+ readonly fieldName: string;
245
+ readonly issuedBy?: string;
246
+ }): string {
247
+ if (kind.issuedBy) {
248
+ return `Call \`${kind.issuedBy}\` again and pass the new \`${kind.fieldName}\` exactly as returned.`;
249
+ }
250
+ return `Request a new \`${kind.fieldName}\` and pass it exactly as returned.`;
251
+ }
252
+
253
+ // ---------------------------------------------------------------------------
254
+ // Durations
255
+ // ---------------------------------------------------------------------------
256
+
257
+ const SHORT_DURATION_PATTERN = /^(\d+)(ms|s|m|h|d)$/;
258
+ const ISO_DURATION_PATTERN = /^PT(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?$/;
259
+
260
+ /** Parses a `ProviderStateDurationString` to milliseconds; throws on invalid or non-positive input. */
261
+ export function parseHandleDurationMs(value: ProviderStateDurationString, label: string): number {
262
+ const short = SHORT_DURATION_PATTERN.exec(value);
263
+ let ms: number | undefined;
264
+ if (short) {
265
+ const amount = Number(short[1]);
266
+ const unit = short[2];
267
+ const multiplier =
268
+ unit === "ms"
269
+ ? 1
270
+ : unit === "s"
271
+ ? 1_000
272
+ : unit === "m"
273
+ ? 60_000
274
+ : unit === "h"
275
+ ? 3_600_000
276
+ : 86_400_000;
277
+ ms = amount * multiplier;
278
+ } else {
279
+ const iso = ISO_DURATION_PATTERN.exec(value);
280
+ if (iso && (iso[1] !== undefined || iso[2] !== undefined || iso[3] !== undefined)) {
281
+ ms =
282
+ Number(iso[1] ?? 0) * 3_600_000 +
283
+ Number(iso[2] ?? 0) * 60_000 +
284
+ Number(iso[3] ?? 0) * 1_000;
285
+ }
286
+ }
287
+ if (ms === undefined || !Number.isFinite(ms) || ms <= 0) {
288
+ throw new Error(
289
+ `Handle kind ${label} must be a positive duration such as "10m", "2h", or "PT30M" (received ${JSON.stringify(value)}).`,
290
+ );
291
+ }
292
+ return Math.floor(ms);
293
+ }
294
+
295
+ // ---------------------------------------------------------------------------
296
+ // Kind definitions
297
+ // ---------------------------------------------------------------------------
298
+
299
+ export interface DefineCursorOptions<TSchema extends ZodType> {
300
+ /** Kind name, `/^[a-z]{2,12}$/`; becomes the handle prefix. */
301
+ readonly name: string;
302
+ /** Schema property key carrying the handle. Default `${name}_token`. */
303
+ readonly fieldName?: string;
304
+ readonly schema: TSchema;
305
+ readonly ttl: ProviderStateDurationString;
306
+ /** `"bound"` (default): connection-scoped, 2 words. `"public"`: provider-scoped, 4-5 words. */
307
+ readonly access?: HandleAccess;
308
+ /** Required when public. Bound default 200 per connection. */
309
+ readonly maxEntries?: number;
310
+ /** Default 16,000. */
311
+ readonly maxValueBytes?: number;
312
+ /** Public only; `"high"` forces 5 words. Auto-high when ttl > 1h. */
313
+ readonly strength?: HandleStrength;
314
+ /** Operation key that issues this handle; used in error text and lint. */
315
+ readonly issuedBy?: string;
316
+ }
317
+
318
+ export interface DefineDraftOptions<
319
+ TSchema extends ZodType,
320
+ TResultSchema extends ZodType | undefined,
321
+ > {
322
+ readonly name: string;
323
+ readonly fieldName?: string;
324
+ readonly schema: TSchema;
325
+ /** Optional schema of the commit result (type-level). */
326
+ readonly result?: TResultSchema;
327
+ readonly ttl: {
328
+ readonly idle: ProviderStateDurationString;
329
+ readonly max: ProviderStateDurationString;
330
+ };
331
+ /** How long a committed record stays for replay. Default "24h". */
332
+ readonly resultTtl?: ProviderStateDurationString;
333
+ /** Default 200 per connection. */
334
+ readonly maxEntries?: number;
335
+ /** Default 64,000. */
336
+ readonly maxValueBytes?: number;
337
+ readonly issuedBy?: string;
338
+ }
339
+
340
+ function assertKindName(name: unknown, define: string): asserts name is string {
341
+ if (typeof name !== "string" || !HANDLE_KIND_NAME_PATTERN.test(name)) {
342
+ throw new Error(
343
+ `${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)}.`,
344
+ );
345
+ }
346
+ }
347
+
348
+ function assertFieldName(fieldName: string, define: string): void {
349
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(fieldName)) {
350
+ throw new Error(
351
+ `${define}: fieldName must be a plain identifier usable as a schema property key; received ${JSON.stringify(fieldName)}.`,
352
+ );
353
+ }
354
+ }
355
+
356
+ function assertPositiveInteger(value: number, label: string, define: string): void {
357
+ if (!Number.isInteger(value) || value <= 0) {
358
+ throw new Error(`${define}: ${label} must be a positive integer; received ${String(value)}.`);
359
+ }
360
+ }
361
+
362
+ function createHandleField(meta: HandleFieldMeta): ZodString {
363
+ const described = z.string().min(1).describe(handleFieldDescription(meta));
364
+ // zod v4 `.meta()` replaces the registry entry, so carry the description over.
365
+ const existing = described.meta() ?? {};
366
+ return described.meta({ ...existing, [APIFUSE_HANDLE_META_KEY]: meta });
367
+ }
368
+
369
+ /** Defines an immutable cursor kind (pagination, offered option lists). */
370
+ export function defineCursor<TSchema extends ZodType>(
371
+ options: DefineCursorOptions<TSchema>,
372
+ ): CursorKind<TSchema> {
373
+ const define = "defineCursor";
374
+ assertKindName(options.name, define);
375
+ const fieldName = options.fieldName ?? `${options.name}_token`;
376
+ assertFieldName(fieldName, define);
377
+ const access: HandleAccess = options.access ?? "bound";
378
+ if (access !== "bound" && access !== "public") {
379
+ throw new Error(`${define}: access must be "bound" or "public"; received ${String(access)}.`);
380
+ }
381
+ const ttlMs = parseHandleDurationMs(options.ttl, `"${options.name}" ttl`);
382
+ const strength: HandleStrength = options.strength ?? "standard";
383
+ if (strength !== "standard" && strength !== "high") {
384
+ throw new Error(
385
+ `${define}: strength must be "standard" or "high"; received ${String(strength)}.`,
386
+ );
387
+ }
388
+ if (access === "public" && options.maxEntries === undefined) {
389
+ throw new Error(
390
+ `${define}: public cursor "${options.name}" must declare maxEntries (provider-wide live-entry quota).`,
391
+ );
392
+ }
393
+ const maxEntries = options.maxEntries ?? DEFAULT_BOUND_MAX_ENTRIES;
394
+ assertPositiveInteger(maxEntries, "maxEntries", define);
395
+ const maxValueBytes = options.maxValueBytes ?? DEFAULT_CURSOR_MAX_VALUE_BYTES;
396
+ assertPositiveInteger(maxValueBytes, "maxValueBytes", define);
397
+ const wordCount: HandleWordCount =
398
+ access === "bound"
399
+ ? BOUND_HANDLE_WORD_COUNT
400
+ : strength === "high" || ttlMs > AUTO_HIGH_TTL_MS
401
+ ? HIGH_PUBLIC_HANDLE_WORD_COUNT
402
+ : PUBLIC_HANDLE_WORD_COUNT;
403
+ const meta: HandleFieldMeta = {
404
+ kind: options.name,
405
+ type: "cursor",
406
+ fieldName,
407
+ ...(options.issuedBy ? { issuedBy: options.issuedBy } : {}),
408
+ };
409
+ return Object.freeze({
410
+ name: options.name,
411
+ type: "cursor",
412
+ fieldName,
413
+ access,
414
+ issuedBy: options.issuedBy,
415
+ schema: options.schema,
416
+ ttl: options.ttl,
417
+ ttlMs,
418
+ strength,
419
+ maxEntries,
420
+ maxValueBytes,
421
+ wordCount,
422
+ field: () => createHandleField(meta),
423
+ });
424
+ }
425
+
426
+ /** Defines a mutable, always-bound draft kind (multi-turn forms with one-shot commit). */
427
+ export function defineDraft<
428
+ TSchema extends ZodType,
429
+ TResultSchema extends ZodType | undefined = undefined,
430
+ >(options: DefineDraftOptions<TSchema, TResultSchema>): DraftKind<TSchema, TResultSchema> {
431
+ const define = "defineDraft";
432
+ assertKindName(options.name, define);
433
+ const fieldName = options.fieldName ?? `${options.name}_token`;
434
+ assertFieldName(fieldName, define);
435
+ if (!options.ttl || typeof options.ttl !== "object") {
436
+ throw new Error(`${define}: draft "${options.name}" ttl must be { idle, max }.`);
437
+ }
438
+ const idleTtlMs = parseHandleDurationMs(options.ttl.idle, `"${options.name}" ttl.idle`);
439
+ const maxTtlMs = parseHandleDurationMs(options.ttl.max, `"${options.name}" ttl.max`);
440
+ if (idleTtlMs > maxTtlMs) {
441
+ throw new Error(
442
+ `${define}: draft "${options.name}" ttl.idle (${idleTtlMs}ms) must not exceed ttl.max (${maxTtlMs}ms).`,
443
+ );
444
+ }
445
+ const resultTtl = options.resultTtl ?? DEFAULT_RESULT_TTL;
446
+ const resultTtlMs = parseHandleDurationMs(resultTtl, `"${options.name}" resultTtl`);
447
+ const maxEntries = options.maxEntries ?? DEFAULT_BOUND_MAX_ENTRIES;
448
+ assertPositiveInteger(maxEntries, "maxEntries", define);
449
+ const maxValueBytes = options.maxValueBytes ?? DEFAULT_DRAFT_MAX_VALUE_BYTES;
450
+ assertPositiveInteger(maxValueBytes, "maxValueBytes", define);
451
+ const meta: HandleFieldMeta = {
452
+ kind: options.name,
453
+ type: "draft",
454
+ fieldName,
455
+ ...(options.issuedBy ? { issuedBy: options.issuedBy } : {}),
456
+ };
457
+ return Object.freeze({
458
+ name: options.name,
459
+ type: "draft",
460
+ fieldName,
461
+ access: "bound",
462
+ issuedBy: options.issuedBy,
463
+ schema: options.schema,
464
+ result: options.result,
465
+ ttl: options.ttl,
466
+ idleTtlMs,
467
+ maxTtlMs,
468
+ resultTtl,
469
+ resultTtlMs,
470
+ maxEntries,
471
+ maxValueBytes,
472
+ wordCount: BOUND_HANDLE_WORD_COUNT,
473
+ field: () => createHandleField(meta),
474
+ });
475
+ }
476
+
477
+ export function isDraftKind(kind: HandleKind): kind is DraftKind<any, any> {
478
+ return kind.type === "draft";
479
+ }
480
+
481
+ export function isCursorKind(kind: HandleKind): kind is CursorKind<any> {
482
+ return kind.type === "cursor";
483
+ }
484
+
485
+ // ---------------------------------------------------------------------------
486
+ // pick
487
+ // ---------------------------------------------------------------------------
488
+
489
+ export interface PickOptions<T> {
490
+ /** Input field name, used in the error message. */
491
+ readonly field: string;
492
+ /** Item property compared against `value`. Default = `field`. */
493
+ readonly by?: keyof T & string;
494
+ /** Operation that listed the items; used in the error message when known. */
495
+ readonly issuedBy?: string;
496
+ }
497
+
498
+ /**
499
+ * Chooses one offered item by a plain value the LLM copied from the offer.
500
+ * Exact match first, then a unique case-insensitive trimmed match; otherwise
501
+ * `PICK_NOT_OFFERED` with the allowed values so the LLM can self-correct. The
502
+ * server holds the offer, so a fabricated value fails here instead of reaching
503
+ * upstream. This is the "one handle per offer + plain picks" half of ADR-0012.
504
+ */
505
+ export function pick<T extends Record<string, unknown>>(
506
+ items: readonly T[],
507
+ value: string,
508
+ options: PickOptions<T>,
509
+ ): T {
510
+ const by = options.by ?? options.field;
511
+ const keyOf = (item: T): string => {
512
+ const raw = item[by];
513
+ return typeof raw === "string" ? raw : String(raw);
514
+ };
515
+ const exact = items.find((item) => keyOf(item) === value);
516
+ if (exact) return exact;
517
+ const folded = value.trim().toLowerCase();
518
+ const loose = items.filter((item) => keyOf(item).trim().toLowerCase() === folded);
519
+ if (loose.length === 1) return loose[0]!;
520
+ const allowed = items.map(keyOf);
521
+ const listed = options.issuedBy
522
+ ? ` Use the values exactly as listed by \`${options.issuedBy}\`.`
523
+ : " Use the values exactly as listed.";
524
+ throw new HandleError(
525
+ "PICK_NOT_OFFERED",
526
+ `\`${options.field}\` must be one of: ${allowed.join(", ")}.${listed}`,
527
+ { details: { field: options.field, allowed } },
528
+ );
529
+ }
@@ -191,6 +191,28 @@ export function localizeAuthTurn(
191
191
  };
192
192
  }
193
193
 
194
+ /**
195
+ * Markers that indicate a locale value was scaffolded but never translated.
196
+ *
197
+ * ASCII tokens are matched case-sensitively as whole `\w` tokens so ordinary
198
+ * prose such as "todo list" or identifiers like "TBDx" are not flagged. Locale
199
+ * tags such as `[ko]` are matched literally (the brackets are the boundary), and
200
+ * the Korean/Japanese phrases are matched as-is since CJK text has no `\b`.
201
+ */
202
+ const PROVIDER_LOCALE_PLACEHOLDER_PATTERNS: readonly RegExp[] = [
203
+ /\b(?:TODO|FIXME|TBD|TRANSLATE)\b/,
204
+ /\[(?:en|ko|ja)\]/i,
205
+ /번역\s*필요/,
206
+ /翻訳が必要/,
207
+ ];
208
+
209
+ function isProviderLocalePlaceholderText(text: string): boolean {
210
+ if (text.trim().length === 0) {
211
+ return true;
212
+ }
213
+ return PROVIDER_LOCALE_PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(text));
214
+ }
215
+
194
216
  export function validateProviderLocaleCatalogs(options: {
195
217
  catalogs: ProviderLocaleCatalogMap;
196
218
  requiredLocales: readonly ProviderLocale[];
@@ -239,7 +261,7 @@ export function validateProviderLocaleCatalogs(options: {
239
261
  continue;
240
262
  }
241
263
  for (const text of Array.isArray(value) ? value : [value]) {
242
- if (text.trim().length === 0 || /\bTODO\b/i.test(text)) {
264
+ if (isProviderLocalePlaceholderText(text)) {
243
265
  issues.push({
244
266
  locale,
245
267
  key,