@to11ai/sdk 3.1.0-rc.1 → 4.0.0-rc.1
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/README.md +30 -42
- package/dist/behaviors/store.d.ts +1 -1
- package/dist/client.cjs +17 -71
- package/dist/client.d.ts +16 -112
- package/dist/client.js +22 -72
- package/dist/config.d.ts +3 -6
- package/dist/errors.cjs +0 -72
- package/dist/errors.d.ts +0 -77
- package/dist/errors.js +0 -72
- package/dist/generated/index.d.ts +1 -1
- package/dist/generated/types.gen.d.ts +3025 -17437
- package/dist/generated/zod.gen.d.ts +2548 -11589
- package/dist/projectEnvironments/resource.cjs +0 -2
- package/dist/projectEnvironments/resource.d.ts +3 -12
- package/dist/projectEnvironments/resource.js +0 -2
- package/dist/projectEnvironments/types.d.ts +0 -2
- package/dist/{gateway.d.ts → prompts/convert.d.ts} +12 -75
- package/dist/prompts/resource.d.ts +7 -7
- package/dist/prompts/shape.d.ts +4 -5
- package/dist/prompts/types.d.ts +5 -17
- package/package.json +7 -24
- package/src/behaviors/store.ts +1 -1
- package/src/client.ts +36 -242
- package/src/config.ts +3 -9
- package/src/errors.ts +0 -132
- package/src/generated/index.ts +1 -1
- package/src/generated/types.gen.ts +2905 -17897
- package/src/generated/zod.gen.ts +1985 -10118
- package/src/projectEnvironments/resource.ts +3 -14
- package/src/projectEnvironments/types.ts +0 -2
- package/src/{gateway.ts → prompts/convert.ts} +18 -152
- package/src/prompts/resource.ts +10 -12
- package/src/prompts/shape.ts +4 -5
- package/src/prompts/types.ts +5 -17
- package/src/transport.ts +0 -133
- package/dist/context.d.ts +0 -124
- package/dist/gateway.cjs +0 -264
- package/dist/gateway.js +0 -226
- package/dist/routingRules/resource.d.ts +0 -64
- package/dist/routingRules/types.d.ts +0 -88
- package/dist/traceparent.d.ts +0 -61
- package/dist/usage/resource.cjs +0 -113
- package/dist/usage/resource.d.ts +0 -29
- package/dist/usage/resource.js +0 -78
- package/dist/usage/types.d.ts +0 -81
- package/src/context.ts +0 -196
- package/src/routingRules/resource.ts +0 -261
- package/src/routingRules/types.ts +0 -120
- package/src/traceparent.ts +0 -189
- package/src/usage/resource.ts +0 -183
- package/src/usage/types.ts +0 -121
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# @to11ai/sdk
|
|
2
2
|
|
|
3
|
-
JavaScript/TypeScript SDK for [to11ai](https://to11ai.com) — the
|
|
3
|
+
JavaScript/TypeScript SDK for [to11ai](https://to11ai.com) — the platform for managing prompts and skills and reviewing coding-agent sessions.
|
|
4
4
|
|
|
5
|
-
Use it to **render managed prompts** at runtime,
|
|
5
|
+
Use it to **render managed prompts** at runtime, shaped for your own provider client (OpenAI, Anthropic, …), and to manage prompts, versions and project environments from code.
|
|
6
6
|
|
|
7
7
|
Ships ESM, CommonJS, and raw TypeScript source in the same package. Runtimes and bundlers pick the right variant automatically.
|
|
8
8
|
|
|
@@ -13,11 +13,11 @@ npm install @to11ai/sdk
|
|
|
13
13
|
# or: bun add @to11ai/sdk · pnpm add @to11ai/sdk · yarn add @to11ai/sdk
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
Runs anywhere Node, Bun, Deno, or edge runs — servers, CLIs, and backend jobs. Not for browsers: a to11 API key
|
|
16
|
+
Runs anywhere Node, Bun, Deno, or edge runs — servers, CLIs, and backend jobs. Not for browsers: a to11 API key must never ship in client-side code.
|
|
17
17
|
|
|
18
18
|
### Upgrading from 2.x
|
|
19
19
|
|
|
20
|
-
3.0 takes environments out of prompt resolution: a prompt has one label, `latest
|
|
20
|
+
3.0 takes environments out of prompt resolution: a prompt has one label, `latest`. `moveLabel()`, the project label registry and weighted releases are gone, and `listVersions()`, `listLabels()` and `projectEnvironments.list()` return cursor pages instead of arrays. See [Migrating from 2.x to 3.0](https://github.com/to11ai/platform/blob/main/packages/js-sdk/CHANGELOG.md#migrating-from-2x-to-30) for the full list.
|
|
21
21
|
|
|
22
22
|
### Upgrading from 1.x
|
|
23
23
|
|
|
@@ -25,7 +25,7 @@ Runs anywhere Node, Bun, Deno, or edge runs — servers, CLIs, and backend jobs.
|
|
|
25
25
|
|
|
26
26
|
## Quick start
|
|
27
27
|
|
|
28
|
-
Create a client, render a prompt, and send it
|
|
28
|
+
Create a client, render a prompt, and send it with your normal provider client:
|
|
29
29
|
|
|
30
30
|
```typescript
|
|
31
31
|
import { createClient } from "@to11ai/sdk";
|
|
@@ -37,7 +37,6 @@ const to11 = createClient({
|
|
|
37
37
|
baseUrl: process.env.TO11_API_URL, // → https://api.to11.ai
|
|
38
38
|
apiKey: process.env.TO11_API_KEY, // → TO11_API_KEY
|
|
39
39
|
projectId: process.env.TO11_PROJECT_ID, // → TO11_PROJECT_ID
|
|
40
|
-
env: process.env.TO11_ENV, // "prod", "staging", … → TO11_ENV
|
|
41
40
|
});
|
|
42
41
|
|
|
43
42
|
// Render the prompt's `latest` version for the client's project.
|
|
@@ -46,15 +45,15 @@ const prompt = await to11.prompts.render("welcome-message", {
|
|
|
46
45
|
format: "openai", // omit for the provider-neutral result
|
|
47
46
|
});
|
|
48
47
|
|
|
49
|
-
//
|
|
50
|
-
const openai = new OpenAI(
|
|
51
|
-
const completion = await openai.chat.completions.create(
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
);
|
|
48
|
+
// Send it with your own provider client and provider key.
|
|
49
|
+
const openai = new OpenAI();
|
|
50
|
+
const completion = await openai.chat.completions.create({
|
|
51
|
+
...prompt.config,
|
|
52
|
+
messages: prompt.messages,
|
|
53
|
+
});
|
|
55
54
|
```
|
|
56
55
|
|
|
57
|
-
`prompt.config` carries the model parameters
|
|
56
|
+
`prompt.config` carries the model parameters and `prompt.messages` the rendered messages. `prompt.metadata` records which prompt version produced them.
|
|
58
57
|
|
|
59
58
|
## Configuring the client
|
|
60
59
|
|
|
@@ -63,18 +62,15 @@ const completion = await openai.chat.completions.create(
|
|
|
63
62
|
| Option | Resolves from | Default |
|
|
64
63
|
| --- | --- | --- |
|
|
65
64
|
| `baseUrl` | option → `TO11_API_URL` | `https://api.to11.ai` |
|
|
66
|
-
| `gatewayUrl` | option → `TO11_GATEWAY_URL` | `https://gw.to11.ai` |
|
|
67
65
|
| `apiKey` | option → `TO11_API_KEY` | — (throws if constructed in a browser) |
|
|
68
66
|
| `projectId` | option → `TO11_PROJECT_ID` | — |
|
|
69
|
-
| `env` | option → `TO11_ENV` | — (gateway routing via `x-to11-env`; must match `^[a-z0-9-]{1,63}$`) |
|
|
70
|
-
| `providerApiKey` | option | — (BYOK; carried by `openaiOptions()`/`anthropicOptions()`) |
|
|
71
67
|
| `format` | option | — (`"openai"` \| `"anthropic"`; omit for the neutral result) |
|
|
72
68
|
| `onUnknownRole` | option | `"drop"` |
|
|
73
69
|
| `timeoutMs` / `maxRetries` | option | `30000` / `3` |
|
|
74
70
|
|
|
75
|
-
> **Keep credentials server-side.** A to11 API key
|
|
71
|
+
> **Keep credentials server-side.** A to11 API key must never ship in browser code — the SDK throws if you construct a client with `apiKey` in a browser context (like OpenAI's `dangerouslyAllowBrowser`). Use the SDK from a server, CLI, or backend job.
|
|
76
72
|
|
|
77
|
-
The client exposes read-only accessors for the resolved values — **`to11.baseUrl`**, **`to11.
|
|
73
|
+
The client exposes read-only accessors for the resolved values — **`to11.baseUrl`**, **`to11.apiKey`**, and **`to11.projectId`**. Use the non-secret ones (`baseUrl`/`projectId`) for diagnostics; treat `apiKey` as a secret and never log it.
|
|
78
74
|
|
|
79
75
|
## Rendering prompts
|
|
80
76
|
|
|
@@ -94,22 +90,29 @@ const prompt = await to11.prompts.render("weather-concierge", {
|
|
|
94
90
|
|
|
95
91
|
Authored `developer` blocks come back as-is; the SDK maps them per provider (OpenAI keeps `developer`; Anthropic folds `system`/`developer` into the top-level `system`). `onUnknownRole` (`"drop"` default, `"warn"`, `"error"`) controls how an unrecognized role is handled during provider conversion.
|
|
96
92
|
|
|
97
|
-
> Prompts render as **chat blocks**. The pre-2.0 `resolve()` and the `text` render format have been removed — use `render()`. A prompt carries one label, `latest`, which follows the newest version
|
|
93
|
+
> Prompts render as **chat blocks**. The pre-2.0 `resolve()` and the `text` render format have been removed — use `render()`. A prompt carries one label, `latest`, which follows the newest version.
|
|
98
94
|
|
|
99
|
-
## Sending
|
|
95
|
+
## Sending with Anthropic
|
|
100
96
|
|
|
101
|
-
|
|
97
|
+
With `format: "anthropic"` the result carries the folded `system` text alongside `messages`:
|
|
102
98
|
|
|
103
99
|
```typescript
|
|
104
100
|
import Anthropic from "@anthropic-ai/sdk";
|
|
105
|
-
|
|
101
|
+
|
|
102
|
+
const prompt = await to11.prompts.render("weather-concierge", { format: "anthropic" });
|
|
103
|
+
const anthropic = new Anthropic();
|
|
104
|
+
const message = await anthropic.messages.create({
|
|
105
|
+
...prompt.config,
|
|
106
|
+
system: prompt.system,
|
|
107
|
+
messages: prompt.messages,
|
|
108
|
+
});
|
|
106
109
|
```
|
|
107
110
|
|
|
108
|
-
|
|
111
|
+
`prompt.config` spreads the version's stored model config, so the prompt version must set `model` and `max_tokens` (or you pass them yourself).
|
|
109
112
|
|
|
110
|
-
|
|
113
|
+
### Converting messages yourself
|
|
111
114
|
|
|
112
|
-
|
|
115
|
+
The converters behind `format` are exported for history you build yourself: `toOpenAIMessages`, `toOpenAITools`, `toOpenAIToolChoice`, `toAnthropicMessages`, `toAnthropicSystem`, `toAnthropicTools`, and `toAnthropicToolChoice`. Each takes the provider-neutral shape (`RenderedChatMessage[]`, `prompt.tools`, `prompt.toolChoice`) and returns the provider's request shape.
|
|
113
116
|
|
|
114
117
|
## Managing prompts, versions & labels
|
|
115
118
|
|
|
@@ -137,26 +140,11 @@ Full set: `render`, `create`, `list`, `get`, `update`, `archive`, `createVersion
|
|
|
137
140
|
Skills across an organization: `listOrgPrompts` lists the skills in every project of an org you may read prompts in, each with the version `latest` serves (at most `limit` rows, default 20, max 50). Render exactly that version with `renderSkillVersion`:
|
|
138
141
|
|
|
139
142
|
```typescript
|
|
140
|
-
const { items
|
|
143
|
+
const { items } = await to11.prompts.listOrgPrompts({ orgId: "org_1", query: "release" });
|
|
141
144
|
const skill = await to11.prompts.renderSkillVersion({ projectId: items[0].projectId, slug: items[0].slug, version: items[0].version });
|
|
142
145
|
// skill.files: [{ filename: "SKILL.md", content, … }]
|
|
143
146
|
```
|
|
144
147
|
|
|
145
|
-
## Organization usage
|
|
146
|
-
|
|
147
|
-
`client.usage` reads an organization's usage. Every method takes the `orgId` and, except `findPrincipals`, a `window`: absolute (`{ from, to }`, ISO 8601 with an offset) or a preset the server resolves in an IANA time zone (`{ preset, n?, timezone }`; `n` only for `last_n_hours` / `last_n_days`). Figures carry `billedUsd` and `apiEquivalentUsd`; every response echoes the absolute window and lists the readable projects it left out (`excludedProjects`).
|
|
148
|
-
|
|
149
|
-
```typescript
|
|
150
|
-
const { items } = await to11.usage.findPrincipals({ orgId: "org_1", query: "nigel" }); // or { email }
|
|
151
|
-
const window = { preset: "last_n_days", n: 7, timezone: "Europe/Berlin" } as const;
|
|
152
|
-
|
|
153
|
-
await to11.usage.listSessions({ orgId: "org_1", window, principalId: items[0].principalId }); // cursor-paged
|
|
154
|
-
await to11.usage.getCosts({ orgId: "org_1", window, groupBy: ["principal", "model"] });
|
|
155
|
-
await to11.usage.listTopTraces({ orgId: "org_1", window, sort: "cost", limit: 5 }); // window ≤ 60 days
|
|
156
|
-
```
|
|
157
|
-
|
|
158
|
-
Types: `import type { UsageWindow, GetCostsResult, … } from "@to11ai/sdk/usage"`.
|
|
159
|
-
|
|
160
148
|
## Error handling
|
|
161
149
|
|
|
162
150
|
`To11aiError` is the base; catch it broadly or match a subclass:
|
|
@@ -185,7 +173,7 @@ try {
|
|
|
185
173
|
|
|
186
174
|
## TypeScript types
|
|
187
175
|
|
|
188
|
-
All inputs/outputs are typed; declarations ship as `dist/*.d.ts` (no separate `@types`). Import types from the entrypoint or the `@to11ai/sdk/prompts`
|
|
176
|
+
All inputs/outputs are typed; declarations ship as `dist/*.d.ts` (no separate `@types`). Import types from the entrypoint or the `@to11ai/sdk/prompts` subpath:
|
|
189
177
|
|
|
190
178
|
```typescript
|
|
191
179
|
import type { ClientOptions, RenderOptions, RenderedPrompt } from "@to11ai/sdk";
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* The to11 platform evaluates flags that influence *shipped-SDK behavior*
|
|
5
5
|
* server-side and delivers their values on the optional `sdkBehavior` field of
|
|
6
|
-
* the success envelope (PRD Decision 7). This SDK carries **no**
|
|
6
|
+
* the success envelope (PRD Decision 7). This SDK carries **no** feature-flag vendor
|
|
7
7
|
* dependency and never connects to to11's control plane — it only reads the
|
|
8
8
|
* value the server already evaluated.
|
|
9
9
|
*
|
package/dist/client.cjs
CHANGED
|
@@ -39,48 +39,43 @@ var __export = (target, all) => {
|
|
|
39
39
|
// src/client.ts
|
|
40
40
|
var exports_client = {};
|
|
41
41
|
__export(exports_client, {
|
|
42
|
-
|
|
43
|
-
ENV_SLUG_REGEX: () => import_types2.ENV_SLUG_REGEX,
|
|
42
|
+
ENV_SLUG_REGEX: () => import_types.ENV_SLUG_REGEX,
|
|
44
43
|
LabelNotFoundError: () => import_errors.LabelNotFoundError,
|
|
45
|
-
ProjectEnvironmentResource: () =>
|
|
44
|
+
ProjectEnvironmentResource: () => import_resource3.ProjectEnvironmentResource,
|
|
46
45
|
PromptHasNoVersionsError: () => import_errors.PromptHasNoVersionsError,
|
|
47
46
|
PromptNotFoundError: () => import_errors.PromptNotFoundError,
|
|
48
47
|
PromptPolicyViolationError: () => import_errors.PromptPolicyViolationError,
|
|
49
|
-
PromptResource: () =>
|
|
50
|
-
Session: () => import_context2.Session,
|
|
48
|
+
PromptResource: () => import_resource4.PromptResource,
|
|
51
49
|
To11aiApiError: () => import_errors.To11aiApiError,
|
|
52
50
|
To11aiAuthError: () => import_errors.To11aiAuthError,
|
|
53
51
|
To11aiError: () => import_errors.To11aiError,
|
|
54
52
|
To11aiNetworkError: () => import_errors.To11aiNetworkError,
|
|
55
53
|
To11aiRateLimitError: () => import_errors.To11aiRateLimitError,
|
|
56
54
|
To11aiValidationError: () => import_errors.To11aiValidationError,
|
|
57
|
-
Turn: () => import_context2.Turn,
|
|
58
55
|
UnknownRoleError: () => import_errors.UnknownRoleError,
|
|
59
|
-
UsageResource: () => import_resource6.UsageResource,
|
|
60
56
|
createClient: () => createClient,
|
|
61
|
-
gatewayAuthHeaders: () => import_gateway2.gatewayAuthHeaders,
|
|
62
|
-
gatewayPromptHeaders: () => import_gateway2.gatewayPromptHeaders,
|
|
63
57
|
iterateCursorItems: () => import_pagination.iterateCursorItems,
|
|
64
|
-
iterateCursorPages: () => import_pagination.iterateCursorPages
|
|
58
|
+
iterateCursorPages: () => import_pagination.iterateCursorPages,
|
|
59
|
+
toAnthropicMessages: () => import_convert.toAnthropicMessages,
|
|
60
|
+
toAnthropicSystem: () => import_convert.toAnthropicSystem,
|
|
61
|
+
toAnthropicToolChoice: () => import_convert.toAnthropicToolChoice,
|
|
62
|
+
toAnthropicTools: () => import_convert.toAnthropicTools,
|
|
63
|
+
toOpenAIMessages: () => import_convert.toOpenAIMessages,
|
|
64
|
+
toOpenAIToolChoice: () => import_convert.toOpenAIToolChoice,
|
|
65
|
+
toOpenAITools: () => import_convert.toOpenAITools
|
|
65
66
|
});
|
|
66
67
|
module.exports = __toCommonJS(exports_client);
|
|
67
68
|
var import_store = require("./behaviors/store");
|
|
68
69
|
var import_config = require("./config");
|
|
69
|
-
var import_context = require("./context");
|
|
70
|
-
var import_gateway = require("./gateway");
|
|
71
70
|
var import_resource = require("./projectEnvironments/resource");
|
|
72
71
|
var import_resource2 = require("./prompts/resource");
|
|
73
|
-
var import_types = require("./prompts/types");
|
|
74
72
|
var import_transport = require("./transport");
|
|
75
|
-
var import_resource3 = require("./usage/resource");
|
|
76
|
-
var import_context2 = require("./context");
|
|
77
73
|
var import_errors = require("./errors");
|
|
78
|
-
var import_gateway2 = require("./gateway");
|
|
79
74
|
var import_pagination = require("./pagination");
|
|
80
|
-
var
|
|
81
|
-
var
|
|
82
|
-
var
|
|
83
|
-
var
|
|
75
|
+
var import_resource3 = require("./projectEnvironments/resource");
|
|
76
|
+
var import_convert = require("./prompts/convert");
|
|
77
|
+
var import_resource4 = require("./prompts/resource");
|
|
78
|
+
var import_types = require("./prompts/types");
|
|
84
79
|
function createClient(options = {}) {
|
|
85
80
|
const isDomBrowser = typeof globalThis === "object" && typeof globalThis.document !== "undefined";
|
|
86
81
|
const workerLikeGlobal = globalThis;
|
|
@@ -96,13 +91,10 @@ function createClient(options = {}) {
|
|
|
96
91
|
return fromEnv ? fromEnv : undefined;
|
|
97
92
|
};
|
|
98
93
|
const baseUrl = pick(options.baseUrl, "TO11_API_URL") ?? import_config.DEFAULT_API_URL;
|
|
99
|
-
const gatewayUrl = (pick(options.gatewayUrl, "TO11_GATEWAY_URL") ?? import_config.DEFAULT_GATEWAY_URL).replace(/\/+$/, "").replace(/\/v1$/, "");
|
|
100
94
|
const apiKey = pick(options.apiKey, "TO11_API_KEY");
|
|
101
95
|
const projectId = pick(options.projectId, "TO11_PROJECT_ID");
|
|
102
|
-
const env = pick(options.env, "TO11_ENV");
|
|
103
|
-
const providerApiKey = options.providerApiKey?.trim() || undefined;
|
|
104
96
|
if (isBrowser && options.apiKey !== undefined) {
|
|
105
|
-
throw new Error("[to11ai/sdk] Do not use `apiKey` in a browser — a to11 API key
|
|
97
|
+
throw new Error("[to11ai/sdk] Do not use `apiKey` in a browser — a to11 API key must stay server-side (server, CLI, or backend job).");
|
|
106
98
|
}
|
|
107
99
|
if (options.apiKey !== undefined && options.apiKey.trim() === "") {
|
|
108
100
|
throw new Error("[to11ai/sdk] `apiKey` must not be an empty string.");
|
|
@@ -110,12 +102,6 @@ function createClient(options = {}) {
|
|
|
110
102
|
if (options.projectId !== undefined && options.projectId.trim() === "") {
|
|
111
103
|
throw new Error("[to11ai/sdk] `projectId` must not be an empty string — omit it or pass a valid project id.");
|
|
112
104
|
}
|
|
113
|
-
if (options.env !== undefined && options.env.trim() === "") {
|
|
114
|
-
throw new Error("[to11ai/sdk] `env` must not be an empty string — omit it or pass a valid env slug.");
|
|
115
|
-
}
|
|
116
|
-
if (env !== undefined && !import_types.ENV_SLUG_REGEX.test(env)) {
|
|
117
|
-
throw new Error(`[to11ai/sdk] \`env\` must match ${import_types.ENV_SLUG_REGEX} (lowercase-kebab, 1-63 chars). Received: ${JSON.stringify(env)}`);
|
|
118
|
-
}
|
|
119
105
|
if (apiKey === undefined) {
|
|
120
106
|
throw new Error("[to11ai/sdk] An `apiKey` (or `TO11_API_KEY`) is required.");
|
|
121
107
|
}
|
|
@@ -134,51 +120,11 @@ function createClient(options = {}) {
|
|
|
134
120
|
onUnknownRole: options.onUnknownRole
|
|
135
121
|
});
|
|
136
122
|
const projectEnvironments = new import_resource.ProjectEnvironmentResource(transport);
|
|
137
|
-
const usage = new import_resource3.UsageResource(transport);
|
|
138
|
-
const gatewayAuthContext = () => {
|
|
139
|
-
if (projectId === undefined) {
|
|
140
|
-
throw new Error("[to11ai/sdk] session()/turn() need a `projectId` (or `TO11_PROJECT_ID`).");
|
|
141
|
-
}
|
|
142
|
-
return env !== undefined ? { apiKey, projectId, env } : { apiKey, projectId };
|
|
143
|
-
};
|
|
144
|
-
let defaultSession;
|
|
145
|
-
const clientDefaultSession = () => {
|
|
146
|
-
if (defaultSession === undefined) {
|
|
147
|
-
defaultSession = new import_context.Session(gatewayAuthContext());
|
|
148
|
-
}
|
|
149
|
-
return defaultSession;
|
|
150
|
-
};
|
|
151
|
-
const gatewayClientOptions = (defaultBaseURL, overrides) => {
|
|
152
|
-
if (projectId === undefined) {
|
|
153
|
-
throw new Error("[to11ai/sdk] openaiOptions()/anthropicOptions() need a `projectId` (or `TO11_PROJECT_ID`) — it authenticates the gateway call via `x-to11-project-id`.");
|
|
154
|
-
}
|
|
155
|
-
const authHeaders = import_gateway.gatewayAuthHeaders(env !== undefined ? { apiKey, projectId, env } : { apiKey, projectId });
|
|
156
|
-
const {
|
|
157
|
-
apiKey: overrideApiKey,
|
|
158
|
-
baseURL: overrideBaseURL,
|
|
159
|
-
defaultHeaders: overrideHeaders,
|
|
160
|
-
...passthrough
|
|
161
|
-
} = overrides ?? {};
|
|
162
|
-
return {
|
|
163
|
-
...passthrough,
|
|
164
|
-
baseURL: overrideBaseURL ?? defaultBaseURL,
|
|
165
|
-
apiKey: overrideApiKey ?? providerApiKey ?? apiKey,
|
|
166
|
-
defaultHeaders: { ...authHeaders, ...overrideHeaders }
|
|
167
|
-
};
|
|
168
|
-
};
|
|
169
123
|
return {
|
|
170
124
|
prompts,
|
|
171
125
|
projectEnvironments,
|
|
172
|
-
usage,
|
|
173
126
|
apiKey,
|
|
174
127
|
baseUrl,
|
|
175
|
-
|
|
176
|
-
projectId,
|
|
177
|
-
env,
|
|
178
|
-
session: (id) => new import_context.Session(gatewayAuthContext(), id),
|
|
179
|
-
conversation: (id) => clientDefaultSession().conversation(id),
|
|
180
|
-
turn: () => clientDefaultSession().turn(),
|
|
181
|
-
openaiOptions: (overrides) => gatewayClientOptions(`${gatewayUrl}/v1`, overrides),
|
|
182
|
-
anthropicOptions: (overrides) => gatewayClientOptions(gatewayUrl, overrides)
|
|
128
|
+
projectId
|
|
183
129
|
};
|
|
184
130
|
}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,65 +1,36 @@
|
|
|
1
|
-
import { type Conversation, Session, type Turn } from "./context";
|
|
2
1
|
import { ProjectEnvironmentResource } from "./projectEnvironments/resource";
|
|
3
2
|
import { PromptResource } from "./prompts/resource";
|
|
4
|
-
import {
|
|
5
|
-
import { UsageResource } from "./usage/resource";
|
|
6
|
-
export type { TurnAuthContext } from "./context";
|
|
7
|
-
export { Conversation, Session, Turn } from "./context";
|
|
3
|
+
import type { RenderFormat, UnknownRoleMode } from "./prompts/types";
|
|
8
4
|
export type { PromptHasNoVersionsReason, PromptNotFoundReason, PromptPolicyViolationReason, } from "./errors";
|
|
9
5
|
export { LabelNotFoundError, PromptHasNoVersionsError, PromptNotFoundError, PromptPolicyViolationError, To11aiApiError, To11aiAuthError, To11aiError, To11aiNetworkError, To11aiRateLimitError, To11aiValidationError, UnknownRoleError, } from "./errors";
|
|
10
|
-
export type { ConvertMessagesOptions, GatewayAuthOptions } from "./gateway";
|
|
11
|
-
export { gatewayAuthHeaders, gatewayPromptHeaders } from "./gateway";
|
|
12
6
|
export type { CursorPaginatedResult, CursorPaginationInfo, FetchCursorPage, } from "./pagination";
|
|
13
7
|
export { iterateCursorItems, iterateCursorPages } from "./pagination";
|
|
14
8
|
export type { ArchiveProjectEnvironmentInput, ArchiveProjectEnvironmentResult, CreateProjectEnvironmentInput, CreateProjectEnvironmentResult, GetProjectEnvironmentInput, GetProjectEnvironmentResult, ListProjectEnvironmentsInput, ListProjectEnvironmentsResult, ProjectEnvironment, RestoreProjectEnvironmentInput, RestoreProjectEnvironmentResult, UpdateProjectEnvironmentInput, UpdateProjectEnvironmentResult, } from "./projectEnvironments/resource";
|
|
15
9
|
export { ProjectEnvironmentResource } from "./projectEnvironments/resource";
|
|
10
|
+
export type { AnthropicContentBlock, AnthropicMessage, AnthropicTool, AnthropicToolChoice, ConvertMessagesOptions, OpenAIChatMessage, OpenAITool, OpenAIToolCall, OpenAIToolChoice, } from "./prompts/convert";
|
|
11
|
+
export { toAnthropicMessages, toAnthropicSystem, toAnthropicToolChoice, toAnthropicTools, toOpenAIMessages, toOpenAIToolChoice, toOpenAITools, } from "./prompts/convert";
|
|
16
12
|
export type { PromptResourceConfig } from "./prompts/resource";
|
|
17
13
|
export { PromptResource } from "./prompts/resource";
|
|
18
14
|
export type { AnthropicRenderedPrompt, OpenAiRenderedPrompt, PromptConfig, PromptMetadata, RenderResult, } from "./prompts/shape";
|
|
19
15
|
export type { BlockRenderRecord, RenderedChatMessage, RenderedPrompt, RenderFormat, RenderOptions, UnknownRoleMode, } from "./prompts/types";
|
|
20
16
|
export { ENV_SLUG_REGEX } from "./prompts/types";
|
|
21
|
-
export { UsageResource } from "./usage/resource";
|
|
22
17
|
export interface ClientOptions {
|
|
23
18
|
/**
|
|
24
19
|
* Control-plane base URL. Precedence: this option → `TO11_API_URL` env →
|
|
25
20
|
* `https://api.to11.ai`.
|
|
26
21
|
*/
|
|
27
22
|
baseUrl?: string;
|
|
28
|
-
/**
|
|
29
|
-
* Data-plane gateway URL (the app's provider-client `baseURL`). Precedence:
|
|
30
|
-
* this option → `TO11_GATEWAY_URL` env → `https://gw.to11.ai`.
|
|
31
|
-
*/
|
|
32
|
-
gatewayUrl?: string;
|
|
33
23
|
/**
|
|
34
24
|
* API key for server-side use (server, CLI, backend job). Precedence: this
|
|
35
25
|
* option → `TO11_API_KEY` env. Required. Rejected in browser contexts — a
|
|
36
|
-
* to11 API key
|
|
26
|
+
* to11 API key must never ship in client code.
|
|
37
27
|
*/
|
|
38
28
|
apiKey?: string;
|
|
39
|
-
/**
|
|
40
|
-
* Provider API key (BYOK) carried by `openaiOptions()` / `anthropicOptions()`
|
|
41
|
-
* as the provider client's `apiKey`, so a BYOK call is a single
|
|
42
|
-
* `new OpenAI(to11.openaiOptions())`. When omitted, those helpers fall back to
|
|
43
|
-
* the to11 `apiKey` as a placeholder (the managed / server-side-credential
|
|
44
|
-
* path). Option only — no env fallback. Whether the gateway actually uses this
|
|
45
|
-
* key depends on the provider's passthrough mode; otherwise the project's
|
|
46
|
-
* stored credential wins.
|
|
47
|
-
*/
|
|
48
|
-
providerApiKey?: string;
|
|
49
29
|
/**
|
|
50
30
|
* Project the client is bound to. Precedence: this option → `TO11_PROJECT_ID`
|
|
51
|
-
* env. Required for `prompts.render()
|
|
31
|
+
* env. Required for `prompts.render()`.
|
|
52
32
|
*/
|
|
53
33
|
projectId?: string;
|
|
54
|
-
/**
|
|
55
|
-
* Gateway environment, sent as `x-to11-env` by `turn().headers()` and the
|
|
56
|
-
* `openaiOptions()` / `anthropicOptions()` tenant headers so the gateway
|
|
57
|
-
* routes the call. Precedence: this option → `TO11_ENV` env. Validated
|
|
58
|
-
* eagerly against the project-environments slug rule (`^[a-z0-9-]{1,63}$`).
|
|
59
|
-
* Prompts are not environment-scoped: `prompts.render()` serves `latest`
|
|
60
|
-
* regardless of `env`.
|
|
61
|
-
*/
|
|
62
|
-
env?: string;
|
|
63
34
|
/**
|
|
64
35
|
* Default provider shape for `prompts.render()` output (`"openai"` |
|
|
65
36
|
* `"anthropic"`). Omit for the neutral result. Per-call override allowed.
|
|
@@ -77,106 +48,39 @@ export interface ClientOptions {
|
|
|
77
48
|
/** Max retry attempts for network errors / 5xx. Default: 3 */
|
|
78
49
|
maxRetries?: number;
|
|
79
50
|
}
|
|
80
|
-
/**
|
|
81
|
-
* Overrides accepted by `openaiOptions()` / `anthropicOptions()`. The three
|
|
82
|
-
* known fields are merged (`apiKey` / `baseURL` override; `defaultHeaders`
|
|
83
|
-
* shallow-merges over the tenant-auth headers, caller wins); any other keys —
|
|
84
|
-
* `timeout`, `maxRetries`, `fetch`, … — pass through untouched to the provider
|
|
85
|
-
* client, so `new OpenAI(to11.openaiOptions({ apiKey, timeout }))` needs no
|
|
86
|
-
* outer spread.
|
|
87
|
-
*/
|
|
88
|
-
export interface ProviderClientOverrides {
|
|
89
|
-
apiKey?: string;
|
|
90
|
-
baseURL?: string;
|
|
91
|
-
defaultHeaders?: Record<string, string>;
|
|
92
|
-
}
|
|
93
|
-
/**
|
|
94
|
-
* The spread-ready result of `openaiOptions()` / `anthropicOptions()`: the three
|
|
95
|
-
* managed fields plus whatever passthrough keys the caller supplied (their types
|
|
96
|
-
* preserved), so it drops straight into `new OpenAI(...)` / `new Anthropic(...)`.
|
|
97
|
-
*/
|
|
98
|
-
export type ProviderClientOptions<T extends ProviderClientOverrides = ProviderClientOverrides> = Omit<T, "apiKey" | "baseURL" | "defaultHeaders"> & {
|
|
99
|
-
baseURL: string;
|
|
100
|
-
apiKey: string;
|
|
101
|
-
defaultHeaders: Record<string, string>;
|
|
102
|
-
};
|
|
103
51
|
export interface To11aiClient<F extends RenderFormat | undefined = undefined> {
|
|
104
52
|
readonly prompts: PromptResource<F>;
|
|
105
53
|
readonly projectEnvironments: ProjectEnvironmentResource;
|
|
106
|
-
/** Org usage reads: members, sessions, costs and top traces (`orgId` per call). */
|
|
107
|
-
readonly usage: UsageResource;
|
|
108
54
|
/** Resolved API key (option → `TO11_API_KEY`). */
|
|
109
55
|
readonly apiKey: string;
|
|
110
56
|
/** Resolved control-plane base URL (option → `TO11_API_URL` → default). */
|
|
111
57
|
readonly baseUrl: string;
|
|
112
|
-
/** Resolved data-plane gateway URL (option → `TO11_GATEWAY_URL` → default). */
|
|
113
|
-
readonly gatewayUrl: string;
|
|
114
58
|
/**
|
|
115
59
|
* Resolved project id (option → `TO11_PROJECT_ID`); `undefined` when none is
|
|
116
|
-
* configured. Read-only, for your own logging
|
|
117
|
-
*
|
|
60
|
+
* configured. Read-only, for your own logging — `prompts.*` already default
|
|
61
|
+
* to it, so you don't need to pass it back into calls.
|
|
118
62
|
*/
|
|
119
63
|
readonly projectId: string | undefined;
|
|
120
|
-
/**
|
|
121
|
-
* Resolved gateway environment (option → `TO11_ENV`); `undefined` when none
|
|
122
|
-
* is configured. The gateway helpers already send it as `x-to11-env`.
|
|
123
|
-
*/
|
|
124
|
-
readonly env: string | undefined;
|
|
125
|
-
/** A new session (unit of work). Pass an id to group telemetry by your own id. */
|
|
126
|
-
session(id?: string): Session;
|
|
127
|
-
/**
|
|
128
|
-
* A conversation in the client's default session (for side / parallel agents).
|
|
129
|
-
*
|
|
130
|
-
* @example Two agents under one session
|
|
131
|
-
* const research = to11.conversation(); // a separate thread from to11.turn()'s default
|
|
132
|
-
* const res = await openai.chat.completions.create(
|
|
133
|
-
* { ...researchPrompt.config, messages },
|
|
134
|
-
* { headers: research.turn().headers(researchPrompt) },
|
|
135
|
-
* );
|
|
136
|
-
*/
|
|
137
|
-
conversation(id?: string): Conversation;
|
|
138
|
-
/** A turn in the client's default session + default conversation. */
|
|
139
|
-
turn(): Turn;
|
|
140
|
-
/**
|
|
141
|
-
* Spread-ready options for `new OpenAI(...)` targeting the gateway:
|
|
142
|
-
* `{ baseURL, apiKey, defaultHeaders }` (baseURL carries `/v1`). `defaultHeaders`
|
|
143
|
-
* holds the static tenant auth, so the client authenticates on its own; add
|
|
144
|
-
* `turn().headers(prompt)` per call for trace + prompt provenance. Pass
|
|
145
|
-
* `overrides` to change `apiKey`/`baseURL`, merge extra `defaultHeaders`, or
|
|
146
|
-
* forward any other provider-SDK option (`timeout`, …).
|
|
147
|
-
*
|
|
148
|
-
* @example
|
|
149
|
-
* const openai = new OpenAI(to11.openaiOptions());
|
|
150
|
-
* @example BYOK + a provider-SDK option, no outer spread
|
|
151
|
-
* const openai = new OpenAI(to11.openaiOptions({ apiKey: MY_KEY, timeout: 60_000 }));
|
|
152
|
-
*/
|
|
153
|
-
openaiOptions<T extends ProviderClientOverrides = ProviderClientOverrides>(overrides?: T): ProviderClientOptions<T>;
|
|
154
|
-
/**
|
|
155
|
-
* Spread-ready options for `new Anthropic(...)` targeting the gateway root
|
|
156
|
-
* (the Anthropic SDK appends `/v1/messages` itself). Same shape and merge
|
|
157
|
-
* rules as {@link To11aiClient.openaiOptions}.
|
|
158
|
-
*/
|
|
159
|
-
anthropicOptions<T extends ProviderClientOverrides = ProviderClientOverrides>(overrides?: T): ProviderClientOptions<T>;
|
|
160
64
|
}
|
|
161
65
|
/**
|
|
162
66
|
* Create a to11ai SDK client. Resolution precedence differs per option:
|
|
163
|
-
* -
|
|
67
|
+
* - `baseUrl` — option → `TO11_API_URL` → built-in default.
|
|
164
68
|
* - `apiKey` / `projectId` — option → env var (no default).
|
|
165
|
-
* - `
|
|
69
|
+
* - `format` / `onUnknownRole` — option only.
|
|
166
70
|
* Authenticate with `apiKey` (or `TO11_API_KEY`) — required, and server-side
|
|
167
71
|
* only (server, CLI, backend job); constructing with `apiKey` in a browser throws.
|
|
168
72
|
*
|
|
169
|
-
* @example
|
|
73
|
+
* @example Render a prompt and send it with your own provider client
|
|
170
74
|
* import { createClient } from "@to11ai/sdk";
|
|
171
75
|
* import OpenAI from "openai";
|
|
172
76
|
*
|
|
173
|
-
* const to11 = createClient({
|
|
174
|
-
* const openai = new OpenAI(
|
|
77
|
+
* const to11 = createClient({ format: "openai" });
|
|
78
|
+
* const openai = new OpenAI();
|
|
175
79
|
* const prompt = await to11.prompts.render("weather-concierge", { variables: { city: "NYC" } });
|
|
176
|
-
* const res = await openai.chat.completions.create(
|
|
177
|
-
*
|
|
178
|
-
*
|
|
179
|
-
* );
|
|
80
|
+
* const res = await openai.chat.completions.create({
|
|
81
|
+
* ...prompt.config,
|
|
82
|
+
* messages: prompt.messages,
|
|
83
|
+
* });
|
|
180
84
|
*/
|
|
181
85
|
export declare function createClient<const F extends RenderFormat | undefined = undefined>(options?: Omit<ClientOptions, "format"> & {
|
|
182
86
|
format?: F;
|