@m6d/cortex 0.3.0 → 0.5.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.
package/dist/index.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import {
2
2
  BACKEND_ERROR_STATUS,
3
3
  CortexError,
4
+ DATASET_REQUEST_MAX_BYTES,
4
5
  backendErrorSchema,
5
6
  boundDatasetResult,
6
7
  checkDatasetQuery,
8
+ contentVersion,
7
9
  datasetCatalogOf,
8
10
  datasetDefinitionSchema,
9
11
  datasetIdentifierSchema,
@@ -11,13 +13,14 @@ import {
11
13
  envelopeOf,
12
14
  errorEnvelope,
13
15
  isRecord,
14
- unescapePointerToken
15
- } from "./index-dck60t84.js";
16
+ malformedBody,
17
+ protocolBodyLimit,
18
+ readJsonPointer
19
+ } from "./index-jw8cnjqv.js";
16
20
 
17
- // src/server.ts
21
+ // src/server/server.ts
18
22
  import { createHash, timingSafeEqual } from "node:crypto";
19
23
  import { Hono } from "hono";
20
- import { bodyLimit } from "hono/body-limit";
21
24
  import { z as z3 } from "zod";
22
25
 
23
26
  // ../../node_modules/.bun/re2js@2.8.8/node_modules/re2js/build/index.js
@@ -6953,6 +6956,34 @@ var REQUEST_LOCATION_TOOL = "requestLocation";
6953
6956
 
6954
6957
  // ../../internal/contracts/src/triggers/index.ts
6955
6958
  import { z } from "zod";
6959
+
6960
+ // ../../internal/contracts/src/wire/index.ts
6961
+ var LOCALES = ["en", "ar"];
6962
+ var BASE_LOCALE = LOCALES[0];
6963
+ function byLocale(valueOf) {
6964
+ const entries = LOCALES.map((locale) => [locale, valueOf(locale)]);
6965
+ return Object.fromEntries(entries);
6966
+ }
6967
+ var TOOL_SURFACES = ["inline", "modal"];
6968
+ var MEDIA_FORMS = ["mermaid", "vega-lite", "map", "report"];
6969
+ var DEFAULT_MEDIA_FORMS = [
6970
+ "mermaid",
6971
+ "vega-lite",
6972
+ "map"
6973
+ ];
6974
+ var ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024;
6975
+ var APPROVAL_TITLE_FIELD = "approvalTitle";
6976
+ var TRIGGER_DROP_REASONS = ["busy", "approval_pending", "budget", "rate_limited"];
6977
+ var TRIGGER_REASONS = [
6978
+ ...TRIGGER_DROP_REASONS,
6979
+ "invalid_payload",
6980
+ "missing_thread_key",
6981
+ "no_turn",
6982
+ "no_output",
6983
+ "invalid_output"
6984
+ ];
6985
+
6986
+ // ../../internal/contracts/src/triggers/index.ts
6956
6987
  var MESSAGE_TRIGGER_NAME = "message";
6957
6988
  var TRIGGER_ANSWER_TOOL_NAME = "submitAnswer";
6958
6989
  var TRIGGER_OUTCOMES = [
@@ -6963,7 +6994,12 @@ var TRIGGER_OUTCOMES = [
6963
6994
  "rejected",
6964
6995
  "dropped"
6965
6996
  ];
6966
- var TRIGGER_DROP_REASONS = ["busy", "approval_pending", "budget", "rate_limited"];
6997
+ function agentRoute(agentSlug) {
6998
+ return `/agents/${encodeURIComponent(agentSlug)}`;
6999
+ }
7000
+ function triggerRoute(agentSlug, name) {
7001
+ return `${agentRoute(agentSlug)}/triggers/${encodeURIComponent(name)}`;
7002
+ }
6967
7003
  var pendingApprovalSchema = z.object({
6968
7004
  toolCallId: z.string(),
6969
7005
  toolName: z.string(),
@@ -6995,7 +7031,7 @@ var triggerFiringResponseSchema = z.discriminatedUnion("outcome", [
6995
7031
  outcome: z.literal("failed"),
6996
7032
  threadId: z.uuid(),
6997
7033
  runId: z.string(),
6998
- reason: z.string().nullable()
7034
+ reason: z.enum(TRIGGER_REASONS).nullable()
6999
7035
  }),
7000
7036
  z.object({
7001
7037
  firingId: z.uuid(),
@@ -7019,38 +7055,35 @@ var triggerFiringRecordSchema = z.object({
7019
7055
  threadId: z.uuid().nullable(),
7020
7056
  runId: z.string().nullable(),
7021
7057
  outcome: z.enum(TRIGGER_OUTCOMES),
7022
- reason: z.string().nullable(),
7058
+ reason: z.enum(TRIGGER_REASONS).nullable(),
7023
7059
  output: z.unknown(),
7024
7060
  approvals: z.array(pendingApprovalSchema),
7025
7061
  createdAt: z.iso.datetime(),
7026
7062
  finishedAt: z.iso.datetime().nullable()
7027
7063
  });
7028
7064
 
7029
- // ../../internal/contracts/src/wire/index.ts
7030
- var LOCALES = ["en", "ar"];
7031
- var TOOL_SURFACES = ["inline", "modal"];
7032
- var MEDIA_FORMS = ["mermaid", "vega-lite", "map", "report"];
7033
- var DEFAULT_MEDIA_FORMS = [
7034
- "mermaid",
7035
- "vega-lite",
7036
- "map"
7037
- ];
7038
- var ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024;
7039
- var APPROVAL_TITLE_FIELD = "approvalTitle";
7040
-
7041
7065
  // ../../internal/contracts/src/server/index.ts
7042
7066
  var END_USER_TOKEN_HEADER = "X-End-User-Token";
7043
7067
  var AGENT_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;
7044
7068
  var agentSlugSchema = z2.string().regex(AGENT_SLUG_PATTERN);
7045
- var userIdSchema = z2.string().max(255);
7069
+ var USER_ID_MAX_LENGTH = 255;
7070
+ var userIdSchema = z2.string().max(USER_ID_MAX_LENGTH);
7046
7071
  var IDENTIFIER_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
7072
+ var IDENTIFIER_MAX_LENGTH = 64;
7073
+ var identifierSchema = z2.string().regex(IDENTIFIER_PATTERN).max(IDENTIFIER_MAX_LENGTH);
7047
7074
  var localeSchema = z2.enum(LOCALES);
7075
+ var SERVER_MANIFEST_LIMITS = {
7076
+ variables: 100,
7077
+ tools: 500,
7078
+ description: 500,
7079
+ example: 200
7080
+ };
7048
7081
  var variableValueSchema = z2.union([z2.string(), z2.number(), z2.boolean()]);
7049
7082
  var variableValuesSchema = z2.record(z2.string(), variableValueSchema);
7050
7083
  var variableDeclarationSchema = z2.object({
7051
- name: z2.string().regex(IDENTIFIER_PATTERN).max(64),
7052
- description: z2.string().max(500),
7053
- example: z2.string().max(200),
7084
+ name: identifierSchema,
7085
+ description: z2.string().max(SERVER_MANIFEST_LIMITS.description),
7086
+ example: z2.string().max(SERVER_MANIFEST_LIMITS.example),
7054
7087
  type: z2.enum(["string", "number", "boolean"]),
7055
7088
  computed: z2.boolean()
7056
7089
  });
@@ -7093,18 +7126,17 @@ var BUILT_IN_TOOL_NAMES = [
7093
7126
  function isBuiltInToolName(name) {
7094
7127
  return BUILT_IN_TOOL_NAMES.some((builtIn) => builtIn === name);
7095
7128
  }
7096
- var TOOL_NAME_MAX_LENGTH = 64;
7097
- var declaredToolNameSchema = z2.string().regex(IDENTIFIER_PATTERN).max(TOOL_NAME_MAX_LENGTH).refine((name) => !isBuiltInToolName(name), "the name of a built-in tool");
7129
+ var declaredToolNameSchema = identifierSchema.refine((name) => !isBuiltInToolName(name), "the name of a built-in tool");
7098
7130
  var jsonSchemaSchema = z2.record(z2.string(), z2.unknown());
7099
7131
  var serverVariableSchema = z2.object({
7100
- name: z2.string().regex(IDENTIFIER_PATTERN).max(64).refine((name) => !BUILT_IN_VARIABLES.some((builtIn) => builtIn.name === name), "the name of a built-in variable"),
7101
- description: z2.string().max(500),
7102
- example: z2.string().max(200),
7132
+ name: identifierSchema.refine((name) => !BUILT_IN_VARIABLES.some((builtIn) => builtIn.name === name), "the name of a built-in variable"),
7133
+ description: z2.string().max(SERVER_MANIFEST_LIMITS.description),
7134
+ example: z2.string().max(SERVER_MANIFEST_LIMITS.example),
7103
7135
  type: variableDeclarationSchema.shape.type
7104
7136
  });
7105
7137
  var serverToolSchema = z2.object({
7106
7138
  name: declaredToolNameSchema,
7107
- description: z2.string().trim().min(1).max(500),
7139
+ description: z2.string().trim().min(1).max(SERVER_MANIFEST_LIMITS.description),
7108
7140
  inputSchema: jsonSchemaSchema.refine((schema) => schema.type === "object", "a tool's input is an object"),
7109
7141
  outputSchema: jsonSchemaSchema.optional(),
7110
7142
  readOnly: z2.boolean(),
@@ -7124,22 +7156,8 @@ var approvalRequestedEventSchema = z2.object({
7124
7156
  approvals: z2.array(pendingApprovalSchema.partial({ input: true })),
7125
7157
  occurredAt: z2.iso.datetime()
7126
7158
  });
7127
- function pointerKey(token) {
7128
- try {
7129
- return unescapePointerToken(decodeURIComponent(token));
7130
- } catch {
7131
- return;
7132
- }
7133
- }
7134
7159
  function pointedAt(root, ref) {
7135
- if (!ref.startsWith("#"))
7136
- return;
7137
- let node = root;
7138
- for (const token of ref.slice(1).split("/").slice(1)) {
7139
- const key = pointerKey(token);
7140
- node = key !== undefined && (isRecord(node) || Array.isArray(node)) ? new Map(Object.entries(node)).get(key) : undefined;
7141
- }
7142
- return node;
7160
+ return ref.startsWith("#") ? readJsonPointer(root, ref) : undefined;
7143
7161
  }
7144
7162
  function namesApprovalTitle(node) {
7145
7163
  const required = node.required;
@@ -7174,22 +7192,18 @@ function closed(node) {
7174
7192
  function blocksApprovalTitle(inputSchema) {
7175
7193
  return sameObjectNodes(inputSchema).some((node) => namesApprovalTitle(node) || node !== inputSchema && closed(node));
7176
7194
  }
7177
- function refuseBlockedApprovalTitle(tool, context, path) {
7195
+ function refuseBlockedApprovalTitle(tool, context, path, message = `a tool that needs approval cannot take an input named ${APPROVAL_TITLE_FIELD}, nor one a closed sub-schema describes: Cortex adds the approval card's title to it`) {
7178
7196
  if (!tool.requiresApproval || !blocksApprovalTitle(tool.inputSchema))
7179
7197
  return;
7180
- context.addIssue({
7181
- code: "custom",
7182
- path: [...path, "inputSchema"],
7183
- message: `a tool that needs approval cannot take an input named ${APPROVAL_TITLE_FIELD}, nor one a closed sub-schema describes: Cortex adds the approval card's title to it`
7184
- });
7198
+ context.addIssue({ code: "custom", path: [...path, "inputSchema"], message });
7185
7199
  }
7186
7200
  function uniqueNames(entries) {
7187
7201
  return new Set(entries.map((entry) => entry.name)).size === entries.length;
7188
7202
  }
7189
7203
  var serverManifestSchema = z2.object({
7190
7204
  version: z2.string().min(1).max(128),
7191
- variables: z2.array(serverVariableSchema).max(100).refine(uniqueNames, "variable names repeat"),
7192
- tools: z2.array(serverToolSchema).max(500).refine(uniqueNames, "tool names repeat").superRefine((tools, context) => {
7205
+ variables: z2.array(serverVariableSchema).max(SERVER_MANIFEST_LIMITS.variables).refine(uniqueNames, "variable names repeat"),
7206
+ tools: z2.array(serverToolSchema).max(SERVER_MANIFEST_LIMITS.tools).refine(uniqueNames, "tool names repeat").superRefine((tools, context) => {
7193
7207
  tools.forEach((tool, index) => refuseBlockedApprovalTitle(tool, context, [index]));
7194
7208
  }),
7195
7209
  verify: z2.boolean(),
@@ -7221,7 +7235,7 @@ var serverEventSchemas = {
7221
7235
  approval_requested: approvalRequestedEventSchema
7222
7236
  };
7223
7237
 
7224
- // src/server.ts
7238
+ // src/server/server.ts
7225
7239
  function digest(value) {
7226
7240
  return createHash("sha256").update(value).digest();
7227
7241
  }
@@ -7230,7 +7244,6 @@ async function bodyOf(request, schema) {
7230
7244
  return;
7231
7245
  })).data;
7232
7246
  }
7233
- var malformed = errorEnvelope("invalid_request", "Malformed request body");
7234
7247
  function dropUncheckablePatterns({
7235
7248
  zodSchema,
7236
7249
  jsonSchema
@@ -7270,8 +7283,7 @@ function manifestOf(options) {
7270
7283
  verify: options.verify !== undefined,
7271
7284
  events: SERVER_EVENTS.filter((event) => options.events?.[event])
7272
7285
  };
7273
- const version = createHash("sha256").update(JSON.stringify(content)).digest("hex");
7274
- return { version, ...content };
7286
+ return { version: contentVersion(content), ...content };
7275
7287
  }
7276
7288
  function defineServer(options) {
7277
7289
  if (!options.key)
@@ -7297,17 +7309,14 @@ function defineServer(options) {
7297
7309
  }
7298
7310
  await next();
7299
7311
  });
7300
- app.use(bodyLimit({
7301
- maxSize: SERVER_REQUEST_MAX_BYTES,
7302
- onError: (c) => c.json(errorEnvelope("invalid_request", "Request body too large"), 413)
7303
- }));
7312
+ app.use(protocolBodyLimit(SERVER_REQUEST_MAX_BYTES));
7304
7313
  app.get("/", function(c) {
7305
7314
  return c.json(manifest);
7306
7315
  });
7307
7316
  post("/variables", async function(c) {
7308
7317
  const body = await bodyOf(c.req, variablesRequestSchema);
7309
7318
  if (!body)
7310
- return c.json(malformed, 400);
7319
+ return c.json(malformedBody, 400);
7311
7320
  const request = { ...body, token: c.req.header(END_USER_TOKEN_HEADER) };
7312
7321
  const values = await Promise.all(Object.entries(options.variables ?? {}).map(async ([name, variable]) => [name, await variable.resolve(request)]));
7313
7322
  return c.json({ values: Object.fromEntries(values) });
@@ -7319,7 +7328,7 @@ function defineServer(options) {
7319
7328
  }
7320
7329
  const body = await bodyOf(c.req, toolRequestSchema);
7321
7330
  if (!body)
7322
- return c.json(malformed, 400);
7331
+ return c.json(malformedBody, 400);
7323
7332
  const input = tool.input.safeParse(body.input);
7324
7333
  if (!input.success) {
7325
7334
  return c.json(errorEnvelope("invalid_request", z3.prettifyError(input.error)), 400);
@@ -7335,7 +7344,7 @@ function defineServer(options) {
7335
7344
  post("/verify", async function(c) {
7336
7345
  const body = await bodyOf(c.req, verifyRequestSchema);
7337
7346
  if (!body)
7338
- return c.json(malformed, 400);
7347
+ return c.json(malformedBody, 400);
7339
7348
  const verdict = await verify(body.token);
7340
7349
  return c.json(verdict ? { sub: verdict.sub, claims: verdict.claims ?? {} } : { sub: null });
7341
7350
  });
@@ -7347,22 +7356,16 @@ function defineServer(options) {
7347
7356
  post(`/events/${event}`, async function(c) {
7348
7357
  const body = await bodyOf(c.req, serverEventSchemas[event]);
7349
7358
  if (!body)
7350
- return c.json(malformed, 400);
7359
+ return c.json(malformedBody, 400);
7351
7360
  await handler(body);
7352
7361
  return c.body(null, 204);
7353
7362
  });
7354
7363
  }
7355
7364
  return app;
7356
7365
  }
7357
- // src/datasets/index.ts
7358
- import { createHash as createHash2 } from "node:crypto";
7366
+ // src/datasets/dataset-host.ts
7359
7367
  import { Hono as Hono2 } from "hono";
7360
- import { bodyLimit as bodyLimit2 } from "hono/body-limit";
7361
7368
  var DEFAULT_TIMEOUT_MS = 30000;
7362
- var QUERY_BODY_MAX_BYTES = 256 * 1024;
7363
- function manifestVersion(definitions) {
7364
- return createHash2("sha256").update(JSON.stringify(definitions)).digest("hex");
7365
- }
7366
7369
  function tokenFrom(headers, userToken) {
7367
7370
  const raw = headers.get(userToken.header);
7368
7371
  if (!raw)
@@ -7378,7 +7381,7 @@ function defineDatasetHost(options) {
7378
7381
  const definitions = [...sources.values()].map((source) => source.definition).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
7379
7382
  const catalog = datasetCatalogOf(definitions);
7380
7383
  const manifest = {
7381
- version: manifestVersion(definitions),
7384
+ version: contentVersion(definitions),
7382
7385
  datasets: definitions
7383
7386
  };
7384
7387
  const userToken = options.userToken ?? { header: END_USER_TOKEN_HEADER };
@@ -7387,11 +7390,7 @@ function defineDatasetHost(options) {
7387
7390
  app.get("/", function(c) {
7388
7391
  return c.json(manifest);
7389
7392
  });
7390
- const capBody = bodyLimit2({
7391
- maxSize: QUERY_BODY_MAX_BYTES,
7392
- onError: (c) => c.json(errorEnvelope("invalid_request", "Request body too large"), 413)
7393
- });
7394
- app.post("/:name", capBody, async function(c) {
7393
+ app.post("/:name", protocolBodyLimit(DATASET_REQUEST_MAX_BYTES), async function(c) {
7395
7394
  const source = sources.get(c.req.param("name"));
7396
7395
  if (!source) {
7397
7396
  return c.json(errorEnvelope("invalid_request", `Unknown dataset "${c.req.param("name")}"`), 400);
@@ -7400,8 +7399,8 @@ function defineDatasetHost(options) {
7400
7399
  return;
7401
7400
  }));
7402
7401
  if (!body.success)
7403
- return c.json(errorEnvelope("invalid_request", "Malformed request body"), 400);
7404
- const { query: raw } = body.data;
7402
+ return c.json(malformedBody, 400);
7403
+ const { query: raw, context } = body.data;
7405
7404
  if (raw.from !== source.definition.name) {
7406
7405
  return c.json(errorEnvelope("invalid_request", `Query is for "${raw.from}", not "${source.definition.name}"`), 400);
7407
7406
  }
@@ -7413,7 +7412,7 @@ function defineDatasetHost(options) {
7413
7412
  const resolveAndRun = async () => {
7414
7413
  const user = await options.resolveUser({ token: tokenFrom(headers, userToken), headers }, signal);
7415
7414
  signal.throwIfAborted();
7416
- return source.run({ ...query, limit: query.limit + 1 }, user, signal);
7415
+ return source.run({ ...query, limit: query.limit + 1 }, user, signal, context);
7417
7416
  };
7418
7417
  try {
7419
7418
  const rows = await Promise.race([
@@ -7430,7 +7429,7 @@ function defineDatasetHost(options) {
7430
7429
  });
7431
7430
  return app;
7432
7431
  }
7433
- // src/triggers/client.ts
7432
+ // src/triggers/trigger-client.ts
7434
7433
  class TriggerClientError extends Error {
7435
7434
  status;
7436
7435
  body;
@@ -7445,7 +7444,7 @@ function isFiringRunning(firing) {
7445
7444
  return firing.outcome === "started";
7446
7445
  }
7447
7446
  function createTriggerClient(config) {
7448
- const base = `${config.url.replace(/\/+$/, "")}/agents/${encodeURIComponent(config.agent)}/triggers/`;
7447
+ const origin = config.url.replace(/\/+$/, "");
7449
7448
  const fetchFn = config.fetch ?? globalThis.fetch;
7450
7449
  function secretOf(trigger) {
7451
7450
  const { secrets = {} } = config;
@@ -7456,7 +7455,7 @@ function createTriggerClient(config) {
7456
7455
  return secret;
7457
7456
  }
7458
7457
  async function send(trigger, path, init, parse) {
7459
- const response = await fetchFn(`${base}${encodeURIComponent(trigger)}${path}`, {
7458
+ const response = await fetchFn(`${origin}${triggerRoute(config.agent, trigger)}${path}`, {
7460
7459
  ...init,
7461
7460
  headers: { ...init.headers, Authorization: `Bearer ${secretOf(trigger)}` }
7462
7461
  });
@@ -7536,14 +7535,7 @@ var jsonPointerSchema = z4.string().regex(/^\//).max(256);
7536
7535
  var SETTING_BOUNDS = {
7537
7536
  tool: {
7538
7537
  timeoutMs: { min: 100, max: 120000, default: 30000 },
7539
- maxResponseBytes: { min: 1024, max: 1048576, default: 262144 },
7540
- rateLimitRequests: { min: 1, max: 1e4, default: 60 },
7541
- rateLimitWindowSeconds: { min: 1, max: 86400, default: 60 }
7542
- },
7543
- agent: {
7544
- rateLimitRequests: { min: 1, max: 1e4, default: 60 },
7545
- rateLimitWindowSeconds: { min: 1, max: 86400, default: 60 },
7546
- dailyExecutionQuota: { min: 1, max: 1e6, default: 1e4 }
7538
+ maxResponseBytes: { min: 1024, max: 1048576, default: 262144 }
7547
7539
  },
7548
7540
  agentContext: {
7549
7541
  maxContextTokens: { min: 4000, max: 2000000, default: 120000 },
@@ -7558,16 +7550,33 @@ var SETTING_BOUNDS = {
7558
7550
  },
7559
7551
  trigger: { disableAfterFailures: { min: 1, max: 1000, default: 5 } },
7560
7552
  datasetHost: { timeoutMs: { min: 100, max: 120000, default: 30000 } },
7561
- webhook: { timeoutMs: { min: 1000, max: 30000, default: 1e4 } }
7553
+ webhook: { timeoutMs: { min: 1000, max: 30000, default: 1e4 } },
7554
+ recaptcha: { minScore: { min: 0.1, max: 0.9, default: 0.5 } },
7555
+ server: {
7556
+ signInChecksPerMinute: { min: 1, max: 1e5, default: 600 },
7557
+ triggerChecksPerMinute: { min: 1, max: 1e4, default: 60 }
7558
+ }
7562
7559
  };
7563
7560
  function setting({ min, max, default: fallback }) {
7564
7561
  return z4.number().int().min(min).max(max).default(fallback);
7565
7562
  }
7563
+ var RATE_LIMITS = {
7564
+ agent: {
7565
+ messagesPerMinute: { max: 1e4, allUsers: 600, perUser: 20 },
7566
+ tokensPerDay: { max: 1000000000000, allUsers: null, perUser: 1e6 }
7567
+ },
7568
+ tool: { callsPerMinute: { max: 1e4, allUsers: 60, perUser: 20 } },
7569
+ datasetHost: { queriesPerMinute: { max: 1e4, allUsers: 60, perUser: 20 } }
7570
+ };
7571
+ function rateLimit(bound, users) {
7572
+ return z4.number().int().min(1).max(bound.max).nullable().default(bound[users]);
7573
+ }
7566
7574
  function overridable(fields) {
7567
- return z4.array(z4.enum(fields)).refine(uniqueBy((field) => field), "a field repeats").default([]);
7575
+ return z4.array(z4.enum(fields)).refine((listed) => new Set(listed).size === listed.length, "a field repeats").default([]);
7568
7576
  }
7569
7577
  var SLUG_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
7570
- var slugSchema = z4.string().regex(SLUG_PATTERN).max(64);
7578
+ var SLUG_MAX_LENGTH = 64;
7579
+ var slugSchema = z4.string().regex(SLUG_PATTERN).max(SLUG_MAX_LENGTH);
7571
7580
  var HOSTNAME_PATTERN = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/;
7572
7581
  var FETCH_IMAGE_HOSTS_LIMIT = 20;
7573
7582
  var SUGGESTION_LIMITS = { perLocale: 6, titleLength: 120, promptLength: 2000 };
@@ -7607,6 +7616,54 @@ var toolConfigByType = {
7607
7616
  native: z4.object({}),
7608
7617
  client: z4.object({})
7609
7618
  };
7619
+ var TOOL_TYPE_NAMES = ["http", "embedded", "soap", "native", "client"];
7620
+ var TOOL_TYPES = {
7621
+ http: {
7622
+ kind: "server",
7623
+ calls: true,
7624
+ approval: true,
7625
+ sources: true,
7626
+ targets: true,
7627
+ creatable: true
7628
+ },
7629
+ embedded: {
7630
+ kind: "client",
7631
+ calls: true,
7632
+ approval: false,
7633
+ sources: true,
7634
+ targets: false,
7635
+ creatable: true,
7636
+ readOnly: false
7637
+ },
7638
+ soap: {
7639
+ kind: "server",
7640
+ calls: true,
7641
+ approval: true,
7642
+ sources: true,
7643
+ targets: true,
7644
+ creatable: true,
7645
+ method: "POST"
7646
+ },
7647
+ native: {
7648
+ kind: "server",
7649
+ calls: true,
7650
+ approval: true,
7651
+ sources: false,
7652
+ targets: false,
7653
+ creatable: false,
7654
+ method: "POST"
7655
+ },
7656
+ client: {
7657
+ kind: "client",
7658
+ calls: false,
7659
+ approval: false,
7660
+ sources: false,
7661
+ targets: false,
7662
+ creatable: true,
7663
+ readOnly: true
7664
+ }
7665
+ };
7666
+ var CREATABLE_TOOL_TYPES = TOOL_TYPE_NAMES.filter((type) => TOOL_TYPES[type].creatable);
7610
7667
  var ENDPOINT_PARAM_PATTERN = /\{([^{}]+)\}/g;
7611
7668
  function confinesEndpointParams(url) {
7612
7669
  const origin = /^[^:/?#]*:[/\\]*[^/\\?#]*/.exec(url)?.[0] ?? "";
@@ -7615,8 +7672,10 @@ function confinesEndpointParams(url) {
7615
7672
  return ![origin, fragment].some((part) => part.match(ENDPOINT_PARAM_PATTERN));
7616
7673
  }
7617
7674
  var upstreamUrlSchema = z4.url({ protocol: /^https?$/ });
7675
+ var HEADER_LIMITS = { headerLength: 120, prefixLength: 40, headers: 8 };
7618
7676
  var HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
7619
- var headerNameSchema = z4.string().trim().min(1).max(120).regex(HEADER_NAME_PATTERN);
7677
+ var HEADER_VALUE_PATTERN = /^[\t\x20-\x7e\x80-\xff]*$/;
7678
+ var headerNameSchema = z4.string().trim().min(1).max(HEADER_LIMITS.headerLength).regex(HEADER_NAME_PATTERN);
7620
7679
  var transportSetHeaders = ["accept", "content-type", "content-length", "host"];
7621
7680
  var transportForbiddenHeaders = [
7622
7681
  "connection",
@@ -7636,7 +7695,6 @@ var transportOwnedHeaders = new Set([
7636
7695
  ...transportSetHeaders,
7637
7696
  ...transportForbiddenHeaders
7638
7697
  ]);
7639
- var CREDENTIAL_PRESENTATION_LIMIT = 8;
7640
7698
  function repeatedHeaders(entries) {
7641
7699
  const seen = new Set;
7642
7700
  return entries.flatMap((entry, index) => {
@@ -7646,23 +7704,50 @@ function repeatedHeaders(entries) {
7646
7704
  return repeated ? [index] : [];
7647
7705
  });
7648
7706
  }
7649
- var nameSchema = z4.string().trim().min(1).max(120);
7707
+ var NAME_MAX_LENGTH = 120;
7708
+ var nameSchema = z4.string().trim().min(1).max(NAME_MAX_LENGTH);
7650
7709
  var presentedHeaderSchema = headerNameSchema.refine((name) => !transportOwnedHeaders.has(name.toLowerCase()), "a header the transport sets");
7651
- function presentationsSchema(header, credential) {
7652
- return z4.array(z4.strictObject({ header, prefix: z4.string().max(40).default(""), credential })).max(CREDENTIAL_PRESENTATION_LIMIT).superRefine((entries, context) => {
7710
+ function headerListSchema(entry, repeated) {
7711
+ return z4.array(entry).max(HEADER_LIMITS.headers).superRefine((entries, context) => {
7653
7712
  for (const index of repeatedHeaders(entries)) {
7654
7713
  context.addIssue({
7655
7714
  code: "custom",
7656
7715
  path: [index, "header"],
7657
- message: "a header presented twice"
7716
+ message: repeated()
7658
7717
  });
7659
7718
  }
7660
- }).default([]);
7719
+ });
7720
+ }
7721
+ var variableSourceSchema = z4.object({
7722
+ kind: z4.literal("variable"),
7723
+ name: z4.string().trim().min(1).max(64)
7724
+ });
7725
+ var credentialSourceSchema = z4.object({ kind: z4.literal("credential"), name: nameSchema });
7726
+ var constantHeaderSourceSchema = z4.object({
7727
+ kind: z4.literal("constant"),
7728
+ value: z4.string().max(4000)
7729
+ });
7730
+ var headerSourceSchema = z4.discriminatedUnion("kind", [
7731
+ credentialSourceSchema,
7732
+ z4.object({ kind: z4.literal("runToken") }),
7733
+ variableSourceSchema,
7734
+ constantHeaderSourceSchema
7735
+ ]);
7736
+ var runlessHeaderSourceSchema = z4.discriminatedUnion("kind", [
7737
+ credentialSourceSchema,
7738
+ constantHeaderSourceSchema
7739
+ ]);
7740
+ function declaredHeadersSchema(header, from) {
7741
+ return headerListSchema(z4.strictObject({
7742
+ header,
7743
+ prefix: z4.string().max(HEADER_LIMITS.prefixLength).regex(HEADER_VALUE_PATTERN, "a prefix a header cannot carry").default(""),
7744
+ from
7745
+ }).refine((entry) => entry.from.kind !== "constant" || HEADER_VALUE_PATTERN.test(entry.from.value), { path: ["from", "value"], message: "a value a header cannot carry" }), () => "a header declared twice").default([]);
7661
7746
  }
7662
- var credentialsSchema = presentationsSchema(presentedHeaderSchema, nameSchema.nullable());
7747
+ var headersSchema = declaredHeadersSchema(presentedHeaderSchema, headerSourceSchema);
7663
7748
  var fieldSourceSchema = z4.discriminatedUnion("kind", [
7664
- z4.object({ kind: z4.literal("variable"), name: z4.string().trim().min(1).max(64) }),
7665
- z4.object({ kind: z4.literal("secret"), name: z4.string().trim().min(1).max(120) }),
7749
+ variableSourceSchema,
7750
+ z4.object({ kind: z4.literal("secret"), name: nameSchema }),
7666
7751
  z4.object({
7667
7752
  kind: z4.literal("constant"),
7668
7753
  value: z4.union([z4.string().max(4000), z4.number(), z4.boolean()])
@@ -7718,22 +7803,26 @@ var fieldTargetSchema = z4.discriminatedUnion("kind", [
7718
7803
  ]);
7719
7804
  var SCALAR_TYPES = ["string", "number", "integer", "boolean"];
7720
7805
  var schemaTypeSchema = z4.enum([...SCALAR_TYPES, "object", "array"]);
7721
- var propertyNameSchema = z4.string().min(1).max(120).refine((name) => name === name.trim(), "no surrounding spaces");
7806
+ var FIELD_LIMITS = { nameLength: 120, descriptionLength: 500, enumValues: 50 };
7807
+ var propertyNameSchema = z4.string().min(1).max(FIELD_LIMITS.nameLength).refine((name) => name === name.trim(), "no surrounding spaces");
7808
+ var propertyOrderSchema = z4.array(z4.string()).refine((names) => new Set(names).size === names.length, "a name repeats").optional();
7722
7809
  var itemsSchema = z4.strictObject({
7723
7810
  type: z4.enum([...SCALAR_TYPES, "object"]),
7724
7811
  get properties() {
7725
7812
  return z4.record(propertyNameSchema, schemaPropertySchema).optional();
7726
7813
  },
7727
- required: z4.array(z4.string()).optional()
7814
+ required: z4.array(z4.string()).optional(),
7815
+ "x-order": propertyOrderSchema
7728
7816
  });
7729
7817
  var schemaPropertySchema = z4.strictObject({
7730
7818
  type: z4.union([schemaTypeSchema, z4.tuple([schemaTypeSchema, z4.literal("null")])]),
7731
- description: z4.string().trim().max(500).optional(),
7732
- enum: z4.array(z4.union([z4.string().trim().min(1), z4.null()])).min(1).max(51).optional(),
7819
+ description: z4.string().trim().max(FIELD_LIMITS.descriptionLength).optional(),
7820
+ enum: z4.array(z4.union([z4.string().trim().min(1), z4.null()])).min(1).max(FIELD_LIMITS.enumValues + 1).optional(),
7733
7821
  get properties() {
7734
7822
  return z4.record(propertyNameSchema, schemaPropertySchema).optional();
7735
7823
  },
7736
7824
  required: z4.array(z4.string()).optional(),
7825
+ "x-order": propertyOrderSchema,
7737
7826
  get items() {
7738
7827
  return itemsSchema.optional();
7739
7828
  },
@@ -7747,16 +7836,18 @@ function typeOf(node) {
7747
7836
  function nodeIssues(node) {
7748
7837
  const issues = new Array;
7749
7838
  const object = typeOf(node) === "object";
7750
- for (const keyword of ["properties", "required"]) {
7839
+ for (const keyword of ["properties", "required", "x-order"]) {
7751
7840
  if (!object && node[keyword] !== undefined) {
7752
7841
  issues.push({ at: [keyword], message: "only an object has it" });
7753
7842
  }
7754
7843
  }
7755
- node.required?.forEach((name, index) => {
7756
- if (!Object.hasOwn(node.properties ?? {}, name)) {
7757
- issues.push({ at: ["required", index], message: "names no property" });
7758
- }
7759
- });
7844
+ for (const keyword of ["required", "x-order"]) {
7845
+ node[keyword]?.forEach((name, index) => {
7846
+ if (!Object.hasOwn(node.properties ?? {}, name)) {
7847
+ issues.push({ at: [keyword, index], message: "names no property" });
7848
+ }
7849
+ });
7850
+ }
7760
7851
  return issues;
7761
7852
  }
7762
7853
  function enumIssueOf(property, type) {
@@ -7765,14 +7856,15 @@ function enumIssueOf(property, type) {
7765
7856
  if (type !== "string")
7766
7857
  return "an enum lists a string's values";
7767
7858
  const values = property.enum.filter((value) => value !== null);
7768
- if (values.length === 0 || values.length > 50)
7769
- return "an enum lists 1 to 50 values";
7859
+ if (values.length === 0 || values.length > FIELD_LIMITS.enumValues) {
7860
+ return `an enum lists 1 to ${FIELD_LIMITS.enumValues} values`;
7861
+ }
7770
7862
  const nullable = Array.isArray(property.type);
7771
7863
  if (nullable === property.enum.includes(null))
7772
7864
  return;
7773
7865
  return nullable ? "a nullable enum lists null" : "only a nullable enum lists null";
7774
7866
  }
7775
- function propertyIssues(property, bindable) {
7867
+ function propertyIssues(property, bindings) {
7776
7868
  const issues = new Array;
7777
7869
  const type = typeOf(property);
7778
7870
  const enumIssue = enumIssueOf(property, type);
@@ -7784,26 +7876,30 @@ function propertyIssues(property, bindable) {
7784
7876
  message: type === "array" ? "an array declares its items" : "only an array has it"
7785
7877
  });
7786
7878
  }
7787
- const binds = bindable && SCALAR_TYPES.some((scalar) => scalar === type);
7788
- if (property["x-source"] !== undefined && !binds) {
7789
- issues.push({
7790
- at: ["x-source"],
7791
- message: "only a top-level scalar field of a tool's input has it"
7792
- });
7793
- }
7794
- if (property["x-target"] !== undefined && !bindable) {
7879
+ return [...issues, ...bindingIssues(property, type, bindings)];
7880
+ }
7881
+ function bindingIssues(property, type, bindings) {
7882
+ const issues = new Array;
7883
+ const scalar = SCALAR_TYPES.some((scalar2) => scalar2 === type);
7884
+ const fields = { "x-source": "a top-level scalar field", "x-target": "a top-level field" };
7885
+ for (const binding of ["x-source", "x-target"]) {
7886
+ if (property[binding] === undefined)
7887
+ continue;
7888
+ const reaches = bindings !== undefined && (binding === "x-target" || scalar);
7889
+ if (reaches && bindings.includes(binding))
7890
+ continue;
7795
7891
  issues.push({
7796
- at: ["x-target"],
7797
- message: "only a top-level field of a tool's input has it"
7892
+ at: [binding],
7893
+ message: reaches ? "this type of tool takes none" : `only ${fields[binding]} of a tool's input has it`
7798
7894
  });
7799
7895
  }
7800
7896
  const source = property["x-source"];
7801
- if (binds && source && !sourceFits(source, { type, enum: property.enum })) {
7897
+ if (scalar && bindings?.includes("x-source") && source && !sourceFits(source, { type, enum: property.enum })) {
7802
7898
  issues.push({ at: ["x-source"], message: "the source does not fit the field's type" });
7803
7899
  }
7804
7900
  return issues;
7805
7901
  }
7806
- function heldByRows(node, context, path, bindable) {
7902
+ function heldByRows(node, context, path, bindings) {
7807
7903
  const report = (under, issues) => {
7808
7904
  for (const { at, message } of issues) {
7809
7905
  context.addIssue({ code: "custom", path: [...under, ...at], message });
@@ -7812,20 +7908,21 @@ function heldByRows(node, context, path, bindable) {
7812
7908
  report(path, nodeIssues(node));
7813
7909
  for (const [name, property] of Object.entries(node.properties ?? {})) {
7814
7910
  const at = [...path, "properties", name];
7815
- report(at, propertyIssues(property, bindable));
7816
- heldByRows(property, context, at, false);
7911
+ report(at, propertyIssues(property, bindings));
7912
+ heldByRows(property, context, at, undefined);
7817
7913
  if (property.items)
7818
- heldByRows(property.items, context, [...at, "items"], false);
7914
+ heldByRows(property.items, context, [...at, "items"], undefined);
7819
7915
  }
7820
7916
  }
7821
- function objectSchemaOf(bindable) {
7917
+ function objectJsonSchemaOf(bindings) {
7822
7918
  return z4.strictObject({
7823
7919
  type: z4.literal("object"),
7824
7920
  properties: z4.record(propertyNameSchema, schemaPropertySchema).optional(),
7825
- required: z4.array(z4.string()).optional()
7826
- }).superRefine((schema, context) => heldByRows(schema, context, [], bindable));
7921
+ required: z4.array(z4.string()).optional(),
7922
+ "x-order": propertyOrderSchema
7923
+ }).superRefine((schema, context) => heldByRows(schema, context, [], bindings));
7827
7924
  }
7828
- var objectSchema = objectSchemaOf(false);
7925
+ var objectSchema = objectJsonSchemaOf();
7829
7926
  var EMPTY_OBJECT = { type: "object" };
7830
7927
  var audienceSchema = z4.union([
7831
7928
  z4.literal("all"),
@@ -7834,73 +7931,91 @@ var audienceSchema = z4.union([
7834
7931
  agents: z4.array(agentSlugSchema).min(1).refine((slugs) => new Set(slugs).size === slugs.length, "an agent repeats")
7835
7932
  })
7836
7933
  ]);
7934
+ var MODEL_PROVIDER_LIMITS = { urlLength: 2048, modelLength: 200, models: 100 };
7837
7935
  var modelSchema = z4.strictObject({
7838
7936
  provider: nameSchema,
7839
- model: z4.string().trim().min(1).max(200),
7937
+ model: z4.string().trim().min(1).max(MODEL_PROVIDER_LIMITS.modelLength),
7840
7938
  effort: z4.string().trim().min(1).max(64).optional()
7841
7939
  });
7842
- var localizedLineSchema = z4.record(localeSchema, z4.string().trim().min(1).max(120));
7843
- var localizedTextSchema = z4.record(localeSchema, z4.string().trim().min(1).max(4000));
7940
+ var SERVICE_LIMITS = { nameLength: 120, descriptionLength: 4000 };
7941
+ var localizedLineSchema = z4.record(localeSchema, z4.string().trim().min(1).max(SERVICE_LIMITS.nameLength));
7942
+ var localizedTextSchema = z4.record(localeSchema, z4.string().trim().min(1).max(SERVICE_LIMITS.descriptionLength));
7844
7943
  var { tool: toolBounds } = SETTING_BOUNDS;
7944
+ var { tool: toolRateLimits, datasetHost: datasetHostRateLimits } = RATE_LIMITS;
7945
+ function toolInputSchemaOf(type) {
7946
+ const { sources, targets } = TOOL_TYPES[type];
7947
+ return objectJsonSchemaOf([
7948
+ ...sources ? ["x-source"] : [],
7949
+ ...targets ? ["x-target"] : []
7950
+ ]).default(EMPTY_OBJECT);
7951
+ }
7952
+ var TOOL_OVERRIDABLES = [
7953
+ "description",
7954
+ "timeoutMs",
7955
+ "maxResponseBytes",
7956
+ "rateLimits",
7957
+ "pinned",
7958
+ "tags"
7959
+ ];
7960
+ var CALLED_TOOL_OVERRIDABLES = [...TOOL_OVERRIDABLES, "headers"];
7845
7961
  var toolBaseSchema = z4.strictObject({
7846
7962
  ...serverToolSchema.pick({ name: true, description: true }).shape,
7847
- inputSchema: objectSchema.default(EMPTY_OBJECT),
7963
+ inputSchema: toolInputSchemaOf("client"),
7848
7964
  outputSchema: objectSchema.default(EMPTY_OBJECT),
7849
7965
  timeoutMs: setting(toolBounds.timeoutMs),
7850
7966
  maxResponseBytes: setting(toolBounds.maxResponseBytes),
7851
- rateLimitRequests: setting(toolBounds.rateLimitRequests),
7852
- rateLimitWindowSeconds: setting(toolBounds.rateLimitWindowSeconds),
7967
+ rateLimits: z4.strictObject({
7968
+ allUsers: z4.strictObject({
7969
+ callsPerMinute: rateLimit(toolRateLimits.callsPerMinute, "allUsers")
7970
+ }).prefault({}),
7971
+ perUser: z4.strictObject({
7972
+ callsPerMinute: rateLimit(toolRateLimits.callsPerMinute, "perUser")
7973
+ }).prefault({})
7974
+ }).prefault({}),
7853
7975
  projectOutput: z4.boolean().default(false),
7854
7976
  pinned: z4.boolean().default(false),
7855
7977
  tags: toolTagsSchema.default([]),
7856
7978
  audience: audienceSchema,
7857
- overridable: overridable([
7858
- "description",
7859
- "timeoutMs",
7860
- "maxResponseBytes",
7861
- "rateLimitRequests",
7862
- "rateLimitWindowSeconds",
7863
- "pinned",
7864
- "tags"
7865
- ])
7979
+ overridable: overridable(TOOL_OVERRIDABLES)
7866
7980
  });
7867
7981
  var calledToolSchema = toolBaseSchema.extend({
7868
- inputSchema: objectSchemaOf(true).default(EMPTY_OBJECT),
7869
7982
  url: upstreamUrlSchema.refine(confinesEndpointParams, "a {parameter} outside the path or query"),
7870
- credentials: credentialsSchema,
7871
- requiresApproval: z4.boolean().default(false)
7983
+ headers: headersSchema,
7984
+ requiresApproval: z4.boolean().default(false),
7985
+ overridable: overridable(CALLED_TOOL_OVERRIDABLES)
7872
7986
  });
7873
7987
  var manifestToolSchema = z4.discriminatedUnion("type", [
7874
7988
  calledToolSchema.extend({
7875
7989
  type: z4.literal("http"),
7990
+ inputSchema: toolInputSchemaOf("http"),
7876
7991
  method: z4.enum(TOOL_METHODS),
7877
7992
  readOnly: z4.boolean(),
7878
7993
  ...toolConfigByType.http.shape
7879
7994
  }),
7880
- calledToolSchema.extend({
7995
+ calledToolSchema.omit({ requiresApproval: true }).extend({
7881
7996
  type: z4.literal("embedded"),
7997
+ inputSchema: toolInputSchemaOf("embedded"),
7882
7998
  method: z4.enum(TOOL_METHODS),
7883
7999
  ...toolConfigByType.embedded.shape
7884
8000
  }),
7885
8001
  calledToolSchema.extend({
7886
8002
  type: z4.literal("soap"),
8003
+ inputSchema: toolInputSchemaOf("soap"),
7887
8004
  readOnly: z4.boolean(),
7888
8005
  ...toolConfigByType.soap.shape
7889
8006
  }),
7890
8007
  toolBaseSchema.extend({ type: z4.literal("client") })
7891
- ]).superRefine((tool, context) => {
7892
- if (tool.type !== "client")
7893
- refuseBlockedApprovalTitle(tool, context, []);
7894
- });
8008
+ ]).superRefine((tool, context) => refuseBlockedApprovalTitle(tool, context, []));
7895
8009
  var toolNamesSchema = z4.array(serverToolSchema.shape.name).max(500).default([]);
7896
8010
  var manifestOpenApiSchema = z4.strictObject({
7897
8011
  name: nameSchema,
7898
8012
  url: upstreamUrlSchema,
7899
- credentials: credentialsSchema,
8013
+ headers: headersSchema,
7900
8014
  resultPath: jsonPointerSchema.optional(),
7901
8015
  pinned: toolNamesSchema,
7902
8016
  approval: z4.strictObject({ never: toolNamesSchema, always: toolNamesSchema }).prefault({}).refine(({ never, always }) => !never.some((name) => always.includes(name)), "a tool both never and always needs approval"),
7903
- audience: audienceSchema
8017
+ audience: audienceSchema,
8018
+ overridable: overridable(CALLED_TOOL_OVERRIDABLES)
7904
8019
  });
7905
8020
  var manifestServiceSchema = z4.strictObject({
7906
8021
  key: slugSchema,
@@ -7909,9 +8024,10 @@ var manifestServiceSchema = z4.strictObject({
7909
8024
  audience: audienceSchema,
7910
8025
  overridable: overridable(["description"])
7911
8026
  });
8027
+ var SKILL_LIMITS = { descriptionLength: 500 };
7912
8028
  var manifestSkillSchema = z4.strictObject({
7913
8029
  name: slugSchema,
7914
- description: z4.string().trim().min(1).max(500),
8030
+ description: z4.string().trim().min(1).max(SKILL_LIMITS.descriptionLength),
7915
8031
  body: z4.string().trim().min(1),
7916
8032
  service: slugSchema.optional(),
7917
8033
  audience: audienceSchema,
@@ -7923,12 +8039,13 @@ var triggerThreadPolicySchema = z4.discriminatedUnion("policy", [
7923
8039
  z4.object({ policy: z4.literal("ephemeral") }),
7924
8040
  z4.object({ policy: z4.literal("keyed"), key: jsonPointerSchema })
7925
8041
  ]);
8042
+ var TRIGGER_LIMITS = { descriptionLength: 500, instructionsLength: 20000 };
7926
8043
  var manifestTriggerSchema = z4.strictObject({
7927
8044
  name: slugSchema.refine((name) => name !== MESSAGE_TRIGGER_NAME, "the built-in trigger's name"),
7928
- description: z4.string().trim().min(1).max(500),
8045
+ description: z4.string().trim().min(1).max(TRIGGER_LIMITS.descriptionLength),
7929
8046
  inputSchema: objectSchema.default(EMPTY_OBJECT),
7930
8047
  outputSchema: objectSchema.refine((schema) => Object.keys(schema.properties ?? {}).length > 0, "declares a property; leave it out for a free-text answer").optional(),
7931
- instructions: z4.string().trim().min(1).max(20000),
8048
+ instructions: z4.string().trim().min(1).max(TRIGGER_LIMITS.instructionsLength),
7932
8049
  threadPolicy: triggerThreadPolicySchema.default({ policy: "single" }),
7933
8050
  budgetPerDay: z4.number().int().positive().optional(),
7934
8051
  disableAfterFailures: setting(SETTING_BOUNDS.trigger.disableAfterFailures),
@@ -7952,12 +8069,20 @@ function unexposedPins(host) {
7952
8069
  var manifestDatasetHostSchema = z4.strictObject({
7953
8070
  name: datasetIdentifierSchema,
7954
8071
  url: upstreamUrlSchema,
7955
- credentials: credentialsSchema,
8072
+ headers: headersSchema,
7956
8073
  timeoutMs: setting(SETTING_BOUNDS.datasetHost.timeoutMs),
8074
+ rateLimits: z4.strictObject({
8075
+ allUsers: z4.strictObject({
8076
+ queriesPerMinute: rateLimit(datasetHostRateLimits.queriesPerMinute, "allUsers")
8077
+ }).prefault({}),
8078
+ perUser: z4.strictObject({
8079
+ queriesPerMinute: rateLimit(datasetHostRateLimits.queriesPerMinute, "perUser")
8080
+ }).prefault({})
8081
+ }).prefault({}),
7957
8082
  expose: z4.array(datasetIdentifierSchema).min(1).max(500),
7958
8083
  pinned: z4.array(datasetIdentifierSchema).max(50).default([]),
7959
8084
  audience: audienceSchema,
7960
- overridable: overridable(["timeoutMs"])
8085
+ overridable: overridable(["timeoutMs", "rateLimits", "headers"])
7961
8086
  }).superRefine((host, context) => {
7962
8087
  const unexposed = unexposedPins(host);
7963
8088
  if (unexposed.length > 0) {
@@ -7970,27 +8095,28 @@ var manifestDatasetHostSchema = z4.strictObject({
7970
8095
  });
7971
8096
  var mcpToolNamesSchema = z4.array(z4.string().trim().min(1).max(128).regex(/^[^,]*$/, "a tool name holds no comma")).max(200);
7972
8097
  var manifestMcpServerSchema = z4.strictObject({
7973
- name: z4.string().regex(IDENTIFIER_PATTERN).max(64),
8098
+ name: identifierSchema,
7974
8099
  url: upstreamUrlSchema,
7975
- credentials: presentationsSchema(presentedHeaderSchema.refine((name) => !mcpTransportHeaders.has(name.toLowerCase()), "a header the MCP transport sets"), nameSchema.nullable()),
8100
+ headers: declaredHeadersSchema(presentedHeaderSchema.refine((name) => !mcpTransportHeaders.has(name.toLowerCase()), "a header the MCP transport sets"), headerSourceSchema),
7976
8101
  include: mcpToolNamesSchema.default([]),
7977
8102
  exclude: mcpToolNamesSchema.default([]),
7978
8103
  audience: audienceSchema,
7979
- overridable: overridable(["include", "exclude"])
8104
+ overridable: overridable(["include", "exclude", "headers"])
7980
8105
  });
7981
8106
  var manifestWebhookSchema = z4.strictObject({
7982
8107
  name: slugSchema,
7983
8108
  description: z4.string().trim().max(500).default(""),
7984
8109
  event: z4.enum(SERVER_EVENTS),
7985
8110
  url: upstreamUrlSchema,
7986
- credentials: presentationsSchema(presentedHeaderSchema.refine((name) => name.toLowerCase() !== EVENT_HEADER.toLowerCase(), "the header that names the event"), nameSchema),
8111
+ headers: declaredHeadersSchema(presentedHeaderSchema.refine((name) => name.toLowerCase() !== EVENT_HEADER.toLowerCase(), "the header that names the event"), runlessHeaderSourceSchema),
7987
8112
  timeoutMs: setting(SETTING_BOUNDS.webhook.timeoutMs),
7988
8113
  audience: audienceSchema,
7989
- overridable: overridable(["description", "timeoutMs"])
8114
+ overridable: overridable(["description", "timeoutMs", "headers"])
7990
8115
  });
8116
+ var COLLECTION_LIMITS = { nameLength: 80, descriptionLength: 2000 };
7991
8117
  var manifestCollectionSchema = z4.strictObject({
7992
- name: z4.string().trim().min(1).max(80),
7993
- description: z4.string().trim().max(2000).default(""),
8118
+ name: z4.string().trim().min(1).max(COLLECTION_LIMITS.nameLength),
8119
+ description: z4.string().trim().max(COLLECTION_LIMITS.descriptionLength).default(""),
7994
8120
  service: slugSchema.optional(),
7995
8121
  citable: z4.boolean().default(true),
7996
8122
  audience: audienceSchema,
@@ -8013,10 +8139,19 @@ var agentAuthSchema = z4.discriminatedUnion("kind", [
8013
8139
  issuer: issuerSchema,
8014
8140
  audience: tokenAudienceSchema
8015
8141
  }),
8016
- z4.strictObject({ kind: z4.literal("anonymous") }),
8142
+ z4.strictObject({
8143
+ kind: z4.literal("anonymous"),
8144
+ recaptcha: z4.strictObject({
8145
+ siteKey: z4.string().trim().min(1).max(200),
8146
+ projectId: z4.string().trim().min(1).max(200),
8147
+ secret: nameSchema,
8148
+ minScore: z4.number().min(SETTING_BOUNDS.recaptcha.minScore.min).max(SETTING_BOUNDS.recaptcha.minScore.max).default(SETTING_BOUNDS.recaptcha.minScore.default)
8149
+ }).optional()
8150
+ }),
8017
8151
  z4.strictObject({ kind: z4.literal("server") })
8018
8152
  ]);
8019
- var { agent: agentBounds, agentContext, agentLimits } = SETTING_BOUNDS;
8153
+ var { agentContext, agentLimits } = SETTING_BOUNDS;
8154
+ var { agent: agentRateLimits } = RATE_LIMITS;
8020
8155
  var agentSettingsSchema = z4.strictObject({
8021
8156
  ragEnabled: z4.boolean().default(false),
8022
8157
  toolRegistryEnabled: z4.boolean().default(false),
@@ -8026,10 +8161,17 @@ var agentSettingsSchema = z4.strictObject({
8026
8161
  locationPicker: z4.boolean().default(false),
8027
8162
  media: z4.array(z4.enum(MEDIA_FORMS)).default([...DEFAULT_MEDIA_FORMS]),
8028
8163
  messageTrigger: z4.boolean().default(true),
8029
- defaultLocale: localeSchema.default("en"),
8030
- rateLimitRequests: setting(agentBounds.rateLimitRequests),
8031
- rateLimitWindowSeconds: setting(agentBounds.rateLimitWindowSeconds),
8032
- dailyExecutionQuota: setting(agentBounds.dailyExecutionQuota),
8164
+ defaultLocale: localeSchema.default(BASE_LOCALE),
8165
+ rateLimits: z4.strictObject({
8166
+ allUsers: z4.strictObject({
8167
+ messagesPerMinute: rateLimit(agentRateLimits.messagesPerMinute, "allUsers"),
8168
+ tokensPerDay: rateLimit(agentRateLimits.tokensPerDay, "allUsers")
8169
+ }).prefault({}),
8170
+ perUser: z4.strictObject({
8171
+ messagesPerMinute: rateLimit(agentRateLimits.messagesPerMinute, "perUser"),
8172
+ tokensPerDay: rateLimit(agentRateLimits.tokensPerDay, "perUser")
8173
+ }).prefault({})
8174
+ }).prefault({}),
8033
8175
  context: z4.strictObject({
8034
8176
  maxContextTokens: setting(agentContext.maxContextTokens),
8035
8177
  summarizationThreshold: z4.number().min(agentContext.summarizationThreshold.min).max(agentContext.summarizationThreshold.max).default(agentContext.summarizationThreshold.default),
@@ -8042,9 +8184,10 @@ var agentSettingsSchema = z4.strictObject({
8042
8184
  maxResponseBytes: setting(agentLimits.maxResponseBytes)
8043
8185
  }).prefault({})
8044
8186
  });
8187
+ var AGENT_LIMITS = { nameLength: 120 };
8045
8188
  var manifestAgentSchema = z4.strictObject({
8046
8189
  slug: agentSlugSchema,
8047
- name: z4.string().trim().min(1).max(120),
8190
+ name: z4.string().trim().min(1).max(AGENT_LIMITS.nameLength),
8048
8191
  server: nameSchema,
8049
8192
  prompt: z4.string().trim().min(1),
8050
8193
  auth: agentAuthSchema,
@@ -8054,31 +8197,49 @@ var manifestAgentSchema = z4.strictObject({
8054
8197
  summarization: modelSchema.omit({ effort: true }).optional()
8055
8198
  }).default({}),
8056
8199
  settings: agentSettingsSchema.prefault({}),
8057
- suggestions: suggestionsSchema.default({ en: [], ar: [] }),
8058
- greeting: greetingSchema.default({ en: "", ar: "" }),
8200
+ suggestions: suggestionsSchema.default(() => byLocale(() => [])),
8201
+ greeting: greetingSchema.default(() => byLocale(() => "")),
8059
8202
  overridable: overridable(["name", "prompt", "models", "settings", "suggestions", "greeting"])
8060
8203
  });
8061
- function uniqueBy(key) {
8062
- return (entries) => new Set(entries.map(key)).size === entries.length;
8063
- }
8064
- function listOf(entry, key) {
8065
- return z4.array(entry).refine(uniqueBy(key), "a name repeats").default([]);
8204
+ var MANIFEST_KINDS = [
8205
+ "agents",
8206
+ "services",
8207
+ "tools",
8208
+ "skills",
8209
+ "triggers",
8210
+ "datasetHosts",
8211
+ "mcpServers",
8212
+ "webhooks",
8213
+ "collections"
8214
+ ];
8215
+ var MANIFEST_NAME_FIELDS = {
8216
+ agents: "slug",
8217
+ tools: "name",
8218
+ services: "key",
8219
+ skills: "name",
8220
+ triggers: "name",
8221
+ datasetHosts: "name",
8222
+ mcpServers: "name",
8223
+ webhooks: "name",
8224
+ collections: "name"
8225
+ };
8226
+ function listOf(field, entry) {
8227
+ return z4.array(entry).refine((entries) => new Set(entries.map((value) => value[field])).size === entries.length, "a name repeats").default([]);
8066
8228
  }
8067
- var byName = (entry) => entry.name;
8068
8229
  var manifestSchema = z4.strictObject({
8069
8230
  id: slugSchema,
8070
- agents: listOf(manifestAgentSchema, (agent) => agent.slug),
8071
- tools: listOf(manifestToolSchema, byName),
8072
- openapi: listOf(manifestOpenApiSchema, byName),
8073
- services: listOf(manifestServiceSchema, (service) => service.key),
8074
- skills: listOf(manifestSkillSchema, byName),
8075
- triggers: listOf(manifestTriggerSchema, byName),
8076
- datasetHosts: listOf(manifestDatasetHostSchema, byName),
8077
- mcpServers: listOf(manifestMcpServerSchema, byName),
8078
- webhooks: listOf(manifestWebhookSchema, byName),
8079
- collections: listOf(manifestCollectionSchema, byName)
8231
+ agents: listOf(MANIFEST_NAME_FIELDS.agents, manifestAgentSchema),
8232
+ tools: listOf(MANIFEST_NAME_FIELDS.tools, manifestToolSchema),
8233
+ openapi: listOf("name", manifestOpenApiSchema),
8234
+ services: listOf(MANIFEST_NAME_FIELDS.services, manifestServiceSchema),
8235
+ skills: listOf(MANIFEST_NAME_FIELDS.skills, manifestSkillSchema),
8236
+ triggers: listOf(MANIFEST_NAME_FIELDS.triggers, manifestTriggerSchema),
8237
+ datasetHosts: listOf(MANIFEST_NAME_FIELDS.datasetHosts, manifestDatasetHostSchema),
8238
+ mcpServers: listOf(MANIFEST_NAME_FIELDS.mcpServers, manifestMcpServerSchema),
8239
+ webhooks: listOf(MANIFEST_NAME_FIELDS.webhooks, manifestWebhookSchema),
8240
+ collections: listOf(MANIFEST_NAME_FIELDS.collections, manifestCollectionSchema)
8080
8241
  });
8081
- var manifestKindSchema = manifestSchema.keyof().exclude(["id", "openapi"]);
8242
+ var manifestKindSchema = z4.enum(MANIFEST_KINDS);
8082
8243
  var namesByKindSchema = z4.record(manifestKindSchema, z4.array(z4.string()));
8083
8244
  var manifestChangesSchema = z4.object({
8084
8245
  create: namesByKindSchema,