@b2y/ai-service 0.0.0-stage → 1.0.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.
@@ -0,0 +1,243 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { AiServiceError, ErrorCodes, summarizeZodError } from "./Errors.js";
4
+ import { MAX_GRANTS } from "../constants/AssistantConstants.js";
5
+ import { DATA_CLASSIFICATION } from "../enums/DataClassification.js";
6
+ export { AI_ASSISTANT_PERMISSION, MAX_GRANTS } from "../constants/AssistantConstants.js";
7
+
8
+ const DATA_CLASSIFICATIONS = Object.freeze(Object.values(DATA_CLASSIFICATION));
9
+
10
+ /** Dotted lowercase identifiers such as "ticket.summary". */
11
+ export const taskIdSchema = z
12
+ .string()
13
+ .max(100)
14
+ .regex(/^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/);
15
+
16
+ export const dataClassificationSchema = z.enum(DATA_CLASSIFICATIONS);
17
+
18
+ export function classificationRank(classification) {
19
+ return DATA_CLASSIFICATIONS.indexOf(classification);
20
+ }
21
+
22
+ /**
23
+ * Roles and permissions are global across B2Y applications: a role grants named permissions, optionally
24
+ * grouped by module ("Order Management" / "Generate Order Report"), or codes ("VIEW_USERS"); a plan enables
25
+ * features ("ACCESS_ORDER").
26
+ */
27
+ export const grantNameSchema = z.string().regex(/^[a-z0-9_]{1,80}(:[a-z0-9_]{1,80})?$/);
28
+
29
+ const namePart = (value) =>
30
+ String(value ?? "")
31
+ .trim()
32
+ .toLowerCase()
33
+ .replace(/[^a-z0-9]+/g, "_")
34
+ .replace(/^_+|_+$/g, "");
35
+
36
+ /**
37
+ * The normalized key of a permission or feature: "Module:Name", a code, or a role row such as
38
+ * { Module, Name } / { module, name } / { code }. Returns null for anything without a name.
39
+ * @param {string | { module?: string, Module?: string, name?: string, Name?: string, code?: string, Code?: string }} value
40
+ */
41
+ export function permissionKey(value) {
42
+ let module;
43
+ let name;
44
+ if (typeof value === "string") {
45
+ const colon = value.indexOf(":");
46
+ [module, name] = colon >= 0 ? [value.slice(0, colon), value.slice(colon + 1)] : [undefined, value];
47
+ } else if (value && typeof value === "object") {
48
+ module = value.module ?? value.Module;
49
+ name = value.name ?? value.Name ?? value.code ?? value.Code;
50
+ } else {
51
+ return null;
52
+ }
53
+ const key = namePart(name);
54
+ if (!key) return null;
55
+ const group = module === undefined || module === null ? "" : namePart(module);
56
+ return group ? `${group}:${key}` : key;
57
+ }
58
+
59
+ /** Normalized, de-duplicated keys of a role's permissions (rows or names), ready for context.permissions. */
60
+ export function rolePermissions(values) {
61
+ return [...new Set((Array.isArray(values) ? values : []).map(permissionKey).filter(Boolean))];
62
+ }
63
+
64
+ const nameOf = (key) => key.slice(key.indexOf(":") + 1);
65
+ const moduleOf = (key) => (key.includes(":") ? key.slice(0, key.indexOf(":")) : null);
66
+
67
+ /** A granted key satisfies a required key with the same name; modules must match only when both have one. */
68
+ function grants(granted, required) {
69
+ return granted.some((key) => key === required || (nameOf(key) === nameOf(required) && (moduleOf(key) === null || moduleOf(required) === null)));
70
+ }
71
+
72
+ const referenceSchema = z
73
+ .string()
74
+ .min(1)
75
+ .max(128)
76
+ .regex(/^[A-Za-z0-9][A-Za-z0-9._:@-]*$/);
77
+
78
+ /** Identity and authorization facts about one AI request: the application context contract. */
79
+ export const trustedContextSchema = z.strictObject({
80
+ applicationId: z.string().regex(/^[a-z][a-z0-9-]{0,63}$/),
81
+ tenantId: referenceSchema,
82
+ actor: z.strictObject({
83
+ userId: referenceSchema,
84
+ }),
85
+ requestId: referenceSchema,
86
+ permittedTasks: z.array(taskIdSchema).max(100).readonly(),
87
+ dataClassification: dataClassificationSchema,
88
+ permissions: z.array(grantNameSchema).max(MAX_GRANTS).readonly().optional(),
89
+ features: z.array(grantNameSchema).max(MAX_GRANTS).readonly().optional(),
90
+ metadata: z
91
+ .strictObject({
92
+ locale: z
93
+ .string()
94
+ .regex(/^[a-z]{2,3}(-[A-Z]{2})?$/)
95
+ .optional(),
96
+ channel: z
97
+ .string()
98
+ .regex(/^[a-z][a-z0-9-]{0,31}$/)
99
+ .optional(),
100
+ })
101
+ .optional(),
102
+ });
103
+
104
+ /** Validates the context and returns a deep-frozen copy. */
105
+ export function parseTrustedContext(value) {
106
+ // Role permissions and plan features arrive as the application stores them; normalize before checking.
107
+ const normalized =
108
+ value && typeof value === "object"
109
+ ? {
110
+ ...value,
111
+ ...(Array.isArray(value.permissions) ? { permissions: value.permissions.map((item) => permissionKey(item) ?? item) } : {}),
112
+ ...(Array.isArray(value.features) ? { features: value.features.map((item) => permissionKey(item) ?? item) } : {}),
113
+ }
114
+ : value;
115
+ const result = trustedContextSchema.safeParse(normalized);
116
+ if (!result.success) {
117
+ throw new AiServiceError(ErrorCodes.CONTEXT_INVALID, "Trusted context is invalid", {
118
+ details: summarizeZodError(result.error, trustedContextSchema),
119
+ });
120
+ }
121
+ const { actor, permittedTasks, permissions, features, metadata, ...rest } = result.data;
122
+ return Object.freeze({
123
+ ...rest,
124
+ actor: Object.freeze({ ...actor }),
125
+ permittedTasks: Object.freeze([...permittedTasks]),
126
+ ...(permissions === undefined ? {} : { permissions: Object.freeze([...new Set(permissions)]) }),
127
+ ...(features === undefined ? {} : { features: Object.freeze([...new Set(features)]) }),
128
+ ...(metadata === undefined ? {} : { metadata: Object.freeze({ ...metadata }) }),
129
+ });
130
+ }
131
+
132
+ /**
133
+ * Access is decided from the trusted context: the role's permissions and the tenant's plan features, both
134
+ * supplied by the application from its own session. The model never grants anything. A context without
135
+ * `permissions` or `features` grants none.
136
+ *
137
+ * A requirement lists what is needed: `permission` and `feature` each take one name or a list meaning
138
+ * "any of these". Both must be met when both are given.
139
+ * @typedef {{ permission?: string | string[], feature?: string | string[] }} Requirement
140
+ */
141
+
142
+ const asList = (value) => (value === undefined ? [] : Array.isArray(value) ? value : [value]);
143
+
144
+ /** Validates and normalizes a requirement at setup time, so a typo fails at startup rather than per request. */
145
+ export function checkRequirement(requirement, where) {
146
+ if (requirement === undefined) return Object.freeze({});
147
+ const { permission, feature, ...rest } = requirement ?? {};
148
+ const permissions = asList(permission).map(permissionKey);
149
+ const features = asList(feature).map(permissionKey);
150
+ const invalid =
151
+ typeof requirement !== "object" ||
152
+ requirement === null ||
153
+ Object.keys(rest).length > 0 ||
154
+ [...permissions, ...features].some((key) => key === null || !grantNameSchema.safeParse(key).success) ||
155
+ (permission !== undefined && permissions.length === 0) ||
156
+ (feature !== undefined && features.length === 0);
157
+ if (invalid) throw new AiServiceError(ErrorCodes.CONFIG_INVALID, `${where}: a requirement is { permission?, feature? }, each a name or a list of names`);
158
+ return Object.freeze({
159
+ ...(permissions.length ? { permission: Object.freeze(permissions) } : {}),
160
+ ...(features.length ? { feature: Object.freeze(features) } : {}),
161
+ });
162
+ }
163
+
164
+ /**
165
+ * Whether a parsed context meets a checked requirement, and if not, what is missing ("permission" is
166
+ * reported before "feature").
167
+ * @returns {{ ok: boolean, missing: "permission" | "feature" | null }}
168
+ */
169
+ export function meetsRequirement(context, requirement) {
170
+ const permitted = !requirement.permission || requirement.permission.some((key) => grants(context.permissions ?? [], key));
171
+ if (!permitted) return { ok: false, missing: "permission" };
172
+ const enabled = !requirement.feature || requirement.feature.some((key) => grants(context.features ?? [], key));
173
+ return enabled ? { ok: true, missing: null } : { ok: false, missing: "feature" };
174
+ }
175
+
176
+ /** Whether the context's role grants this permission (any of a list). */
177
+ export function hasPermission(context, permission) {
178
+ return meetsRequirement(parseTrustedContext(context), checkRequirement({ permission }, "hasPermission")).ok;
179
+ }
180
+
181
+ /** Whether the tenant's plan enables this feature (any of a list). */
182
+ export function hasFeature(context, feature) {
183
+ return meetsRequirement(parseTrustedContext(context), checkRequirement({ feature }, "hasFeature")).ok;
184
+ }
185
+
186
+ /**
187
+ * Throws NOT_AUTHORIZED or FEATURE_NOT_ENABLED unless the context meets the requirement. Returns the
188
+ * parsed, frozen context. Error details name the requirement, never the context's other grants.
189
+ * @param {TrustedContextInput} context
190
+ * @param {Requirement} requirement
191
+ */
192
+ export function assertAuthorized(context, requirement = {}) {
193
+ const parsed = parseTrustedContext(context);
194
+ const checked = checkRequirement(requirement, "assertAuthorized");
195
+ const { missing } = meetsRequirement(parsed, checked);
196
+ if (missing === "permission") {
197
+ throw new AiServiceError(ErrorCodes.NOT_AUTHORIZED, "The request is not authorized for this operation", { details: { permission: checked.permission.join("|").slice(0, 200) } });
198
+ }
199
+ if (missing === "feature") {
200
+ throw new AiServiceError(ErrorCodes.FEATURE_NOT_ENABLED, "This feature is not enabled for the tenant", { details: { feature: checked.feature.join("|").slice(0, 200) } });
201
+ }
202
+ return parsed;
203
+ }
204
+
205
+ /**
206
+ * The global tenant rule: the tenant the request arrived for (resolved from its domain) must be present and be
207
+ * the tenant of the signed-in session (token). Returns the verified tenant id; throws TENANT_MISMATCH.
208
+ * @param {{ requestTenantId: unknown, sessionTenantId: unknown }} tenants
209
+ */
210
+ export function resolveTenantId({ requestTenantId, sessionTenantId }) {
211
+ const present = (value) => value !== undefined && value !== null && String(value).trim() !== "";
212
+ if (!present(requestTenantId) || !present(sessionTenantId) || String(requestTenantId) !== String(sessionTenantId)) {
213
+ throw new AiServiceError(ErrorCodes.TENANT_MISMATCH, "The session does not belong to the tenant of this request");
214
+ }
215
+ return String(requestTenantId);
216
+ }
217
+
218
+ /**
219
+ * The trusted context for one request, built the same way in every application: the verified tenant (from
220
+ * the request and session tenants, or a fixed scope for applications without tenants), the signed-in user,
221
+ * the role's permissions and the plan's features as stored, and the tasks the assistant may run.
222
+ * @param {{ applicationId: string, requestTenantId?: unknown, sessionTenantId?: unknown, scope?: string, userId: unknown,
223
+ * permissions?: unknown[], features?: unknown[], tasks: readonly ({ id: string } | string)[], dataClassification?: string, requestId?: string }} options
224
+ */
225
+ export function buildTrustedContext({ applicationId, requestTenantId, sessionTenantId, scope, userId, permissions = [], features = [], tasks, dataClassification = DATA_CLASSIFICATION.INTERNAL, requestId = randomUUID() }) {
226
+ const tenantId = scope === undefined ? resolveTenantId({ requestTenantId, sessionTenantId }) : String(scope);
227
+ if (userId === undefined || userId === null || String(userId) === "") throw new AiServiceError(ErrorCodes.CONTEXT_INVALID, "A signed-in user is required");
228
+ return parseTrustedContext({
229
+ applicationId,
230
+ tenantId,
231
+ actor: { userId: String(userId) },
232
+ requestId,
233
+ permittedTasks: (tasks ?? []).map((task) => (typeof task === "string" ? task : task.id)),
234
+ dataClassification,
235
+ permissions: rolePermissions(permissions),
236
+ features: rolePermissions(features),
237
+ });
238
+ }
239
+
240
+ /** An authorization refusal decided by the application (for example an inactive user), handled like the package's own. */
241
+ export function accessDenied(reason) {
242
+ return new AiServiceError(ErrorCodes.NOT_AUTHORIZED, String(reason ?? "Access denied").slice(0, 200));
243
+ }
@@ -0,0 +1,249 @@
1
+ import { z } from "zod";
2
+ import { AI_BUSY_MESSAGE } from "../constants/ProviderConstants.js";
3
+ export { AI_BUSY_MESSAGE } from "../constants/ProviderConstants.js";
4
+
5
+ /** Every code an AiServiceError can carry. */
6
+ export const ErrorCodes = {
7
+ CONFIG_INVALID: "CONFIG_INVALID",
8
+ CONTEXT_INVALID: "CONTEXT_INVALID",
9
+ TASK_UNKNOWN: "TASK_UNKNOWN",
10
+ TASK_NOT_PERMITTED: "TASK_NOT_PERMITTED",
11
+ TENANT_MISMATCH: "TENANT_MISMATCH",
12
+ NOT_AUTHORIZED: "NOT_AUTHORIZED",
13
+ FEATURE_NOT_ENABLED: "FEATURE_NOT_ENABLED",
14
+ CLASSIFICATION_NOT_ALLOWED: "CLASSIFICATION_NOT_ALLOWED",
15
+ INPUT_INVALID: "INPUT_INVALID",
16
+ REQUEST_TOO_LARGE: "REQUEST_TOO_LARGE",
17
+ PROVIDER_TIMEOUT: "PROVIDER_TIMEOUT",
18
+ PROVIDER_UNAVAILABLE: "PROVIDER_UNAVAILABLE",
19
+ PROVIDER_HTTP_ERROR: "PROVIDER_HTTP_ERROR",
20
+ PROVIDER_RATE_LIMITED: "PROVIDER_RATE_LIMITED",
21
+ PROVIDER_OUTPUT_REJECTED: "PROVIDER_OUTPUT_REJECTED",
22
+ PROVIDER_RESPONSE_INVALID: "PROVIDER_RESPONSE_INVALID",
23
+ CANCELLED: "CANCELLED",
24
+ OUTPUT_PARSE_FAILED: "OUTPUT_PARSE_FAILED",
25
+ OUTPUT_SCHEMA_INVALID: "OUTPUT_SCHEMA_INVALID",
26
+ OUTPUT_REJECTED: "OUTPUT_REJECTED",
27
+ DOCUMENT_SOURCE_INVALID: "DOCUMENT_SOURCE_INVALID",
28
+ DOCUMENT_SOURCE_FAILED: "DOCUMENT_SOURCE_FAILED",
29
+ CAPABILITY_FAILED: "CAPABILITY_FAILED",
30
+ CAPABILITY_TIMEOUT: "CAPABILITY_TIMEOUT",
31
+ USAGE_RECORDING_FAILED: "USAGE_RECORDING_FAILED",
32
+ INTERNAL_ERROR: "INTERNAL_ERROR",
33
+ };
34
+
35
+ /**
36
+ * What kind of failure a code is, so consumers can map errors to responses without listing codes:
37
+ * configuration the consumer's setup is invalid (fix the code or config; never retried) context the trusted
38
+ * context is malformed authorization the context does not permit this (task, permission, feature or data
39
+ * classification) validation the request or tool input is invalid provider the model provider failed or
40
+ * returned something unusable rate_limit the provider's rate limit was reached (retry later) output the
41
+ * model's output failed validation execution a consumer-supplied executor (tool, document source) failed or
42
+ * returned invalid data cancelled the caller cancelled internal a bug or an unexpected failure
43
+ */
44
+ export const ErrorCategories = Object.freeze({
45
+ CONFIG_INVALID: "configuration",
46
+ CONTEXT_INVALID: "context",
47
+ TASK_UNKNOWN: "configuration",
48
+ TASK_NOT_PERMITTED: "authorization",
49
+ TENANT_MISMATCH: "authorization",
50
+ NOT_AUTHORIZED: "authorization",
51
+ FEATURE_NOT_ENABLED: "authorization",
52
+ CLASSIFICATION_NOT_ALLOWED: "authorization",
53
+ INPUT_INVALID: "validation",
54
+ REQUEST_TOO_LARGE: "validation",
55
+ PROVIDER_TIMEOUT: "provider",
56
+ PROVIDER_UNAVAILABLE: "provider",
57
+ PROVIDER_HTTP_ERROR: "provider",
58
+ PROVIDER_RATE_LIMITED: "rate_limit",
59
+ PROVIDER_OUTPUT_REJECTED: "output",
60
+ PROVIDER_RESPONSE_INVALID: "provider",
61
+ CANCELLED: "cancelled",
62
+ OUTPUT_PARSE_FAILED: "output",
63
+ OUTPUT_SCHEMA_INVALID: "output",
64
+ OUTPUT_REJECTED: "output",
65
+ DOCUMENT_SOURCE_INVALID: "execution",
66
+ DOCUMENT_SOURCE_FAILED: "execution",
67
+ CAPABILITY_FAILED: "execution",
68
+ CAPABILITY_TIMEOUT: "execution",
69
+ USAGE_RECORDING_FAILED: "internal",
70
+ INTERNAL_ERROR: "internal",
71
+ });
72
+
73
+ /**
74
+ * @typedef {string | number | boolean} ErrorDetailValue
75
+ */
76
+
77
+ /**
78
+ * @typedef {Readonly<Record<string, ErrorDetailValue>>} ErrorDetails
79
+ */
80
+
81
+ /**
82
+ * @typedef {Object} AiServiceErrorOptions
83
+ * @property {boolean} [retryable]
84
+ * @property {ErrorDetails} [details]
85
+ * @property {unknown} [cause] - Underlying error. Only its type name and a well-formed error code are kept (see SafeErrorCause).
86
+ */
87
+
88
+ /**
89
+ * What remains of an underlying error. Raw errors are never retained because their messages can quote secrets or content: a header error quotes the header value, a JSON SyntaxError quotes the parsed text, and errors thrown by application hooks can contain anything.
90
+ * @typedef {Object} SafeErrorCause
91
+ * @property {string} name
92
+ * @property {string} [code]
93
+ */
94
+
95
+ /** What remains of an underlying error. */
96
+
97
+ const SAFE_NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
98
+ const SAFE_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
99
+
100
+ /** The only error type the package throws. */
101
+ export class AiServiceError extends Error {
102
+ code;
103
+ retryable;
104
+ details;
105
+
106
+ constructor(code, message, options = {}) {
107
+ super(message, options.cause === undefined ? undefined : { cause: toSafeCause(options.cause) });
108
+ this.name = "AiServiceError";
109
+ this.code = code;
110
+ this.retryable = options.retryable ?? false;
111
+ this.details = Object.freeze({ ...options.details });
112
+ }
113
+ }
114
+
115
+ export function createCancelledError() {
116
+ return new AiServiceError(ErrorCodes.CANCELLED, "The AI request was cancelled");
117
+ }
118
+
119
+ /** Wraps anything that is not already an AiServiceError, keeping only a safe summary of it. */
120
+ export function toAiServiceError(error) {
121
+ if (error instanceof AiServiceError) {
122
+ return error;
123
+ }
124
+ return new AiServiceError(ErrorCodes.INTERNAL_ERROR, "Unexpected error while running the AI task", {
125
+ cause: error,
126
+ });
127
+ }
128
+
129
+ /**
130
+ * Returns a well-formed system error code (for example ECONNREFUSED or UND_ERR_SOCKET) from the error or its
131
+ * direct cause, or undefined.
132
+ */
133
+ export function systemErrorCode(error) {
134
+ for (const candidate of [error, causeOf(error)]) {
135
+ if (typeof candidate === "object" && candidate !== null && "code" in candidate) {
136
+ const code = candidate.code;
137
+ if (typeof code === "string" && SAFE_CODE.test(code)) {
138
+ return code;
139
+ }
140
+ }
141
+ }
142
+ return undefined;
143
+ }
144
+
145
+ function causeOf(error) {
146
+ return error instanceof Error ? error.cause : undefined;
147
+ }
148
+
149
+ function toSafeCause(cause) {
150
+ if (cause instanceof AiServiceError) {
151
+ return Object.freeze({ name: cause.name, code: cause.code });
152
+ }
153
+ const name = cause instanceof Error && SAFE_NAME.test(cause.name) ? cause.name : typeof cause;
154
+ const code = systemErrorCode(cause);
155
+ return Object.freeze(code === undefined ? { name } : { name, code });
156
+ }
157
+
158
+ /** The category of an error (see ErrorCategories): "rate_limit", "authorization", "provider" ... */
159
+ export function errorCategory(error) {
160
+ return error instanceof AiServiceError && Object.hasOwn(ErrorCategories, error.code) ? ErrorCategories[error.code] : "internal";
161
+ }
162
+
163
+ export function isRateLimited(error) {
164
+ return error instanceof AiServiceError && error.code === ErrorCodes.PROVIDER_RATE_LIMITED;
165
+ }
166
+
167
+ /**
168
+ * Rate-limit details for logs and metadata; cooldown is true when the provider was not called.
169
+ * @returns {{ status: number, retryAfterSeconds: number | null, cooldown: boolean } | null}
170
+ */
171
+ export function rateLimitInfo(error) {
172
+ if (!isRateLimited(error)) return null;
173
+ const seconds = Number(error.details.retryAfterSeconds);
174
+ return { status: 429, retryAfterSeconds: Number.isFinite(seconds) ? seconds : null, cooldown: error.details.cooldown === true };
175
+ }
176
+
177
+ /** The message to show a user for an AI error: AI_BUSY_MESSAGE for rate limits, otherwise the fallback. */
178
+ export function aiUserMessage(error, fallback) {
179
+ return isRateLimited(error) ? AI_BUSY_MESSAGE : fallback;
180
+ }
181
+
182
+ const MAX_REPORTED_ISSUES = 5;
183
+
184
+ /** Placeholder for a path segment that is not a property name declared by the schema. */
185
+ export const REDACTED_SEGMENT = "*";
186
+
187
+ const declaredKeysCache = new WeakMap();
188
+
189
+ /** Reduces a ZodError to issue counts, codes and paths that are safe to log. */
190
+ export function summarizeZodError(error, schema) {
191
+ const declared = declaredKeys(schema);
192
+ const paths = error.issues
193
+ .slice(0, MAX_REPORTED_ISSUES)
194
+ .map((issue) =>
195
+ issue.path.length === 0
196
+ ? "(root)"
197
+ : issue.path
198
+ .map((segment) =>
199
+ typeof segment === "number" || (typeof segment === "string" && declared.has(segment))
200
+ ? String(segment)
201
+ : REDACTED_SEGMENT,
202
+ )
203
+ .join("."),
204
+ );
205
+ const codes = [...new Set(error.issues.map((issue) => issue.code))];
206
+ return {
207
+ issueCount: error.issues.length,
208
+ paths: paths.join(",").slice(0, 300),
209
+ codes: codes.join(",").slice(0, 200),
210
+ };
211
+ }
212
+
213
+ function declaredKeys(schema) {
214
+ const cached = declaredKeysCache.get(schema);
215
+ if (cached !== undefined) {
216
+ return cached;
217
+ }
218
+ const keys = new Set();
219
+ try {
220
+ collectPropertyNames(z.toJSONSchema(schema, { io: "input", unrepresentable: "any" }), keys);
221
+ } catch {
222
+ // A schema that cannot be described yields no declared keys, so every
223
+ // named path segment is redacted: the safe outcome.
224
+ keys.clear();
225
+ }
226
+ declaredKeysCache.set(schema, keys);
227
+ return keys;
228
+ }
229
+
230
+ function collectPropertyNames(node, into) {
231
+ if (Array.isArray(node)) {
232
+ for (const item of node) {
233
+ collectPropertyNames(item, into);
234
+ }
235
+ return;
236
+ }
237
+ if (typeof node !== "object" || node === null) {
238
+ return;
239
+ }
240
+ const entries = Object.entries(node);
241
+ for (const [keyword, value] of entries) {
242
+ if (keyword === "properties" && typeof value === "object" && value !== null && !Array.isArray(value)) {
243
+ for (const name of Object.keys(value)) {
244
+ into.add(name);
245
+ }
246
+ }
247
+ collectPropertyNames(value, into);
248
+ }
249
+ }
@@ -0,0 +1,190 @@
1
+ import { z } from "zod";
2
+ import { dataClassificationSchema, taskIdSchema } from "./Context.js";
3
+ import { AiServiceError, ErrorCodes, summarizeZodError } from "./Errors.js";
4
+
5
+ /**
6
+ * @typedef {{ readonly ok: true } | { readonly ok: false; readonly reason: string }} PostValidationResult
7
+ */
8
+
9
+ /**
10
+ * One AI task. A task never has tools and never builds prompt strings from data: it supplies fixed `instructions`, and the orchestrator places the (minimized) input in a delimited, escaped untrusted-data block.
11
+ * @template TInput
12
+ * @template TOutput
13
+ * @typedef {Object} TaskDefinition
14
+ * @property {string} id
15
+ * @property {number} version - Bump when the input or output contract changes.
16
+ * @property {string} promptVersion - Bump when instructions or generation settings change, for evaluation tracking.
17
+ * @property {string} description
18
+ * @property {string} instructions
19
+ * @property {string} dataLabel - Short label naming the data, for example "support ticket".
20
+ * @property {TInput} inputSchema
21
+ * @property {TOutput} outputSchema
22
+ * @property {GenerationSettings} generation
23
+ * @property {DataClassification} maxClassification - Most sensitive data classification this task is approved for.
24
+ * @property {(input: z.output<TInput>) => unknown} [minimize] - Selects only the fields the model needs. Defaults to the whole validated input.
25
+ * @property {(output: z.output<TOutput>, input: z.output<TInput>) => PostValidationResult} [postValidate] - Business checks on schema-valid output, such as confidence thresholds. Failing it fails the task.
26
+ */
27
+
28
+ /**
29
+ * @template TInput
30
+ * @template TOutput
31
+ * Also has every field of TaskDefinition<TInput, TOutput>.
32
+ * @typedef {Object} RegisteredTask
33
+ * @property {object} outputJsonSchema - JSON Schema generated from outputSchema, sent to the provider for constrained decoding.
34
+ */
35
+
36
+ /**
37
+ * @typedef {RegisteredTask<z.ZodType, z.ZodType>} AnyTask
38
+ */
39
+
40
+ /** One AI task. */
41
+
42
+ const definitionSchema = z.object({
43
+ id: taskIdSchema,
44
+ version: z.number().int().min(1).max(10_000),
45
+ promptVersion: z.string().regex(/^v\d+(\.\d+){0,2}$/),
46
+ description: z.string().min(1).max(500),
47
+ instructions: z.string().trim().min(1).max(8000),
48
+ dataLabel: z.string().regex(/^[a-z][a-z ]{0,39}$/),
49
+ generation: z.strictObject({
50
+ temperature: z.number().min(0).max(2),
51
+ maxTokens: z.number().int().min(1).max(32_768),
52
+ topP: z.number().gt(0).max(1).optional(),
53
+ seed: z.number().int().optional(),
54
+ }),
55
+ maxClassification: dataClassificationSchema,
56
+ });
57
+
58
+ const ALLOWED_KEYS = new Set([...Object.keys(definitionSchema.shape), "inputSchema", "outputSchema", "minimize", "postValidate"]);
59
+
60
+ const definedTasks = new WeakSet();
61
+
62
+ /** Validates and freezes a task definition. */
63
+ export function defineTask(definition) {
64
+ // Unknown keys are refused rather than ignored, so a definition such as
65
+ // `{ tools: [...] }` fails loudly instead of appearing to configure tools.
66
+ const unknownKey = Object.keys(definition).find((key) => !ALLOWED_KEYS.has(key));
67
+ if (unknownKey !== undefined) {
68
+ throw new AiServiceError(ErrorCodes.CONFIG_INVALID, "Task definition has an unsupported field", {
69
+ details: { field: unknownKey.slice(0, 64) },
70
+ });
71
+ }
72
+ const checked = definitionSchema.safeParse(definition);
73
+ if (!checked.success) {
74
+ throw new AiServiceError(ErrorCodes.CONFIG_INVALID, "Task definition is invalid", {
75
+ details: summarizeZodError(checked.error, definitionSchema),
76
+ });
77
+ }
78
+ if (!isZodSchema(definition.inputSchema) || !isZodSchema(definition.outputSchema)) {
79
+ throw new AiServiceError(ErrorCodes.CONFIG_INVALID, "Task schemas must be Zod schemas", {
80
+ details: { taskId: definition.id },
81
+ });
82
+ }
83
+
84
+ let outputJsonSchema;
85
+ try {
86
+ // The model produces the schema's input side, so generate from "input".
87
+ const generated = { ...z.toJSONSchema(definition.outputSchema, { io: "input" }) };
88
+ outputJsonSchema = Object.fromEntries(Object.entries(generated).filter(([keyword]) => keyword !== "$schema"));
89
+ } catch (error) {
90
+ throw new AiServiceError(ErrorCodes.CONFIG_INVALID, "Task output schema cannot be expressed as JSON Schema", {
91
+ details: { taskId: definition.id },
92
+ cause: error,
93
+ });
94
+ }
95
+ if (!("type" in outputJsonSchema) || outputJsonSchema.type !== "object") {
96
+ throw new AiServiceError(ErrorCodes.CONFIG_INVALID, "Task output schema must describe a JSON object", {
97
+ details: { taskId: definition.id },
98
+ });
99
+ }
100
+ // Every object in the output must be strict (z.strictObject).
101
+ const looseObjectPath = findNonStrictObject(outputJsonSchema, "(root)");
102
+ if (looseObjectPath !== undefined) {
103
+ throw new AiServiceError(ErrorCodes.CONFIG_INVALID, "Task output objects must be strict (use z.strictObject)", {
104
+ details: { taskId: definition.id, schemaPath: looseObjectPath.slice(0, 200) },
105
+ });
106
+ }
107
+
108
+ const task = Object.freeze({
109
+ ...definition,
110
+ generation: Object.freeze({ ...definition.generation }),
111
+ outputJsonSchema: deepFreeze(outputJsonSchema),
112
+ });
113
+ definedTasks.add(task);
114
+ return task;
115
+ }
116
+
117
+ export function isRegisteredTask(value) {
118
+ return typeof value === "object" && value !== null && definedTasks.has(value);
119
+ }
120
+
121
+ /** Returns the JSON Schema path of the first object node without `additionalProperties: false`. */
122
+ function findNonStrictObject(node, path) {
123
+ if (Array.isArray(node)) {
124
+ for (const [index, item] of node.entries()) {
125
+ const found = findNonStrictObject(item, `${path}.${String(index)}`);
126
+ if (found !== undefined) {
127
+ return found;
128
+ }
129
+ }
130
+ return undefined;
131
+ }
132
+ if (typeof node !== "object" || node === null) {
133
+ return undefined;
134
+ }
135
+ const isObjectSchema =
136
+ ("type" in node && (node.type === "object" || (Array.isArray(node.type) && node.type.includes("object")))) ||
137
+ "properties" in node;
138
+ if (isObjectSchema && (!("additionalProperties" in node) || node.additionalProperties !== false)) {
139
+ return path;
140
+ }
141
+ for (const [keyword, value] of Object.entries(node)) {
142
+ const found = findNonStrictObject(value, `${path}.${keyword}`);
143
+ if (found !== undefined) {
144
+ return found;
145
+ }
146
+ }
147
+ return undefined;
148
+ }
149
+
150
+ function isZodSchema(value) {
151
+ return value instanceof z.ZodType;
152
+ }
153
+
154
+ function deepFreeze(value) {
155
+ for (const nested of Object.values(value)) {
156
+ if (typeof nested === "object" && nested !== null) {
157
+ deepFreeze(nested);
158
+ }
159
+ }
160
+ return Object.freeze(value);
161
+ }
162
+
163
+ /**
164
+ * @typedef {Object} TaskRegistry
165
+ * @property {readonly string[]} ids
166
+ * @property {(id: string) => AnyTask | undefined} get
167
+ * @property {(task: AnyTask) => boolean} has - True only for the exact task object that was registered.
168
+ */
169
+
170
+ /** Builds an immutable registry. Duplicate IDs and tasks not created by defineTask are refused. */
171
+ export function createTaskRegistry(tasks) {
172
+ const byId = new Map();
173
+ for (const task of tasks) {
174
+ if (!isRegisteredTask(task)) {
175
+ throw new AiServiceError(ErrorCodes.CONFIG_INVALID, "Tasks must be created with defineTask");
176
+ }
177
+ if (byId.has(task.id)) {
178
+ throw new AiServiceError(ErrorCodes.CONFIG_INVALID, "Duplicate task id in registry", {
179
+ details: { taskId: task.id },
180
+ });
181
+ }
182
+ byId.set(task.id, task);
183
+ }
184
+
185
+ return Object.freeze({
186
+ ids: Object.freeze([...byId.keys()]),
187
+ get: (id) => byId.get(id),
188
+ has: (task) => isRegisteredTask(task) && byId.get(task.id) === task,
189
+ });
190
+ }