@to11ai/sdk 2.0.0-rc.1 → 2.0.0-rc.10

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.
package/dist/client.d.ts CHANGED
@@ -1,27 +1,20 @@
1
1
  import { type Conversation, Session, type Turn } from "./context";
2
2
  import { ProjectEnvironmentResource } from "./projectEnvironments/resource";
3
- import type { CacheConfig } from "./prompts/cache";
4
3
  import { PromptResource } from "./prompts/resource";
5
4
  import { type RenderFormat, type UnknownRoleMode } from "./prompts/types";
6
- import { RoutingRulesResource } from "./routingRules/resource";
7
- export { BehaviorStore, type BehaviorStoreOptions, envVarNameForKey, type SdkBehaviorEnvelope, } from "./behaviors/store";
8
5
  export type { TurnAuthContext } from "./context";
9
6
  export { Conversation, Session, Turn } from "./context";
10
- export type { AmbiguousEnvLabelsReason, EnvNotFoundReason, NoActiveReleaseReason, NoApplicableRouteReason, PromptNotFoundReason, PromptPolicyViolationReason, } from "./errors";
11
- export { AmbiguousEnvLabelsError, EnvNotEnabledForProviderError, EnvNotFoundError, NoActiveReleaseError, NoApplicableRouteError, PromptLabelNotRegisteredError, PromptNotFoundError, PromptPolicyViolationError, RuleNotFoundError, RuleVersionInvalidSnapshotError, To11aiApiError, To11aiAuthError, To11aiError, To11aiNetworkError, To11aiRateLimitError, To11aiValidationError, UnknownRoleError, } from "./errors";
7
+ export type { NoActiveReleaseReason, PromptNotFoundReason, PromptPolicyViolationReason, } from "./errors";
8
+ export { LabelNotFoundError, MissingLabelError, NoActiveReleaseError, PromptLabelNotRegisteredError, PromptNotFoundError, PromptPolicyViolationError, To11aiApiError, To11aiAuthError, To11aiError, To11aiNetworkError, To11aiRateLimitError, To11aiValidationError, UnknownRoleError, } from "./errors";
12
9
  export type { ConvertMessagesOptions, GatewayAuthOptions } from "./gateway";
13
10
  export { gatewayAuthHeaders, gatewayPromptHeaders } from "./gateway";
14
11
  export type { ArchiveProjectEnvironmentInput, ArchiveProjectEnvironmentResult, CreateProjectEnvironmentInput, CreateProjectEnvironmentResult, GetProjectEnvironmentInput, GetProjectEnvironmentResult, ListProjectEnvironmentsInput, ListProjectEnvironmentsResult, LivePointerCounts, ProjectEnvironment, RestoreProjectEnvironmentInput, RestoreProjectEnvironmentResult, UpdateProjectEnvironmentInput, UpdateProjectEnvironmentResult, } from "./projectEnvironments/resource";
15
12
  export { ProjectEnvironmentResource } from "./projectEnvironments/resource";
16
- export type { CacheConfig } from "./prompts/cache";
17
13
  export type { PromptResourceConfig } from "./prompts/resource";
18
14
  export { PromptResource } from "./prompts/resource";
19
15
  export type { AnthropicRenderedPrompt, OpenAiRenderedPrompt, PromptConfig, PromptMetadata, RenderResult, } from "./prompts/shape";
20
- export type { BlockRenderRecord, FetchedPrompt, FetchPromptOptions, RenderedChatMessage, RenderedPrompt, RenderFormat, RenderOptions, ResolvedPrompt, ResolvedPromptEnvelope, UnknownRoleMode, } from "./prompts/types";
16
+ export type { BlockRenderRecord, RenderedChatMessage, RenderedPrompt, RenderFormat, RenderOptions, UnknownRoleMode, } from "./prompts/types";
21
17
  export { ENV_SLUG_REGEX } from "./prompts/types";
22
- export type { CreateRuleVersionInput, CreateRuleVersionResult, GetRuleVersionInput, GetRuleVersionResult, ListRuleReleasesInput, ListRuleReleasesResult, ListRuleVersionsInput, ListRuleVersionsResult, RollbackRuleReleaseInput, RollbackRuleReleaseResult, RuleModelBinding, RuleProviderRef, RuleRelease, RuleReleaseActorType, RuleReleaseApprovalStatus, RuleReleaseChangeKind, RuleReleaseStrategy, RuleReleaseWeight, RuleSnapshot, RuleStrategy, RuleVersion, SetRuleReleaseInput, SetRuleReleaseResult, } from "./routingRules/resource";
23
- export { RoutingRuleReleaseResource, RoutingRulesResource, RoutingRuleVersionResource, } from "./routingRules/resource";
24
- export type { Transport } from "./transport";
25
18
  export interface ClientOptions {
26
19
  /**
27
20
  * Control-plane base URL. Precedence: this option → `TO11_API_URL` env →
@@ -34,12 +27,11 @@ export interface ClientOptions {
34
27
  */
35
28
  gatewayUrl?: string;
36
29
  /**
37
- * API key for server-side use. Precedence: this option → `TO11_API_KEY` env.
38
- * Rejected in browser contexts — use `getAccessToken` there.
30
+ * API key for server-side use (server, CLI, backend job). Precedence: this
31
+ * option → `TO11_API_KEY` env. Required. Rejected in browser contexts — a
32
+ * to11 API key carries gateway access and must never ship in client code.
39
33
  */
40
34
  apiKey?: string;
41
- /** Token callback for browser / edge contexts — avoids static secrets. */
42
- getAccessToken?: () => Promise<string>;
43
35
  /**
44
36
  * Provider API key (BYOK) carried by `openaiOptions()` / `anthropicOptions()`
45
37
  * as the provider client's `apiKey`, so a BYOK call is a single
@@ -57,8 +49,9 @@ export interface ClientOptions {
57
49
  projectId?: string;
58
50
  /**
59
51
  * Default serving environment for `prompts.render(slug)`, inherited by every
60
- * render unless overridden per call. Validated eagerly against the
61
- * project-environments slug rule (`^[a-z0-9-]{1,63}$`).
52
+ * render unless overridden per call. Precedence: this option → `TO11_ENV`
53
+ * env. Validated eagerly against the project-environments slug rule
54
+ * (`^[a-z0-9-]{1,63}$`).
62
55
  */
63
56
  env?: string;
64
57
  /**
@@ -73,17 +66,10 @@ export interface ClientOptions {
73
66
  * via `render(slug, { onUnknownRole })`.
74
67
  */
75
68
  onUnknownRole?: UnknownRoleMode;
76
- /** LRU cache configuration for render(). Defaults: ttlSeconds=300, maxEntries=100 */
77
- cache?: CacheConfig;
78
69
  /** Request timeout in milliseconds. Default: 30_000 */
79
70
  timeoutMs?: number;
80
71
  /** Max retry attempts for network errors / 5xx. Default: 3 */
81
72
  maxRetries?: number;
82
- /**
83
- * Purely local overrides for server-evaluated SDK-behavior flags (TO11-2100).
84
- * An init option here wins over a `TO11_SDK_BEHAVIOR_*` env var. No LaunchDarkly.
85
- */
86
- behaviorOverrides?: Record<string, unknown>;
87
73
  }
88
74
  /**
89
75
  * Overrides accepted by `openaiOptions()` / `anthropicOptions()`. The three
@@ -111,21 +97,23 @@ export type ProviderClientOptions<T extends ProviderClientOverrides = ProviderCl
111
97
  export interface To11aiClient<F extends RenderFormat | undefined = undefined> {
112
98
  readonly prompts: PromptResource<F>;
113
99
  readonly projectEnvironments: ProjectEnvironmentResource;
114
- readonly routingRules: RoutingRulesResource;
115
- /**
116
- * Resolve a server-evaluated SDK-behavior flag value (TO11-2100) under the
117
- * fixed precedence: local override (init option → `TO11_SDK_BEHAVIOR_*` env
118
- * var) → server-delivered value (captured from responses the client has
119
- * already made) → the `codedDefault` passed here. A value whose runtime type
120
- * disagrees with `codedDefault` falls through to the next tier. The SDK
121
- * carries no LaunchDarkly dependency; this only reads what the server
122
- * delivered on the envelope.
123
- */
124
- readonly resolveBehavior: <T>(key: string, codedDefault: T) => T;
125
- /** Resolved API key (server mode); `undefined` in browser (`getAccessToken`) mode. */
126
- readonly apiKey: string | undefined;
100
+ /** Resolved API key (option → `TO11_API_KEY`). */
101
+ readonly apiKey: string;
102
+ /** Resolved control-plane base URL (option → `TO11_API_URL` → default). */
103
+ readonly baseUrl: string;
127
104
  /** Resolved data-plane gateway URL (option → `TO11_GATEWAY_URL` → default). */
128
105
  readonly gatewayUrl: string;
106
+ /**
107
+ * Resolved project id (option → `TO11_PROJECT_ID`); `undefined` when none is
108
+ * configured. Read-only, for your own logging / manual headers — `prompts.*`
109
+ * already default to it, so you don't need to pass it back into calls.
110
+ */
111
+ readonly projectId: string | undefined;
112
+ /**
113
+ * Resolved default serving environment (option → `TO11_ENV`); `undefined`
114
+ * when none is configured. `prompts.render()` already defaults to it.
115
+ */
116
+ readonly env: string | undefined;
129
117
  /** A new session (unit of work). Pass an id to group telemetry by your own id. */
130
118
  session(id?: string): Session;
131
119
  /**
@@ -167,9 +155,8 @@ export interface To11aiClient<F extends RenderFormat | undefined = undefined> {
167
155
  * - URLs (`baseUrl` / `gatewayUrl`) — option → env var → built-in default.
168
156
  * - `apiKey` / `projectId` — option → env var (no default).
169
157
  * - `env` / `format` — option only.
170
- * Auth mode:
171
- * - `apiKey` (or `TO11_API_KEY`) → server-side; rejected in browser contexts.
172
- * - `getAccessToken` → browser-safe; token fetched per request.
158
+ * Authenticate with `apiKey` (or `TO11_API_KEY`) — required, and server-side
159
+ * only (server, CLI, backend job); constructing with `apiKey` in a browser throws.
173
160
  *
174
161
  * @example Minimal setup (single call)
175
162
  * import { createClient } from "@to11ai/sdk";
package/dist/client.js CHANGED
@@ -10,24 +10,15 @@ import { PromptResource } from "./prompts/resource";
10
10
  import {
11
11
  ENV_SLUG_REGEX
12
12
  } from "./prompts/types";
13
- import { RoutingRulesResource } from "./routingRules/resource";
14
13
  import { Transport } from "./transport";
15
- import {
16
- BehaviorStore as BehaviorStore2,
17
- envVarNameForKey
18
- } from "./behaviors/store";
19
14
  import { Conversation, Session as Session2, Turn } from "./context";
20
15
  import {
21
- AmbiguousEnvLabelsError,
22
- EnvNotEnabledForProviderError,
23
- EnvNotFoundError,
16
+ LabelNotFoundError,
17
+ MissingLabelError,
24
18
  NoActiveReleaseError,
25
- NoApplicableRouteError,
26
19
  PromptLabelNotRegisteredError,
27
20
  PromptNotFoundError,
28
21
  PromptPolicyViolationError,
29
- RuleNotFoundError,
30
- RuleVersionInvalidSnapshotError,
31
22
  To11aiApiError,
32
23
  To11aiAuthError,
33
24
  To11aiError,
@@ -40,11 +31,6 @@ import { gatewayAuthHeaders as gatewayAuthHeaders2, gatewayPromptHeaders } from
40
31
  import { ProjectEnvironmentResource as ProjectEnvironmentResource2 } from "./projectEnvironments/resource";
41
32
  import { PromptResource as PromptResource2 } from "./prompts/resource";
42
33
  import { ENV_SLUG_REGEX as ENV_SLUG_REGEX2 } from "./prompts/types";
43
- import {
44
- RoutingRuleReleaseResource,
45
- RoutingRulesResource as RoutingRulesResource2,
46
- RoutingRuleVersionResource
47
- } from "./routingRules/resource";
48
34
  function createClient(options = {}) {
49
35
  const isDomBrowser = typeof globalThis === "object" && typeof globalThis.document !== "undefined";
50
36
  const workerLikeGlobal = globalThis;
@@ -61,13 +47,12 @@ function createClient(options = {}) {
61
47
  };
62
48
  const baseUrl = pick(options.baseUrl, "TO11_API_URL") ?? DEFAULT_API_URL;
63
49
  const gatewayUrl = (pick(options.gatewayUrl, "TO11_GATEWAY_URL") ?? DEFAULT_GATEWAY_URL).replace(/\/+$/, "").replace(/\/v1$/, "");
64
- const getAccessToken = options.getAccessToken;
65
- const apiKey = getAccessToken !== undefined ? options.apiKey : pick(options.apiKey, "TO11_API_KEY");
50
+ const apiKey = pick(options.apiKey, "TO11_API_KEY");
66
51
  const projectId = pick(options.projectId, "TO11_PROJECT_ID");
67
- const env = options.env;
52
+ const env = pick(options.env, "TO11_ENV");
68
53
  const providerApiKey = options.providerApiKey?.trim() || undefined;
69
54
  if (isBrowser && options.apiKey !== undefined) {
70
- throw new Error("[to11ai/sdk] Do not use `apiKey` in browser contexts — use `getAccessToken` instead.");
55
+ throw new Error("[to11ai/sdk] Do not use `apiKey` in a browser — a to11 API key carries gateway access and must stay server-side (server, CLI, or backend job).");
71
56
  }
72
57
  if (options.apiKey !== undefined && options.apiKey.trim() === "") {
73
58
  throw new Error("[to11ai/sdk] `apiKey` must not be an empty string.");
@@ -75,19 +60,17 @@ function createClient(options = {}) {
75
60
  if (options.projectId !== undefined && options.projectId.trim() === "") {
76
61
  throw new Error("[to11ai/sdk] `projectId` must not be an empty string — omit it or pass a valid project id.");
77
62
  }
63
+ if (options.env !== undefined && options.env.trim() === "") {
64
+ throw new Error("[to11ai/sdk] `env` must not be an empty string — omit it or pass a valid env slug.");
65
+ }
78
66
  if (env !== undefined && !ENV_SLUG_REGEX.test(env)) {
79
67
  throw new Error(`[to11ai/sdk] \`env\` must match ${ENV_SLUG_REGEX} (lowercase-kebab, 1-63 chars). Received: ${JSON.stringify(env)}`);
80
68
  }
81
- const hasApiKey = apiKey !== undefined;
82
- const hasGetAccessToken = getAccessToken !== undefined;
83
- if (hasApiKey === hasGetAccessToken) {
84
- throw new Error("[to11ai/sdk] Provide exactly one of `apiKey` (or `TO11_API_KEY`) or `getAccessToken`.");
69
+ if (apiKey === undefined) {
70
+ throw new Error("[to11ai/sdk] An `apiKey` (or `TO11_API_KEY`) is required.");
85
71
  }
86
- const auth = hasApiKey ? { apiKey } : { getAccessToken };
87
- const behaviorStore = new BehaviorStore({
88
- initOverrides: options.behaviorOverrides,
89
- env: processEnv
90
- });
72
+ const auth = { apiKey };
73
+ const behaviorStore = new BehaviorStore({ env: processEnv });
91
74
  const transport = new Transport({
92
75
  baseUrl,
93
76
  auth,
@@ -95,18 +78,14 @@ function createClient(options = {}) {
95
78
  maxRetries: options.maxRetries,
96
79
  behaviorStore
97
80
  });
98
- const prompts = new PromptResource(transport, options.cache, {
81
+ const prompts = new PromptResource(transport, {
99
82
  projectId,
100
83
  env,
101
84
  format: options.format,
102
85
  onUnknownRole: options.onUnknownRole
103
86
  });
104
87
  const projectEnvironments = new ProjectEnvironmentResource(transport);
105
- const routingRules = new RoutingRulesResource(transport);
106
88
  const gatewayAuthContext = () => {
107
- if (apiKey === undefined) {
108
- throw new Error("[to11ai/sdk] session()/turn()/openaiOptions() need an `apiKey` (or `TO11_API_KEY`) — gateway calls require a server-side key. In the browser use `getAccessToken` for control-plane calls only.");
109
- }
110
89
  if (projectId === undefined) {
111
90
  throw new Error("[to11ai/sdk] session()/turn() need a `projectId` (or `TO11_PROJECT_ID`).");
112
91
  }
@@ -120,9 +99,6 @@ function createClient(options = {}) {
120
99
  return defaultSession;
121
100
  };
122
101
  const gatewayClientOptions = (defaultBaseURL, overrides) => {
123
- if (apiKey === undefined) {
124
- throw new Error("[to11ai/sdk] openaiOptions()/anthropicOptions() need an `apiKey` (or `TO11_API_KEY`) — gateway calls require a server-side key. In the browser use `getAccessToken` for control-plane calls only.");
125
- }
126
102
  if (projectId === undefined) {
127
103
  throw new Error("[to11ai/sdk] openaiOptions()/anthropicOptions() need a `projectId` (or `TO11_PROJECT_ID`) — it authenticates the gateway call via `x-to11-project-id`.");
128
104
  }
@@ -143,10 +119,11 @@ function createClient(options = {}) {
143
119
  return {
144
120
  prompts,
145
121
  projectEnvironments,
146
- routingRules,
147
- resolveBehavior: (key, codedDefault) => behaviorStore.resolve(key, codedDefault),
148
122
  apiKey,
123
+ baseUrl,
149
124
  gatewayUrl,
125
+ projectId,
126
+ env,
150
127
  session: (id) => new Session(gatewayAuthContext(), id),
151
128
  conversation: (id) => clientDefaultSession().conversation(id),
152
129
  turn: () => clientDefaultSession().turn(),
@@ -157,7 +134,6 @@ function createClient(options = {}) {
157
134
  export {
158
135
  gatewayPromptHeaders,
159
136
  gatewayAuthHeaders2 as gatewayAuthHeaders,
160
- envVarNameForKey,
161
137
  createClient,
162
138
  UnknownRoleError,
163
139
  Turn,
@@ -168,22 +144,14 @@ export {
168
144
  To11aiAuthError,
169
145
  To11aiApiError,
170
146
  Session2 as Session,
171
- RuleVersionInvalidSnapshotError,
172
- RuleNotFoundError,
173
- RoutingRulesResource2 as RoutingRulesResource,
174
- RoutingRuleVersionResource,
175
- RoutingRuleReleaseResource,
176
147
  PromptResource2 as PromptResource,
177
148
  PromptPolicyViolationError,
178
149
  PromptNotFoundError,
179
150
  PromptLabelNotRegisteredError,
180
151
  ProjectEnvironmentResource2 as ProjectEnvironmentResource,
181
- NoApplicableRouteError,
182
152
  NoActiveReleaseError,
183
- EnvNotFoundError,
184
- EnvNotEnabledForProviderError,
153
+ MissingLabelError,
154
+ LabelNotFoundError,
185
155
  ENV_SLUG_REGEX2 as ENV_SLUG_REGEX,
186
- Conversation,
187
- BehaviorStore2 as BehaviorStore,
188
- AmbiguousEnvLabelsError
156
+ Conversation
189
157
  };
package/dist/context.d.ts CHANGED
@@ -17,7 +17,7 @@ export interface TurnAuthContext {
17
17
  }
18
18
  /**
19
19
  * A prompt argument accepted by `turn.headers()`. Either the flat provenance
20
- * (a neutral `FetchedPrompt`) or a `format`-shaped result carrying it under
20
+ * (a neutral `RenderedPrompt`) or a `format`-shaped result carrying it under
21
21
  * `metadata` — both are accepted so the format and neutral render paths carry
22
22
  * provenance identically.
23
23
  */
package/dist/errors.cjs CHANGED
@@ -54,9 +54,9 @@ __export(exports_errors, {
54
54
  PromptLabelNotRegisteredError: () => PromptLabelNotRegisteredError,
55
55
  NoApplicableRouteError: () => NoApplicableRouteError,
56
56
  NoActiveReleaseError: () => NoActiveReleaseError,
57
- EnvNotFoundError: () => EnvNotFoundError,
58
- EnvNotEnabledForProviderError: () => EnvNotEnabledForProviderError,
59
- AmbiguousEnvLabelsError: () => AmbiguousEnvLabelsError
57
+ MissingLabelError: () => MissingLabelError,
58
+ LabelNotFoundError: () => LabelNotFoundError,
59
+ EnvNotEnabledForProviderError: () => EnvNotEnabledForProviderError
60
60
  });
61
61
  module.exports = __toCommonJS(exports_errors);
62
62
 
@@ -226,19 +226,27 @@ class PromptNotFoundError extends To11aiApiError {
226
226
  }
227
227
  }
228
228
 
229
- class EnvNotFoundError extends To11aiApiError {
230
- reason;
231
- constructor(message, reason, details, statusCode) {
229
+ class LabelNotFoundError extends To11aiApiError {
230
+ label;
231
+ constructor(message, label, details, statusCode) {
232
232
  super(message, statusCode, "ENV_NOT_FOUND", details);
233
- this.name = "EnvNotFoundError";
234
- this.reason = reason;
233
+ this.name = "LabelNotFoundError";
234
+ this.label = label;
235
235
  Object.setPrototypeOf(this, new.target.prototype);
236
236
  }
237
- static missing(env) {
238
- return new EnvNotFoundError("[to11ai/sdk] No environment resolvable for prompts.render(): none supplied at client init and none supplied per call. Pass `env` to createClient or render(slug, { env }).", { env, source: "missing" }, undefined, 0);
237
+ static is(err) {
238
+ return err instanceof LabelNotFoundError;
239
+ }
240
+ }
241
+
242
+ class MissingLabelError extends To11aiError {
243
+ constructor(message = "[to11ai/sdk] No label resolvable for prompts.render(): none supplied per call, and no client env (or TO11_ENV) to fall back to. Pass `label` to render(slug, { label }) or set `env` on createClient.") {
244
+ super(message);
245
+ this.name = "MissingLabelError";
246
+ Object.setPrototypeOf(this, new.target.prototype);
239
247
  }
240
248
  static is(err) {
241
- return err instanceof EnvNotFoundError;
249
+ return err instanceof MissingLabelError;
242
250
  }
243
251
  }
244
252
 
@@ -268,19 +276,6 @@ class PromptPolicyViolationError extends To11aiApiError {
268
276
  }
269
277
  }
270
278
 
271
- class AmbiguousEnvLabelsError extends To11aiApiError {
272
- reason;
273
- constructor(message, reason, details, statusCode = 409) {
274
- super(message, statusCode, "AMBIGUOUS_ENV_LABELS", details);
275
- this.name = "AmbiguousEnvLabelsError";
276
- this.reason = reason;
277
- Object.setPrototypeOf(this, new.target.prototype);
278
- }
279
- static is(err) {
280
- return err instanceof AmbiguousEnvLabelsError;
281
- }
282
- }
283
-
284
279
  class RuleVersionInvalidSnapshotError extends To11aiApiError {
285
280
  field;
286
281
  reason;
package/dist/errors.d.ts CHANGED
@@ -171,35 +171,29 @@ export declare class PromptNotFoundError extends To11aiApiError {
171
171
  static is(err: unknown): err is PromptNotFoundError;
172
172
  }
173
173
  /**
174
- * Reason payload for `EnvNotFoundError`.
174
+ * Thrown when the label supplied to `prompts.render()` does not resolve to an
175
+ * existing (active) label on the server. Surfaced from the server's
176
+ * `ENV_NOT_FOUND` code; `label` carries the rejected slug when the server
177
+ * echoes it.
175
178
  *
176
- * `source` discriminates the two failure modes (D2):
177
- * - `"missing"` — no env was supplied at init OR at call time. Raised
178
- * CLIENT-side, eagerly, before any request (R4 / AC4); `env` is absent.
179
- * - `"unknown"` — an env was supplied but the server's registry has no
180
- * such (active) env. Surfaced from the `ENV_NOT_FOUND` server code; `env`
181
- * carries the rejected slug when the server echoes it.
179
+ * This is distinct from `MissingLabelError`, which is raised client-side when
180
+ * no label was supplied at all.
182
181
  */
183
- export interface EnvNotFoundReason {
184
- env?: string;
185
- source: "missing" | "unknown";
182
+ export declare class LabelNotFoundError extends To11aiApiError {
183
+ /** The label slug that could not be found, when the server echoes it. */
184
+ readonly label?: string;
185
+ constructor(message: string, label: string | undefined, details: unknown, statusCode: number);
186
+ static is(err: unknown): err is LabelNotFoundError;
186
187
  }
187
188
  /**
188
- * Thrown when no serving environment can be resolved for a `prompts.render()`
189
- * call. One class, two `reason.source` discriminants (see
190
- * `EnvNotFoundReason`): client-eager `"missing"` (R4) and server-forwarded
191
- * `"unknown"` (`ENV_NOT_FOUND`).
192
- *
193
- * The client-eager variant carries no `statusCode`/`errorCode` from the wire
194
- * (no request was made); it reports status `0` and errorCode `ENV_NOT_FOUND`
195
- * for a uniform catch surface.
189
+ * Thrown CLIENT-side, eagerly (before any request), when `prompts.render()` is
190
+ * called but no label is resolvable at all: none supplied per call, and no
191
+ * client `env` (or `TO11_ENV`) to fall back to. A usage error, not a lookup
192
+ * failure — distinct from `LabelNotFoundError`.
196
193
  */
197
- export declare class EnvNotFoundError extends To11aiApiError {
198
- readonly reason: EnvNotFoundReason;
199
- constructor(message: string, reason: EnvNotFoundReason, details: unknown, statusCode: number);
200
- /** Build the client-eager (missing-at-both) variant — no transport call. */
201
- static missing(env?: string): EnvNotFoundError;
202
- static is(err: unknown): err is EnvNotFoundError;
194
+ export declare class MissingLabelError extends To11aiError {
195
+ constructor(message?: string);
196
+ static is(err: unknown): err is MissingLabelError;
203
197
  }
204
198
  /**
205
199
  * Reason payload for `NoActiveReleaseError`.
@@ -250,28 +244,6 @@ export declare class PromptPolicyViolationError extends To11aiApiError {
250
244
  constructor(message: string, reason: PromptPolicyViolationReason, details?: unknown, statusCode?: number);
251
245
  static is(err: unknown): err is PromptPolicyViolationError;
252
246
  }
253
- /**
254
- * Reason payload for `AmbiguousEnvLabelsError`.
255
- *
256
- * Carried when the supplied env-label matched more than one candidate
257
- * version and the server cannot pick deterministically
258
- * (`AMBIGUOUS_ENV_LABELS`).
259
- */
260
- export interface AmbiguousEnvLabelsReason {
261
- env?: string;
262
- slug?: string;
263
- }
264
- /**
265
- * Thrown when the env→label resolution is ambiguous on the server
266
- * (`AMBIGUOUS_ENV_LABELS`) — the label matched multiple candidates and the
267
- * server declines to guess. Surfaces (rather than 500ing) so callers get a
268
- * typed, actionable error.
269
- */
270
- export declare class AmbiguousEnvLabelsError extends To11aiApiError {
271
- readonly reason: AmbiguousEnvLabelsReason;
272
- constructor(message: string, reason: AmbiguousEnvLabelsReason, details?: unknown, statusCode?: number);
273
- static is(err: unknown): err is AmbiguousEnvLabelsError;
274
- }
275
247
  /**
276
248
  * Thrown when version create rejects the snapshot for a structural
277
249
  * reason — invalid variant params, malformed `when` clause, illegal
package/dist/errors.js CHANGED
@@ -165,19 +165,27 @@ class PromptNotFoundError extends To11aiApiError {
165
165
  }
166
166
  }
167
167
 
168
- class EnvNotFoundError extends To11aiApiError {
169
- reason;
170
- constructor(message, reason, details, statusCode) {
168
+ class LabelNotFoundError extends To11aiApiError {
169
+ label;
170
+ constructor(message, label, details, statusCode) {
171
171
  super(message, statusCode, "ENV_NOT_FOUND", details);
172
- this.name = "EnvNotFoundError";
173
- this.reason = reason;
172
+ this.name = "LabelNotFoundError";
173
+ this.label = label;
174
174
  Object.setPrototypeOf(this, new.target.prototype);
175
175
  }
176
- static missing(env) {
177
- return new EnvNotFoundError("[to11ai/sdk] No environment resolvable for prompts.render(): none supplied at client init and none supplied per call. Pass `env` to createClient or render(slug, { env }).", { env, source: "missing" }, undefined, 0);
176
+ static is(err) {
177
+ return err instanceof LabelNotFoundError;
178
+ }
179
+ }
180
+
181
+ class MissingLabelError extends To11aiError {
182
+ constructor(message = "[to11ai/sdk] No label resolvable for prompts.render(): none supplied per call, and no client env (or TO11_ENV) to fall back to. Pass `label` to render(slug, { label }) or set `env` on createClient.") {
183
+ super(message);
184
+ this.name = "MissingLabelError";
185
+ Object.setPrototypeOf(this, new.target.prototype);
178
186
  }
179
187
  static is(err) {
180
- return err instanceof EnvNotFoundError;
188
+ return err instanceof MissingLabelError;
181
189
  }
182
190
  }
183
191
 
@@ -207,19 +215,6 @@ class PromptPolicyViolationError extends To11aiApiError {
207
215
  }
208
216
  }
209
217
 
210
- class AmbiguousEnvLabelsError extends To11aiApiError {
211
- reason;
212
- constructor(message, reason, details, statusCode = 409) {
213
- super(message, statusCode, "AMBIGUOUS_ENV_LABELS", details);
214
- this.name = "AmbiguousEnvLabelsError";
215
- this.reason = reason;
216
- Object.setPrototypeOf(this, new.target.prototype);
217
- }
218
- static is(err) {
219
- return err instanceof AmbiguousEnvLabelsError;
220
- }
221
- }
222
-
223
218
  class RuleVersionInvalidSnapshotError extends To11aiApiError {
224
219
  field;
225
220
  reason;
@@ -252,7 +247,7 @@ export {
252
247
  PromptLabelNotRegisteredError,
253
248
  NoApplicableRouteError,
254
249
  NoActiveReleaseError,
255
- EnvNotFoundError,
256
- EnvNotEnabledForProviderError,
257
- AmbiguousEnvLabelsError
250
+ MissingLabelError,
251
+ LabelNotFoundError,
252
+ EnvNotEnabledForProviderError
258
253
  };
package/dist/gateway.cjs CHANGED
@@ -75,18 +75,27 @@ function gatewayAuthHeaders(options) {
75
75
  return headers;
76
76
  }
77
77
  function gatewayPromptHeaders(prompt) {
78
- const headers = {
79
- "x-to11-prompt-id": prompt.promptId,
80
- "x-to11-prompt-version": String(prompt.version)
81
- };
82
- if (typeof prompt.releaseId === "string" && prompt.releaseId.length > 0) {
83
- headers["x-to11-release-id"] = prompt.releaseId;
78
+ const p = prompt != null && "metadata" in prompt ? prompt.metadata : prompt;
79
+ const headers = {};
80
+ if (p == null)
81
+ return headers;
82
+ if (typeof p.promptId === "string" && p.promptId.length > 0) {
83
+ headers["x-to11-prompt-id"] = p.promptId;
84
+ }
85
+ if (typeof p.version === "number" && Number.isFinite(p.version)) {
86
+ headers["x-to11-prompt-version"] = String(p.version);
87
+ }
88
+ if (typeof p.releaseId === "string" && p.releaseId.length > 0) {
89
+ headers["x-to11-release-id"] = p.releaseId;
84
90
  }
85
- if (typeof prompt.variantName === "string" && prompt.variantName.length > 0) {
86
- headers["x-to11-variant-name"] = prompt.variantName;
91
+ if (typeof p.variantName === "string" && p.variantName.length > 0) {
92
+ headers["x-to11-variant-name"] = p.variantName;
87
93
  }
88
- if (prompt.label.length > 0) {
89
- headers["x-to11-prompt-label"] = prompt.label;
94
+ if (typeof p.label === "string" && p.label.length > 0) {
95
+ headers["x-to11-prompt-label"] = p.label;
96
+ }
97
+ if (typeof p.slug === "string" && p.slug.length > 0) {
98
+ headers["x-to11-prompt-slug"] = p.slug;
90
99
  }
91
100
  return headers;
92
101
  }
@@ -174,24 +183,29 @@ function toOpenAIMessages(messages, options = {}) {
174
183
  return;
175
184
  }
176
185
  if (message.role === "assistant") {
177
- const msg = {
186
+ const content2 = message.content ?? null;
187
+ out.push(message.toolCalls != null && message.toolCalls.length > 0 ? {
178
188
  role: "assistant",
179
- content: message.content ?? null
180
- };
181
- if (message.toolCalls != null && message.toolCalls.length > 0) {
182
- msg.tool_calls = message.toolCalls.map((call) => ({
189
+ content: content2,
190
+ tool_calls: message.toolCalls.map((call) => ({
183
191
  id: requireToolCallId(call.id),
184
192
  type: "function",
185
193
  function: {
186
194
  name: call.name,
187
195
  arguments: JSON.stringify(call.arguments)
188
196
  }
189
- }));
190
- }
191
- out.push(msg);
197
+ }))
198
+ } : { role: "assistant", content: content2 });
192
199
  return;
193
200
  }
194
- out.push({ role: message.role, content: message.content ?? "" });
201
+ const content = message.content ?? "";
202
+ if (message.role === "user") {
203
+ out.push({ role: "user", content });
204
+ } else if (message.role === "developer") {
205
+ out.push({ role: "developer", content });
206
+ } else {
207
+ out.push({ role: "system", content });
208
+ }
195
209
  });
196
210
  return out;
197
211
  }