@nixet/contracts 0.0.0-stage → 0.1.0

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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/cjs/domains/agents.d.ts +284 -0
  4. package/dist/cjs/domains/agents.js +244 -0
  5. package/dist/cjs/domains/api-keys.d.ts +265 -0
  6. package/dist/cjs/domains/api-keys.js +87 -0
  7. package/dist/cjs/domains/billing.d.ts +98 -0
  8. package/dist/cjs/domains/billing.js +122 -0
  9. package/dist/cjs/domains/connections.d.ts +101 -0
  10. package/dist/cjs/domains/connections.js +130 -0
  11. package/dist/cjs/domains/conversations.d.ts +113 -0
  12. package/dist/cjs/domains/conversations.js +85 -0
  13. package/dist/cjs/domains/documents.d.ts +48 -0
  14. package/dist/cjs/domains/documents.js +64 -0
  15. package/dist/cjs/domains/guardrails.d.ts +211 -0
  16. package/dist/cjs/domains/guardrails.js +206 -0
  17. package/dist/cjs/domains/identity.d.ts +55 -0
  18. package/dist/cjs/domains/identity.js +26 -0
  19. package/dist/cjs/domains/knowledge.d.ts +167 -0
  20. package/dist/cjs/domains/knowledge.js +174 -0
  21. package/dist/cjs/domains/mcp.d.ts +189 -0
  22. package/dist/cjs/domains/mcp.js +183 -0
  23. package/dist/cjs/domains/memory.d.ts +109 -0
  24. package/dist/cjs/domains/memory.js +92 -0
  25. package/dist/cjs/domains/redaction.d.ts +181 -0
  26. package/dist/cjs/domains/redaction.js +166 -0
  27. package/dist/cjs/domains/runs.d.ts +260 -0
  28. package/dist/cjs/domains/runs.js +260 -0
  29. package/dist/cjs/domains/secrets.d.ts +56 -0
  30. package/dist/cjs/domains/secrets.js +72 -0
  31. package/dist/cjs/domains/skills.d.ts +70 -0
  32. package/dist/cjs/domains/skills.js +82 -0
  33. package/dist/cjs/domains/tasks.d.ts +111 -0
  34. package/dist/cjs/domains/tasks.js +113 -0
  35. package/dist/cjs/domains/tools.d.ts +159 -0
  36. package/dist/cjs/domains/tools.js +203 -0
  37. package/dist/cjs/domains/users.d.ts +40 -0
  38. package/dist/cjs/domains/users.js +48 -0
  39. package/dist/cjs/index.d.ts +25 -0
  40. package/dist/cjs/index.js +41 -0
  41. package/dist/cjs/primitives.d.ts +75 -0
  42. package/dist/cjs/primitives.js +117 -0
  43. package/dist/esm/domains/agents.js +239 -0
  44. package/dist/esm/domains/api-keys.js +83 -0
  45. package/dist/esm/domains/billing.js +116 -0
  46. package/dist/esm/domains/connections.js +127 -0
  47. package/dist/esm/domains/conversations.js +82 -0
  48. package/dist/esm/domains/documents.js +61 -0
  49. package/dist/esm/domains/guardrails.js +202 -0
  50. package/dist/esm/domains/identity.js +23 -0
  51. package/dist/esm/domains/knowledge.js +170 -0
  52. package/dist/esm/domains/mcp.js +178 -0
  53. package/dist/esm/domains/memory.js +89 -0
  54. package/dist/esm/domains/redaction.js +162 -0
  55. package/dist/esm/domains/runs.js +256 -0
  56. package/dist/esm/domains/secrets.js +68 -0
  57. package/dist/esm/domains/skills.js +79 -0
  58. package/dist/esm/domains/tasks.js +109 -0
  59. package/dist/esm/domains/tools.js +196 -0
  60. package/dist/esm/domains/users.js +45 -0
  61. package/dist/esm/index.js +25 -0
  62. package/dist/esm/package.json +1 -0
  63. package/dist/esm/primitives.js +114 -0
  64. package/package.json +38 -4
@@ -0,0 +1,75 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Shared wire primitives.
4
+ *
5
+ * Wire fields are snake_case and timestamps are RFC 3339 UTC strings. Nothing
6
+ * in the contract may describe a recoverable secret: a plaintext key appears
7
+ * only in the single creation response, never in a list or get payload.
8
+ */
9
+ export declare const API_VERSION: "v1";
10
+ /** Scope headers. A dashboard selects scope; a scoped key derives it. */
11
+ export declare const SCOPE_HEADERS: {
12
+ readonly organization: "Nixet-Organization";
13
+ readonly project: "Nixet-Project";
14
+ readonly environment: "Nixet-Environment";
15
+ };
16
+ export declare const IDEMPOTENCY_HEADER = "Idempotency-Key";
17
+ export declare const REQUEST_ID_HEADER = "X-Request-Id";
18
+ export declare const environmentSchema: z.ZodEnum<{
19
+ development: "development";
20
+ production: "production";
21
+ }>;
22
+ export type Environment = z.infer<typeof environmentSchema>;
23
+ export declare const scopeSchema: z.ZodObject<{
24
+ organization_id: z.ZodString;
25
+ project_id: z.ZodString;
26
+ environment_id: z.ZodEnum<{
27
+ development: "development";
28
+ production: "production";
29
+ }>;
30
+ }, z.core.$strip>;
31
+ export type Scope = z.infer<typeof scopeSchema>;
32
+ /**
33
+ * Permissions an issued key may carry. `api_keys:write` is deliberately absent:
34
+ * a customer key must never be able to mint further credentials.
35
+ *
36
+ * `billing:write` is absent for a different reason: there is no such operation.
37
+ * A plan change moves money, so it happens through Stripe and arrives as a
38
+ * webhook. An API that could set a plan would be an API that could grant a
39
+ * customer Scale's allowance without charging for it.
40
+ */
41
+ export declare const permissionSchema: z.ZodEnum<{
42
+ "api_keys:read": "api_keys:read";
43
+ "agents:read": "agents:read";
44
+ "agents:write": "agents:write";
45
+ "runs:read": "runs:read";
46
+ "runs:write": "runs:write";
47
+ "users:read": "users:read";
48
+ "users:write": "users:write";
49
+ "conversations:read": "conversations:read";
50
+ "conversations:write": "conversations:write";
51
+ "memory:read": "memory:read";
52
+ "memory:write": "memory:write";
53
+ "secrets:read": "secrets:read";
54
+ "secrets:write": "secrets:write";
55
+ "mcp:read": "mcp:read";
56
+ "mcp:write": "mcp:write";
57
+ "connections:read": "connections:read";
58
+ "connections:write": "connections:write";
59
+ "knowledge:read": "knowledge:read";
60
+ "knowledge:write": "knowledge:write";
61
+ "billing:read": "billing:read";
62
+ }>;
63
+ export type Permission = z.infer<typeof permissionSchema>;
64
+ export declare const PERMISSION_PRESETS: {
65
+ readonly read: readonly ["api_keys:read", "agents:read", "runs:read", "users:read", "conversations:read", "memory:read", "secrets:read", "mcp:read", "connections:read", "knowledge:read", "billing:read"];
66
+ readonly standard: readonly ["api_keys:read", "agents:read", "agents:write", "runs:read", "runs:write", "users:read", "users:write", "conversations:read", "conversations:write", "memory:read", "memory:write", "secrets:read", "secrets:write", "mcp:read", "mcp:write", "connections:read", "connections:write", "knowledge:read", "knowledge:write", "billing:read"];
67
+ };
68
+ export type PermissionPreset = keyof typeof PERMISSION_PRESETS;
69
+ export declare const ERROR_CODES: readonly ["BAD_REQUEST", "UNAUTHENTICATED", "FORBIDDEN", "NOT_FOUND", "CONFLICT", "IDEMPOTENCY_CONFLICT", "INVALID_CURSOR", "SCOPE_MISMATCH", "RATE_LIMITED", "INTERNAL"];
70
+ export type ErrorCode = (typeof ERROR_CODES)[number];
71
+ /** Framework error envelope: a status code plus `{ message }`. */
72
+ export declare const errorResponseSchema: z.ZodObject<{
73
+ message: z.ZodString;
74
+ }, z.core.$strip>;
75
+ export type ErrorResponse = z.infer<typeof errorResponseSchema>;
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.errorResponseSchema = exports.ERROR_CODES = exports.PERMISSION_PRESETS = exports.permissionSchema = exports.scopeSchema = exports.environmentSchema = exports.REQUEST_ID_HEADER = exports.IDEMPOTENCY_HEADER = exports.SCOPE_HEADERS = exports.API_VERSION = void 0;
4
+ const zod_1 = require("zod");
5
+ /**
6
+ * Shared wire primitives.
7
+ *
8
+ * Wire fields are snake_case and timestamps are RFC 3339 UTC strings. Nothing
9
+ * in the contract may describe a recoverable secret: a plaintext key appears
10
+ * only in the single creation response, never in a list or get payload.
11
+ */
12
+ exports.API_VERSION = "v1";
13
+ /** Scope headers. A dashboard selects scope; a scoped key derives it. */
14
+ exports.SCOPE_HEADERS = {
15
+ organization: "Nixet-Organization",
16
+ project: "Nixet-Project",
17
+ environment: "Nixet-Environment",
18
+ };
19
+ exports.IDEMPOTENCY_HEADER = "Idempotency-Key";
20
+ exports.REQUEST_ID_HEADER = "X-Request-Id";
21
+ exports.environmentSchema = zod_1.z.enum(["development", "production"]);
22
+ exports.scopeSchema = zod_1.z.object({
23
+ organization_id: zod_1.z.string().min(1).max(64),
24
+ project_id: zod_1.z.string().min(1).max(64),
25
+ environment_id: exports.environmentSchema,
26
+ });
27
+ /**
28
+ * Permissions an issued key may carry. `api_keys:write` is deliberately absent:
29
+ * a customer key must never be able to mint further credentials.
30
+ *
31
+ * `billing:write` is absent for a different reason: there is no such operation.
32
+ * A plan change moves money, so it happens through Stripe and arrives as a
33
+ * webhook. An API that could set a plan would be an API that could grant a
34
+ * customer Scale's allowance without charging for it.
35
+ */
36
+ exports.permissionSchema = zod_1.z.enum([
37
+ "api_keys:read",
38
+ "agents:read",
39
+ "agents:write",
40
+ "runs:read",
41
+ "runs:write",
42
+ "users:read",
43
+ "users:write",
44
+ "conversations:read",
45
+ "conversations:write",
46
+ "memory:read",
47
+ "memory:write",
48
+ "secrets:read",
49
+ "secrets:write",
50
+ "mcp:read",
51
+ "mcp:write",
52
+ "connections:read",
53
+ "connections:write",
54
+ "knowledge:read",
55
+ "knowledge:write",
56
+ "billing:read",
57
+ ]);
58
+ exports.PERMISSION_PRESETS = {
59
+ read: [
60
+ "api_keys:read",
61
+ "agents:read",
62
+ "runs:read",
63
+ "users:read",
64
+ "conversations:read",
65
+ "memory:read",
66
+ // Reading a secret never returns its value, so this is genuinely a read.
67
+ "secrets:read",
68
+ "mcp:read",
69
+ // A connection read returns status and expiry, never the credential.
70
+ "connections:read",
71
+ // Reading a collection returns counts and the chunking rule, never a line
72
+ // of a document, so this is a read in the same sense the rest are.
73
+ "knowledge:read",
74
+ // Usage is not a credential, and hiding spend from the person causing it is
75
+ // how surprise invoices happen. There is no write to pair this with.
76
+ "billing:read",
77
+ ],
78
+ standard: [
79
+ "api_keys:read",
80
+ "agents:read",
81
+ "agents:write",
82
+ "runs:read",
83
+ "runs:write",
84
+ "users:read",
85
+ "users:write",
86
+ "conversations:read",
87
+ "conversations:write",
88
+ "memory:read",
89
+ "memory:write",
90
+ "secrets:read",
91
+ "secrets:write",
92
+ "mcp:read",
93
+ "mcp:write",
94
+ "connections:read",
95
+ "connections:write",
96
+ "knowledge:read",
97
+ "knowledge:write",
98
+ // No `billing:write` to go beside it: a plan change is a Stripe webhook.
99
+ "billing:read",
100
+ ],
101
+ };
102
+ exports.ERROR_CODES = [
103
+ "BAD_REQUEST",
104
+ "UNAUTHENTICATED",
105
+ "FORBIDDEN",
106
+ "NOT_FOUND",
107
+ "CONFLICT",
108
+ "IDEMPOTENCY_CONFLICT",
109
+ "INVALID_CURSOR",
110
+ "SCOPE_MISMATCH",
111
+ "RATE_LIMITED",
112
+ "INTERNAL",
113
+ ];
114
+ /** Framework error envelope: a status code plus `{ message }`. */
115
+ exports.errorResponseSchema = zod_1.z.object({
116
+ message: zod_1.z.string(),
117
+ });
@@ -0,0 +1,239 @@
1
+ import { z } from "zod";
2
+ import { REDACTION_OFF, redactionPolicySchema } from "./redaction.js";
3
+ import { toolPoliciesSchema } from "./tools.js";
4
+ import { GUARDRAILS_OFF, guardrailBindingSchema } from "./guardrails.js";
5
+ /**
6
+ * Agents and their versions.
7
+ *
8
+ * An agent is a stable identity. A version is an immutable snapshot of the
9
+ * configuration used to build it: instructions, model, tools. A run pins one
10
+ * version, so a run can always be reproduced from what it recorded.
11
+ */
12
+ export const MAX_AGENT_NAME = 80;
13
+ export const MAX_INSTRUCTIONS = 20_000;
14
+ export const agentSchema = z.object({
15
+ id: z.string().describe("Unique identifier, prefixed `agt_`."),
16
+ name: z.string().describe("Human-readable name."),
17
+ description: z.string().nullable().describe("Optional summary of what the agent does."),
18
+ current_version: z
19
+ .string()
20
+ .nullable()
21
+ .describe("Version used when a run does not name one. Null until the first publish."),
22
+ created_at: z.string().describe("RFC 3339 creation timestamp."),
23
+ updated_at: z.string().describe("RFC 3339 timestamp of the last change."),
24
+ });
25
+ /** Ownership is never accepted from a body: scope comes from the API key. */
26
+ export const createAgentSchema = z
27
+ .object({
28
+ name: z.string().trim().min(1).max(MAX_AGENT_NAME).describe("Human-readable name."),
29
+ description: z
30
+ .string()
31
+ .trim()
32
+ .max(500)
33
+ .optional()
34
+ .describe("Optional summary of what the agent does."),
35
+ })
36
+ .strict();
37
+ /**
38
+ * Model selection.
39
+ *
40
+ * `nix` is the managed default and needs no customer credential. The other
41
+ * providers use a key the customer supplies. The model behind `nix` is
42
+ * deliberately not part of the contract.
43
+ */
44
+ export const providerSchema = z.enum(["nix", "openai", "anthropic"]);
45
+ /**
46
+ * Capability tier for the managed `nix` provider.
47
+ *
48
+ * A tier states intent rather than naming a model, so the backing model can
49
+ * change without breaking callers and without disclosing which model serves a
50
+ * request. Callers who need an exact model bring their own provider key.
51
+ */
52
+ export const tierSchema = z.enum(["fast", "balanced", "powerful"]);
53
+ export const modelSchema = z
54
+ .object({
55
+ provider: providerSchema
56
+ .default("nix")
57
+ .describe("`nix` is managed and needs no key of your own."),
58
+ model: z
59
+ .string()
60
+ .min(1)
61
+ .max(100)
62
+ .optional()
63
+ .describe("Model identifier. Required for `openai` and `anthropic`; rejected for `nix`, which selects by tier."),
64
+ tier: tierSchema
65
+ .optional()
66
+ .describe("Capability tier for `nix`, defaulting to `balanced`. Rejected for other providers."),
67
+ temperature: z.number().min(0).max(2).optional().describe("Sampling temperature."),
68
+ max_tokens: z
69
+ .number()
70
+ .int()
71
+ .min(1)
72
+ .max(200_000)
73
+ .optional()
74
+ .describe("Upper bound on generated tokens."),
75
+ })
76
+ .strict()
77
+ .superRefine((value, ctx) => {
78
+ if (value.provider === "nix" && value.model) {
79
+ // Accepting a model id here would publish a third party's model names as
80
+ // part of this contract and undo the non-disclosure the tier provides.
81
+ ctx.addIssue({
82
+ code: "custom",
83
+ path: ["model"],
84
+ message: "The nix provider selects a model by tier. Use `tier` instead.",
85
+ });
86
+ }
87
+ if (value.provider !== "nix") {
88
+ if (!value.model) {
89
+ ctx.addIssue({
90
+ code: "custom",
91
+ path: ["model"],
92
+ message: `A model is required for the ${value.provider} provider.`,
93
+ });
94
+ }
95
+ if (value.tier) {
96
+ ctx.addIssue({
97
+ code: "custom",
98
+ path: ["tier"],
99
+ message: "Tiers apply only to the nix provider. Name a model instead.",
100
+ });
101
+ }
102
+ }
103
+ });
104
+ /** A tool the runtime resolves by name from its registry. */
105
+ export const toolRefSchema = z.object({ name: z.string().max(80) }).strict();
106
+ /** Skills an agent version uses, stored already resolved to a version. */
107
+ export const agentSkillSchema = z.object({
108
+ name: z.string(),
109
+ version: z.string(),
110
+ digest: z.string(),
111
+ });
112
+ /**
113
+ * A placeholder an agent's instructions may contain.
114
+ *
115
+ * Lowercase, because `{{Data_Context}}` and `{{data_context}}` being different
116
+ * slots is a bug waiting to be filed.
117
+ */
118
+ export const variableNameSchema = z
119
+ .string()
120
+ .trim()
121
+ .min(1)
122
+ .max(64)
123
+ .regex(/^[a-z][a-z0-9_]*$/, "A variable name starts with a letter and holds lowercase letters, numbers and underscores.");
124
+ /** The most a run may substitute into one placeholder. */
125
+ export const MAX_VARIABLE_VALUE = 10_000;
126
+ /**
127
+ * Finds `{{name}}` in instructions.
128
+ *
129
+ * Deliberately strict: no spaces inside the braces, no nesting, no
130
+ * expressions. A template language here would be a second thing to learn and a
131
+ * second thing to get wrong, and the requirement is substitution.
132
+ */
133
+ export const VARIABLE_PATTERN = /\{\{([a-z][a-z0-9_]*)\}\}/g;
134
+ /** Every placeholder an instruction string names, in order, without repeats. */
135
+ export function variablesIn(instructions) {
136
+ const found = new Set();
137
+ for (const match of instructions.matchAll(VARIABLE_PATTERN))
138
+ found.add(match[1]);
139
+ return [...found];
140
+ }
141
+ /**
142
+ * Substitute a run's values into a version's instructions.
143
+ *
144
+ * Values are inserted literally and never re-scanned, so a value that itself
145
+ * contains `{{other}}` cannot pull in a second variable. That matters because
146
+ * values come from a customer's backend at run time while the template was
147
+ * fixed at publish: re-scanning would let a value reach a placeholder the
148
+ * version never declared.
149
+ */
150
+ export function applyVariables(instructions, values) {
151
+ return instructions.replace(VARIABLE_PATTERN, (whole, name) => Object.prototype.hasOwnProperty.call(values, name) ? values[name] : whole);
152
+ }
153
+ export const agentVersionSchema = z.object({
154
+ id: z.string(),
155
+ agent_id: z.string(),
156
+ /** Monotonic within an agent: v1, v2, v3. */
157
+ version: z.string(),
158
+ instructions: z.string(),
159
+ model: modelSchema,
160
+ tools: z.array(toolRefSchema),
161
+ skills: z.array(agentSkillSchema).describe("Resolved at publish, not at run."),
162
+ redaction: redactionPolicySchema.describe("Masking applied to run input and output."),
163
+ mcp_servers: z
164
+ .array(z.string())
165
+ .describe("MCP servers this version may use, pinned by name at publish."),
166
+ tool_policies: toolPoliciesSchema.describe("Per-tool overrides as `server.tool`. Anything unnamed takes its tag's default."),
167
+ knowledge_collections: z
168
+ .array(z.string())
169
+ .describe("Knowledge collections this version may search, pinned by name at publish."),
170
+ variables: z
171
+ .array(z.string())
172
+ .describe("Placeholders in `instructions` that a run must supply."),
173
+ guardrails: guardrailBindingSchema.describe("Guardrails this version runs, pinned by name at publish."),
174
+ /** Content hash of the frozen configuration, recorded on every run. */
175
+ digest: z.string(),
176
+ created_at: z.string(),
177
+ });
178
+ export const createAgentVersionSchema = z
179
+ .object({
180
+ instructions: z
181
+ .string()
182
+ .trim()
183
+ .min(1)
184
+ .max(MAX_INSTRUCTIONS)
185
+ .describe("System prompt that defines the agent's behaviour."),
186
+ model: modelSchema.default({ provider: "nix" }).describe("Model configuration."),
187
+ tools: z
188
+ .array(toolRefSchema)
189
+ .max(32)
190
+ .default([])
191
+ .describe("Tools the agent may call, by name. Unknown names are rejected at publish rather " +
192
+ "than failing a run. Nixet provides `current_time`, `calculate`, `web_search` and " +
193
+ "`fetch_url`; your own tools reach an agent through an MCP server instead. " +
194
+ "`fetch_url` reads a page the model chose, so the address is resolved and checked " +
195
+ "first — a private, loopback or cloud-metadata address is refused."),
196
+ skills: z
197
+ .array(z.string())
198
+ .max(16)
199
+ .default([])
200
+ .describe("Skills to use, as `name` or `name@v2`."),
201
+ redaction: redactionPolicySchema
202
+ .default(REDACTION_OFF)
203
+ .describe("Mask personal data in run input and output before dispatch. Traces are not redacted."),
204
+ mcp_servers: z
205
+ .array(z.string().min(1).max(64))
206
+ .max(10)
207
+ .default([])
208
+ .describe("Names of registered MCP servers. Cannot be combined with redaction: a masked " +
209
+ "run would hand tools placeholders instead of values."),
210
+ tool_policies: toolPoliciesSchema
211
+ .default({})
212
+ .describe("Per-tool overrides as `server.tool`, each `allow`, `ask` or `deny`. Only the " +
213
+ "exceptions: anything unnamed takes its tag's default, so a server adding a " +
214
+ "tool does not require republishing. `ask` is refused until approvals exist."),
215
+ knowledge_collections: z
216
+ .array(z.string().min(1).max(64))
217
+ .max(10)
218
+ .default([])
219
+ .describe("Names of knowledge collections this version may search. A collection with no " +
220
+ "ready sources is not an error: it returns nothing until one finishes."),
221
+ variables: z
222
+ .array(variableNameSchema)
223
+ .max(16)
224
+ .default([])
225
+ .describe("Placeholders in `instructions`, as `{{name}}`, that a run supplies. Declared here " +
226
+ "so a run can only fill slots this version named: a run that could inject arbitrary " +
227
+ "prompt text would make the caller's own backend a prompt-injection surface, and the " +
228
+ "version would no longer describe how the agent behaves."),
229
+ guardrails: guardrailBindingSchema
230
+ .default(GUARDRAILS_OFF)
231
+ .describe("Named guardrails to run, per stage. Order is the order given: under `run_all` each " +
232
+ "guard sees the text the previous one produced, so which runs first is part of the " +
233
+ "configuration rather than incidental."),
234
+ publish: z
235
+ .boolean()
236
+ .default(true)
237
+ .describe("Make this the version new runs use by default."),
238
+ })
239
+ .strict();
@@ -0,0 +1,83 @@
1
+ import { z } from "zod";
2
+ import { scopeSchema, permissionSchema } from "../primitives.js";
3
+ export const apiKeyStatusSchema = z.enum(["active", "revoked", "expired"]);
4
+ /** Key metadata. Safe to list, cache and render. Carries no secret material. */
5
+ export const apiKeySchema = z.object({
6
+ id: z.string(),
7
+ name: z.string(),
8
+ prefix: z.string(),
9
+ status: apiKeyStatusSchema,
10
+ permissions: z.array(permissionSchema),
11
+ scope: scopeSchema,
12
+ created_at: z.string(),
13
+ expires_at: z.string(),
14
+ last_used_at: z.string().nullable(),
15
+ revoked_at: z.string().nullable(),
16
+ });
17
+ export const MAX_KEY_NAME_LENGTH = 80;
18
+ export const MIN_EXPIRY_DAYS = 1;
19
+ export const MAX_EXPIRY_DAYS = 365;
20
+ export const DEFAULT_EXPIRY_DAYS = 90;
21
+ /**
22
+ * Creation request. Ownership is never accepted from the body: scope comes from
23
+ * verified session context and scope headers, so `strict()` rejects any attempt
24
+ * to smuggle `organization_id` or a status field through creation.
25
+ */
26
+ export const createApiKeySchema = z
27
+ .object({
28
+ name: z.string().trim().min(1).max(MAX_KEY_NAME_LENGTH),
29
+ // Derived, not a literal: a hardcoded cap silently rejects every key once
30
+ // a new permission is added.
31
+ permissions: z
32
+ .array(permissionSchema)
33
+ .min(1)
34
+ .max(permissionSchema.options.length),
35
+ expires_in_days: z
36
+ .number()
37
+ .int()
38
+ .min(MIN_EXPIRY_DAYS)
39
+ .max(MAX_EXPIRY_DAYS)
40
+ .default(DEFAULT_EXPIRY_DAYS),
41
+ })
42
+ .strict();
43
+ export const DEFAULT_PAGE_SIZE = 25;
44
+ export const MAX_PAGE_SIZE = 100;
45
+ /**
46
+ * List query, paginated with `$limit` and `$offset`.
47
+ */
48
+ export const listApiKeysQuerySchema = z
49
+ .object({
50
+ $limit: z.number().int().min(1).max(MAX_PAGE_SIZE).default(DEFAULT_PAGE_SIZE),
51
+ $offset: z.number().int().min(0).default(0),
52
+ status: apiKeyStatusSchema.optional(),
53
+ })
54
+ .strict();
55
+ /**
56
+ * List envelope. Matches the framework response shape `{ message, data, count }`,
57
+ * where `count` is the total number of scoped rows.
58
+ */
59
+ export const apiKeyListResponseSchema = z.object({
60
+ message: z.string(),
61
+ data: z.array(apiKeySchema),
62
+ count: z.number().int().nonnegative(),
63
+ });
64
+ export const apiKeyResponseSchema = z.object({
65
+ message: z.string(),
66
+ data: apiKeySchema,
67
+ });
68
+ /**
69
+ * Creation response. `secret` is present exactly once, on the original 201.
70
+ * A replayed idempotent request returns `replayed: true` with no secret,
71
+ * because the plaintext is unrecoverable by design.
72
+ */
73
+ export const createApiKeyResponseSchema = z.object({
74
+ message: z.string(),
75
+ data: z.object({
76
+ key: apiKeySchema,
77
+ secret: z.string().optional(),
78
+ replayed: z.boolean(),
79
+ }),
80
+ });
81
+ export const KEY_PREFIX = "nxt";
82
+ /** `nxt_<env>_<random>` — the prefix is stored, the random tail never is. */
83
+ export const keyPrefixFor = (environment) => `${KEY_PREFIX}_${environment === "production" ? "live" : "dev"}`;
@@ -0,0 +1,116 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Billing: what a workspace is allowed, and what it has used.
4
+ *
5
+ * An organization exists in the identity provider, which owns identity. The row here is the
6
+ * part that is ours — a plan, a counter, and eventually a Stripe customer —
7
+ * created the first time we see a workspace rather than at signup, because
8
+ * signup is a flow we do not own.
9
+ *
10
+ * A run is the billable unit. Not tokens, which are the provider's unit, and
11
+ * not seats, which would charge for the second person to look at a failure.
12
+ */
13
+ export const planSchema = z.enum(["free", "pro", "scale", "enterprise"]);
14
+ /**
15
+ * What each plan includes.
16
+ *
17
+ * `runsIncluded` is copied onto the organization when the plan is set, so a
18
+ * negotiated enterprise allowance is a column rather than a special case in
19
+ * code. These are the defaults, not the authority.
20
+ *
21
+ * `overage` is null where there is none: Free is a wall, Enterprise is a
22
+ * committed rate with no wall at all. Stopping an enterprise customer's
23
+ * production traffic over a counter is a support incident, not a control.
24
+ */
25
+ export const PLANS = {
26
+ free: {
27
+ runsIncluded: 1_000,
28
+ overagePerThousand: null,
29
+ retentionDays: 7,
30
+ inferenceMarkup: 0,
31
+ monthlyUsd: 0,
32
+ },
33
+ pro: {
34
+ runsIncluded: 25_000,
35
+ overagePerThousand: 2,
36
+ retentionDays: 90,
37
+ inferenceMarkup: 0.15,
38
+ monthlyUsd: 29,
39
+ },
40
+ scale: {
41
+ runsIncluded: 500_000,
42
+ overagePerThousand: 1.2,
43
+ retentionDays: 365,
44
+ inferenceMarkup: 0.08,
45
+ monthlyUsd: 249,
46
+ },
47
+ enterprise: {
48
+ runsIncluded: Number.MAX_SAFE_INTEGER,
49
+ overagePerThousand: null,
50
+ retentionDays: 365,
51
+ inferenceMarkup: 0,
52
+ monthlyUsd: null,
53
+ },
54
+ };
55
+ /** Whether a plan stops at its allowance or bills past it. */
56
+ export function isHardLimit(plan) {
57
+ return PLANS[plan].overagePerThousand === null && plan !== "enterprise";
58
+ }
59
+ export const organizationSchema = z.object({
60
+ id: z.string().describe("The workspace identifier, as identity reports it."),
61
+ plan: planSchema,
62
+ /** Copied from the plan when it is set, so a negotiated rate is a value. */
63
+ runs_included: z.number(),
64
+ /** When the current period began. Not a calendar month: the plan's own date. */
65
+ period_start: z.string(),
66
+ period_end: z.string(),
67
+ /** Null until they pay. */
68
+ stripe_customer_id: z.string().nullable(),
69
+ stripe_subscription_id: z.string().nullable(),
70
+ created_at: z.string(),
71
+ updated_at: z.string(),
72
+ });
73
+ /**
74
+ * What a workspace has used this period.
75
+ *
76
+ * `runs_used` is incremented as runs finish rather than counted on demand:
77
+ * admission has to answer on every request, and a count over the runs table is
78
+ * a scan of the busiest thing we have. `usage_events` is what makes that
79
+ * honest — the counter is a cache of a sum that can always be rebuilt.
80
+ */
81
+ export const periodUsageSchema = z.object({
82
+ plan: planSchema,
83
+ period_start: z.string(),
84
+ period_end: z.string(),
85
+ runs_used: z.number(),
86
+ runs_included: z.number(),
87
+ /** What the runs cost us in inference, before any markup. */
88
+ cost_usd: z.number(),
89
+ /** Runs past the allowance, zero when within it. */
90
+ overage_runs: z.number(),
91
+ /** What the overage will add to the invoice. */
92
+ overage_usd: z.number(),
93
+ /** Whether a further run would be refused. */
94
+ at_limit: z.boolean(),
95
+ });
96
+ /**
97
+ * What the overage costs, given a plan and how many runs were used.
98
+ *
99
+ * Charged per thousand and rounded up, which is how the plans are written: a
100
+ * single run past the allowance costs the first thousand's price. Returns zero
101
+ * where the plan has no overage, because there the answer is a refusal rather
102
+ * than a charge.
103
+ */
104
+ export function overageFor(plan, runsUsed, runsIncluded) {
105
+ const over = Math.max(0, runsUsed - runsIncluded);
106
+ const rate = PLANS[plan].overagePerThousand;
107
+ if (over === 0 || rate === null)
108
+ return { runs: over, usd: 0 };
109
+ return { runs: over, usd: Math.ceil(over / 1_000) * rate };
110
+ }
111
+ /** Whether another run may start. */
112
+ export function withinAllowance(plan, runsUsed, runsIncluded) {
113
+ if (!isHardLimit(plan))
114
+ return true;
115
+ return runsUsed < runsIncluded;
116
+ }