@to11ai/sdk 3.0.0-rc.16 → 3.0.0-rc.18

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.
@@ -1,7 +1,13 @@
1
- import { To11aiApiError, To11aiNetworkError } from "../errors";
2
1
  import {
2
+ To11aiApiError,
3
+ To11aiNetworkError,
4
+ To11aiValidationError,
5
+ } from "../errors";
6
+ import {
7
+ zOrgPromptsListOrgPromptsResponse,
3
8
  zPromptsListPromptLabelsResponse,
4
9
  zPromptsListPromptVersionsResponse,
10
+ zPromptsRenderSkillVersionResponse,
5
11
  zResolvedPrompt,
6
12
  } from "../generated/zod.gen";
7
13
  import { iterateCursorItems } from "../pagination";
@@ -25,6 +31,8 @@ import type {
25
31
  GetPromptVersionResult,
26
32
  IterateLabelsInput,
27
33
  IterateVersionsInput,
34
+ ListOrgPromptsInput,
35
+ ListOrgPromptsResult,
28
36
  ListPromptLabelsInput,
29
37
  ListPromptLabelsResult,
30
38
  ListPromptsInput,
@@ -36,8 +44,10 @@ import type {
36
44
  PromptVersionSummary,
37
45
  RenderedChatMessage,
38
46
  RenderedPrompt,
47
+ RenderedSkillVersion,
39
48
  RenderFormat,
40
49
  RenderOptions,
50
+ RenderSkillVersionInput,
41
51
  ResolvedPrompt,
42
52
  ResolvedPromptEnvelope,
43
53
  UnknownRoleMode,
@@ -64,12 +74,15 @@ export type {
64
74
  GetPromptVersionResult,
65
75
  IterateLabelsInput,
66
76
  IterateVersionsInput,
77
+ ListOrgPromptsInput,
78
+ ListOrgPromptsResult,
67
79
  ListPromptLabelsInput,
68
80
  ListPromptLabelsResult,
69
81
  ListPromptsInput,
70
82
  ListPromptsResult,
71
83
  ListPromptVersionsInput,
72
84
  ListPromptVersionsResult,
85
+ OrgPromptRow,
73
86
  PaginatedResult,
74
87
  PaginationInfo,
75
88
  Prompt,
@@ -80,8 +93,11 @@ export type {
80
93
  PromptVersionSummary,
81
94
  RenderedChatMessage,
82
95
  RenderedPrompt,
96
+ RenderedSkillFile,
97
+ RenderedSkillVersion,
83
98
  RenderFormat,
84
99
  RenderOptions,
100
+ RenderSkillVersionInput,
85
101
  ResolvedPrompt,
86
102
  ResolvedPromptEnvelope,
87
103
  ResolvedToolCall,
@@ -102,6 +118,8 @@ const LATEST_PROMPT_LABEL = "latest";
102
118
  // To11aiResponseValidationError instead of a TypeError while paging.
103
119
  const versionsPage = zPromptsListPromptVersionsResponse.shape.data.unwrap();
104
120
  const labelsPage = zPromptsListPromptLabelsResponse.shape.data.unwrap();
121
+ const orgPromptsData = zOrgPromptsListOrgPromptsResponse.shape.data.unwrap();
122
+ const skillVersionData = zPromptsRenderSkillVersionResponse.shape.data.unwrap();
105
123
 
106
124
  function unwrap<T>(envelope: ApiEnvelope<T>): T {
107
125
  if (envelope.data === null || envelope.data === undefined) {
@@ -206,6 +224,23 @@ function liftFallbackToRendered(
206
224
  return { ...structuredClone(fallback), slug: fallback.slug || slug };
207
225
  }
208
226
 
227
+ /**
228
+ * `encodeURIComponent` leaves `.` alone, and URL parsing resolves a `.` or
229
+ * `..` segment, so such a path param would send the request to a different
230
+ * route. Refuse it before any request is made.
231
+ */
232
+ function rejectDotSegments(params: Record<string, string>): void {
233
+ for (const [name, value] of Object.entries(params)) {
234
+ if (value === "." || value === "..") {
235
+ throw new To11aiValidationError(
236
+ `[to11ai/sdk] \`${name}\` cannot be "${value}": a path segment of only dots`,
237
+ "invalid_path_param",
238
+ { param: name },
239
+ );
240
+ }
241
+ }
242
+ }
243
+
209
244
  function getProjectPromptPath(projectId: string, promptId: string): string {
210
245
  return `${getProjectPromptsPath(projectId)}/${encodeURIComponent(promptId)}`;
211
246
  }
@@ -467,6 +502,51 @@ export class PromptResource<F extends RenderFormat | undefined = undefined> {
467
502
  );
468
503
  }
469
504
 
505
+ // ─── Org skills (TO11-3690) ───────────────────────────────────────────────
506
+
507
+ /**
508
+ * Skills across every project of `orgId` the caller may read prompts in,
509
+ * each with the version its `latest` label serves at listing time. At most
510
+ * `limit` rows (default 20, max 50): a picker, not a list to page. Projects
511
+ * the read left out are listed in `excludedProjects`.
512
+ */
513
+ async listOrgPrompts(
514
+ input: ListOrgPromptsInput,
515
+ ): Promise<ListOrgPromptsResult> {
516
+ const { orgId, kind, query, limit } = input;
517
+ const envelope = await this.transport.request<ListOrgPromptsResult>(
518
+ "GET",
519
+ `/v1/orgs/${encodeURIComponent(orgId)}/prompts`,
520
+ {
521
+ query: { kind, query, limit },
522
+ decode: (data) => orgPromptsData.parse(data) as ListOrgPromptsResult,
523
+ },
524
+ );
525
+ return unwrap(envelope);
526
+ }
527
+
528
+ /**
529
+ * One exact version of a skill, by slug, with its files. Pass the
530
+ * `version` `listOrgPrompts()` returned so the caller runs exactly the
531
+ * version it listed, whatever `latest` serves by then. A chat prompt at
532
+ * this address is a 409.
533
+ */
534
+ async renderSkillVersion(
535
+ input: RenderSkillVersionInput,
536
+ ): Promise<RenderedSkillVersion> {
537
+ const projectId = this.resolveProjectId(input.projectId);
538
+ rejectDotSegments({ projectId, slug: input.slug });
539
+ const envelope = await this.transport.request<RenderedSkillVersion>(
540
+ "POST",
541
+ `${getProjectPromptsPath(projectId)}/by-slug/${encodeURIComponent(input.slug)}/versions/${encodeURIComponent(String(input.version))}/render`,
542
+ {
543
+ body: {},
544
+ decode: (data) => skillVersionData.parse(data) as RenderedSkillVersion,
545
+ },
546
+ );
547
+ return unwrap(envelope);
548
+ }
549
+
470
550
  // ─── Render (resolution + format shaping, TO11-980 / TO11-2691) ──────────
471
551
 
472
552
  /**
@@ -1,9 +1,13 @@
1
1
  import type {
2
+ OrgPromptRow as GenOrgPromptRow,
3
+ OrgPromptsResponse as GenOrgPromptsResponse,
2
4
  Prompt as GenPrompt,
3
5
  PromptLabelPointer as GenPromptLabelPointer,
4
6
  PromptVersion as GenPromptVersion,
5
7
  PromptVersionSummary as GenPromptVersionSummary,
6
8
  RenderedChatPrompt as GenRenderedChatPrompt,
9
+ RenderedSkillFile as GenRenderedSkillFile,
10
+ RenderedSkillVersion as GenRenderedSkillVersion,
7
11
  ResolvedPrompt as GenResolvedPrompt,
8
12
  ResolvedToolCall as GenResolvedToolCall,
9
13
  ResolvedToolDefinition as GenResolvedToolDefinition,
@@ -276,3 +280,30 @@ export interface RenderOptions {
276
280
  */
277
281
  onUnknownRole?: UnknownRoleMode;
278
282
  }
283
+
284
+ // ─── Org prompts (TO11-3690) ─────────────────────────────────────────────────
285
+
286
+ /** `GET /v1/orgs/:orgId/prompts`: skills across the projects the caller reads. */
287
+ export interface ListOrgPromptsInput {
288
+ readonly orgId: string;
289
+ /** Only `skill` today; the server's default. */
290
+ readonly kind?: "skill";
291
+ /** Case-insensitive substring of the skill's name or slug; 1–100 chars. */
292
+ readonly query?: string;
293
+ /** Default 20, max 50: a picker, not a list to page. */
294
+ readonly limit?: number;
295
+ }
296
+
297
+ /** One skill and the version its `latest` label serves at listing time. */
298
+ export type OrgPromptRow = GenOrgPromptRow;
299
+ export type ListOrgPromptsResult = GenOrgPromptsResponse;
300
+
301
+ /** Render one exact skill version (`OrgPromptRow.version`) by slug. */
302
+ export interface RenderSkillVersionInput {
303
+ readonly projectId: string;
304
+ readonly slug: string;
305
+ readonly version: number;
306
+ }
307
+
308
+ export type RenderedSkillVersion = GenRenderedSkillVersion;
309
+ export type RenderedSkillFile = GenRenderedSkillFile;
package/src/transport.ts CHANGED
@@ -393,7 +393,14 @@ export class Transport {
393
393
  method: string,
394
394
  path: string,
395
395
  options?: {
396
- query?: Record<string, string | number | boolean | undefined>;
396
+ /**
397
+ * Query params. An array value repeats the param once per element
398
+ * (`?groupBy=model&groupBy=project`); `undefined` or `null` omits it.
399
+ */
400
+ query?: Record<
401
+ string,
402
+ string | number | boolean | ReadonlyArray<string> | null | undefined
403
+ >;
397
404
  body?: unknown;
398
405
  /**
399
406
  * Runtime validator for the envelope `data` on a 2xx response. When
@@ -408,7 +415,12 @@ export class Transport {
408
415
 
409
416
  if (options?.query) {
410
417
  for (const [key, value] of Object.entries(options.query)) {
411
- if (value !== undefined) {
418
+ // `null` too: an untyped caller's null means "not set", and
419
+ // `typeof null` is "object", which the array branch would iterate.
420
+ if (value === undefined || value === null) continue;
421
+ if (Array.isArray(value)) {
422
+ for (const item of value) url.searchParams.append(key, item);
423
+ } else {
412
424
  url.searchParams.set(key, String(value));
413
425
  }
414
426
  }
@@ -0,0 +1,189 @@
1
+ // ---------------------------------------------------------------------------
2
+ // UsageResource — the organization's usage reads (TO11-3689 / TO11-3690).
3
+ // ---------------------------------------------------------------------------
4
+ // Spec: docs/specs/2026-10-20-to11-assistant/SPEC.md § Tools
5
+ //
6
+ // Org-scoped: every method takes the `orgId` it reads. Figures carry both
7
+ // what was billed and the API-price equivalent; every response lists the
8
+ // readable projects it left out (`excludedProjects`).
9
+ // ---------------------------------------------------------------------------
10
+
11
+ import { To11aiValidationError } from "../errors";
12
+ import {
13
+ zUsageGetUsageCostsResponse,
14
+ zUsageListTopTracesResponse,
15
+ zUsageListUsagePrincipalsResponse,
16
+ zUsageListUsageSessionsResponse,
17
+ } from "../generated/zod.gen";
18
+ import type { ApiEnvelope, Transport } from "../transport";
19
+ import type {
20
+ FindPrincipalsInput,
21
+ FindPrincipalsResult,
22
+ GetCostsInput,
23
+ GetCostsResult,
24
+ ListSessionsInput,
25
+ ListSessionsResult,
26
+ ListTopTracesInput,
27
+ ListTopTracesResult,
28
+ UsageWindow,
29
+ } from "./types";
30
+
31
+ export type {
32
+ CostGroup,
33
+ CostGroupBy,
34
+ FindPrincipalsInput,
35
+ FindPrincipalsResult,
36
+ GetCostsInput,
37
+ GetCostsResult,
38
+ ListSessionsInput,
39
+ ListSessionsResult,
40
+ ListTopTracesInput,
41
+ ListTopTracesResult,
42
+ ResolvedUsageWindow,
43
+ TopTrace,
44
+ TopTraceStatus,
45
+ TopTracesSort,
46
+ UsageBillingMode,
47
+ UsageExcludedProject,
48
+ UsagePrincipal,
49
+ UsageRunRow,
50
+ UsageSessionRow,
51
+ UsageSessionsGroupBy,
52
+ UsageWindow,
53
+ UsageWindowPreset,
54
+ } from "./types";
55
+
56
+ // The response schemas are the `data` of the generated envelope schemas, so a
57
+ // wrong-shaped response raises To11aiResponseValidationError.
58
+ const principalsData = zUsageListUsagePrincipalsResponse.shape.data.unwrap();
59
+ const sessionsData = zUsageListUsageSessionsResponse.shape.data.unwrap();
60
+ const costsData = zUsageGetUsageCostsResponse.shape.data.unwrap();
61
+ const topTracesData = zUsageListTopTracesResponse.shape.data.unwrap();
62
+
63
+ type Query = Record<
64
+ string,
65
+ string | number | boolean | ReadonlyArray<string> | undefined
66
+ >;
67
+
68
+ function unwrap<T>(envelope: ApiEnvelope<T>): T {
69
+ if (envelope.data === null || envelope.data === undefined) {
70
+ throw new Error("API returned success but data is null");
71
+ }
72
+ return envelope.data;
73
+ }
74
+
75
+ function orgPath(orgId: string, rest: string): string {
76
+ return `/v1/orgs/${encodeURIComponent(orgId)}/${rest}`;
77
+ }
78
+
79
+ /** The window as the API's query params: `from`+`to`, or `preset` (+`n`) + `timezone`. */
80
+ function windowQuery(window: UsageWindow): Query {
81
+ if ("from" in window) return { from: window.from, to: window.to };
82
+ return { preset: window.preset, n: window.n, timezone: window.timezone };
83
+ }
84
+
85
+ /**
86
+ * The lookup's one query param: exactly one of `email` or `query`, decided
87
+ * by value (a key present but `undefined` is unset), as the Python SDK's
88
+ * `find_principals` does. Neither or both is refused before any request.
89
+ */
90
+ function principalsQuery(input: FindPrincipalsInput): Query {
91
+ const { email, query } = input as {
92
+ readonly email?: string | null;
93
+ readonly query?: string | null;
94
+ };
95
+ const hasEmail = typeof email === "string";
96
+ const hasQuery = typeof query === "string";
97
+ if (hasEmail && !hasQuery) return { email };
98
+ if (hasQuery && !hasEmail) return { query };
99
+ throw new To11aiValidationError(
100
+ "[to11ai/sdk] findPrincipals() needs exactly one of `query` or `email`",
101
+ "invalid_principal_lookup",
102
+ { query: hasQuery, email: hasEmail },
103
+ );
104
+ }
105
+
106
+ /**
107
+ * SDK resource for the organization usage reads. Constructed by
108
+ * `createClient` and exposed as `client.usage`.
109
+ */
110
+ export class UsageResource {
111
+ private readonly transport: Transport;
112
+
113
+ constructor(transport: Transport) {
114
+ this.transport = transport;
115
+ }
116
+
117
+ /**
118
+ * Members of the organization by name (`query`) or exact `email`, as
119
+ * `{ principalId, displayName }`. Pass a `principalId` to the other reads.
120
+ */
121
+ async findPrincipals(
122
+ input: FindPrincipalsInput,
123
+ ): Promise<FindPrincipalsResult> {
124
+ const query = principalsQuery(input);
125
+ const envelope = await this.transport.request<FindPrincipalsResult>(
126
+ "GET",
127
+ orgPath(input.orgId, "usage/principals"),
128
+ {
129
+ query,
130
+ decode: (data) => principalsData.parse(data) as FindPrincipalsResult,
131
+ },
132
+ );
133
+ return unwrap(envelope);
134
+ }
135
+
136
+ /**
137
+ * Sessions (or runs, with `groupBy: "run"`) with usage in the window, one
138
+ * page at a time, plus totals over all of them and the usage outside any
139
+ * session. Pass `pagination.nextCursor` back as `cursor` until it is `null`.
140
+ */
141
+ async listSessions(input: ListSessionsInput): Promise<ListSessionsResult> {
142
+ const { orgId, window, ...filters } = input;
143
+ const envelope = await this.transport.request<ListSessionsResult>(
144
+ "GET",
145
+ orgPath(orgId, "usage/sessions"),
146
+ {
147
+ query: { ...windowQuery(window), ...filters },
148
+ decode: (data) => sessionsData.parse(data) as ListSessionsResult,
149
+ },
150
+ );
151
+ return unwrap(envelope);
152
+ }
153
+
154
+ /**
155
+ * Billed cost and API-price equivalent in the window, grouped by up to six
156
+ * keys (`groupBy`), with totals and a per-billing-mode split.
157
+ */
158
+ async getCosts(input: GetCostsInput): Promise<GetCostsResult> {
159
+ const { orgId, window, groupBy, ...filters } = input;
160
+ const envelope = await this.transport.request<GetCostsResult>(
161
+ "GET",
162
+ orgPath(orgId, "usage/costs"),
163
+ {
164
+ query: {
165
+ ...windowQuery(window),
166
+ // Repeated param (`?groupBy=model&groupBy=project`).
167
+ groupBy: typeof groupBy === "string" ? [groupBy] : groupBy,
168
+ ...filters,
169
+ },
170
+ decode: (data) => costsData.parse(data) as GetCostsResult,
171
+ },
172
+ );
173
+ return unwrap(envelope);
174
+ }
175
+
176
+ /** The slowest, costliest, or largest traces in the window (at most 60 days). */
177
+ async listTopTraces(input: ListTopTracesInput): Promise<ListTopTracesResult> {
178
+ const { orgId, window, ...filters } = input;
179
+ const envelope = await this.transport.request<ListTopTracesResult>(
180
+ "GET",
181
+ orgPath(orgId, "traces/top"),
182
+ {
183
+ query: { ...windowQuery(window), ...filters },
184
+ decode: (data) => topTracesData.parse(data) as ListTopTracesResult,
185
+ },
186
+ );
187
+ return unwrap(envelope);
188
+ }
189
+ }
@@ -0,0 +1,120 @@
1
+ import type {
2
+ TopTracesResponse,
3
+ UsageCostsResponse,
4
+ UsageListUsageSessionsData,
5
+ UsagePrincipalsResponse,
6
+ UsageSessionsResponse,
7
+ } from "../generated/types.gen";
8
+
9
+ // ─── Window ────────────────────────────────────────────────────────────────
10
+
11
+ /** A preset the server resolves in the window's `timezone`. Weeks start on Monday. */
12
+ export type UsageWindowPreset =
13
+ | "last_n_hours"
14
+ | "last_n_days"
15
+ | "today"
16
+ | "yesterday"
17
+ | "this_week"
18
+ | "last_week"
19
+ | "this_month"
20
+ | "last_month";
21
+
22
+ /**
23
+ * The time window of a usage read: absolute (`from`/`to`, ISO 8601 with a
24
+ * zone offset, `[from, to)`), or a preset the server resolves in an IANA
25
+ * `timezone`. `n` is required by `last_n_hours` / `last_n_days` and rejected
26
+ * by the calendar presets. Every response echoes the absolute window it used.
27
+ */
28
+ export type UsageWindow =
29
+ | { readonly from: string; readonly to: string }
30
+ | {
31
+ readonly preset: UsageWindowPreset;
32
+ readonly n?: number;
33
+ readonly timezone: string;
34
+ };
35
+
36
+ // ─── Shared filters ────────────────────────────────────────────────────────
37
+
38
+ export type UsageBillingMode = "subscription" | "api" | "unknown";
39
+ export type UsageSessionsGroupBy = NonNullable<
40
+ NonNullable<UsageListUsageSessionsData["query"]>["groupBy"]
41
+ >;
42
+ export type CostGroupBy =
43
+ | "principal"
44
+ | "vendor"
45
+ | "provider"
46
+ | "model"
47
+ | "project"
48
+ | "billingMode";
49
+ export type TopTracesSort = TopTracesResponse["sort"];
50
+ export type TopTraceStatus = TopTracesResponse["items"][number]["status"];
51
+
52
+ // ─── Results ───────────────────────────────────────────────────────────────
53
+
54
+ export type FindPrincipalsResult = UsagePrincipalsResponse;
55
+ export type UsagePrincipal = FindPrincipalsResult["items"][number];
56
+ export type ListSessionsResult = UsageSessionsResponse;
57
+ export type UsageSessionRow = NonNullable<
58
+ ListSessionsResult["sessions"]
59
+ >[number];
60
+ export type UsageRunRow = NonNullable<ListSessionsResult["runs"]>[number];
61
+ export type GetCostsResult = UsageCostsResponse;
62
+ export type CostGroup = GetCostsResult["groups"][number];
63
+ export type ListTopTracesResult = TopTracesResponse;
64
+ export type TopTrace = ListTopTracesResult["items"][number];
65
+ /** The absolute window a usage response used, plus the preset it came from. */
66
+ export type ResolvedUsageWindow = GetCostsResult["window"];
67
+ /** A readable project a read left out, so totals are never silently partial. */
68
+ export type UsageExcludedProject =
69
+ FindPrincipalsResult["excludedProjects"][number];
70
+
71
+ // ─── Inputs ────────────────────────────────────────────────────────────────
72
+
73
+ /** Look a member up by name (`query`, matched in the API) or exact `email`. */
74
+ export type FindPrincipalsInput =
75
+ | { readonly orgId: string; readonly query: string }
76
+ | { readonly orgId: string; readonly email: string };
77
+
78
+ export interface ListSessionsInput {
79
+ readonly orgId: string;
80
+ readonly window: UsageWindow;
81
+ /** `session` (default) or `run`. */
82
+ readonly groupBy?: UsageSessionsGroupBy;
83
+ readonly principalId?: string;
84
+ readonly projectId?: string;
85
+ readonly billingMode?: UsageBillingMode;
86
+ /** `pagination.nextCursor` of the previous page. */
87
+ readonly cursor?: string;
88
+ /** Clamped by the server into [1, 50]; default 20. */
89
+ readonly limit?: number;
90
+ }
91
+
92
+ export interface GetCostsInput {
93
+ readonly orgId: string;
94
+ readonly window: UsageWindow;
95
+ /** One key or several; the groups are the cross product. */
96
+ readonly groupBy?: CostGroupBy | ReadonlyArray<CostGroupBy>;
97
+ readonly principalId?: string;
98
+ readonly vendor?: string;
99
+ readonly provider?: string;
100
+ readonly model?: string;
101
+ readonly projectId?: string;
102
+ readonly billingMode?: UsageBillingMode;
103
+ /** 1–50; default 10. Groups beyond it count in `totals` and `otherGroups`. */
104
+ readonly limit?: number;
105
+ }
106
+
107
+ export interface ListTopTracesInput {
108
+ readonly orgId: string;
109
+ /** At most 60 days. */
110
+ readonly window: UsageWindow;
111
+ readonly sort: TopTracesSort;
112
+ readonly principalId?: string;
113
+ readonly projectId?: string;
114
+ readonly vendor?: string;
115
+ readonly provider?: string;
116
+ readonly model?: string;
117
+ readonly status?: TopTraceStatus;
118
+ /** 1–20; default 10. */
119
+ readonly limit?: number;
120
+ }