@nylorun/admin 0.9.0-beta → 0.11.1-beta

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.
@@ -0,0 +1,120 @@
1
+ import { type CreateCredentialRequest, type CreateVaultRequest, type CredentialInfo, type HostModelCatalog, type HostModelView, type ListProvidersResponse, type ModelCallExportPage, type ModelBudgets, type ModelUsageQuery, type ModelUsageTotals, type OperatorKey, type PutHostModelRequest, type PutModelBudgetsRequest, type PutOperatorKeyResponse, type PutTenantArtifactsRequest, type PutTenantSandboxRequest, type ResetTenantRequest, type ResetTenantResponse, type RotateCredentialRequest, type SeedTenantConfigRequest, type SeedTenantConfigResponse, type SelectHostModelRequest, type SigningKeyView, type StartOAuthRequest, type StartOAuthResponse, type TenantArtifactsView, type TenantSandboxView, type TenantStatus, type VaultInfo } from "@nylorun/core/contracts";
2
+ export interface ManagementClientOptions {
3
+ /** The Tenant's URL, or a proxy in front of it. */
4
+ url: string;
5
+ /** A management key. Omit it behind a proxy that adds the credential (Studio's). */
6
+ key?: string;
7
+ /** Default: the global `fetch`. */
8
+ fetch?: typeof fetch;
9
+ /** Sent on every request, after the client's own headers. */
10
+ headers?: Record<string, string>;
11
+ }
12
+ /** A request body without its `requestId`: the client makes one when it is not given. */
13
+ type Body<T> = Omit<T, "requestId"> & {
14
+ requestId?: string;
15
+ };
16
+ export interface ManagementTenant {
17
+ /** The Tenant's status: its envelope, schema, streams and harnesses. */
18
+ status(): Promise<TenantStatus>;
19
+ /** Seeds the Tenant's configuration where it is unset (`nylorun start` does this). */
20
+ seed(request: Body<SeedTenantConfigRequest>): Promise<SeedTenantConfigResponse>;
21
+ /** Resets the Tenant's sessions, sandboxes or both. */
22
+ reset(request: Body<ResetTenantRequest>): Promise<ResetTenantResponse>;
23
+ }
24
+ /** The Tenant's keys: application keys are managed here; management keys only on its machine. */
25
+ export interface ManagementKeys {
26
+ /** Every key by name, with its role and when it was issued; never the keys. */
27
+ list(): Promise<OperatorKey[]>;
28
+ /** Creates or rotates application key `id`; the key is in the answer this once. */
29
+ put(id: string): Promise<PutOperatorKeyResponse>;
30
+ /** Deletes application key `id`: true when it existed. */
31
+ delete(id: string): Promise<boolean>;
32
+ }
33
+ export interface ManagementModels {
34
+ /** Every provider and model the Runtime knows. */
35
+ catalog(): Promise<HostModelCatalog>;
36
+ /** The providers the Tenant has credentials for. */
37
+ providers(): Promise<ListProvidersResponse>;
38
+ /** The Tenant's model: provider, model and whether a credential is set. */
39
+ get(): Promise<HostModelView>;
40
+ /** Sets a provider's credential (and, optionally, the model). */
41
+ put(request: Body<PutHostModelRequest>): Promise<HostModelView>;
42
+ /** Chooses the provider and model among those with credentials. */
43
+ select(request: Body<SelectHostModelRequest>): Promise<HostModelView>;
44
+ /** What the Tenant's model calls used, for one scope and period. */
45
+ usage(query: ModelUsageQuery): Promise<ModelUsageTotals>;
46
+ /**
47
+ * Every recorded model call, unfiltered, in safe transaction order (Host feature
48
+ * `calls-export`): pages from `after` until `caughtUp`. Each page's `next` is the position to
49
+ * resume from; call again to follow. Deduplicate by row id.
50
+ */
51
+ exportCalls(options?: {
52
+ after?: string;
53
+ limit?: number;
54
+ }): AsyncIterable<ModelCallExportPage>;
55
+ readonly budgets: {
56
+ get(): Promise<ModelBudgets>;
57
+ /** Replaces every budget; an empty list removes every cap. */
58
+ put(request: Body<PutModelBudgetsRequest>): Promise<ModelBudgets>;
59
+ };
60
+ }
61
+ export interface ManagementVaults {
62
+ create(request: Body<CreateVaultRequest>): Promise<VaultInfo>;
63
+ /** The installation vaults, after `ownerUserId`'s when it is given. */
64
+ list(ownerUserId?: string): Promise<VaultInfo[]>;
65
+ get(vaultId: string): Promise<VaultInfo>;
66
+ delete(vaultId: string): Promise<{
67
+ id: string;
68
+ }>;
69
+ readonly credentials: {
70
+ create(vaultId: string, request: Body<CreateCredentialRequest>): Promise<CredentialInfo>;
71
+ list(vaultId: string): Promise<CredentialInfo[]>;
72
+ get(vaultId: string, credentialId: string): Promise<CredentialInfo>;
73
+ /** Rotates the credential's secret. */
74
+ rotate(vaultId: string, credentialId: string, request: Body<RotateCredentialRequest>): Promise<CredentialInfo>;
75
+ delete(vaultId: string, credentialId: string): Promise<{
76
+ id: string;
77
+ }>;
78
+ };
79
+ /** Starts an MCP OAuth connect into an installation vault: open `authorizeUrl` in a browser. */
80
+ startOAuth(vaultId: string, request: StartOAuthRequest): Promise<StartOAuthResponse>;
81
+ }
82
+ export interface ManagementSigningKeys {
83
+ list(): Promise<SigningKeyView[]>;
84
+ /**
85
+ * standby → current → previous → revoked, and a new standby. Refused while the key it would
86
+ * revoke may still verify a live token; `force` skips that and ends those tokens.
87
+ */
88
+ rotate(options?: {
89
+ force?: boolean;
90
+ }): Promise<SigningKeyView[]>;
91
+ /** Revokes a previous or standby key; rotate before revoking the current one. */
92
+ revoke(keyId: string): Promise<SigningKeyView>;
93
+ }
94
+ export interface ManagementSettings {
95
+ readonly sandbox: {
96
+ get(): Promise<TenantSandboxView>;
97
+ put(request: Body<PutTenantSandboxRequest>): Promise<TenantSandboxView>;
98
+ };
99
+ readonly artifacts: {
100
+ get(): Promise<TenantArtifactsView>;
101
+ put(request: Body<PutTenantArtifactsRequest>): Promise<TenantArtifactsView>;
102
+ };
103
+ }
104
+ /** One client of the Management API. */
105
+ export declare class ManagementClient {
106
+ #private;
107
+ readonly url: string;
108
+ readonly tenant: ManagementTenant;
109
+ readonly keys: ManagementKeys;
110
+ readonly models: ManagementModels;
111
+ readonly vaults: ManagementVaults;
112
+ readonly signingKeys: ManagementSigningKeys;
113
+ readonly settings: ManagementSettings;
114
+ constructor(options: ManagementClientOptions);
115
+ private pageCalls;
116
+ private request;
117
+ }
118
+ /** A Management API client for `url`, with a management key (or behind a proxy that adds one). */
119
+ export declare function createManagementClient(options: ManagementClientOptions): ManagementClient;
120
+ export {};
@@ -0,0 +1,161 @@
1
+ /**
2
+ * The Management API client (`/v1/tenant/*`, protocol 8): the Tenant's settings, models,
3
+ * vaults, signing keys and application keys, with a management key. It imports nothing from
4
+ * Node, so a browser app that reaches the Runtime through its own proxy (Studio) uses it too:
5
+ * `@nylorun/admin/client`. `createAdmin()` in the package's main entry finds the URL and key.
6
+ */
7
+ import { PROTOCOL_HEADER, PROTOCOL_VERSION, } from "@nylorun/core/compatibility";
8
+ import { ModelCallExportPageSchema, RejectedResponseSchema, } from "@nylorun/core/contracts";
9
+ import { AdminError } from "./errors.js";
10
+ const segment = (value) => encodeURIComponent(value);
11
+ const withId = (body) => ({
12
+ requestId: crypto.randomUUID(),
13
+ ...body,
14
+ });
15
+ /** One client of the Management API. */
16
+ export class ManagementClient {
17
+ url;
18
+ tenant;
19
+ keys;
20
+ models;
21
+ vaults;
22
+ signingKeys;
23
+ settings;
24
+ #key;
25
+ #fetch;
26
+ #headers;
27
+ constructor(options) {
28
+ this.url = options.url.replace(/\/$/, "");
29
+ this.#key = options.key;
30
+ this.#fetch = options.fetch ?? ((input, init) => fetch(input, init));
31
+ this.#headers = options.headers ?? {};
32
+ const call = (method, path, body) => this.request(method, path, body);
33
+ this.tenant = {
34
+ status: () => call("GET", "/v1/tenant"),
35
+ seed: (request) => call("PUT", "/v1/tenant/config/seed", withId(request)),
36
+ reset: (request) => call("POST", "/v1/tenant/reset", withId(request)),
37
+ };
38
+ this.keys = {
39
+ list: async () => (await call("GET", "/v1/tenant/keys")).keys,
40
+ put: (id) => call("PUT", `/v1/tenant/keys/${segment(id)}`),
41
+ delete: async (id) => {
42
+ try {
43
+ await call("DELETE", `/v1/tenant/keys/${segment(id)}`);
44
+ return true;
45
+ }
46
+ catch (error) {
47
+ if (error instanceof AdminError && error.status === 404 && error.message === `No key ${id}`)
48
+ return false;
49
+ throw error;
50
+ }
51
+ },
52
+ };
53
+ this.models = {
54
+ catalog: () => call("GET", "/v1/tenant/models"),
55
+ providers: () => call("GET", "/v1/tenant/providers"),
56
+ get: () => call("GET", "/v1/tenant/model"),
57
+ put: (request) => call("PUT", "/v1/tenant/model", withId(request)),
58
+ select: (request) => call("PUT", "/v1/tenant/model/selection", withId(request)),
59
+ usage: (query) => {
60
+ const search = new URLSearchParams(Object.entries(query).flatMap(([name, value]) => value === undefined ? [] : [[name, String(value)]]));
61
+ return call("GET", `/v1/tenant/usage?${search}`);
62
+ },
63
+ exportCalls: (options = {}) => this.pageCalls(options),
64
+ budgets: {
65
+ get: () => call("GET", "/v1/tenant/budgets"),
66
+ put: (request) => call("PUT", "/v1/tenant/budgets", withId(request)),
67
+ },
68
+ };
69
+ const vault = (vaultId) => `/v1/tenant/vaults/${segment(vaultId)}`;
70
+ const credential = (vaultId, credentialId) => `${vault(vaultId)}/credentials/${segment(credentialId)}`;
71
+ this.vaults = {
72
+ create: (request) => call("POST", "/v1/tenant/vaults", withId(request)),
73
+ list: async (ownerUserId) => (await call("GET", ownerUserId === undefined
74
+ ? "/v1/tenant/vaults"
75
+ : `/v1/tenant/vaults?ownerUserId=${segment(ownerUserId)}`)).vaults,
76
+ get: (vaultId) => call("GET", vault(vaultId)),
77
+ delete: (vaultId) => call("DELETE", vault(vaultId)),
78
+ credentials: {
79
+ create: (vaultId, request) => call("POST", `${vault(vaultId)}/credentials`, withId(request)),
80
+ list: async (vaultId) => (await call("GET", `${vault(vaultId)}/credentials`))
81
+ .credentials,
82
+ get: (vaultId, credentialId) => call("GET", credential(vaultId, credentialId)),
83
+ rotate: (vaultId, credentialId, request) => call("POST", credential(vaultId, credentialId), withId(request)),
84
+ delete: (vaultId, credentialId) => call("DELETE", credential(vaultId, credentialId)),
85
+ },
86
+ startOAuth: (vaultId, request) => call("POST", `${vault(vaultId)}/oauth/start`, request),
87
+ };
88
+ this.signingKeys = {
89
+ list: async () => (await call("GET", "/v1/tenant/signing-keys")).keys,
90
+ rotate: async (options = {}) => (await call("POST", "/v1/tenant/signing-keys/rotate", withId(options.force ? { force: true } : {}))).keys,
91
+ revoke: (keyId) => call("POST", `/v1/tenant/signing-keys/${segment(keyId)}/revoke`, withId({})),
92
+ };
93
+ this.settings = {
94
+ sandbox: {
95
+ get: () => call("GET", "/v1/tenant/sandbox"),
96
+ put: (request) => call("PUT", "/v1/tenant/sandbox", withId(request)),
97
+ },
98
+ artifacts: {
99
+ get: () => call("GET", "/v1/tenant/artifacts"),
100
+ put: (request) => call("PUT", "/v1/tenant/artifacts", withId(request)),
101
+ },
102
+ };
103
+ }
104
+ async *pageCalls(options) {
105
+ let after = options.after;
106
+ while (true) {
107
+ const query = new URLSearchParams({ limit: String(options.limit ?? 200) });
108
+ if (after !== undefined)
109
+ query.set("after", after);
110
+ const page = ModelCallExportPageSchema.parse(await this.request("GET", `/v1/tenant/calls/model?${query}`));
111
+ yield page;
112
+ if (page.caughtUp)
113
+ return;
114
+ if (page.next === null || page.next === after)
115
+ throw new Error("Model export did not advance its cursor");
116
+ after = page.next;
117
+ }
118
+ }
119
+ async request(method, path, body) {
120
+ const headers = {
121
+ [PROTOCOL_HEADER]: String(PROTOCOL_VERSION),
122
+ accept: "application/json",
123
+ ...(this.#key ? { authorization: `Bearer ${this.#key}` } : {}),
124
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
125
+ ...this.#headers,
126
+ };
127
+ const response = await this.#fetch(this.url + path, {
128
+ method,
129
+ headers,
130
+ redirect: "error",
131
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
132
+ });
133
+ const text = await response.text();
134
+ let parsed = undefined;
135
+ if (text) {
136
+ try {
137
+ parsed = JSON.parse(text);
138
+ }
139
+ catch {
140
+ parsed = text;
141
+ }
142
+ }
143
+ if (!response.ok) {
144
+ const rejected = RejectedResponseSchema.safeParse(parsed);
145
+ if (rejected.success)
146
+ throw new AdminError(rejected.data.code, rejected.data.message, {
147
+ status: response.status,
148
+ details: rejected.data.details,
149
+ });
150
+ throw new AdminError("not_found", `${method} ${path} failed (${response.status})`, {
151
+ status: response.status,
152
+ details: parsed,
153
+ });
154
+ }
155
+ return parsed;
156
+ }
157
+ }
158
+ /** A Management API client for `url`, with a management key (or behind a proxy that adds one). */
159
+ export function createManagementClient(options) {
160
+ return new ManagementClient(options);
161
+ }
@@ -1,8 +1,8 @@
1
1
  import { type StudioLoginTokenResponse } from "@nylorun/core/contracts";
2
2
  /**
3
3
  * Mints a single-use Studio login token with the admin key (`POST
4
- * /_studio/login-tokens`, Studio §8.4). An app that embeds Studio, such as
5
- * Babai, calls this from its backend and hands only the token to its page,
4
+ * /_studio/login-tokens`, Studio §8.4). An app that embeds Studio calls this
5
+ * from its backend and hands only the token to its page,
6
6
  * which passes it to the framed Studio in `init`.
7
7
  *
8
8
  * - `tenant` names the Host's one Tenant, for embedders that pass it (the embed
@@ -2,8 +2,8 @@ import { StudioLoginTokenRequestSchema, StudioLoginTokenResponseSchema, } from "
2
2
  import { AdminError } from "./errors.js";
3
3
  /**
4
4
  * Mints a single-use Studio login token with the admin key (`POST
5
- * /_studio/login-tokens`, Studio §8.4). An app that embeds Studio, such as
6
- * Babai, calls this from its backend and hands only the token to its page,
5
+ * /_studio/login-tokens`, Studio §8.4). An app that embeds Studio calls this
6
+ * from its backend and hands only the token to its page,
7
7
  * which passes it to the framed Studio in `init`.
8
8
  *
9
9
  * - `tenant` names the Host's one Tenant, for embedders that pass it (the embed
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nylorun/admin",
3
- "version": "0.9.0-beta",
4
- "description": "Nylorun Admin API client for Tenants and Host status",
3
+ "version": "0.11.1-beta",
4
+ "description": "Nylorun Management API client: the Tenant's models, vaults, signing keys, settings and application keys",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
7
7
  "files": [
@@ -15,6 +15,10 @@
15
15
  ".": {
16
16
  "types": "./dist/index.d.ts",
17
17
  "import": "./dist/index.js"
18
+ },
19
+ "./client": {
20
+ "types": "./dist/management.d.ts",
21
+ "import": "./dist/management.js"
18
22
  }
19
23
  },
20
24
  "scripts": {
@@ -24,7 +28,7 @@
24
28
  "clean": "node -e \"import('node:fs').then(({rmSync})=>rmSync('dist',{recursive:true,force:true}))\""
25
29
  },
26
30
  "dependencies": {
27
- "@nylorun/core": "0.12.0-beta"
31
+ "@nylorun/core": "0.15.0-beta"
28
32
  },
29
33
  "peerDependencies": {
30
34
  "zod": "^4.6.5"