@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,127 @@
1
+ import { z } from "zod";
2
+ import { mcpConnectionSchemeSchema } from "./mcp.js";
3
+ /**
4
+ * An end user's credential for one MCP server.
5
+ *
6
+ * The catalog and the connection are deliberately separate. A server is
7
+ * registered once — `https://broker.example.com/mcp` is the same URL for every user, and
8
+ * only the token differs — and a connection binds one user to one credential
9
+ * for it. That split is what keeps an agent version about behaviour: the
10
+ * version names which servers it may reach, and a connection decides whose
11
+ * account it reaches them as.
12
+ *
13
+ * A stored value is write-only. Nothing here returns it over HTTP; it is
14
+ * decrypted only when a run is dispatched, into a header the runtime receives.
15
+ */
16
+ export const MAX_CONNECTION_VALUE = 8_192;
17
+ /**
18
+ * Whether a connection can currently authenticate a run.
19
+ *
20
+ * `pending` exists because an OAuth connection is created before the user has
21
+ * consented: the row is the thing the callback completes. A run naming a
22
+ * pending or expired connection fails rather than calling the server without
23
+ * a credential — the server would answer as an anonymous caller, and for a
24
+ * broker that is a worse outcome than a refused run.
25
+ */
26
+ export const connectionStatusSchema = z.enum([
27
+ "pending",
28
+ "active",
29
+ "expired",
30
+ "revoked",
31
+ ]);
32
+ export const connectionSchema = z.object({
33
+ id: z.string().describe("Unique identifier, prefixed `con_`."),
34
+ user_id: z.string().describe("The end user this credential belongs to."),
35
+ server: z.string().describe("Name of the registered MCP server."),
36
+ scheme: mcpConnectionSchemeSchema,
37
+ status: connectionStatusSchema,
38
+ /**
39
+ * When the credential stops working, where the provider said so.
40
+ *
41
+ * Null for a scheme that does not expire, and for a provider that returned
42
+ * no expiry. A null expiry is not a promise that the credential is valid: it
43
+ * means nobody told us otherwise, and a rejected call is what reveals it.
44
+ */
45
+ expires_at: z.string().nullable(),
46
+ /** Set when a run last authenticated with it. Null until one does. */
47
+ last_used_at: z.string().nullable(),
48
+ created_at: z.string(),
49
+ updated_at: z.string(),
50
+ });
51
+ /**
52
+ * Supply a credential directly.
53
+ *
54
+ * For `api_key`, where the user already holds the value and there is nothing
55
+ * to redirect them through. Also the path a platform uses to push a token it
56
+ * obtained itself, which is how refresh works until Nixet performs it.
57
+ */
58
+ export const createConnectionSchema = z
59
+ .object({
60
+ user_id: z.string().min(1).max(64).describe("End user to bind this credential to."),
61
+ server: z
62
+ .string()
63
+ .min(1)
64
+ .max(64)
65
+ .describe("Registered MCP server. Its auth must be `per_user`."),
66
+ value: z
67
+ .string()
68
+ .min(1)
69
+ .max(MAX_CONNECTION_VALUE)
70
+ .describe("The credential. Stored encrypted and never returned."),
71
+ /**
72
+ * Optional, and trusted when given.
73
+ *
74
+ * A platform pushing an OAuth token knows when it expires; Nixet cannot
75
+ * infer it from an opaque string. Omitted means no known expiry, which the
76
+ * dispatch check treats as usable until the server says otherwise.
77
+ */
78
+ expires_at: z
79
+ .string()
80
+ .datetime()
81
+ .optional()
82
+ .describe("When the credential stops working, if known."),
83
+ refresh_value: z
84
+ .string()
85
+ .min(1)
86
+ .max(MAX_CONNECTION_VALUE)
87
+ .optional()
88
+ .describe("Refresh token, where the provider issued one."),
89
+ })
90
+ .strict();
91
+ /**
92
+ * Begin a scheme that cannot be completed in one request.
93
+ *
94
+ * `oauth2` needs the user at the provider's consent screen, and `session`
95
+ * needs them at a sign-in page whose URL the server itself returns. Both answer
96
+ * with somewhere to send the user, and both leave a `pending` connection that
97
+ * the callback completes.
98
+ */
99
+ export const authorizeConnectionSchema = z
100
+ .object({
101
+ user_id: z.string().min(1).max(64),
102
+ server: z.string().min(1).max(64),
103
+ /**
104
+ * Where to send the user once the provider is done.
105
+ *
106
+ * Required, and checked against the workspace's registered origins: an
107
+ * open redirect here would hand an authorization code to whoever asked.
108
+ */
109
+ return_url: z.string().url().max(500),
110
+ })
111
+ .strict();
112
+ export const authorizationSchema = z.object({
113
+ connection_id: z.string(),
114
+ /** Send the user here. Single use, and short lived. */
115
+ redirect_url: z.string(),
116
+ expires_at: z.string(),
117
+ });
118
+ /** Filters for listing a user's connections. */
119
+ export const findConnectionsSchema = z
120
+ .object({
121
+ user_id: z.string().min(1).max(64).optional(),
122
+ server: z.string().min(1).max(64).optional(),
123
+ status: connectionStatusSchema.optional(),
124
+ $limit: z.coerce.number().int().min(1).max(100).optional(),
125
+ $offset: z.coerce.number().int().min(0).optional(),
126
+ })
127
+ .strict();
@@ -0,0 +1,82 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Conversations.
4
+ *
5
+ * A durable thread between one agent and one user. Each message sent creates a
6
+ * run, so cost, usage and the trace stay exactly as they are for a single-shot
7
+ * run; the conversation adds the history around them.
8
+ */
9
+ export const MAX_MESSAGE_LENGTH = 100_000;
10
+ /**
11
+ * Which memories an agent may keep from this conversation.
12
+ *
13
+ * All default to off. The product rule is that an agent must not retain
14
+ * information without being told to, so retention is something a caller asks
15
+ * for rather than something they have to remember to switch off.
16
+ */
17
+ export const memoryPolicySchema = z
18
+ .object({
19
+ conversation: z.boolean().default(false).describe("Facts within this thread."),
20
+ user: z.boolean().default(false).describe("Facts about this person."),
21
+ agent: z.boolean().default(false).describe("Facts shared by every user."),
22
+ })
23
+ .strict();
24
+ export const conversationStatusSchema = z.enum(["open", "closed"]);
25
+ export const conversationSchema = z.object({
26
+ id: z.string().describe("Unique identifier, prefixed `cnv_`."),
27
+ agent_id: z.string(),
28
+ agent_version: z
29
+ .string()
30
+ .nullable()
31
+ .describe("Pinned at creation, so a long thread cannot change behaviour."),
32
+ user_id: z.string().nullable().describe("The person this thread is with."),
33
+ title: z.string().nullable(),
34
+ status: conversationStatusSchema,
35
+ memory: memoryPolicySchema,
36
+ message_count: z.number().int().nonnegative(),
37
+ last_run_id: z.string().nullable(),
38
+ created_at: z.string(),
39
+ updated_at: z.string(),
40
+ });
41
+ export const createConversationSchema = z
42
+ .object({
43
+ agent_id: z.string().min(1),
44
+ user_id: z.string().min(1).optional(),
45
+ title: z.string().trim().min(1).max(200).optional(),
46
+ memory: memoryPolicySchema.partial().optional(),
47
+ /** Pins the agent version, so a long thread cannot change behaviour mid-way. */
48
+ agent_version: z.string().min(1).optional(),
49
+ })
50
+ .strict();
51
+ export const messageRoleSchema = z.enum(["user", "assistant", "system", "summary"]);
52
+ export const conversationMessageSchema = z.object({
53
+ id: z.string().describe("Unique identifier, prefixed `msg_`."),
54
+ conversation_id: z.string(),
55
+ /** Monotonic within a conversation, so a transcript has a stable order. */
56
+ sequence: z.number().int().nonnegative(),
57
+ role: messageRoleSchema,
58
+ content: z.string(),
59
+ /** The run that produced an assistant message; null for anything else. */
60
+ run_id: z.string().nullable(),
61
+ token_count: z.number().int().nonnegative().nullable(),
62
+ created_at: z.string(),
63
+ });
64
+ export const sendMessageSchema = z
65
+ .object({
66
+ input: z.string().trim().min(1).max(MAX_MESSAGE_LENGTH),
67
+ /** Overrides the model provider for this message only. */
68
+ provider: z.string().min(1).optional(),
69
+ })
70
+ .strict();
71
+ /** What a send returns: the reply, plus the run that produced it. */
72
+ export const sendMessageResponseSchema = z.object({
73
+ message: conversationMessageSchema,
74
+ run_id: z.string(),
75
+ usage: z
76
+ .object({
77
+ input_tokens: z.number().int().nonnegative(),
78
+ output_tokens: z.number().int().nonnegative(),
79
+ })
80
+ .nullable(),
81
+ cost_usd: z.number().nullable(),
82
+ });
@@ -0,0 +1,61 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Converting a document to Markdown.
4
+ *
5
+ * The same conversion knowledge ingestion runs, exposed on its own. Ingestion
6
+ * chunks and embeds what it converts and keeps the result in a vector store;
7
+ * this answers with the Markdown and stores nothing, which is what a caller
8
+ * wanting to read a PDF rather than search it needs.
9
+ *
10
+ * Synchronous, so the Markdown is in the response rather than behind a job id.
11
+ * That is only honest below a size: conversion is local and fast for a
12
+ * document with a text layer, and a scanned document needs an OCR engine and
13
+ * minutes rather than milliseconds. The limit here is what keeps the
14
+ * difference from reaching the caller as a timeout.
15
+ */
16
+ /** Fourteen formats, identified from content rather than extension. */
17
+ export const MAX_DOCUMENT_BYTES = 20 * 1024 * 1024;
18
+ export const documentConversionSchema = z.object({
19
+ /** The document, as Markdown. */
20
+ markdown: z.string(),
21
+ /** Bytes read. Useful when the caller streamed rather than measured. */
22
+ bytes: z.number().int().nonnegative(),
23
+ /**
24
+ * Pages that held no text and were read by an OCR engine.
25
+ *
26
+ * Empty for a document with a text layer, which is most of them. Non-empty
27
+ * means the Markdown came from reading pictures of text, and is worth
28
+ * showing a caller deciding whether to trust it.
29
+ */
30
+ ocr_pages: z.array(z.number().int().positive()),
31
+ /** Total pages, where the format has them. Null for a spreadsheet. */
32
+ page_count: z.number().int().positive().nullable(),
33
+ });
34
+ /**
35
+ * A conversion, and the knowledge source it was filed as if one was asked for.
36
+ *
37
+ * Converting stores nothing by default: the bytes live for the length of the
38
+ * request and the Markdown is the answer. Naming a collection keeps the
39
+ * document as well, which means it is chunked, embedded and searchable by an
40
+ * agent — the same thing uploading it as a source would have done, in one
41
+ * call instead of two.
42
+ *
43
+ * `source` is null when nothing was stored, rather than the field being
44
+ * absent, so a caller reads one shape either way.
45
+ */
46
+ export const documentConversionResultSchema = documentConversionSchema.extend({
47
+ source: z
48
+ .object({
49
+ id: z.string().describe("Identifier of the stored source, prefixed `src_`."),
50
+ collection: z.string(),
51
+ /**
52
+ * Always `pending` here.
53
+ *
54
+ * The row is written once the bytes are in storage, and a worker claims
55
+ * it afterwards to chunk and embed. So the Markdown in this response is
56
+ * ready and the searchable copy is not yet.
57
+ */
58
+ status: z.string(),
59
+ })
60
+ .nullable(),
61
+ });
@@ -0,0 +1,202 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Guardrails: inspecting and rewriting what an agent is given and what it says.
4
+ *
5
+ * A guard belongs to the workspace, not to a version. A rule like "never name
6
+ * a specific fund" applies to every agent a customer will ever run, and
7
+ * defining it per version would mean maintaining it in as many places as there
8
+ * are versions. A version names the guards it uses, the same way it names MCP
9
+ * servers and knowledge collections, and pins them by name at publish.
10
+ *
11
+ * Declarative rather than code. A guard runs on every turn, and an output
12
+ * guard runs inside the stream, so a network hop per guard would be paid in
13
+ * first-token latency — four guards on one turn would be felt. Patterns and
14
+ * the built-in detectors cover the common rules; anything needing real logic
15
+ * is a separate question with a different cost, and is deliberately not
16
+ * pretended to here.
17
+ */
18
+ /**
19
+ * Where a guard runs.
20
+ *
21
+ * `tool_result` is the one that is easy to leave out and the one that leaves a
22
+ * hole. A tool returning structured data — a component tree, a row set —
23
+ * reaches the caller without passing through the agent's text, so an output
24
+ * guard never sees it. Any agent that renders what a tool returns needs this
25
+ * stage.
26
+ */
27
+ export const guardrailStageSchema = z.enum(["input", "output", "tool_result"]);
28
+ /**
29
+ * What a guard does when it matches.
30
+ *
31
+ * `modify` is the one that earns its place. "Scrub the fund name and let the
32
+ * rest through" is better product behaviour than refusing the turn, and
33
+ * refusing is what a guard that can only block has to do.
34
+ *
35
+ * `warn` passes the text through unchanged and records that it matched, which
36
+ * is how a rule is introduced before it is enforced.
37
+ */
38
+ export const guardrailActionSchema = z.enum(["allow", "modify", "warn", "block"]);
39
+ /** What a guard inspects with. */
40
+ export const guardrailKindSchema = z.enum(["patterns", "builtin"]);
41
+ /**
42
+ * The detectors the runtime already carries.
43
+ *
44
+ * Named rather than described, because each is code in the runtime and a
45
+ * customer choosing one is choosing behaviour that already exists rather than
46
+ * specifying new behaviour.
47
+ */
48
+ export const guardrailDetectorSchema = z.enum([
49
+ /** Personal data: names, emails, phone numbers, account identifiers. */
50
+ "pii",
51
+ /** Refuses text about a named subject. Needs `topics`. */
52
+ "topics",
53
+ /** Refuses text longer than `max_characters`. */
54
+ "length",
55
+ ]);
56
+ /**
57
+ * One find-and-replace rule.
58
+ *
59
+ * `replace` is what makes a pattern guard a rewriter rather than only a
60
+ * detector. Omitted, a match means the guard's action fires with nothing
61
+ * substituted, which is what `block` and `warn` want.
62
+ */
63
+ export const guardrailPatternSchema = z
64
+ .object({
65
+ match: z
66
+ .string()
67
+ .min(1)
68
+ .max(500)
69
+ .describe("A regular expression, applied case-insensitively."),
70
+ replace: z
71
+ .string()
72
+ .max(200)
73
+ .optional()
74
+ .describe("What to put in its place. Required by `modify`, ignored otherwise."),
75
+ })
76
+ .strict();
77
+ export const guardrailSchema = z.object({
78
+ id: z.string().describe("Unique identifier, prefixed `grd_`."),
79
+ name: z.string().describe("The handle a version pins."),
80
+ description: z.string().nullable(),
81
+ stage: guardrailStageSchema,
82
+ kind: guardrailKindSchema,
83
+ action: guardrailActionSchema,
84
+ patterns: z.array(guardrailPatternSchema),
85
+ detector: guardrailDetectorSchema.nullable(),
86
+ topics: z.array(z.string()),
87
+ max_characters: z.number().int().positive().nullable(),
88
+ /** Shown to the caller when the guard blocks, and recorded when it matches. */
89
+ message: z.string().nullable(),
90
+ created_at: z.string(),
91
+ updated_at: z.string(),
92
+ });
93
+ export const createGuardrailSchema = z
94
+ .object({
95
+ name: z
96
+ .string()
97
+ .trim()
98
+ .min(1)
99
+ .max(64)
100
+ .regex(/^[a-z0-9][a-z0-9-]*$/, "A guardrail name holds lowercase letters, numbers and hyphens.")
101
+ .describe("How a version refers to this guard."),
102
+ description: z.string().trim().max(200).optional(),
103
+ stage: guardrailStageSchema,
104
+ action: guardrailActionSchema.describe("What happens on a match. `modify` needs a `replace` on every pattern."),
105
+ patterns: z
106
+ .array(guardrailPatternSchema)
107
+ .max(50)
108
+ .default([])
109
+ .describe("Rules for a `patterns` guard. Omit for a `builtin` one."),
110
+ detector: guardrailDetectorSchema
111
+ .optional()
112
+ .describe("One of the runtime's own detectors. Omit for a `patterns` guard."),
113
+ topics: z
114
+ .array(z.string().trim().min(1).max(80))
115
+ .max(50)
116
+ .default([])
117
+ .describe("Subjects the `topics` detector refuses."),
118
+ max_characters: z
119
+ .number()
120
+ .int()
121
+ .positive()
122
+ .max(1_000_000)
123
+ .optional()
124
+ .describe("Limit for the `length` detector."),
125
+ message: z
126
+ .string()
127
+ .trim()
128
+ .max(500)
129
+ .optional()
130
+ .describe("Shown when this guard blocks. Recorded whenever it matches."),
131
+ })
132
+ .strict()
133
+ .refine((value) => Boolean(value.detector) !== value.patterns.length > 0, {
134
+ message: "A guardrail is either patterns or a built-in detector, not both and not neither.",
135
+ })
136
+ .refine((value) => value.action !== "modify" ||
137
+ value.detector !== undefined ||
138
+ value.patterns.every((pattern) => pattern.replace !== undefined), {
139
+ message: "A `modify` guardrail needs a `replace` on every pattern: there is nothing to rewrite with otherwise.",
140
+ })
141
+ .refine((value) => value.detector !== "topics" || value.topics.length > 0, {
142
+ message: "The `topics` detector needs at least one topic.",
143
+ })
144
+ .refine((value) => value.detector !== "length" || value.max_characters !== undefined, {
145
+ message: "The `length` detector needs `max_characters`.",
146
+ });
147
+ /**
148
+ * How a version runs the guards it names.
149
+ *
150
+ * `fail_fast` stops at the first block, which is what a caller wants when any
151
+ * single refusal ends the turn. `run_all` applies every guard, and each sees
152
+ * the text the previous one produced — so four scrubbing rules compose into
153
+ * one rewritten response instead of the last one winning. Ordering within each
154
+ * stage is the order given here, and is therefore explicit rather than
155
+ * incidental.
156
+ */
157
+ export const guardrailModeSchema = z.enum(["fail_fast", "run_all"]);
158
+ /**
159
+ * What a blocked run answers with.
160
+ *
161
+ * `return_message` completes the run with the guard's message as the output,
162
+ * which is a turn the caller can show someone. `error` fails the run, which is
163
+ * right when a block means the request should never have been made.
164
+ */
165
+ export const guardrailOnBlockSchema = z.enum(["return_message", "error"]);
166
+ export const guardrailBindingSchema = z
167
+ .object({
168
+ input: z.array(z.string().min(1).max(64)).max(10).default([]),
169
+ output: z.array(z.string().min(1).max(64)).max(10).default([]),
170
+ tool_result: z.array(z.string().min(1).max(64)).max(10).default([]),
171
+ mode: guardrailModeSchema.default("run_all"),
172
+ on_block: guardrailOnBlockSchema.default("return_message"),
173
+ })
174
+ .strict();
175
+ export const GUARDRAILS_OFF = {
176
+ input: [],
177
+ output: [],
178
+ tool_result: [],
179
+ mode: "run_all",
180
+ on_block: "return_message",
181
+ };
182
+ /** Every guard a binding names, across all three stages, without repeats. */
183
+ export function guardrailNamesIn(binding) {
184
+ return [
185
+ ...new Set([...binding.input, ...binding.output, ...binding.tool_result]),
186
+ ];
187
+ }
188
+ /**
189
+ * One guard's verdict on one piece of text.
190
+ *
191
+ * Reported per guard rather than collapsed, so a trace can say which rule
192
+ * rewrote what. A `modify` carries the text it produced, which is also the
193
+ * input to the next guard in `run_all`.
194
+ */
195
+ export const guardrailOutcomeSchema = z.object({
196
+ guardrail: z.string(),
197
+ stage: guardrailStageSchema,
198
+ action: guardrailActionSchema,
199
+ message: z.string().nullable(),
200
+ /** How many of its patterns or detections matched. Zero means it allowed. */
201
+ matches: z.number().int().nonnegative(),
202
+ });
@@ -0,0 +1,23 @@
1
+ import { z } from "zod";
2
+ export const roleSchema = z.enum([
3
+ "owner",
4
+ "admin",
5
+ "developer",
6
+ "operator",
7
+ "viewer",
8
+ ]);
9
+ export const membershipSchema = z.object({
10
+ organization_id: z.string(),
11
+ project_id: z.string(),
12
+ role: roleSchema,
13
+ });
14
+ /** Verified console identity. Never carries a credential. */
15
+ export const sessionSchema = z.object({
16
+ subject: z.string(),
17
+ email: z.string().nullable(),
18
+ memberships: z.array(membershipSchema),
19
+ });
20
+ export const sessionResponseSchema = z.object({
21
+ message: z.string(),
22
+ data: sessionSchema,
23
+ });
@@ -0,0 +1,170 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Knowledge: a customer's own documents, searchable by an agent.
4
+ *
5
+ * A collection is a named index an agent version pins, the way it pins an MCP
6
+ * server. A source is one document in it. Chunks are what a search returns,
7
+ * and they are not a resource here: they live in the vector store the runtime
8
+ * owns, because a hundred chunks of one PDF do not belong in a response about
9
+ * that PDF.
10
+ *
11
+ * Ingestion is asynchronous. A source is registered immediately and processed
12
+ * by a worker, so the status on the row is the honest answer to "can my agent
13
+ * use this yet".
14
+ */
15
+ /** Where a source's content came from. */
16
+ export const sourceKindSchema = z.enum(["file", "text", "url"]);
17
+ /**
18
+ * How far a source has got.
19
+ *
20
+ * Named after the step in progress rather than a generic "processing", so a
21
+ * customer waiting on a slow document can see whether it is being OCR'd — the
22
+ * one step that takes minutes rather than milliseconds.
23
+ */
24
+ export const sourceStatusSchema = z.enum([
25
+ "pending",
26
+ "converting",
27
+ "ocr",
28
+ "chunking",
29
+ "embedding",
30
+ "ready",
31
+ "failed",
32
+ ]);
33
+ /**
34
+ * How a collection splits a document.
35
+ *
36
+ * `markdown` follows headings, which suits documents with a structure worth
37
+ * preserving. `recursive` splits on paragraph and sentence boundaries and is
38
+ * the safe default for prose that has none.
39
+ */
40
+ export const chunkStrategySchema = z.enum(["markdown", "recursive"]);
41
+ export const knowledgeNameSchema = z
42
+ .string()
43
+ .trim()
44
+ .min(1)
45
+ .max(64)
46
+ .regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, "Use lowercase letters, numbers and hyphens, e.g. `support-policies`.");
47
+ /**
48
+ * A collection.
49
+ *
50
+ * `chunk_size` and `chunk_overlap` are fixed when it is created, because
51
+ * changing them would make the chunks already in it inconsistent with the ones
52
+ * added next. Re-chunking differently means a new collection.
53
+ */
54
+ export const knowledgeCollectionSchema = z.object({
55
+ id: z.string().describe("Unique identifier, prefixed `kbc_`."),
56
+ name: z
57
+ .string()
58
+ .describe("Stable handle a version pins, e.g. `support-policies`."),
59
+ description: z.string().nullable(),
60
+ chunk_strategy: chunkStrategySchema,
61
+ chunk_size: z.number(),
62
+ chunk_overlap: z.number(),
63
+ /** The model that embedded every chunk in here. */
64
+ embedding_model: z.string(),
65
+ /** How many sources are in this collection, whatever their status. */
66
+ source_count: z.number(),
67
+ /** Chunks across every source that reached `ready`. */
68
+ chunk_count: z.number(),
69
+ created_at: z.string(),
70
+ updated_at: z.string(),
71
+ });
72
+ export const createKnowledgeCollectionSchema = z
73
+ .object({
74
+ name: knowledgeNameSchema,
75
+ description: z.string().trim().max(200).optional(),
76
+ chunk_strategy: chunkStrategySchema.default("recursive"),
77
+ chunk_size: z.number().int().min(128).max(8000).default(1000),
78
+ chunk_overlap: z.number().int().min(0).max(2000).default(200),
79
+ })
80
+ .strict()
81
+ .refine((value) => value.chunk_overlap < value.chunk_size, {
82
+ message: "chunk_overlap must be smaller than chunk_size.",
83
+ path: ["chunk_overlap"],
84
+ });
85
+ /**
86
+ * A source.
87
+ *
88
+ * `storage_key` and `checksum` describe the original, which is kept:
89
+ * re-chunking at a different size, or re-running a better OCR engine, should
90
+ * not require the customer to upload the file again.
91
+ *
92
+ * `generation` increments when a source is re-ingested. The chunks of an older
93
+ * generation stay in the store, so a run that already happened can still be
94
+ * explained by what it actually searched.
95
+ */
96
+ export const knowledgeSourceSchema = z.object({
97
+ id: z.string().describe("Unique identifier, prefixed `kbs_`."),
98
+ collection_id: z.string(),
99
+ /** The collection's handle, so a source can be read without a second call. */
100
+ collection_name: z.string(),
101
+ kind: sourceKindSchema,
102
+ /** A file's original name, a URL, or a title given to pasted text. */
103
+ title: z.string(),
104
+ status: sourceStatusSchema,
105
+ /** Why ingestion failed, when it did. */
106
+ error: z.string().nullable(),
107
+ /** Bytes of the original. Zero for text that was pasted rather than uploaded. */
108
+ size: z.number(),
109
+ mime_type: z.string().nullable(),
110
+ checksum: z.string().nullable(),
111
+ /** How many chunks this source produced. Zero until it is `ready`. */
112
+ chunk_count: z.number(),
113
+ /**
114
+ * Pages that needed OCR, and how many there were.
115
+ *
116
+ * anydoc names the scanned pages when it refuses a PDF, so "2 of 340 pages
117
+ * were scanned" is answerable when someone asks why ingestion was slow.
118
+ */
119
+ ocr_pages: z.array(z.number()).nullable(),
120
+ page_count: z.number().nullable(),
121
+ /**
122
+ * The page a `url` source was actually read from, when a redirect moved it.
123
+ *
124
+ * Null when nothing redirected, and for every other kind. `title` holds the
125
+ * address that was asked for, so a source that ended up somewhere else says
126
+ * both.
127
+ */
128
+ fetched_url: z.string().nullable(),
129
+ generation: z.number(),
130
+ created_at: z.string(),
131
+ updated_at: z.string(),
132
+ });
133
+ /**
134
+ * Registering a source.
135
+ *
136
+ * A file arrives as multipart rather than through this schema — bytes do not
137
+ * belong in JSON — so this covers `text` and `url`, and the file path carries
138
+ * its own validation.
139
+ */
140
+ export const createKnowledgeSourceSchema = z
141
+ .object({
142
+ collection: knowledgeNameSchema,
143
+ kind: z.enum(["text", "url"]),
144
+ title: z.string().trim().min(1).max(200),
145
+ /** The text itself for `text`, the address for `url`. */
146
+ content: z.string().trim().min(1).max(1_000_000),
147
+ })
148
+ .strict();
149
+ /**
150
+ * What a run searched, recorded on the trace.
151
+ *
152
+ * The chunk's text is not here. A trace is read by people who may not be
153
+ * entitled to the document, and a retrieval event that quoted it would be a
154
+ * copy of the content outside the store that governs access to it.
155
+ */
156
+ export const retrievedChunkSchema = z.object({
157
+ source_id: z.string(),
158
+ source_title: z.string(),
159
+ collection_name: z.string(),
160
+ score: z.number(),
161
+ generation: z.number(),
162
+ });
163
+ /** The states a worker may claim, and what it moves them to. */
164
+ export const INGESTIBLE_STATUSES = ["pending"];
165
+ /** Statuses from which nothing further happens on its own. */
166
+ export const TERMINAL_STATUSES = ["ready", "failed"];
167
+ /** Whether a source is still on its way to being searchable. */
168
+ export function isInFlight(status) {
169
+ return !TERMINAL_STATUSES.includes(status);
170
+ }