@to11ai/sdk 3.1.0-rc → 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.
Files changed (51) hide show
  1. package/README.md +30 -42
  2. package/dist/behaviors/store.d.ts +1 -1
  3. package/dist/client.cjs +17 -71
  4. package/dist/client.d.ts +16 -112
  5. package/dist/client.js +22 -72
  6. package/dist/config.d.ts +3 -6
  7. package/dist/errors.cjs +0 -72
  8. package/dist/errors.d.ts +0 -77
  9. package/dist/errors.js +0 -72
  10. package/dist/generated/index.d.ts +1 -1
  11. package/dist/generated/types.gen.d.ts +2962 -17155
  12. package/dist/generated/zod.gen.d.ts +2576 -11477
  13. package/dist/projectEnvironments/resource.cjs +0 -2
  14. package/dist/projectEnvironments/resource.d.ts +3 -12
  15. package/dist/projectEnvironments/resource.js +0 -2
  16. package/dist/projectEnvironments/types.d.ts +0 -2
  17. package/dist/{gateway.d.ts → prompts/convert.d.ts} +12 -75
  18. package/dist/prompts/resource.d.ts +7 -7
  19. package/dist/prompts/shape.d.ts +4 -5
  20. package/dist/prompts/types.d.ts +5 -17
  21. package/package.json +7 -24
  22. package/src/behaviors/store.ts +1 -1
  23. package/src/client.ts +36 -242
  24. package/src/config.ts +3 -9
  25. package/src/errors.ts +0 -132
  26. package/src/generated/index.ts +1 -1
  27. package/src/generated/types.gen.ts +2889 -17652
  28. package/src/generated/zod.gen.ts +1980 -9967
  29. package/src/projectEnvironments/resource.ts +3 -14
  30. package/src/projectEnvironments/types.ts +0 -2
  31. package/src/{gateway.ts → prompts/convert.ts} +18 -152
  32. package/src/prompts/resource.ts +10 -12
  33. package/src/prompts/shape.ts +4 -5
  34. package/src/prompts/types.ts +5 -17
  35. package/src/transport.ts +0 -133
  36. package/dist/context.d.ts +0 -124
  37. package/dist/gateway.cjs +0 -264
  38. package/dist/gateway.js +0 -226
  39. package/dist/routingRules/resource.d.ts +0 -64
  40. package/dist/routingRules/types.d.ts +0 -88
  41. package/dist/traceparent.d.ts +0 -61
  42. package/dist/usage/resource.cjs +0 -113
  43. package/dist/usage/resource.d.ts +0 -29
  44. package/dist/usage/resource.js +0 -78
  45. package/dist/usage/types.d.ts +0 -81
  46. package/src/context.ts +0 -196
  47. package/src/routingRules/resource.ts +0 -261
  48. package/src/routingRules/types.ts +0 -120
  49. package/src/traceparent.ts +0 -189
  50. package/src/usage/resource.ts +0 -183
  51. package/src/usage/types.ts +0 -121
@@ -1,88 +0,0 @@
1
- import type { RuleModelBinding as GenRuleModelBinding, RuleProviderRef as GenRuleProviderRef, RuleRelease as GenRuleRelease, RuleReleaseWeight as GenRuleReleaseWeight, RuleSnapshot as GenRuleSnapshot, RuleVersion as GenRuleVersion } from "../generated/types.gen";
2
- import type { CursorPaginatedResult } from "../pagination";
3
- export type RuleProviderRef = GenRuleProviderRef;
4
- export type RuleModelBinding = GenRuleModelBinding;
5
- export type RuleStrategy = GenRuleSnapshot["strategy"];
6
- export type RuleSnapshot = GenRuleSnapshot;
7
- export type RuleVersion = GenRuleVersion;
8
- export interface CreateRuleVersionInput {
9
- projectId: string;
10
- ruleId: string;
11
- snapshot: RuleSnapshot | unknown;
12
- description?: string;
13
- }
14
- export type CreateRuleVersionResult = RuleVersion;
15
- /**
16
- * Input of `versions.list()`. `cursor` is the previous page's
17
- * `pagination.nextCursor`; `limit` is the page size (the server clamps it
18
- * into 1..100 and defaults to 50).
19
- */
20
- export interface ListRuleVersionsInput {
21
- projectId: string;
22
- ruleId: string;
23
- cursor?: string;
24
- limit?: number;
25
- }
26
- /**
27
- * Input of `versions.iterate()`: `versions.list()` without `cursor`, which the
28
- * iterator manages. `limit` is the page size of each request.
29
- */
30
- export type IterateRuleVersionsInput = Omit<ListRuleVersionsInput, "cursor">;
31
- /**
32
- * One page of a rule's versions, newest first (`version` descending):
33
- * `{ items, pagination: { nextCursor, limit } }`.
34
- */
35
- export type ListRuleVersionsResult = CursorPaginatedResult<RuleVersion>;
36
- export interface GetRuleVersionInput {
37
- projectId: string;
38
- ruleId: string;
39
- versionId: string;
40
- }
41
- export type GetRuleVersionResult = RuleVersion;
42
- export type RuleReleaseStrategy = GenRuleRelease["strategy"];
43
- export type RuleReleaseChangeKind = GenRuleRelease["changeKind"];
44
- export type RuleReleaseApprovalStatus = GenRuleRelease["approvalStatus"];
45
- export type RuleReleaseActorType = GenRuleRelease["actorType"];
46
- export type RuleReleaseWeight = GenRuleReleaseWeight;
47
- export type RuleRelease = GenRuleRelease;
48
- export interface SetRuleReleaseInput {
49
- projectId: string;
50
- ruleId: string;
51
- envSlug: string;
52
- strategy: RuleReleaseStrategy;
53
- versionId?: string;
54
- weights?: RuleReleaseWeight[];
55
- reason?: string;
56
- }
57
- export type SetRuleReleaseResult = RuleRelease;
58
- export interface RollbackRuleReleaseInput {
59
- projectId: string;
60
- ruleId: string;
61
- envSlug: string;
62
- reason: string;
63
- targetReleaseId?: string;
64
- }
65
- export type RollbackRuleReleaseResult = RuleRelease;
66
- /**
67
- * Input of `releases.list()`. Without `envSlug` the call lists the rule's
68
- * releases across every environment; with it, one environment's. `cursor` is
69
- * the previous page's `pagination.nextCursor`; `limit` is the page size (the
70
- * server clamps it into 1..100 and defaults to 50).
71
- */
72
- export interface ListRuleReleasesInput {
73
- projectId: string;
74
- ruleId: string;
75
- envSlug?: string;
76
- cursor?: string;
77
- limit?: number;
78
- }
79
- /**
80
- * Input of `releases.iterate()`: `releases.list()` without `cursor`, which the
81
- * iterator manages. `limit` is the page size of each request.
82
- */
83
- export type IterateRuleReleasesInput = Omit<ListRuleReleasesInput, "cursor">;
84
- /**
85
- * One page of a rule's releases, newest first:
86
- * `{ items, pagination: { nextCursor, limit } }`.
87
- */
88
- export type ListRuleReleasesResult = CursorPaginatedResult<RuleRelease>;
@@ -1,61 +0,0 @@
1
- /**
2
- * W3C Trace Context propagation for outbound SDK calls.
3
- *
4
- * Reads the host process's active OpenTelemetry span — if any — and formats a
5
- * W3C `traceparent` (and optional `tracestate`) string for injection as
6
- * outbound HTTP headers. Lets customers correlate their tracer's spans with
7
- * the gateway-emitted span we record.
8
- *
9
- * Design constraints (from TO11-1016 / S8c spec):
10
- * 1. NO runtime dependency on `@opentelemetry/api`. The package is detected
11
- * at runtime via a try/require shim; if it is not loadable, this module
12
- * is a strict no-op and `activeTraceContext()` returns `null`.
13
- * 2. NO SDK config surface change. There is no constructor option or env
14
- * var; behavior is invisible if the host has no OTel installed.
15
- * 3. Header omitted, not zero-filled — W3C §3.2.2.5 forbids all-zero
16
- * trace/span ids in `traceparent`. We return `null` (caller omits).
17
- *
18
- * @see https://www.w3.org/TR/trace-context/ for the wire format.
19
- * @see docs/archive-2026-08/specs/2026-05-20-to11-1016-sdk-traceparent-propagation.md
20
- */
21
- interface OtelTraceState {
22
- serialize(): string;
23
- }
24
- interface OtelSpanContext {
25
- traceId: string;
26
- spanId: string;
27
- traceFlags: number;
28
- traceState?: OtelTraceState;
29
- }
30
- interface OtelSpan {
31
- spanContext(): OtelSpanContext;
32
- }
33
- interface OtelTrace {
34
- getActiveSpan(): OtelSpan | undefined;
35
- }
36
- interface OtelApi {
37
- trace: OtelTrace;
38
- }
39
- type OtelLoader = () => OtelApi | null;
40
- /**
41
- * Return the W3C `traceparent` (and optional `tracestate`) string pair for
42
- * the currently active OpenTelemetry span in the host process, or `null` if
43
- * no active span exists or `@opentelemetry/api` is not installed.
44
- *
45
- * Idempotent and side-effect-free past the one-time module probe. Callers
46
- * inject the returned strings as outbound HTTP headers when non-null.
47
- */
48
- export declare function activeTraceContext(): {
49
- traceparent: string;
50
- tracestate?: string;
51
- } | null;
52
- /**
53
- * Test-only seam: install a deterministic OTel loader and reset the
54
- * module-level cache. Underscore-prefixed and intentionally NOT re-exported
55
- * from the package entry-point.
56
- *
57
- * Production code never calls this. Tests call it to simulate
58
- * "OTel installed" / "OTel absent" / "broken OTel install" cells.
59
- */
60
- export declare function _loadOtelForTests(injected: OtelLoader | undefined): void;
61
- export {};
@@ -1,113 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- function __accessProp(key) {
6
- return this[key];
7
- }
8
- var __toCommonJS = (from) => {
9
- var entry = (__moduleCache ??= new WeakMap).get(from), desc;
10
- if (entry)
11
- return entry;
12
- entry = __defProp({}, "__esModule", { value: true });
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (var key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(entry, key))
16
- __defProp(entry, key, {
17
- get: __accessProp.bind(from, key),
18
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
- });
20
- }
21
- __moduleCache.set(from, entry);
22
- return entry;
23
- };
24
- var __moduleCache;
25
- var __returnValue = (v) => v;
26
- function __exportSetter(name, newValue) {
27
- this[name] = __returnValue.bind(null, newValue);
28
- }
29
- var __export = (target, all) => {
30
- for (var name in all)
31
- __defProp(target, name, {
32
- get: all[name],
33
- enumerable: true,
34
- configurable: true,
35
- set: __exportSetter.bind(all, name)
36
- });
37
- };
38
-
39
- // src/usage/resource.ts
40
- var exports_resource = {};
41
- __export(exports_resource, {
42
- UsageResource: () => UsageResource
43
- });
44
- module.exports = __toCommonJS(exports_resource);
45
- var import_errors = require("../errors");
46
- var import_zod = require("../generated/zod.gen");
47
- var principalsData = import_zod.zUsageListUsagePrincipalsResponse.shape.data.unwrap();
48
- var sessionsData = import_zod.zUsageListUsageSessionsResponse.shape.data.unwrap();
49
- var costsData = import_zod.zUsageGetUsageCostsResponse.shape.data.unwrap();
50
- var topTracesData = import_zod.zUsageListTopTracesResponse.shape.data.unwrap();
51
- function unwrap(envelope) {
52
- if (envelope.data === null || envelope.data === undefined) {
53
- throw new Error("API returned success but data is null");
54
- }
55
- return envelope.data;
56
- }
57
- function orgPath(orgId, rest) {
58
- return `/v1/orgs/${encodeURIComponent(orgId)}/${rest}`;
59
- }
60
- function windowQuery(window) {
61
- if ("from" in window)
62
- return { from: window.from, to: window.to };
63
- return { preset: window.preset, n: window.n, timezone: window.timezone };
64
- }
65
- function principalsQuery(input) {
66
- const { query } = input;
67
- if (typeof query === "string")
68
- return { query };
69
- throw new import_errors.To11aiValidationError("[to11ai/sdk] findPrincipals() needs `query`", "invalid_principal_lookup", { query: false });
70
- }
71
-
72
- class UsageResource {
73
- transport;
74
- constructor(transport) {
75
- this.transport = transport;
76
- }
77
- async findPrincipals(input) {
78
- const query = principalsQuery(input);
79
- const envelope = await this.transport.request("GET", orgPath(input.orgId, "usage/principals"), {
80
- query,
81
- decode: (data) => principalsData.parse(data)
82
- });
83
- return unwrap(envelope);
84
- }
85
- async listSessions(input) {
86
- const { orgId, window, ...filters } = input;
87
- const envelope = await this.transport.request("GET", orgPath(orgId, "usage/sessions"), {
88
- query: { ...windowQuery(window), ...filters },
89
- decode: (data) => sessionsData.parse(data)
90
- });
91
- return unwrap(envelope);
92
- }
93
- async getCosts(input) {
94
- const { orgId, window, groupBy, ...filters } = input;
95
- const envelope = await this.transport.request("GET", orgPath(orgId, "usage/costs"), {
96
- query: {
97
- ...windowQuery(window),
98
- groupBy: typeof groupBy === "string" ? [groupBy] : groupBy,
99
- ...filters
100
- },
101
- decode: (data) => costsData.parse(data)
102
- });
103
- return unwrap(envelope);
104
- }
105
- async listTopTraces(input) {
106
- const { orgId, window, ...filters } = input;
107
- const envelope = await this.transport.request("GET", orgPath(orgId, "traces/top"), {
108
- query: { ...windowQuery(window), ...filters },
109
- decode: (data) => topTracesData.parse(data)
110
- });
111
- return unwrap(envelope);
112
- }
113
- }
@@ -1,29 +0,0 @@
1
- import type { Transport } from "../transport";
2
- import type { FindPrincipalsInput, FindPrincipalsResult, GetCostsInput, GetCostsResult, ListSessionsInput, ListSessionsResult, ListTopTracesInput, ListTopTracesResult } from "./types";
3
- export type { CostGroup, CostGroupBy, FindPrincipalsInput, FindPrincipalsResult, GetCostsInput, GetCostsResult, ListSessionsInput, ListSessionsResult, ListTopTracesInput, ListTopTracesResult, ResolvedUsageWindow, TopTrace, TopTraceStatus, TopTracesSort, UsageBillingMode, UsageExcludedProject, UsagePrincipal, UsageRunRow, UsageSessionRow, UsageSessionsGroupBy, UsageWindow, UsageWindowPreset, } from "./types";
4
- /**
5
- * SDK resource for the organization usage reads. Constructed by
6
- * `createClient` and exposed as `client.usage`.
7
- */
8
- export declare class UsageResource {
9
- private readonly transport;
10
- constructor(transport: Transport);
11
- /**
12
- * Members of the organization by name (`query`), as
13
- * `{ principalId, displayName }`. Pass a `principalId` to the other reads.
14
- */
15
- findPrincipals(input: FindPrincipalsInput): Promise<FindPrincipalsResult>;
16
- /**
17
- * Sessions (or runs, with `groupBy: "run"`) with usage in the window, one
18
- * page at a time, plus totals over all of them and the usage outside any
19
- * session. Pass `pagination.nextCursor` back as `cursor` until it is `null`.
20
- */
21
- listSessions(input: ListSessionsInput): Promise<ListSessionsResult>;
22
- /**
23
- * Billed cost and API-price equivalent in the window, grouped by up to six
24
- * keys (`groupBy`), with totals and a per-billing-mode split.
25
- */
26
- getCosts(input: GetCostsInput): Promise<GetCostsResult>;
27
- /** The slowest, costliest, or largest traces in the window (at most 60 days). */
28
- listTopTraces(input: ListTopTracesInput): Promise<ListTopTracesResult>;
29
- }
@@ -1,78 +0,0 @@
1
- // src/usage/resource.ts
2
- import { To11aiValidationError } from "../errors";
3
- import {
4
- zUsageGetUsageCostsResponse,
5
- zUsageListTopTracesResponse,
6
- zUsageListUsagePrincipalsResponse,
7
- zUsageListUsageSessionsResponse
8
- } from "../generated/zod.gen";
9
- var principalsData = zUsageListUsagePrincipalsResponse.shape.data.unwrap();
10
- var sessionsData = zUsageListUsageSessionsResponse.shape.data.unwrap();
11
- var costsData = zUsageGetUsageCostsResponse.shape.data.unwrap();
12
- var topTracesData = zUsageListTopTracesResponse.shape.data.unwrap();
13
- function unwrap(envelope) {
14
- if (envelope.data === null || envelope.data === undefined) {
15
- throw new Error("API returned success but data is null");
16
- }
17
- return envelope.data;
18
- }
19
- function orgPath(orgId, rest) {
20
- return `/v1/orgs/${encodeURIComponent(orgId)}/${rest}`;
21
- }
22
- function windowQuery(window) {
23
- if ("from" in window)
24
- return { from: window.from, to: window.to };
25
- return { preset: window.preset, n: window.n, timezone: window.timezone };
26
- }
27
- function principalsQuery(input) {
28
- const { query } = input;
29
- if (typeof query === "string")
30
- return { query };
31
- throw new To11aiValidationError("[to11ai/sdk] findPrincipals() needs `query`", "invalid_principal_lookup", { query: false });
32
- }
33
-
34
- class UsageResource {
35
- transport;
36
- constructor(transport) {
37
- this.transport = transport;
38
- }
39
- async findPrincipals(input) {
40
- const query = principalsQuery(input);
41
- const envelope = await this.transport.request("GET", orgPath(input.orgId, "usage/principals"), {
42
- query,
43
- decode: (data) => principalsData.parse(data)
44
- });
45
- return unwrap(envelope);
46
- }
47
- async listSessions(input) {
48
- const { orgId, window, ...filters } = input;
49
- const envelope = await this.transport.request("GET", orgPath(orgId, "usage/sessions"), {
50
- query: { ...windowQuery(window), ...filters },
51
- decode: (data) => sessionsData.parse(data)
52
- });
53
- return unwrap(envelope);
54
- }
55
- async getCosts(input) {
56
- const { orgId, window, groupBy, ...filters } = input;
57
- const envelope = await this.transport.request("GET", orgPath(orgId, "usage/costs"), {
58
- query: {
59
- ...windowQuery(window),
60
- groupBy: typeof groupBy === "string" ? [groupBy] : groupBy,
61
- ...filters
62
- },
63
- decode: (data) => costsData.parse(data)
64
- });
65
- return unwrap(envelope);
66
- }
67
- async listTopTraces(input) {
68
- const { orgId, window, ...filters } = input;
69
- const envelope = await this.transport.request("GET", orgPath(orgId, "traces/top"), {
70
- query: { ...windowQuery(window), ...filters },
71
- decode: (data) => topTracesData.parse(data)
72
- });
73
- return unwrap(envelope);
74
- }
75
- }
76
- export {
77
- UsageResource
78
- };
@@ -1,81 +0,0 @@
1
- import type { TopTracesResponse, UsageCostsResponse, UsageListUsageSessionsData, UsagePrincipalsResponse, UsageSessionsResponse } from "../generated/types.gen";
2
- /** A preset the server resolves in the window's `timezone`. Weeks start on Monday. */
3
- export type UsageWindowPreset = "last_n_hours" | "last_n_days" | "today" | "yesterday" | "this_week" | "last_week" | "this_month" | "last_month";
4
- /**
5
- * The time window of a usage read: absolute (`from`/`to`, ISO 8601 with a
6
- * zone offset, `[from, to)`), or a preset the server resolves in an IANA
7
- * `timezone`. `n` is required by `last_n_hours` / `last_n_days` and rejected
8
- * by the calendar presets. Every response echoes the absolute window it used.
9
- */
10
- export type UsageWindow = {
11
- readonly from: string;
12
- readonly to: string;
13
- } | {
14
- readonly preset: UsageWindowPreset;
15
- readonly n?: number;
16
- readonly timezone: string;
17
- };
18
- export type UsageBillingMode = "subscription" | "api" | "unknown";
19
- export type UsageSessionsGroupBy = NonNullable<NonNullable<UsageListUsageSessionsData["query"]>["groupBy"]>;
20
- export type CostGroupBy = "principal" | "vendor" | "provider" | "model" | "project" | "billingMode";
21
- export type TopTracesSort = TopTracesResponse["sort"];
22
- export type TopTraceStatus = TopTracesResponse["items"][number]["status"];
23
- export type FindPrincipalsResult = UsagePrincipalsResponse;
24
- export type UsagePrincipal = FindPrincipalsResult["items"][number];
25
- export type ListSessionsResult = UsageSessionsResponse;
26
- export type UsageSessionRow = NonNullable<ListSessionsResult["sessions"]>[number];
27
- export type UsageRunRow = NonNullable<ListSessionsResult["runs"]>[number];
28
- export type GetCostsResult = UsageCostsResponse;
29
- export type CostGroup = GetCostsResult["groups"][number];
30
- export type ListTopTracesResult = TopTracesResponse;
31
- export type TopTrace = ListTopTracesResult["items"][number];
32
- /** The absolute window a usage response used, plus the preset it came from. */
33
- export type ResolvedUsageWindow = GetCostsResult["window"];
34
- /** A readable project a read left out, so totals are never silently partial. */
35
- export type UsageExcludedProject = FindPrincipalsResult["excludedProjects"][number];
36
- /** Look a member up by name (`query`, matched in the API). */
37
- export type FindPrincipalsInput = {
38
- readonly orgId: string;
39
- readonly query: string;
40
- };
41
- export interface ListSessionsInput {
42
- readonly orgId: string;
43
- readonly window: UsageWindow;
44
- /** `session` (default) or `run`. */
45
- readonly groupBy?: UsageSessionsGroupBy;
46
- readonly principalId?: string;
47
- readonly projectId?: string;
48
- readonly billingMode?: UsageBillingMode;
49
- /** `pagination.nextCursor` of the previous page. */
50
- readonly cursor?: string;
51
- /** Clamped by the server into [1, 50]; default 20. */
52
- readonly limit?: number;
53
- }
54
- export interface GetCostsInput {
55
- readonly orgId: string;
56
- readonly window: UsageWindow;
57
- /** One key or several; the groups are the cross product. */
58
- readonly groupBy?: CostGroupBy | ReadonlyArray<CostGroupBy>;
59
- readonly principalId?: string;
60
- readonly vendor?: string;
61
- readonly provider?: string;
62
- readonly model?: string;
63
- readonly projectId?: string;
64
- readonly billingMode?: UsageBillingMode;
65
- /** 1–50; default 10. Groups beyond it count in `totals` and `otherGroups`. */
66
- readonly limit?: number;
67
- }
68
- export interface ListTopTracesInput {
69
- readonly orgId: string;
70
- /** At most 60 days. */
71
- readonly window: UsageWindow;
72
- readonly sort: TopTracesSort;
73
- readonly principalId?: string;
74
- readonly projectId?: string;
75
- readonly vendor?: string;
76
- readonly provider?: string;
77
- readonly model?: string;
78
- readonly status?: TopTraceStatus;
79
- /** 1–20; default 10. */
80
- readonly limit?: number;
81
- }
package/src/context.ts DELETED
@@ -1,196 +0,0 @@
1
- /**
2
- * Observability context — the `session → conversation → turn` hierarchy that
3
- * maps onto to11's telemetry grouping (Session → Conversation → Turn →
4
- * LLM-Call). Each level provides a lazy default for the level below; explicit
5
- * control is opt-in per use case. See
6
- * docs/archive-2026-08/specs/2026-07-14-to11-2691-sdk-simpler-setup.md.
7
- *
8
- * Header-only: `turn.headers(prompt?)` returns a plain object the caller applies
9
- * to their own provider client. It never sends a request.
10
- */
11
-
12
- import {
13
- type GatewayPromptProvenance,
14
- gatewayAuthHeaders,
15
- gatewayPromptHeaders,
16
- } from "./gateway";
17
-
18
- /** Auth/config the client hands to the context for gateway header building. */
19
- export interface TurnAuthContext {
20
- readonly apiKey: string;
21
- readonly projectId: string;
22
- readonly env?: string;
23
- }
24
-
25
- /**
26
- * A prompt argument accepted by `turn.headers()`. Either the flat provenance
27
- * (a neutral `RenderedPrompt`) or a `format`-shaped result carrying it under
28
- * `metadata` — both are accepted so the format and neutral render paths carry
29
- * provenance identically.
30
- */
31
- export type PromptForHeaders =
32
- | GatewayPromptProvenance
33
- | { metadata: GatewayPromptProvenance };
34
-
35
- function randomHex(bytes: number): string {
36
- const buf = new Uint8Array(bytes);
37
- crypto.getRandomValues(buf);
38
- let out = "";
39
- for (const b of buf) out += b.toString(16).padStart(2, "0");
40
- return out;
41
- }
42
-
43
- /** A fresh, sampled W3C `traceparent` (`00-<32hex>-<16hex>-01`). */
44
- function newTraceparent(): string {
45
- return `00-${randomHex(16)}-${randomHex(8)}-01`;
46
- }
47
-
48
- function newId(): string {
49
- return crypto.randomUUID();
50
- }
51
-
52
- /**
53
- * One agent turn — a single trace. A turn's `traceparent` is fixed for its
54
- * lifetime, so every LLM-call made under it groups into one trace.
55
- */
56
- export class Turn {
57
- /** The fixed W3C traceparent for this turn (one trace). */
58
- readonly traceparent: string;
59
-
60
- constructor(
61
- private readonly auth: TurnAuthContext,
62
- readonly sessionId: string,
63
- readonly conversationId: string,
64
- traceparent?: string,
65
- ) {
66
- this.traceparent = traceparent ?? newTraceparent();
67
- }
68
-
69
- /**
70
- * The complete gateway header bag: auth + session + conversation +
71
- * traceparent, plus prompt provenance when a `prompt` is supplied. A pure
72
- * read of the turn's fixed ids — reuse it across a tool-loop or call per
73
- * request; the result is identical.
74
- *
75
- * Only valid for requests targeting the gateway (`GATEWAY_URL`); it carries
76
- * the to11 API key and must never be attached to a direct provider endpoint.
77
- *
78
- * @example One call (inline turn)
79
- * const res = await openai.chat.completions.create(
80
- * { ...prompt.config, messages: prompt.messages },
81
- * { headers: to11.turn().headers(prompt) },
82
- * );
83
- *
84
- * @example Tool loop — hoist the turn so every call shares one trace
85
- * const turn = to11.turn();
86
- * const headers = turn.headers(prompt);
87
- * while (true) {
88
- * const res = await openai.chat.completions.create({ ...prompt.config, messages, tools }, { headers });
89
- * // …reuse `headers` for every call in the loop…
90
- * }
91
- */
92
- headers(prompt?: PromptForHeaders): Record<string, string> {
93
- const headers: Record<string, string> = {
94
- ...gatewayAuthHeaders({
95
- apiKey: this.auth.apiKey,
96
- projectId: this.auth.projectId,
97
- ...(this.auth.env !== undefined ? { env: this.auth.env } : {}),
98
- }),
99
- "x-to11-session-id": this.sessionId,
100
- "x-to11-conversation-id": this.conversationId,
101
- traceparent: this.traceparent,
102
- };
103
- if (prompt !== undefined) {
104
- // gatewayPromptHeaders accepts a RenderedPrompt or a format-shaped
105
- // result and unwraps `metadata` itself.
106
- Object.assign(headers, gatewayPromptHeaders(prompt));
107
- }
108
- return headers;
109
- }
110
- }
111
-
112
- /** One agent thread — a stable conversation id shared across all its turns. */
113
- export class Conversation {
114
- /** Stable conversation id, reused by every turn created from this object. */
115
- readonly id: string;
116
-
117
- constructor(
118
- private readonly auth: TurnAuthContext,
119
- readonly sessionId: string,
120
- id?: string,
121
- ) {
122
- this.id = id ?? newId();
123
- }
124
-
125
- /** Start a new turn (fresh trace) in this conversation. */
126
- turn(): Turn {
127
- return new Turn(this.auth, this.sessionId, this.id);
128
- }
129
- }
130
-
131
- /**
132
- * One unit of work. Groups conversations under a single session id. A session
133
- * lazily owns one default conversation, used by `session.turn()`; call
134
- * `session.conversation()` for additional (side/parallel) agent threads.
135
- */
136
- export class Session {
137
- /** Stable session id, carried by every conversation and turn beneath it. */
138
- readonly id: string;
139
- private defaultConversation: Conversation | undefined;
140
-
141
- constructor(
142
- private readonly auth: TurnAuthContext,
143
- id?: string,
144
- ) {
145
- this.id = id ?? newId();
146
- }
147
-
148
- /**
149
- * Create a distinct conversation (a separate agent thread) in this session.
150
- * Use this when one unit of work runs multiple agents (side / parallel
151
- * agents): each conversation gets its own `x-to11-conversation-id`, all under
152
- * the one session.
153
- *
154
- * @example Multiple agents in one session
155
- * const session = to11.session();
156
- * const main = session.conversation(); // main agent thread
157
- * const research = session.conversation(); // separate research thread, same session
158
- *
159
- * await openai.chat.completions.create(
160
- * { ...mainPrompt.config, messages: mainMessages },
161
- * { headers: main.turn().headers(mainPrompt) },
162
- * );
163
- * await openai.chat.completions.create(
164
- * { ...researchPrompt.config, messages: researchMessages },
165
- * { headers: research.turn().headers(researchPrompt) },
166
- * );
167
- */
168
- conversation(id?: string): Conversation {
169
- return new Conversation(this.auth, this.id, id);
170
- }
171
-
172
- /**
173
- * Start a turn in the session's single implicit conversation. The default
174
- * conversation is created lazily on first call and reused, so consecutive
175
- * `session.turn()` calls share one `x-to11-conversation-id` (each with its
176
- * own `traceparent`).
177
- *
178
- * @example Multi-turn chat — every turn shares the session's conversation
179
- * const session = to11.session();
180
- * for await (const input of inputs) {
181
- * messages.push({ role: "user", content: input });
182
- * const turn = session.turn(); // fresh trace, same conversation id
183
- * const res = await openai.chat.completions.create(
184
- * { ...prompt.config, messages },
185
- * { headers: turn.headers(prompt) },
186
- * );
187
- * messages.push(res.choices[0].message);
188
- * }
189
- */
190
- turn(): Turn {
191
- if (this.defaultConversation === undefined) {
192
- this.defaultConversation = this.conversation();
193
- }
194
- return this.defaultConversation.turn();
195
- }
196
- }