@m6d/cortex 0.13.1 → 0.15.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
@@ -2,6 +2,8 @@ import {
2
2
  BACKEND_ERROR_STATUS,
3
3
  backendErrorSchema,
4
4
  errorEnvelope,
5
+ jsonValueSchema,
6
+ jsonObjectSchema,
5
7
  isRecord,
6
8
  readJsonPointer,
7
9
  CortexError2,
@@ -16,7 +18,7 @@ import {
16
18
  datasetCatalogOf,
17
19
  checkDatasetQuery,
18
20
  boundDatasetResult
19
- } from "./index-j0kpmpfv.js";
21
+ } from "./index-ycr8n8r9.js";
20
22
  import { createRequire } from "node:module";
21
23
  var __create = Object.create;
22
24
  var __getProtoOf = Object.getPrototypeOf;
@@ -13461,7 +13463,7 @@ var runWaitSchema = z.object({
13461
13463
  kind: z.enum(WAIT_KINDS),
13462
13464
  toolCallId: z.string(),
13463
13465
  toolName: z.string(),
13464
- input: z.unknown()
13466
+ input: jsonValueSchema
13465
13467
  });
13466
13468
  var runRecordSchema = z.object({
13467
13469
  id: z.uuid(),
@@ -13471,11 +13473,11 @@ var runRecordSchema = z.object({
13471
13473
  subagentRunId: z.string().nullable(),
13472
13474
  status: z.enum(RUN_STATUSES),
13473
13475
  reason: z.enum(RUN_REASONS).nullable(),
13474
- result: z.unknown(),
13476
+ result: jsonValueSchema.nullable(),
13475
13477
  waits: z.array(runWaitSchema),
13476
13478
  createdAt: z.iso.datetime(),
13477
13479
  finishedAt: z.iso.datetime().nullable()
13478
- });
13480
+ }).meta({ id: "RunRecord" });
13479
13481
  var runListSchema = z.object({ runs: z.array(runRecordSchema) });
13480
13482
  var runCancelSchema = z.object({ cancelled: z.boolean() });
13481
13483
  var runAnswerSchema = z.object({
@@ -13536,6 +13538,7 @@ var DEFAULT_MEDIA_FORMS = [
13536
13538
  ];
13537
13539
  var WHILE_BUSY = ["refuse", "queue", "steer"];
13538
13540
  var ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024;
13541
+ var CLIENT_PLATFORMS = ["web", "ios", "android"];
13539
13542
  var APPROVAL_TITLE_FIELD = "approvalTitle";
13540
13543
  var DELEGATE_TASK_TOOL = "delegateTask";
13541
13544
  var CANCEL_TASK_TOOL = "cancelTask";
@@ -13567,7 +13570,7 @@ var variableDeclarationSchema = z3.object({
13567
13570
  name: identifierSchema,
13568
13571
  description: z3.string().max(SERVER_MANIFEST_LIMITS.description),
13569
13572
  example: z3.string().max(SERVER_MANIFEST_LIMITS.example),
13570
- type: z3.enum(["string", "number", "boolean"]),
13573
+ type: z3.enum(["string", "number", "boolean"]).meta({ id: "VariableType" }),
13571
13574
  computed: z3.boolean()
13572
13575
  });
13573
13576
  var BUILT_IN_VARIABLES = [
@@ -13621,7 +13624,6 @@ function isBuiltInToolName(name) {
13621
13624
  return BUILT_IN_TOOL_NAMES.some((builtIn) => builtIn === name);
13622
13625
  }
13623
13626
  var declaredToolNameSchema = identifierSchema.refine((name) => !isBuiltInToolName(name), "the name of a built-in tool");
13624
- var jsonSchemaSchema = z3.record(z3.string(), z3.unknown());
13625
13627
  var serverVariableSchema = z3.object({
13626
13628
  name: identifierSchema.refine((name) => !BUILT_IN_VARIABLES.some((builtIn) => builtIn.name === name), "the name of a built-in variable"),
13627
13629
  description: z3.string().max(SERVER_MANIFEST_LIMITS.description),
@@ -13632,8 +13634,8 @@ var serverToolSchema = z3.object({
13632
13634
  name: declaredToolNameSchema,
13633
13635
  displayName: displayNameSchema.optional(),
13634
13636
  description: z3.string().trim().min(1).max(SERVER_MANIFEST_LIMITS.description),
13635
- inputSchema: jsonSchemaSchema.refine((schema) => schema.type === "object", "a tool's input is an object"),
13636
- outputSchema: jsonSchemaSchema.optional(),
13637
+ inputSchema: jsonObjectSchema.refine((schema) => schema["type"] === "object", "a tool's input is an object"),
13638
+ outputSchema: jsonObjectSchema.optional(),
13637
13639
  readOnly: z3.boolean(),
13638
13640
  requiresApproval: z3.boolean().optional()
13639
13641
  });
@@ -13666,11 +13668,11 @@ function pointedAt(root, ref) {
13666
13668
  return ref.startsWith("#") ? readJsonPointer(root, ref) : undefined;
13667
13669
  }
13668
13670
  function namesApprovalTitle(node) {
13669
- const required = node.required;
13670
- return isRecord(node.properties) && Object.hasOwn(node.properties, APPROVAL_TITLE_FIELD) || Array.isArray(required) && required.includes(APPROVAL_TITLE_FIELD);
13671
+ const required = node["required"];
13672
+ return isRecord(node["properties"]) && Object.hasOwn(node["properties"], APPROVAL_TITLE_FIELD) || Array.isArray(required) && required.includes(APPROVAL_TITLE_FIELD);
13671
13673
  }
13672
13674
  function sameObjectSchemas(node, root) {
13673
- const schemas = typeof node.$ref === "string" ? [pointedAt(root, node.$ref)] : [];
13675
+ const schemas = typeof node["$ref"] === "string" ? [pointedAt(root, node["$ref"])] : [];
13674
13676
  for (const keyword of ["allOf", "anyOf", "oneOf"]) {
13675
13677
  const members = node[keyword];
13676
13678
  if (!Array.isArray(members))
@@ -13693,7 +13695,7 @@ function sameObjectNodes(inputSchema) {
13693
13695
  return nodes;
13694
13696
  }
13695
13697
  function closed(node) {
13696
- return node.additionalProperties === false || node.unevaluatedProperties === false;
13698
+ return node["additionalProperties"] === false || node["unevaluatedProperties"] === false;
13697
13699
  }
13698
13700
  function blocksApprovalTitle(inputSchema) {
13699
13701
  return sameObjectNodes(inputSchema).some((node) => namesApprovalTitle(node) || node !== inputSchema && closed(node));
@@ -13724,7 +13726,7 @@ var delegationSchema = z3.object({
13724
13726
  });
13725
13727
  var serverUserSchema = z3.object({
13726
13728
  id: userIdSchema,
13727
- claims: z3.record(z3.string(), z3.unknown()),
13729
+ claims: jsonObjectSchema,
13728
13730
  delegated: delegationSchema.optional()
13729
13731
  }).nullable();
13730
13732
  var variablesRequestSchema = z3.object({
@@ -13735,16 +13737,16 @@ var variablesRequestSchema = z3.object({
13735
13737
  });
13736
13738
  var variablesResponseSchema = z3.object({ values: variableValuesSchema });
13737
13739
  var toolRequestSchema = z3.object({
13738
- input: z3.record(z3.string(), z3.unknown()),
13740
+ input: jsonObjectSchema,
13739
13741
  context: variablesRequestSchema.pick({ agent: true, thread: true, user: true }).extend({
13740
- variables: z3.record(z3.string(), z3.unknown())
13742
+ variables: jsonObjectSchema
13741
13743
  })
13742
13744
  });
13743
13745
  var SERVER_REQUEST_MAX_BYTES = 4 * 1024 * 1024;
13744
13746
  var toolResponseSchema = z3.union([backendErrorSchema, z3.object({ output: z3.json() })]);
13745
13747
  var verifyRequestSchema = z3.object({ token: z3.string().min(1) });
13746
13748
  var verifyResponseSchema = z3.union([
13747
- z3.object({ sub: userIdSchema.min(1), claims: z3.record(z3.string(), z3.unknown()) }),
13749
+ z3.object({ sub: userIdSchema.min(1), claims: jsonObjectSchema }),
13748
13750
  z3.object({ sub: z3.null() })
13749
13751
  ]);
13750
13752
 
@@ -13800,19 +13802,26 @@ function manifestOf(options) {
13800
13802
  };
13801
13803
  return { version: contentVersion(content), ...content };
13802
13804
  }
13805
+ function logFailure(error, { request }) {
13806
+ console.error(`Server call ${new URL(request.url).pathname} failed`, error);
13807
+ }
13803
13808
  function defineServer(options) {
13804
- if (!options.key)
13809
+ if (!options.key?.trim())
13805
13810
  throw new Error("defineServer needs the server key");
13806
13811
  const manifest = serverManifestSchema.parse(manifestOf(options));
13807
13812
  const tools = new Map(Object.entries(options.tools ?? {}));
13808
13813
  const expected = digest(options.key);
13814
+ const onError = options.onError ?? logFailure;
13809
13815
  const app = new Hono;
13810
13816
  function post(path, route) {
13811
13817
  app.post(path, async function(c) {
13818
+ const http = { request: c.req.raw, signal: c.req.raw.signal };
13812
13819
  try {
13813
- return await route(c);
13820
+ return await route(c, http);
13814
13821
  } catch (error) {
13815
13822
  const envelope = envelopeOf(error);
13823
+ if (envelope.error.kind === "internal")
13824
+ onError(error, http);
13816
13825
  return c.json(envelope, BACKEND_ERROR_STATUS[envelope.error.kind]);
13817
13826
  }
13818
13827
  });
@@ -13828,15 +13837,15 @@ function defineServer(options) {
13828
13837
  app.get("/", function(c) {
13829
13838
  return c.json(manifest);
13830
13839
  });
13831
- post("/variables", async function(c) {
13840
+ post("/variables", async function(c, http) {
13832
13841
  const body = await bodyOf(c.req, variablesRequestSchema);
13833
13842
  if (!body)
13834
13843
  return c.json(malformedBody, 400);
13835
13844
  const request = { ...body, token: c.req.header(END_USER_TOKEN_HEADER) };
13836
- const values = await Promise.all(Object.entries(options.variables ?? {}).map(async ([name, variable]) => [name, await variable.resolve(request)]));
13845
+ const values = await Promise.all(Object.entries(options.variables ?? {}).map(async ([name, variable]) => [name, await variable.resolve(request, http)]));
13837
13846
  return c.json({ values: Object.fromEntries(values) });
13838
13847
  });
13839
- post("/tools/:name", async function(c) {
13848
+ post("/tools/:name", async function(c, http) {
13840
13849
  const tool = tools.get(c.req.param("name"));
13841
13850
  if (!tool) {
13842
13851
  return c.json(errorEnvelope("invalid_request", `Unknown tool "${c.req.param("name")}"`), 404);
@@ -13848,19 +13857,17 @@ function defineServer(options) {
13848
13857
  if (!input.success) {
13849
13858
  return c.json(errorEnvelope("invalid_request", z4.prettifyError(input.error)), 400);
13850
13859
  }
13851
- const output = await tool.run(input.data, {
13852
- ...body.context,
13853
- token: c.req.header(END_USER_TOKEN_HEADER)
13854
- });
13860
+ const result = await tool.run(input.data, { ...body.context, token: c.req.header(END_USER_TOKEN_HEADER) }, http);
13861
+ const output = tool.output ? tool.output.parse(result) : result;
13855
13862
  return c.json({ output: output ?? null });
13856
13863
  });
13857
13864
  const verify = options.verify;
13858
13865
  if (verify) {
13859
- post("/verify", async function(c) {
13866
+ post("/verify", async function(c, http) {
13860
13867
  const body = await bodyOf(c.req, verifyRequestSchema);
13861
13868
  if (!body)
13862
13869
  return c.json(malformedBody, 400);
13863
- const verdict = await verify(body.token);
13870
+ const verdict = await verify(body.token, http);
13864
13871
  return c.json(verdict ? { sub: verdict.sub, claims: verdict.claims ?? {} } : { sub: null });
13865
13872
  });
13866
13873
  }
@@ -13868,11 +13875,11 @@ function defineServer(options) {
13868
13875
  for (const event of SERVER_EVENTS) {
13869
13876
  if (!events[event])
13870
13877
  continue;
13871
- post(`/events/${event}`, async function(c) {
13878
+ post(`/events/${event}`, async function(c, http) {
13872
13879
  const body = await bodyOf(c.req, serverEventSchema);
13873
13880
  if (!body || body.event !== event)
13874
13881
  return c.json(malformedBody, 400);
13875
- await (body.event === "run_waiting" ? events.run_waiting?.(body) : events.run_finished?.(body));
13882
+ await (body.event === "run_waiting" ? events.run_waiting?.(body, http) : events.run_finished?.(body, http));
13876
13883
  return c.body(null, 204);
13877
13884
  });
13878
13885
  }
@@ -13881,6 +13888,29 @@ function defineServer(options) {
13881
13888
  // src/datasets/dataset-host.ts
13882
13889
  import { Hono as Hono2 } from "hono";
13883
13890
  var DEFAULT_TIMEOUT_MS = 30000;
13891
+ function logFailure2(error, { dataset }) {
13892
+ console.error(`Dataset query for ${dataset} failed`, error);
13893
+ }
13894
+ function subjectOf(token) {
13895
+ const [, payload, ...signature] = token.split(".");
13896
+ if (payload === undefined || signature.length !== 1)
13897
+ return;
13898
+ try {
13899
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString());
13900
+ return isRecord(claims) && typeof claims["sub"] === "string" ? claims["sub"] : undefined;
13901
+ } catch {
13902
+ return;
13903
+ }
13904
+ }
13905
+ function unverifiedJwtSubject({ token }) {
13906
+ if (token === undefined)
13907
+ return null;
13908
+ const sub = subjectOf(token);
13909
+ if (sub === undefined) {
13910
+ throw new CortexError2("forbidden", "The end-user token is not a JWT with a subject");
13911
+ }
13912
+ return { sub };
13913
+ }
13884
13914
  function tokenFrom(headers, userToken) {
13885
13915
  const raw = headers.get(userToken.header);
13886
13916
  if (!raw)
@@ -13889,10 +13919,17 @@ function tokenFrom(headers, userToken) {
13889
13919
  return raw.startsWith(prefix) ? raw.slice(prefix.length) : raw;
13890
13920
  }
13891
13921
  function defineDatasetHost(options) {
13892
- const sources = new Map(options.expose.map((source) => {
13922
+ if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1)) {
13923
+ throw new Error("defineDatasetHost needs a timeoutMs of whole milliseconds above 0");
13924
+ }
13925
+ const sources = new Map;
13926
+ for (const source of options.expose) {
13893
13927
  const definition = datasetDefinitionSchema.parse(source.definition);
13894
- return [definition.name, { ...source, definition }];
13895
- }));
13928
+ if (sources.has(definition.name)) {
13929
+ throw new Error(`Dataset "${definition.name}" is exposed twice`);
13930
+ }
13931
+ sources.set(definition.name, { ...source, definition });
13932
+ }
13896
13933
  const definitions = [...sources.values()].map((source) => source.definition).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
13897
13934
  const catalog = datasetCatalogOf(definitions);
13898
13935
  const manifest = {
@@ -13901,6 +13938,7 @@ function defineDatasetHost(options) {
13901
13938
  };
13902
13939
  const userToken = options.userToken ?? { header: END_USER_TOKEN_HEADER };
13903
13940
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
13941
+ const onError = options.onError ?? logFailure2;
13904
13942
  const app = new Hono2;
13905
13943
  app.get("/", function(c) {
13906
13944
  return c.json(manifest);
@@ -13923,7 +13961,7 @@ function defineDatasetHost(options) {
13923
13961
  if (issues.length)
13924
13962
  return c.json(errorEnvelope("invalid_request", issues.join("; ")), 400);
13925
13963
  const headers = c.req.raw.headers;
13926
- const signal = AbortSignal.timeout(timeoutMs);
13964
+ const signal = AbortSignal.any([c.req.raw.signal, AbortSignal.timeout(timeoutMs)]);
13927
13965
  const resolveAndRun = async () => {
13928
13966
  const user = await options.resolveUser({ token: tokenFrom(headers, userToken), headers }, signal);
13929
13967
  signal.throwIfAborted();
@@ -13932,614 +13970,322 @@ function defineDatasetHost(options) {
13932
13970
  try {
13933
13971
  const rows = await Promise.race([
13934
13972
  resolveAndRun(),
13935
- new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason), {
13936
- once: true
13937
- }))
13973
+ new Promise((_, reject) => {
13974
+ if (signal.aborted)
13975
+ reject(signal.reason);
13976
+ signal.addEventListener("abort", () => reject(signal.reason), {
13977
+ once: true
13978
+ });
13979
+ })
13938
13980
  ]);
13939
13981
  return c.json(boundDatasetResult({ rows, rowCount: rows.length, truncated: false }, query.limit));
13940
13982
  } catch (error) {
13941
13983
  const envelope = envelopeOf(error);
13984
+ if (envelope.error.kind === "internal") {
13985
+ onError(error, { dataset: source.definition.name, request: c.req.raw });
13986
+ }
13942
13987
  return c.json(envelope, BACKEND_ERROR_STATUS[envelope.error.kind]);
13943
13988
  }
13944
13989
  });
13945
13990
  return app;
13946
13991
  }
13947
- // src/triggers/trigger-client.ts
13948
- class TriggerClientError extends Error {
13949
- status;
13950
- body;
13951
- constructor(status, body) {
13952
- super(`Cortex answered ${status}: ${body}`);
13953
- this.status = status;
13954
- this.body = body;
13955
- this.name = "TriggerClientError";
13956
- }
13992
+ // ../../internal/contracts/src/manifest/fields.ts
13993
+ import { z as z5 } from "zod";
13994
+
13995
+ // ../../internal/contracts/src/egress-policy/url.ts
13996
+ function isLoopback(hostname) {
13997
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
13957
13998
  }
13958
- function createTriggerClient(config) {
13959
- const origin = config.url.replace(/\/+$/, "");
13960
- const fetchFn = config.fetch ?? globalThis.fetch;
13961
- function secretOf(trigger) {
13962
- const { secrets = {} } = config;
13963
- const own = Object.hasOwn(secrets, trigger) ? secrets[trigger] : undefined;
13964
- const secret = own?.trim() ? own : config.secret;
13965
- if (!secret?.trim())
13966
- throw new Error(`No secret configured for trigger "${trigger}"`);
13967
- return secret;
13968
- }
13969
- function runPath(runId) {
13970
- return runRoute(config, config.agent, runId);
13971
- }
13972
- async function send(trigger, path, init, parse, acceptedErrors = []) {
13973
- const headers = new Headers(init.headers);
13974
- headers.set("Authorization", `Bearer ${secretOf(trigger)}`);
13975
- const response = await fetchFn(`${origin}${path}`, { ...init, headers });
13976
- const body = await response.text();
13977
- if (!response.ok && !acceptedErrors.includes(response.status))
13978
- throw new TriggerClientError(response.status, body);
13979
- try {
13980
- return parse(JSON.parse(body));
13981
- } catch {
13982
- throw new TriggerClientError(response.status, body);
13983
- }
13999
+ function normalizeHost(hostname) {
14000
+ const bare = hostname.toLowerCase().replace(/\.$/, "").replace(/^\[(.*)]$/, "$1");
14001
+ if (!bare.includes(":"))
14002
+ return bare;
14003
+ try {
14004
+ return new URL(`http://[${bare}]`).hostname.replace(/^\[(.*)]$/, "$1");
14005
+ } catch {
14006
+ return bare;
13984
14007
  }
13985
- async function post(trigger, path, payload, options) {
13986
- const headers = new Headers({ "Content-Type": "application/json" });
13987
- if (options.idempotencyKey !== undefined)
13988
- headers.set("Idempotency-Key", options.idempotencyKey);
13989
- return await send(trigger, `${path}${query(options)}`, { method: "POST", headers, body: JSON.stringify(payload), signal: options.signal }, (answer) => fireAnswerSchema.parse(answer), [409, 422, 429]);
14008
+ }
14009
+ function egressAllowedHosts() {
14010
+ return (globalThis.process?.env?.EGRESS_ALLOWED_HOSTS ?? "").split(",").map((host) => host.trim()).filter(Boolean);
14011
+ }
14012
+ function isEgressAllowedHost(hostname, allowed = egressAllowedHosts()) {
14013
+ const wanted = normalizeHost(hostname);
14014
+ return allowed.some((host) => host === "*" || normalizeHost(host) === wanted);
14015
+ }
14016
+ function canCarrySecret(url, allowed = egressAllowedHosts()) {
14017
+ try {
14018
+ const { protocol, hostname } = new URL(url);
14019
+ if (protocol === "https:")
14020
+ return true;
14021
+ if (protocol !== "http:")
14022
+ return false;
14023
+ return isLoopback(normalizeHost(hostname)) || isEgressAllowedHost(hostname, allowed);
14024
+ } catch {
14025
+ return false;
13990
14026
  }
13991
- function query(options) {
13992
- const params = new URLSearchParams;
13993
- if (options.wait !== undefined) {
13994
- if (!Number.isInteger(options.wait) || options.wait < 0 || options.wait > 300000)
13995
- throw new RangeError("wait must be an integer from 0 to 300000 milliseconds");
13996
- params.set("wait", String(options.wait));
13997
- }
13998
- if (options.busy !== undefined)
13999
- params.set("busy", options.busy);
14000
- return params.size ? `?${params.toString()}` : "";
14027
+ }
14028
+ // ../../internal/contracts/src/manifest/bounds.ts
14029
+ var TOOL_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
14030
+ var SETTING_BOUNDS = {
14031
+ tool: {
14032
+ timeoutMs: { min: 100, max: 120000, default: 30000 },
14033
+ maxResponseBytes: { min: 1024, max: 1048576, default: 262144 }
14034
+ },
14035
+ agentContext: {
14036
+ maxContextTokens: { min: 4000, max: 2000000, default: 120000 },
14037
+ summarizationThreshold: { min: 0.1, max: 0.95, default: 0.75 },
14038
+ toolResultMaxTokens: { min: 500, max: 200000, default: 1e4 },
14039
+ recentMessagesToKeep: { min: 0, max: 100, default: 6 }
14040
+ },
14041
+ agentLimits: {
14042
+ resolveTokenBudget: { min: 500, max: 64000, default: 4000 },
14043
+ executeTimeoutMs: { min: 1000, max: 300000, default: 30000 },
14044
+ maxResponseBytes: { min: 1024, max: 1048576, default: 262144 },
14045
+ subagentDepth: { min: 1, max: 3, default: 1 },
14046
+ subagentsAtOnce: { min: 1, max: 10, default: 3 }
14047
+ },
14048
+ trigger: { disableAfterFailures: { min: 1, max: 1000, default: 5 } },
14049
+ datasetHost: { timeoutMs: { min: 100, max: 120000, default: 30000 } },
14050
+ webhook: { timeoutMs: { min: 1000, max: 30000, default: 1e4 } },
14051
+ recaptcha: { minScore: { min: 0.1, max: 0.9, default: 0.5 } },
14052
+ server: {
14053
+ signInChecksPerMinute: { min: 1, max: 1e5, default: 600 },
14054
+ triggerChecksPerMinute: { min: 1, max: 1e4, default: 60 }
14001
14055
  }
14002
- return {
14003
- async fire(trigger, payload, options = {}) {
14004
- return await post(trigger, triggerRoute(config, config.agent, trigger), payload, options);
14005
- },
14006
- async answer(trigger, runId, decision, options = {}) {
14007
- return await post(trigger, `${runPath(runId)}/answer`, runAnswerSchema.parse(decision), options);
14008
- },
14009
- async read(trigger, runId, options = {}) {
14010
- return await send(trigger, runPath(runId), { method: "GET", signal: options.signal }, (answer) => runRecordSchema.parse(answer));
14011
- },
14012
- async list(trigger, options = {}) {
14013
- const query = new URLSearchParams;
14014
- if (options.limit !== undefined) {
14015
- if (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 200)
14016
- throw new RangeError("limit must be an integer from 1 to 200");
14017
- query.set("limit", String(options.limit));
14018
- }
14019
- if (options.before !== undefined)
14020
- query.set("before", options.before);
14021
- const suffix = query.size ? `?${query.toString()}` : "";
14022
- return await send(trigger, `${triggerRoute(config, config.agent, trigger)}/runs${suffix}`, { method: "GET", signal: options.signal }, (answer) => runListSchema.parse(answer));
14023
- },
14024
- async cancel(trigger, runId, options = {}) {
14025
- return await send(trigger, `${runPath(runId)}/cancel`, { method: "POST", signal: options.signal }, (answer) => runCancelSchema.parse(answer));
14026
- }
14027
- };
14056
+ };
14057
+ var RATE_LIMITS = {
14058
+ agent: {
14059
+ messagesPerMinute: { max: 1e4, allUsers: 600, perUser: 20 },
14060
+ tokensPerDay: { max: 1000000000000, allUsers: null, perUser: 1e6 }
14061
+ },
14062
+ tool: { callsPerMinute: { max: 1e4, allUsers: 60, perUser: 20 } },
14063
+ datasetHost: { queriesPerMinute: { max: 1e4, allUsers: 60, perUser: 20 } }
14064
+ };
14065
+ var TOOL_TYPE_NAMES = ["http", "embedded", "soap", "native", "client"];
14066
+ var MCP_CONNECTION_OWNERS = ["shared", "endUser"];
14067
+ var RESPONSE_WRAPS = ["items", "value"];
14068
+ var QUERY_STYLES = ["form", "spaceDelimited", "pipeDelimited", "deepObject"];
14069
+ var PATH_STYLES = ["simple", "label", "matrix"];
14070
+ var SOAP_VERSIONS = ["1.1", "1.2"];
14071
+ 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])?)*$/;
14072
+ var FETCH_IMAGE_HOSTS_LIMIT = 20;
14073
+ var A2A_PUSH_HOSTS_LIMIT = 20;
14074
+ var SUGGESTION_LIMITS = { perLocale: 6, titleLength: 120, promptLength: 2000 };
14075
+ var GREETING_MAX_LENGTH = 200;
14076
+ var FORM_MEDIA_TYPES = [
14077
+ "application/x-www-form-urlencoded",
14078
+ "multipart/form-data"
14079
+ ];
14080
+ var ENDPOINT_PARAM_PATTERN = /\{([^{}]+)\}/g;
14081
+ var HEADER_LIMITS = { headerLength: 120, prefixLength: 40, headers: 8 };
14082
+ var HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
14083
+ var HEADER_VALUE_PATTERN = /^[\t\x20-\x7e\x80-\xff]*$/;
14084
+ var transportSetHeaders = ["accept", "content-type", "content-length", "host"];
14085
+ var transportForbiddenHeaders = [
14086
+ "connection",
14087
+ "transfer-encoding",
14088
+ "upgrade",
14089
+ "expect",
14090
+ "te",
14091
+ "trailer",
14092
+ "proxy-authorization"
14093
+ ];
14094
+ var mcpTransportHeaders = new Set([
14095
+ "mcp-session-id",
14096
+ "mcp-protocol-version",
14097
+ "last-event-id"
14098
+ ]);
14099
+ var transportOwnedHeaders = new Set([
14100
+ ...transportSetHeaders,
14101
+ ...transportForbiddenHeaders
14102
+ ]);
14103
+ var SCALAR_TYPES = ["string", "number", "integer", "boolean"];
14104
+ var FIELD_LIMITS = { nameLength: 120, descriptionLength: 500, enumValues: 50 };
14105
+ var MODEL_PROVIDER_LIMITS = { urlLength: 2048, modelLength: 200, models: 100 };
14106
+ var SERVICE_LIMITS = { descriptionLength: 4000 };
14107
+ var SKILL_LIMITS = { descriptionLength: 500 };
14108
+ var TRIGGER_LIMITS = { descriptionLength: 500, instructionsLength: 20000 };
14109
+ var COLLECTION_LIMITS = { descriptionLength: 2000, documents: 100 };
14110
+ var DOCUMENT_LIMITS = { nameLength: 255, bytes: 10 * 1024 * 1024 };
14111
+ var DOCX_MIME_TYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
14112
+ var AUTH_JWT_SECRET_ALGORITHMS = ["HS256", "HS384", "HS512"];
14113
+ var MANIFEST_KINDS = [
14114
+ "agents",
14115
+ "services",
14116
+ "tools",
14117
+ "skills",
14118
+ "triggers",
14119
+ "datasetHosts",
14120
+ "mcpServers",
14121
+ "webhooks",
14122
+ "collections"
14123
+ ];
14124
+
14125
+ // ../../internal/contracts/src/manifest/fields.ts
14126
+ var jsonPointerSchema = z5.string().regex(/^\//).max(256);
14127
+ function setting({ min, max, default: fallback }) {
14128
+ return z5.number().int().min(min).max(max).default(fallback);
14028
14129
  }
14029
- // ../../internal/contracts/src/management/index.ts
14030
- import { z as z5 } from "zod";
14130
+ function rateLimit(bound, users) {
14131
+ return z5.number().int().min(1).max(bound.max).nullable().default(bound[users]);
14132
+ }
14133
+ function overridable(fields) {
14134
+ return z5.array(z5.enum(fields)).refine((listed) => new Set(listed).size === listed.length, "a field repeats").default([]);
14135
+ }
14136
+ var tlsUrlSchema = z5.url().refine((url) => canCarrySecret(url, []));
14137
+ var upstreamUrlSchema = z5.url({ protocol: /^https?$/ });
14138
+ var audienceSchema = z5.union([
14139
+ z5.literal("all"),
14140
+ z5.strictObject({ server: nameSchema }),
14141
+ z5.strictObject({
14142
+ agents: z5.array(nameSchema).min(1).refine((names) => new Set(names).size === names.length, "an agent repeats")
14143
+ })
14144
+ ]).meta({ id: "ManifestAudience" });
14145
+ var modelSchema = z5.strictObject({
14146
+ provider: nameSchema,
14147
+ model: z5.string().trim().min(1).max(MODEL_PROVIDER_LIMITS.modelLength),
14148
+ effort: z5.string().trim().min(1).max(64).optional()
14149
+ });
14150
+ // ../../internal/contracts/src/manifest/manifest.ts
14151
+ import { z as z18 } from "zod";
14031
14152
 
14032
- // ../../internal/contracts/src/management/procedures.generated.ts
14033
- var managementProcedureKinds = {
14034
- "agents.addAlias": "mutation",
14035
- "agents.create": "mutation",
14036
- "agents.delete": "mutation",
14037
- "agents.deleteAlias": "mutation",
14038
- "agents.get": "query",
14039
- "agents.list": "query",
14040
- "agents.listAliases": "query",
14041
- "agents.options": "query",
14042
- "agents.publishPrompt": "mutation",
14043
- "agents.rollbackPrompt": "mutation",
14044
- "agents.savePrompt": "mutation",
14045
- "agents.saveSettings": "mutation",
14046
- "agents.update": "mutation",
14047
- "audit.filters": "query",
14048
- "audit.get": "query",
14049
- "audit.list": "query",
14050
- "collections.create": "mutation",
14051
- "collections.delete": "mutation",
14052
- "collections.get": "query",
14053
- "collections.list": "query",
14054
- "collections.setAudience": "mutation",
14055
- "collections.testRetrieval": "mutation",
14056
- "collections.update": "mutation",
14057
- "credentials.create": "mutation",
14058
- "credentials.delete": "mutation",
14059
- "credentials.list": "query",
14060
- "credentials.names": "query",
14061
- "credentials.rotateKey": "mutation",
14062
- "credentials.update": "mutation",
14063
- "datasetHosts.create": "mutation",
14064
- "datasetHosts.delete": "mutation",
14065
- "datasetHosts.get": "query",
14066
- "datasetHosts.list": "query",
14067
- "datasetHosts.publish": "mutation",
14068
- "datasetHosts.rollback": "mutation",
14069
- "datasetHosts.setAudience": "mutation",
14070
- "datasetHosts.sync": "mutation",
14071
- "datasetHosts.test": "mutation",
14072
- "datasetHosts.toggle": "mutation",
14073
- "datasetHosts.update": "mutation",
14074
- "documents.chunks": "query",
14075
- "documents.completeUpload": "mutation",
14076
- "documents.list": "query",
14077
- "documents.prepareUpload": "mutation",
14078
- "documents.remove": "mutation",
14079
- "documents.retry": "mutation",
14080
- "managementKeys.mine": "query",
14081
- "manifests.preview": "mutation",
14082
- "manifests.sync": "mutation",
14083
- "mcpServers.create": "mutation",
14084
- "mcpServers.delete": "mutation",
14085
- "mcpServers.detectSignIn": "query",
14086
- "mcpServers.disconnect": "mutation",
14087
- "mcpServers.get": "query",
14088
- "mcpServers.list": "query",
14089
- "mcpServers.publish": "mutation",
14090
- "mcpServers.rollback": "mutation",
14091
- "mcpServers.setAudience": "mutation",
14092
- "mcpServers.test": "mutation",
14093
- "mcpServers.toggle": "mutation",
14094
- "mcpServers.update": "mutation",
14095
- "modelProviders.create": "mutation",
14096
- "modelProviders.delete": "mutation",
14097
- "modelProviders.inherited": "query",
14098
- "modelProviders.list": "query",
14099
- "modelProviders.options": "query",
14100
- "modelProviders.update": "mutation",
14101
- "observability.getExecution": "query",
14102
- "observability.getExecutionSummary": "query",
14103
- "observability.getRetrievalQuality": "query",
14104
- "observability.getRun": "query",
14105
- "observability.getUsage": "query",
14106
- "observability.listDatasetReads": "query",
14107
- "observability.listExecutions": "query",
14108
- "observability.listRuns": "query",
14109
- "observability.listSchemaDrifts": "query",
14110
- "observability.listSkillLoads": "query",
14111
- "observability.listSkillMisses": "query",
14112
- "observability.listSkillUsage": "query",
14113
- "observability.listToolHealth": "query",
14114
- "observability.listUsageUsers": "query",
14115
- "observability.unhealthyToolIds": "query",
14116
- "observability.unusedSkillIds": "query",
14117
- "observability.updateSchemaDrift": "mutation",
14118
- "orgs.create": "mutation",
14119
- "orgs.delete": "mutation",
14120
- "orgs.deleteEnvironment": "mutation",
14121
- "orgs.deleteProject": "mutation",
14122
- "orgs.inviteOwner": "mutation",
14123
- "orgs.list": "query",
14124
- "orgs.options": "query",
14125
- "orgs.rename": "mutation",
14126
- "orgs.restore": "mutation",
14127
- "orgs.suspend": "mutation",
14128
- "orgs.updateProject": "mutation",
14129
- "publishing.exclusive": "query",
14130
- "publishing.history": "query",
14131
- "publishing.latest": "query",
14132
- "roles.create": "mutation",
14133
- "roles.delete": "mutation",
14134
- "roles.list": "query",
14135
- "roles.update": "mutation",
14136
- "secrets.delete": "mutation",
14137
- "secrets.list": "query",
14138
- "secrets.names": "query",
14139
- "secrets.rotate": "mutation",
14140
- "secrets.set": "mutation",
14141
- "secrets.update": "mutation",
14142
- "servers.create": "mutation",
14143
- "servers.delete": "mutation",
14144
- "servers.get": "query",
14145
- "servers.list": "query",
14146
- "servers.options": "query",
14147
- "servers.sync": "mutation",
14148
- "servers.update": "mutation",
14149
- "services.create": "mutation",
14150
- "services.delete": "mutation",
14151
- "services.get": "query",
14152
- "services.list": "query",
14153
- "services.options": "query",
14154
- "services.publish": "mutation",
14155
- "services.rollback": "mutation",
14156
- "services.setAudience": "mutation",
14157
- "services.toggle": "mutation",
14158
- "services.update": "mutation",
14159
- "settings.get": "query",
14160
- "settings.update": "mutation",
14161
- "skills.countPublished": "query",
14162
- "skills.create": "mutation",
14163
- "skills.delete": "mutation",
14164
- "skills.get": "query",
14165
- "skills.list": "query",
14166
- "skills.publish": "mutation",
14167
- "skills.rollback": "mutation",
14168
- "skills.setAudience": "mutation",
14169
- "skills.toggle": "mutation",
14170
- "skills.update": "mutation",
14171
- "threads.get": "query",
14172
- "threads.list": "query",
14173
- "threads.llmRequests": "query",
14174
- "threads.transcript": "query",
14175
- "tools.applyDiff": "mutation",
14176
- "tools.countPinned": "query",
14177
- "tools.create": "mutation",
14178
- "tools.createDrafts": "mutation",
14179
- "tools.delete": "mutation",
14180
- "tools.diff": "query",
14181
- "tools.get": "query",
14182
- "tools.list": "query",
14183
- "tools.options": "query",
14184
- "tools.preview": "mutation",
14185
- "tools.publish": "mutation",
14186
- "tools.rollback": "mutation",
14187
- "tools.setAudience": "mutation",
14188
- "tools.test": "mutation",
14189
- "tools.toggle": "mutation",
14190
- "tools.update": "mutation",
14191
- "triggers.answerRun": "mutation",
14192
- "triggers.create": "mutation",
14193
- "triggers.delete": "mutation",
14194
- "triggers.fire": "mutation",
14195
- "triggers.get": "query",
14196
- "triggers.list": "query",
14197
- "triggers.publish": "mutation",
14198
- "triggers.rollback": "mutation",
14199
- "triggers.rotateSecret": "mutation",
14200
- "triggers.setAudience": "mutation",
14201
- "triggers.toggle": "mutation",
14202
- "triggers.update": "mutation",
14203
- "users.accounts": "query",
14204
- "users.invite": "mutation",
14205
- "users.list": "query",
14206
- "users.listInvitations": "query",
14207
- "users.remove": "mutation",
14208
- "users.revokeInvitation": "mutation",
14209
- "users.roleOptions": "query",
14210
- "users.setAccountActive": "mutation",
14211
- "users.setActive": "mutation",
14212
- "users.setRoles": "mutation",
14213
- "users.setTempPassword": "mutation",
14214
- "webhooks.create": "mutation",
14215
- "webhooks.delete": "mutation",
14216
- "webhooks.get": "query",
14217
- "webhooks.list": "query",
14218
- "webhooks.listDeliveries": "query",
14219
- "webhooks.setAudience": "mutation",
14220
- "webhooks.test": "mutation",
14221
- "webhooks.toggle": "mutation",
14222
- "webhooks.update": "mutation"
14223
- };
14224
-
14225
- // ../../internal/contracts/src/management/index.ts
14226
- var MANAGEMENT_BASE_PATH = "/api/management";
14227
- function managementPath(procedure) {
14228
- const kebab = procedure.replace(/[A-Z]/g, (upper) => `-${upper.toLowerCase()}`);
14229
- return `/${kebab.replaceAll(".", "/")}`;
14230
- }
14231
- function isScalar(value) {
14232
- return value === null || ["string", "number", "boolean"].includes(typeof value);
14233
- }
14234
- function managementQuery(input) {
14235
- const params = new URLSearchParams;
14236
- for (const [name, value] of Object.entries(input)) {
14237
- if (value === undefined)
14238
- continue;
14239
- if (isScalar(value))
14240
- params.set(name, String(value));
14241
- else if (Array.isArray(value) && value.length > 0 && value.every(isScalar)) {
14242
- for (const item of value)
14243
- params.append(name, String(item));
14244
- } else
14245
- params.set(name, JSON.stringify(value));
14153
+ // ../../internal/contracts/src/manifest/agents.ts
14154
+ import { z as z6 } from "zod";
14155
+ var trimmedText = (max) => z6.string().min(1).max(max).refine((text) => text === text.trim(), "text has surrounding whitespace");
14156
+ var suggestionsSchema = z6.record(localeSchema, z6.array(z6.object({
14157
+ title: trimmedText(SUGGESTION_LIMITS.titleLength),
14158
+ prompt: trimmedText(SUGGESTION_LIMITS.promptLength)
14159
+ })).max(SUGGESTION_LIMITS.perLocale));
14160
+ var greetingSchema = z6.record(localeSchema, z6.string().max(GREETING_MAX_LENGTH).refine((text) => text === text.trim(), "greeting has surrounding whitespace"));
14161
+ var issuerSchema = z6.string().trim().min(1).max(2048);
14162
+ var tokenAudienceSchema = z6.string().trim().min(1).max(2048).optional();
14163
+ var siteKeySchema = z6.string().trim().min(1).max(200);
14164
+ var appIdSchema = z6.string().trim().min(1).max(255);
14165
+ var recaptchaKeysSchema = z6.strictObject({
14166
+ web: z6.strictObject({ siteKey: siteKeySchema }).optional(),
14167
+ ios: z6.strictObject({ siteKey: siteKeySchema, bundleId: appIdSchema }).optional(),
14168
+ android: z6.strictObject({ siteKey: siteKeySchema, packageName: appIdSchema }).optional()
14169
+ }).refine((keys) => CLIENT_PLATFORMS.some((platform) => keys[platform]), "recaptcha needs a key for at least one client platform");
14170
+ var agentAuthSchema = z6.discriminatedUnion("kind", [
14171
+ z6.strictObject({
14172
+ kind: z6.literal("jwks"),
14173
+ jwksUri: tlsUrlSchema,
14174
+ issuer: issuerSchema,
14175
+ audience: tokenAudienceSchema
14176
+ }),
14177
+ z6.strictObject({
14178
+ kind: z6.literal("jwt-secret"),
14179
+ secret: nameSchema,
14180
+ algorithm: z6.enum(AUTH_JWT_SECRET_ALGORITHMS).meta({ id: "JwtSecretAlgorithm" }),
14181
+ issuer: issuerSchema,
14182
+ audience: tokenAudienceSchema
14183
+ }),
14184
+ z6.strictObject({
14185
+ kind: z6.literal("anonymous"),
14186
+ recaptcha: z6.strictObject({
14187
+ keys: recaptchaKeysSchema,
14188
+ projectId: z6.string().trim().min(1).max(200),
14189
+ secret: nameSchema,
14190
+ minScore: z6.number().min(SETTING_BOUNDS.recaptcha.minScore.min).max(SETTING_BOUNDS.recaptcha.minScore.max).default(SETTING_BOUNDS.recaptcha.minScore.default)
14191
+ }).optional()
14192
+ }),
14193
+ z6.strictObject({ kind: z6.literal("server") })
14194
+ ]);
14195
+ var { agentContext, agentLimits } = SETTING_BOUNDS;
14196
+ var SUBAGENT_WHEN_MAX = 1000;
14197
+ var { agent: agentRateLimits } = RATE_LIMITS;
14198
+ var agentSettingsSchema = z6.strictObject({
14199
+ ragEnabled: z6.boolean().default(false),
14200
+ toolRegistryEnabled: z6.boolean().default(false),
14201
+ serviceRegistryEnabled: z6.boolean().default(false),
14202
+ subagents: z6.array(z6.strictObject({
14203
+ agent: nameSchema,
14204
+ when: z6.string().trim().max(SUBAGENT_WHEN_MAX).default("")
14205
+ })).default([]),
14206
+ checkBacksEnabled: z6.boolean().default(false),
14207
+ attachmentsEnabled: z6.boolean().default(true),
14208
+ fetchImageHostnames: z6.array(z6.string().max(253).regex(HOSTNAME_PATTERN)).max(FETCH_IMAGE_HOSTS_LIMIT).default([]),
14209
+ locationPicker: z6.boolean().default(false),
14210
+ media: z6.array(z6.enum(MEDIA_FORMS)).default([...DEFAULT_MEDIA_FORMS]),
14211
+ messages: z6.boolean().default(true),
14212
+ whileBusy: z6.enum(WHILE_BUSY).default("refuse"),
14213
+ a2a: z6.boolean().default(false),
14214
+ a2aPushHostnames: z6.array(z6.string().max(253).regex(HOSTNAME_PATTERN)).max(A2A_PUSH_HOSTS_LIMIT).default([]),
14215
+ description: z6.string().trim().max(1000).default(""),
14216
+ defaultLocale: localeSchema.default(BASE_LOCALE),
14217
+ context: z6.strictObject({
14218
+ maxContextTokens: setting(agentContext.maxContextTokens),
14219
+ summarizationThreshold: z6.number().min(agentContext.summarizationThreshold.min).max(agentContext.summarizationThreshold.max).default(agentContext.summarizationThreshold.default),
14220
+ toolResultMaxTokens: setting(agentContext.toolResultMaxTokens),
14221
+ recentMessagesToKeep: setting(agentContext.recentMessagesToKeep)
14222
+ }).prefault({}),
14223
+ limits: z6.strictObject({
14224
+ resolveTokenBudget: setting(agentLimits.resolveTokenBudget),
14225
+ executeTimeoutMs: setting(agentLimits.executeTimeoutMs),
14226
+ maxResponseBytes: setting(agentLimits.maxResponseBytes),
14227
+ subagentDepth: setting(agentLimits.subagentDepth),
14228
+ subagentsAtOnce: setting(agentLimits.subagentsAtOnce)
14229
+ }).prefault({})
14230
+ });
14231
+ var manifestAgentSchema = z6.strictObject({
14232
+ name: nameSchema,
14233
+ displayName: displayNameSchema.default({}),
14234
+ server: nameSchema.optional(),
14235
+ prompt: z6.string().trim().min(1),
14236
+ auth: agentAuthSchema,
14237
+ models: z6.strictObject({
14238
+ chat: modelSchema.optional(),
14239
+ vision: modelSchema.omit({ effort: true }).optional(),
14240
+ summarization: modelSchema.omit({ effort: true }).optional()
14241
+ }).default({}),
14242
+ settings: agentSettingsSchema.prefault({}),
14243
+ rateLimits: z6.strictObject({
14244
+ allUsers: z6.strictObject({
14245
+ messagesPerMinute: rateLimit(agentRateLimits.messagesPerMinute, "allUsers"),
14246
+ tokensPerDay: rateLimit(agentRateLimits.tokensPerDay, "allUsers")
14247
+ }).prefault({}),
14248
+ perUser: z6.strictObject({
14249
+ messagesPerMinute: rateLimit(agentRateLimits.messagesPerMinute, "perUser"),
14250
+ tokensPerDay: rateLimit(agentRateLimits.tokensPerDay, "perUser")
14251
+ }).prefault({})
14252
+ }).prefault({}),
14253
+ suggestions: suggestionsSchema.default(() => byLocale(() => [])),
14254
+ greeting: greetingSchema.default(() => byLocale(() => "")),
14255
+ overridable: overridable([
14256
+ "displayName",
14257
+ "prompt",
14258
+ "models",
14259
+ "settings",
14260
+ "rateLimits",
14261
+ "suggestions",
14262
+ "greeting"
14263
+ ])
14264
+ }).superRefine((agent, context) => {
14265
+ if (agent.server !== undefined)
14266
+ return;
14267
+ if (agent.auth.kind === "server") {
14268
+ context.addIssue({
14269
+ code: "custom",
14270
+ path: ["auth"],
14271
+ message: "server auth needs a server"
14272
+ });
14273
+ }
14274
+ if (agent.models.chat === undefined) {
14275
+ context.addIssue({
14276
+ code: "custom",
14277
+ path: ["models", "chat"],
14278
+ message: "an agent with no server names its own chat model"
14279
+ });
14246
14280
  }
14247
- const encoded = params.toString();
14248
- return encoded === "" ? "" : `?${encoded}`;
14249
- }
14250
- var refusalBodySchema = z5.object({
14251
- code: z5.string().optional().catch(undefined),
14252
- message: z5.string().optional().catch(undefined),
14253
- refusal: z5.string().optional().catch(undefined),
14254
- cause: z5.record(z5.string(), z5.unknown()).optional().catch(undefined)
14255
14281
  });
14256
14282
 
14257
- class ManagementClientError extends Error {
14258
- status;
14259
- code;
14260
- detail;
14261
- refusal;
14262
- constructor(status, code, message, detail, refusal) {
14263
- super(message);
14264
- this.status = status;
14265
- this.code = code;
14266
- this.detail = detail;
14267
- this.refusal = refusal;
14268
- this.name = "ManagementClientError";
14269
- }
14270
- }
14271
- async function callManagement(target, request) {
14272
- const { method, path, input, signal } = request;
14273
- const query = method === "get" && isRecord(input) ? managementQuery(input) : "";
14274
- const url = `${target.url.replace(/\/+$/, "")}${MANAGEMENT_BASE_PATH}${path}${query}`;
14275
- const response = await (target.fetch ?? globalThis.fetch)(url, {
14276
- method: method.toUpperCase(),
14277
- headers: {
14278
- Authorization: `Bearer ${target.key}`,
14279
- ...method === "post" ? { "Content-Type": "application/json" } : {},
14280
- ...target.locale ? { "Accept-Language": target.locale } : {},
14281
- ...target.timeZone ? { [TIMEZONE_HEADER]: target.timeZone } : {}
14282
- },
14283
- body: method === "post" && input !== undefined ? JSON.stringify(input) : undefined,
14284
- signal
14285
- });
14286
- if (response.ok) {
14287
- const output = await response.json();
14288
- return output;
14289
- }
14290
- const body = await response.json().catch(() => null);
14291
- const refused = refusalBodySchema.safeParse(body).data ?? {};
14292
- throw new ManagementClientError(response.status, refused.code ?? "error", refused.message ?? response.statusText, refused.cause, refused.refusal);
14293
- }
14294
- function createManagementClient(target) {
14295
- const client = {};
14296
- for (const [procedure, kind] of Object.entries(managementProcedureKinds)) {
14297
- const [router = "", name = ""] = procedure.split(".");
14298
- (client[router] ??= {})[name] = (input, options) => callManagement(target, {
14299
- method: kind === "query" ? "get" : "post",
14300
- path: managementPath(procedure),
14301
- input,
14302
- signal: options?.signal
14303
- });
14304
- }
14305
- return client;
14306
- }
14307
- // ../../internal/contracts/src/manifest/index.ts
14308
- import { z as z7 } from "zod";
14309
-
14310
- // ../../internal/contracts/src/egress-policy/url.ts
14311
- function isLoopback(hostname) {
14312
- return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
14313
- }
14314
- function normalizeHost(hostname) {
14315
- const bare = hostname.toLowerCase().replace(/\.$/, "").replace(/^\[(.*)]$/, "$1");
14316
- if (!bare.includes(":"))
14317
- return bare;
14318
- try {
14319
- return new URL(`http://[${bare}]`).hostname.replace(/^\[(.*)]$/, "$1");
14320
- } catch {
14321
- return bare;
14322
- }
14323
- }
14324
- function egressAllowedHosts() {
14325
- return (globalThis.process?.env?.EGRESS_ALLOWED_HOSTS ?? "").split(",").map((host) => host.trim()).filter(Boolean);
14326
- }
14327
- function isEgressAllowedHost(hostname, allowed = egressAllowedHosts()) {
14328
- const wanted = normalizeHost(hostname);
14329
- return allowed.some((host) => host === "*" || normalizeHost(host) === wanted);
14330
- }
14331
- function canCarrySecret(url, allowed = egressAllowedHosts()) {
14332
- try {
14333
- const { protocol, hostname } = new URL(url);
14334
- if (protocol === "https:")
14335
- return true;
14336
- if (protocol !== "http:")
14337
- return false;
14338
- return isLoopback(normalizeHost(hostname)) || isEgressAllowedHost(hostname, allowed);
14339
- } catch {
14340
- return false;
14341
- }
14342
- }
14343
- // ../../internal/contracts/src/schedule/index.ts
14344
- var import_cron_parser = __toESM(require_dist(), 1);
14345
- import { z as z6 } from "zod";
14346
- function isTimeZone(timeZone) {
14347
- try {
14348
- new Intl.DateTimeFormat("en", { timeZone });
14349
- return true;
14350
- } catch {
14351
- return false;
14352
- }
14353
- }
14354
- function isCron(cron) {
14355
- if (cron.split(/\s+/).length !== 5 || /\bH\b/i.test(cron))
14356
- return false;
14357
- try {
14358
- import_cron_parser.CronExpressionParser.parse(cron);
14359
- return true;
14360
- } catch {
14361
- return false;
14362
- }
14363
- }
14364
- function triggerScheduleSchemaWith(messages) {
14365
- return z6.object({
14366
- cron: z6.string().trim().refine(isCron, { error: messages.cron }),
14367
- timeZone: z6.string().trim().refine(isTimeZone, { error: messages.timeZone })
14368
- });
14369
- }
14370
- var triggerScheduleSchema = triggerScheduleSchemaWith({
14371
- cron: () => "is not a cron of five fields: minute, hour, day of month, month, day of week",
14372
- timeZone: () => "is not an IANA time zone, such as Asia/Dubai"
14373
- });
14283
+ // ../../internal/contracts/src/manifest/datasets.ts
14284
+ import { z as z8 } from "zod";
14374
14285
 
14375
- // ../../internal/contracts/src/manifest/index.ts
14376
- var TOOL_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
14377
- var RESPONSE_WRAPS = ["items", "value"];
14378
- var QUERY_STYLES = ["form", "spaceDelimited", "pipeDelimited", "deepObject"];
14379
- var PATH_STYLES = ["simple", "label", "matrix"];
14380
- var SOAP_VERSIONS = ["1.1", "1.2"];
14381
- var jsonPointerSchema = z7.string().regex(/^\//).max(256);
14382
- var SETTING_BOUNDS = {
14383
- tool: {
14384
- timeoutMs: { min: 100, max: 120000, default: 30000 },
14385
- maxResponseBytes: { min: 1024, max: 1048576, default: 262144 }
14386
- },
14387
- agentContext: {
14388
- maxContextTokens: { min: 4000, max: 2000000, default: 120000 },
14389
- summarizationThreshold: { min: 0.1, max: 0.95, default: 0.75 },
14390
- toolResultMaxTokens: { min: 500, max: 200000, default: 1e4 },
14391
- recentMessagesToKeep: { min: 0, max: 100, default: 6 }
14392
- },
14393
- agentLimits: {
14394
- resolveTokenBudget: { min: 500, max: 64000, default: 4000 },
14395
- executeTimeoutMs: { min: 1000, max: 300000, default: 30000 },
14396
- maxResponseBytes: { min: 1024, max: 1048576, default: 262144 }
14397
- },
14398
- trigger: { disableAfterFailures: { min: 1, max: 1000, default: 5 } },
14399
- datasetHost: { timeoutMs: { min: 100, max: 120000, default: 30000 } },
14400
- webhook: { timeoutMs: { min: 1000, max: 30000, default: 1e4 } },
14401
- recaptcha: { minScore: { min: 0.1, max: 0.9, default: 0.5 } },
14402
- server: {
14403
- signInChecksPerMinute: { min: 1, max: 1e5, default: 600 },
14404
- triggerChecksPerMinute: { min: 1, max: 1e4, default: 60 }
14405
- }
14406
- };
14407
- function setting({ min, max, default: fallback }) {
14408
- return z7.number().int().min(min).max(max).default(fallback);
14409
- }
14410
- var RATE_LIMITS = {
14411
- agent: {
14412
- messagesPerMinute: { max: 1e4, allUsers: 600, perUser: 20 },
14413
- tokensPerDay: { max: 1000000000000, allUsers: null, perUser: 1e6 }
14414
- },
14415
- tool: { callsPerMinute: { max: 1e4, allUsers: 60, perUser: 20 } },
14416
- datasetHost: { queriesPerMinute: { max: 1e4, allUsers: 60, perUser: 20 } }
14417
- };
14418
- function rateLimit(bound, users) {
14419
- return z7.number().int().min(1).max(bound.max).nullable().default(bound[users]);
14420
- }
14421
- function overridable(fields) {
14422
- return z7.array(z7.enum(fields)).refine((listed) => new Set(listed).size === listed.length, "a field repeats").default([]);
14423
- }
14424
- 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])?)*$/;
14425
- var FETCH_IMAGE_HOSTS_LIMIT = 20;
14426
- var A2A_PUSH_HOSTS_LIMIT = 20;
14427
- var SUGGESTION_LIMITS = { perLocale: 6, titleLength: 120, promptLength: 2000 };
14428
- var trimmedText = (max) => z7.string().min(1).max(max).refine((text) => text === text.trim(), "text has surrounding whitespace");
14429
- var suggestionsSchema = z7.record(localeSchema, z7.array(z7.object({
14430
- title: trimmedText(SUGGESTION_LIMITS.titleLength),
14431
- prompt: trimmedText(SUGGESTION_LIMITS.promptLength)
14432
- })).max(SUGGESTION_LIMITS.perLocale));
14433
- var GREETING_MAX_LENGTH = 200;
14434
- var greetingSchema = z7.record(localeSchema, z7.string().max(GREETING_MAX_LENGTH).refine((text) => text === text.trim(), "greeting has surrounding whitespace"));
14435
- var toolTagsSchema = z7.array(z7.string().trim().min(1).max(60).regex(/^[^,]*$/, "a tag holds no comma")).max(20);
14436
- var tlsUrlSchema = z7.url().refine((url) => canCarrySecret(url, []));
14437
- var embedOriginSchema = tlsUrlSchema.transform((value) => new URL(value).origin);
14438
- var soapActionSchema = z7.string().regex(/^[^"\\\u0000-\u001f\u007f]*$/);
14439
- var envelopeTemplateSchema = z7.string().refine((template) => template.trim().length > 0);
14440
- var FORM_MEDIA_TYPES = [
14441
- "application/x-www-form-urlencoded",
14442
- "multipart/form-data"
14443
- ];
14444
- var toolConfigByType = {
14445
- http: z7.object({
14446
- responseWrap: z7.enum(RESPONSE_WRAPS).optional(),
14447
- requestMediaType: z7.enum(FORM_MEDIA_TYPES).optional(),
14448
- resultPath: jsonPointerSchema.optional()
14449
- }),
14450
- embedded: z7.object({ embedOrigin: embedOriginSchema, surface: z7.enum(TOOL_SURFACES) }),
14451
- soap: z7.object({
14452
- soapVersion: z7.enum(SOAP_VERSIONS),
14453
- soapAction: soapActionSchema,
14454
- envelopeTemplate: envelopeTemplateSchema,
14455
- tokenCall: z7.object({
14456
- envelopeTemplate: envelopeTemplateSchema,
14457
- soapAction: soapActionSchema,
14458
- tokenPath: z7.string().trim().min(1)
14459
- }).optional()
14460
- }),
14461
- native: z7.object({}),
14462
- client: z7.object({})
14463
- };
14464
- var TOOL_TYPE_NAMES = ["http", "embedded", "soap", "native", "client"];
14465
- var TOOL_TYPES = {
14466
- http: {
14467
- kind: "server",
14468
- calls: true,
14469
- approval: true,
14470
- sources: true,
14471
- targets: true,
14472
- creatable: true
14473
- },
14474
- embedded: {
14475
- kind: "client",
14476
- calls: true,
14477
- approval: false,
14478
- sources: true,
14479
- targets: false,
14480
- creatable: true,
14481
- readOnly: false
14482
- },
14483
- soap: {
14484
- kind: "server",
14485
- calls: true,
14486
- approval: true,
14487
- sources: true,
14488
- targets: true,
14489
- creatable: true,
14490
- method: "POST"
14491
- },
14492
- native: {
14493
- kind: "server",
14494
- calls: true,
14495
- approval: true,
14496
- sources: false,
14497
- targets: false,
14498
- creatable: false,
14499
- method: "POST"
14500
- },
14501
- client: {
14502
- kind: "client",
14503
- calls: false,
14504
- approval: false,
14505
- sources: false,
14506
- targets: false,
14507
- creatable: true,
14508
- readOnly: true
14509
- }
14510
- };
14511
- var CREATABLE_TOOL_TYPES = TOOL_TYPE_NAMES.filter((type) => TOOL_TYPES[type].creatable);
14512
- var ENDPOINT_PARAM_PATTERN = /\{([^{}]+)\}/g;
14513
- function confinesEndpointParams(url) {
14514
- const origin = /^[^:/?#]*:[/\\]*[^/\\?#]*/.exec(url)?.[0] ?? "";
14515
- const hash = url.indexOf("#", origin.length);
14516
- const fragment = hash < 0 ? "" : url.slice(hash);
14517
- return ![origin, fragment].some((part) => part.match(ENDPOINT_PARAM_PATTERN));
14518
- }
14519
- var upstreamUrlSchema = z7.url({ protocol: /^https?$/ });
14520
- var HEADER_LIMITS = { headerLength: 120, prefixLength: 40, headers: 8 };
14521
- var HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
14522
- var HEADER_VALUE_PATTERN = /^[\t\x20-\x7e\x80-\xff]*$/;
14286
+ // ../../internal/contracts/src/manifest/headers.ts
14287
+ import { z as z7 } from "zod";
14523
14288
  var headerNameSchema = z7.string().trim().min(1).max(HEADER_LIMITS.headerLength).regex(HEADER_NAME_PATTERN);
14524
- var transportSetHeaders = ["accept", "content-type", "content-length", "host"];
14525
- var transportForbiddenHeaders = [
14526
- "connection",
14527
- "transfer-encoding",
14528
- "upgrade",
14529
- "expect",
14530
- "te",
14531
- "trailer",
14532
- "proxy-authorization"
14533
- ];
14534
- var mcpTransportHeaders = new Set([
14535
- "mcp-session-id",
14536
- "mcp-protocol-version",
14537
- "last-event-id"
14538
- ]);
14539
- var transportOwnedHeaders = new Set([
14540
- ...transportSetHeaders,
14541
- ...transportForbiddenHeaders
14542
- ]);
14543
14289
  function repeatedHeaders(entries) {
14544
14290
  const seen = new Set;
14545
14291
  return entries.flatMap((entry, index) => {
@@ -14578,7 +14324,7 @@ var headerSourceSchema = z7.discriminatedUnion("kind", [
14578
14324
  z7.object({ kind: z7.literal("runToken") }),
14579
14325
  variableSourceSchema,
14580
14326
  constantHeaderSourceSchema
14581
- ]);
14327
+ ]).meta({ id: "HeaderSource" });
14582
14328
  var runlessHeaderSourceSchema = z7.discriminatedUnion("kind", [
14583
14329
  credentialSourceSchema,
14584
14330
  constantHeaderSourceSchema
@@ -14591,16 +14337,232 @@ function declaredHeadersSchema(header, from) {
14591
14337
  }).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([]);
14592
14338
  }
14593
14339
  var headersSchema = declaredHeadersSchema(presentedHeaderSchema, headerSourceSchema);
14594
- var fieldSourceSchema = z7.discriminatedUnion("kind", [
14595
- variableSourceSchema,
14596
- z7.object({ kind: z7.literal("secret"), name: nameSchema }),
14597
- z7.object({
14598
- kind: z7.literal("constant"),
14599
- value: z7.union([z7.string().max(4000), z7.number(), z7.boolean()])
14600
- }),
14601
- z7.object({ kind: z7.literal("endUserToken") })
14602
- ]);
14603
- function sourceFits(source, field) {
14340
+
14341
+ // ../../internal/contracts/src/manifest/datasets.ts
14342
+ function unexposedPins(host) {
14343
+ const exposed = new Set(host.expose);
14344
+ return host.pinned.filter((name) => !exposed.has(name));
14345
+ }
14346
+ var { datasetHost: datasetHostRateLimits } = RATE_LIMITS;
14347
+ var manifestDatasetHostSchema = z8.strictObject({
14348
+ name: datasetIdentifierSchema,
14349
+ displayName: displayNameSchema.default({}),
14350
+ url: upstreamUrlSchema,
14351
+ headers: headersSchema,
14352
+ timeoutMs: setting(SETTING_BOUNDS.datasetHost.timeoutMs),
14353
+ rateLimits: z8.strictObject({
14354
+ allUsers: z8.strictObject({
14355
+ queriesPerMinute: rateLimit(datasetHostRateLimits.queriesPerMinute, "allUsers")
14356
+ }).prefault({}),
14357
+ perUser: z8.strictObject({
14358
+ queriesPerMinute: rateLimit(datasetHostRateLimits.queriesPerMinute, "perUser")
14359
+ }).prefault({})
14360
+ }).prefault({}),
14361
+ expose: z8.array(datasetIdentifierSchema).min(1).max(500),
14362
+ pinned: z8.array(datasetIdentifierSchema).max(50).default([]),
14363
+ audience: audienceSchema,
14364
+ overridable: overridable(["displayName", "timeoutMs", "rateLimits", "headers"])
14365
+ }).superRefine((host, context) => {
14366
+ const unexposed = unexposedPins(host);
14367
+ if (unexposed.length > 0) {
14368
+ context.addIssue({
14369
+ code: "custom",
14370
+ path: ["pinned"],
14371
+ message: `not exposed: ${unexposed.join(", ")}`
14372
+ });
14373
+ }
14374
+ });
14375
+
14376
+ // ../../internal/contracts/src/manifest/knowledge.ts
14377
+ import { z as z9 } from "zod";
14378
+ var mimeTypeByExtension = new Map([
14379
+ ["md", "text/markdown"],
14380
+ ["txt", "text/plain"],
14381
+ ["html", "text/html"],
14382
+ ["htm", "text/html"],
14383
+ ["pdf", "application/pdf"],
14384
+ ["docx", DOCX_MIME_TYPE]
14385
+ ]);
14386
+ function documentType(name) {
14387
+ const dot = name.lastIndexOf(".");
14388
+ return dot === -1 ? undefined : mimeTypeByExtension.get(name.slice(dot + 1).toLowerCase());
14389
+ }
14390
+ function base64Bytes(data) {
14391
+ const padding = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
14392
+ return data.length / 4 * 3 - padding;
14393
+ }
14394
+ var documentNameSchema = z9.string().trim().min(1).max(DOCUMENT_LIMITS.nameLength);
14395
+ var textDocumentSchema = z9.strictObject({
14396
+ name: documentNameSchema,
14397
+ text: z9.string().min(1).refine((text) => new TextEncoder().encode(text).byteLength <= DOCUMENT_LIMITS.bytes, `larger than ${DOCUMENT_LIMITS.bytes} bytes`)
14398
+ });
14399
+ var pathDocumentSchema = z9.strictObject({
14400
+ path: z9.string().trim().min(1),
14401
+ name: documentNameSchema.optional()
14402
+ });
14403
+ var urlDocumentSchema = z9.strictObject({
14404
+ url: upstreamUrlSchema,
14405
+ name: documentNameSchema.optional()
14406
+ });
14407
+ var dataDocumentSchema = z9.strictObject({
14408
+ name: documentNameSchema,
14409
+ data: z9.base64().refine((data) => base64Bytes(data) <= DOCUMENT_LIMITS.bytes, `larger than ${DOCUMENT_LIMITS.bytes} bytes`)
14410
+ });
14411
+ function documentName(document) {
14412
+ if (document.name !== undefined)
14413
+ return document.name;
14414
+ if (document.path !== undefined)
14415
+ return document.path.split(/[/\\]/).pop() ?? "";
14416
+ const segment = new URL(document.url ?? "", "https://x").pathname.split("/").pop() ?? "";
14417
+ try {
14418
+ return decodeURIComponent(segment);
14419
+ } catch {
14420
+ return segment;
14421
+ }
14422
+ }
14423
+ function documentsSchema(document) {
14424
+ return z9.array(document).max(COLLECTION_LIMITS.documents).superRefine((documents, ctx) => {
14425
+ const names = documents.map(documentName);
14426
+ names.forEach((name, index) => {
14427
+ if (documentType(name) === undefined) {
14428
+ ctx.addIssue({
14429
+ code: "custom",
14430
+ path: [index, "name"],
14431
+ message: "a document's name ends in .md, .txt, .html, .htm, .pdf or .docx"
14432
+ });
14433
+ } else if (names.indexOf(name) !== index) {
14434
+ ctx.addIssue({
14435
+ code: "custom",
14436
+ path: [index, "name"],
14437
+ message: "a name repeats"
14438
+ });
14439
+ }
14440
+ });
14441
+ }).default([]);
14442
+ }
14443
+ function collectionSchema(document) {
14444
+ return z9.strictObject({
14445
+ name: nameSchema,
14446
+ displayName: displayNameSchema.default({}),
14447
+ description: z9.string().trim().max(COLLECTION_LIMITS.descriptionLength).default(""),
14448
+ service: nameSchema.optional(),
14449
+ citable: z9.boolean().default(true),
14450
+ documents: documentsSchema(document),
14451
+ audience: audienceSchema,
14452
+ overridable: overridable(["displayName", "description", "documents"])
14453
+ });
14454
+ }
14455
+ var manifestDocumentSchema = z9.union([textDocumentSchema, pathDocumentSchema, urlDocumentSchema]);
14456
+ var manifestCollectionSchema = collectionSchema(manifestDocumentSchema);
14457
+ var resolvedCollectionSchema = collectionSchema(z9.union([textDocumentSchema, dataDocumentSchema, urlDocumentSchema]));
14458
+
14459
+ // ../../internal/contracts/src/manifest/mcp-servers.ts
14460
+ import { z as z10 } from "zod";
14461
+ var mcpToolNamesSchema = z10.array(z10.string().trim().min(1).max(128).regex(/^[^,]*$/, "a tool name holds no comma")).max(200);
14462
+ var MAX_AUTHORIZATION_PARAMS = 10;
14463
+ var RESERVED_AUTHORIZATION_PARAMS = new Set([
14464
+ "response_type",
14465
+ "client_id",
14466
+ "redirect_uri",
14467
+ "state",
14468
+ "scope",
14469
+ "code_challenge",
14470
+ "code_challenge_method",
14471
+ "resource",
14472
+ "request",
14473
+ "request_uri",
14474
+ "response_mode"
14475
+ ]);
14476
+ var mcpSignInSchema = z10.strictObject({
14477
+ connects: z10.enum(MCP_CONNECTION_OWNERS),
14478
+ scope: z10.string().trim().min(1).max(1000).optional(),
14479
+ credential: nameSchema.optional(),
14480
+ authorizationParams: z10.array(z10.strictObject({
14481
+ name: z10.string().trim().min(1).max(64),
14482
+ value: z10.string().max(512)
14483
+ })).max(MAX_AUTHORIZATION_PARAMS).optional()
14484
+ });
14485
+ function refusedAuthorizationParam(signIn) {
14486
+ const params = signIn?.authorizationParams ?? [];
14487
+ for (const [index, { name }] of params.entries()) {
14488
+ if (RESERVED_AUTHORIZATION_PARAMS.has(name))
14489
+ return { index, reason: "reserved" };
14490
+ if (params.slice(0, index).some((earlier) => earlier.name === name)) {
14491
+ return { index, reason: "repeated" };
14492
+ }
14493
+ }
14494
+ return;
14495
+ }
14496
+ function authorizationBesideSignIn(server) {
14497
+ return server.signIn ? server.headers.findIndex((entry) => entry.header.toLowerCase() === "authorization") : -1;
14498
+ }
14499
+ var manifestMcpServerSchema = z10.strictObject({
14500
+ name: identifierSchema,
14501
+ displayName: displayNameSchema.default({}),
14502
+ url: upstreamUrlSchema,
14503
+ headers: declaredHeadersSchema(presentedHeaderSchema.refine((name) => !mcpTransportHeaders.has(name.toLowerCase()), "a header the MCP transport sets"), headerSourceSchema),
14504
+ signIn: mcpSignInSchema.optional(),
14505
+ include: mcpToolNamesSchema.default([]),
14506
+ exclude: mcpToolNamesSchema.default([]),
14507
+ audience: audienceSchema,
14508
+ overridable: overridable(["displayName", "include", "exclude", "headers", "signIn"])
14509
+ }).superRefine((server, context) => {
14510
+ const index = authorizationBesideSignIn(server);
14511
+ if (index >= 0) {
14512
+ context.addIssue({
14513
+ code: "custom",
14514
+ path: ["headers", index, "header"],
14515
+ message: "the sign-in's token travels under Authorization"
14516
+ });
14517
+ }
14518
+ const refused = refusedAuthorizationParam(server.signIn);
14519
+ if (refused) {
14520
+ context.addIssue({
14521
+ code: "custom",
14522
+ path: ["signIn", "authorizationParams", refused.index, "name"],
14523
+ message: refused.reason === "reserved" ? "a parameter Cortex sets" : "a parameter an earlier one names"
14524
+ });
14525
+ }
14526
+ });
14527
+
14528
+ // ../../internal/contracts/src/manifest/services.ts
14529
+ import { z as z11 } from "zod";
14530
+ var localizedTextSchema = z11.record(localeSchema, z11.string().trim().min(1).max(SERVICE_LIMITS.descriptionLength));
14531
+ var manifestServiceSchema = z11.strictObject({
14532
+ name: nameSchema,
14533
+ displayName: displayNameSchema.default({}),
14534
+ description: localizedTextSchema,
14535
+ audience: audienceSchema,
14536
+ overridable: overridable(["displayName", "description"])
14537
+ });
14538
+
14539
+ // ../../internal/contracts/src/manifest/skills.ts
14540
+ import { z as z12 } from "zod";
14541
+ var manifestSkillSchema = z12.strictObject({
14542
+ name: nameSchema,
14543
+ displayName: displayNameSchema.default({}),
14544
+ description: z12.string().trim().min(1).max(SKILL_LIMITS.descriptionLength),
14545
+ body: z12.string().trim().min(1),
14546
+ service: nameSchema.optional(),
14547
+ audience: audienceSchema,
14548
+ overridable: overridable(["displayName", "description", "body"])
14549
+ });
14550
+
14551
+ // ../../internal/contracts/src/manifest/tools.ts
14552
+ import { z as z14 } from "zod";
14553
+
14554
+ // ../../internal/contracts/src/manifest/json-schema.ts
14555
+ import { z as z13 } from "zod";
14556
+ var fieldSourceSchema = z13.discriminatedUnion("kind", [
14557
+ variableSourceSchema,
14558
+ z13.object({ kind: z13.literal("secret"), name: nameSchema }),
14559
+ z13.object({
14560
+ kind: z13.literal("constant"),
14561
+ value: z13.union([z13.string().max(4000), z13.number(), z13.boolean()])
14562
+ }),
14563
+ z13.object({ kind: z13.literal("endUserToken") })
14564
+ ]);
14565
+ function sourceFits(source, field) {
14604
14566
  switch (source.kind) {
14605
14567
  case "variable":
14606
14568
  return true;
@@ -14621,52 +14583,50 @@ function sourceFits(source, field) {
14621
14583
  }
14622
14584
  }
14623
14585
  }
14624
- var fieldTargetSchema = z7.discriminatedUnion("kind", [
14625
- z7.strictObject({
14626
- kind: z7.literal("body"),
14627
- contentType: z7.enum(["application/json", "text/plain"]).optional(),
14628
- style: z7.enum(QUERY_STYLES).optional(),
14629
- explode: z7.boolean().optional()
14586
+ var fieldTargetSchema = z13.discriminatedUnion("kind", [
14587
+ z13.strictObject({
14588
+ kind: z13.literal("body"),
14589
+ contentType: z13.enum(["application/json", "text/plain"]).optional(),
14590
+ style: z13.enum(QUERY_STYLES).optional(),
14591
+ explode: z13.boolean().optional()
14630
14592
  }),
14631
- z7.strictObject({
14632
- kind: z7.literal("query"),
14633
- name: z7.string().trim().min(1).max(120).optional(),
14634
- style: z7.enum(QUERY_STYLES).optional(),
14635
- explode: z7.boolean().optional()
14593
+ z13.strictObject({
14594
+ kind: z13.literal("query"),
14595
+ name: z13.string().trim().min(1).max(120).optional(),
14596
+ style: z13.enum(QUERY_STYLES).optional(),
14597
+ explode: z13.boolean().optional()
14636
14598
  }),
14637
- z7.strictObject({
14638
- kind: z7.literal("path"),
14639
- name: z7.string().trim().min(1).max(120).optional(),
14640
- style: z7.enum(PATH_STYLES).optional(),
14641
- explode: z7.boolean().optional()
14599
+ z13.strictObject({
14600
+ kind: z13.literal("path"),
14601
+ name: z13.string().trim().min(1).max(120).optional(),
14602
+ style: z13.enum(PATH_STYLES).optional(),
14603
+ explode: z13.boolean().optional()
14642
14604
  }),
14643
- z7.strictObject({
14644
- kind: z7.literal("header"),
14605
+ z13.strictObject({
14606
+ kind: z13.literal("header"),
14645
14607
  name: headerNameSchema.optional(),
14646
- explode: z7.boolean().optional()
14608
+ explode: z13.boolean().optional()
14647
14609
  }),
14648
- z7.strictObject({ kind: z7.literal("cookie"), name: headerNameSchema.optional() })
14610
+ z13.strictObject({ kind: z13.literal("cookie"), name: headerNameSchema.optional() })
14649
14611
  ]);
14650
- var SCALAR_TYPES = ["string", "number", "integer", "boolean"];
14651
- var schemaTypeSchema = z7.enum([...SCALAR_TYPES, "object", "array"]);
14652
- var FIELD_LIMITS = { nameLength: 120, descriptionLength: 500, enumValues: 50 };
14653
- var propertyNameSchema = z7.string().min(1).max(FIELD_LIMITS.nameLength).refine((name) => name === name.trim(), "no surrounding spaces");
14654
- var propertyOrderSchema = z7.array(z7.string()).refine((names) => new Set(names).size === names.length, "a name repeats").optional();
14655
- var countSchema = z7.number().int().min(0).optional();
14656
- var valueKeywordsSchema = z7.strictObject({
14657
- pattern: z7.string().min(1).max(1000).refine((pattern) => linearPattern(pattern) !== undefined, "a pattern Cortex cannot match").optional(),
14612
+ var schemaTypeSchema = z13.enum([...SCALAR_TYPES, "object", "array"]);
14613
+ var propertyNameSchema = z13.string().min(1).max(FIELD_LIMITS.nameLength).refine((name) => name === name.trim(), "no surrounding spaces");
14614
+ var propertyOrderSchema = z13.array(z13.string()).refine((names) => new Set(names).size === names.length, "a name repeats").optional();
14615
+ var countSchema = z13.number().int().min(0).optional();
14616
+ var valueKeywordsSchema = z13.strictObject({
14617
+ pattern: z13.string().min(1).max(1000).refine((pattern) => linearPattern(pattern) !== undefined, "a pattern Cortex cannot match").optional(),
14658
14618
  minLength: countSchema,
14659
14619
  maxLength: countSchema,
14660
- format: z7.string().trim().min(1).max(100).optional(),
14661
- minimum: z7.number().optional(),
14662
- maximum: z7.number().optional(),
14663
- exclusiveMinimum: z7.number().optional(),
14664
- exclusiveMaximum: z7.number().optional(),
14665
- multipleOf: z7.number().positive().optional(),
14620
+ format: z13.string().trim().min(1).max(100).optional(),
14621
+ minimum: z13.number().optional(),
14622
+ maximum: z13.number().optional(),
14623
+ exclusiveMinimum: z13.number().optional(),
14624
+ exclusiveMaximum: z13.number().optional(),
14625
+ multipleOf: z13.number().positive().optional(),
14666
14626
  minItems: countSchema,
14667
14627
  maxItems: countSchema,
14668
- uniqueItems: z7.boolean().optional(),
14669
- const: z7.union([z7.string().max(4000), z7.number(), z7.boolean()]).optional()
14628
+ uniqueItems: z13.boolean().optional(),
14629
+ const: z13.union([z13.string().max(4000), z13.number(), z13.boolean()]).optional()
14670
14630
  });
14671
14631
  var NUMERIC_TYPES = ["number", "integer"];
14672
14632
  var VALUE_KEYWORD_TYPES = {
@@ -14684,18 +14644,18 @@ var VALUE_KEYWORD_TYPES = {
14684
14644
  uniqueItems: ["array"],
14685
14645
  const: SCALAR_TYPES
14686
14646
  };
14687
- var ruleTypeSchema = z7.enum([...SCALAR_TYPES, "object", "array", "null"]);
14688
- var conditionSchema = z7.lazy(() => z7.strictObject({
14689
- type: z7.union([ruleTypeSchema, z7.array(ruleTypeSchema).min(1)]).optional(),
14690
- enum: z7.array(z7.union([z7.string(), z7.number(), z7.boolean(), z7.null()])).min(1).optional(),
14647
+ var ruleTypeSchema = z13.enum([...SCALAR_TYPES, "object", "array", "null"]);
14648
+ var conditionSchema = z13.lazy(() => z13.strictObject({
14649
+ type: z13.union([ruleTypeSchema, z13.array(ruleTypeSchema).min(1)]).optional(),
14650
+ enum: z13.array(z13.union([z13.string(), z13.number(), z13.boolean(), z13.null()])).min(1).optional(),
14691
14651
  ...valueKeywordsSchema.shape,
14692
- required: z7.array(z7.string()).optional(),
14693
- properties: z7.record(z7.string(), conditionSchema).optional(),
14652
+ required: z13.array(z13.string()).optional(),
14653
+ properties: z13.record(z13.string(), conditionSchema).optional(),
14694
14654
  items: conditionSchema.optional(),
14695
14655
  ...objectRulesSchema.shape
14696
14656
  })).meta({ id: "SchemaCondition" });
14697
- var conditionsSchema = z7.array(conditionSchema).min(1).meta({ id: "SchemaConditions" });
14698
- var objectRulesSchema = z7.strictObject({
14657
+ var conditionsSchema = z13.array(conditionSchema).min(1).meta({ id: "SchemaConditions" });
14658
+ var objectRulesSchema = z13.strictObject({
14699
14659
  anyOf: conditionsSchema.optional(),
14700
14660
  oneOf: conditionsSchema.optional(),
14701
14661
  allOf: conditionsSchema.optional(),
@@ -14703,8 +14663,8 @@ var objectRulesSchema = z7.strictObject({
14703
14663
  if: conditionSchema.optional(),
14704
14664
  then: conditionSchema.optional(),
14705
14665
  else: conditionSchema.optional(),
14706
- dependentRequired: z7.record(z7.string(), z7.array(z7.string())).optional(),
14707
- dependentSchemas: z7.record(z7.string(), conditionSchema).optional(),
14666
+ dependentRequired: z13.record(z13.string(), z13.array(z13.string())).optional(),
14667
+ dependentSchemas: z13.record(z13.string(), conditionSchema).optional(),
14708
14668
  minProperties: countSchema,
14709
14669
  maxProperties: countSchema
14710
14670
  });
@@ -14741,31 +14701,32 @@ function ruleNames(rule) {
14741
14701
  ...Object.keys(keyed(node.dependentSchemas))
14742
14702
  ]).filter((name) => typeof name === "string");
14743
14703
  }
14744
- var itemTypeSchema = z7.enum([...SCALAR_TYPES, "object"]);
14745
- var enumSchema = z7.array(z7.union([z7.string().trim().min(1), z7.null()])).min(1).max(FIELD_LIMITS.enumValues + 1).optional();
14746
- var itemsSchema = z7.lazy(() => z7.strictObject({
14747
- type: z7.union([itemTypeSchema, z7.tuple([itemTypeSchema, z7.literal("null")])]),
14704
+ var itemTypeSchema = z13.enum([...SCALAR_TYPES, "object"]);
14705
+ var enumSchema = z13.array(z13.union([z13.string().trim().min(1), z13.null()])).min(1).max(FIELD_LIMITS.enumValues + 1).optional();
14706
+ var itemsSchema = z13.lazy(() => z13.strictObject({
14707
+ type: z13.union([itemTypeSchema, z13.tuple([itemTypeSchema, z13.literal("null")])]),
14748
14708
  enum: enumSchema,
14749
- properties: z7.record(propertyNameSchema, schemaPropertySchema).optional(),
14750
- required: z7.array(z7.string()).optional(),
14709
+ properties: z13.record(propertyNameSchema, schemaPropertySchema).optional(),
14710
+ required: z13.array(z13.string()).optional(),
14751
14711
  "x-order": propertyOrderSchema,
14752
14712
  ...valueKeywordsSchema.shape,
14753
14713
  ...objectRulesSchema.shape
14754
- }));
14755
- var schemaPropertySchema = z7.lazy(() => z7.strictObject({
14756
- type: z7.union([schemaTypeSchema, z7.tuple([schemaTypeSchema, z7.literal("null")])]),
14757
- description: z7.string().trim().max(FIELD_LIMITS.descriptionLength).optional(),
14714
+ })).meta({ id: "SchemaItems" });
14715
+ var schemaPropertySchema = z13.lazy(() => z13.strictObject({
14716
+ type: z13.union([schemaTypeSchema, z13.tuple([schemaTypeSchema, z13.literal("null")])]),
14717
+ description: z13.string().trim().max(FIELD_LIMITS.descriptionLength).optional(),
14758
14718
  enum: enumSchema,
14759
- properties: z7.record(propertyNameSchema, schemaPropertySchema).optional(),
14760
- required: z7.array(z7.string()).optional(),
14719
+ properties: z13.record(propertyNameSchema, schemaPropertySchema).optional(),
14720
+ required: z13.array(z13.string()).optional(),
14761
14721
  "x-order": propertyOrderSchema,
14762
14722
  items: itemsSchema.optional(),
14763
- "x-sensitive": z7.boolean().optional(),
14723
+ "x-sensitive": z13.boolean().optional(),
14724
+ "x-displayName": displayNameSchema.optional(),
14764
14725
  "x-source": fieldSourceSchema.optional(),
14765
14726
  "x-target": fieldTargetSchema.optional(),
14766
14727
  ...valueKeywordsSchema.shape,
14767
14728
  ...objectRulesSchema.shape
14768
- }));
14729
+ })).meta({ id: "SchemaProperty" });
14769
14730
  function typeOf(node) {
14770
14731
  return [node.type].flat()[0];
14771
14732
  }
@@ -14868,10 +14829,10 @@ function heldByRows(node, context, path, bindings) {
14868
14829
  }
14869
14830
  }
14870
14831
  function objectJsonSchemaOf(bindings) {
14871
- return z7.strictObject({
14872
- type: z7.literal("object"),
14873
- properties: z7.record(propertyNameSchema, schemaPropertySchema).optional(),
14874
- required: z7.array(z7.string()).optional(),
14832
+ return z13.strictObject({
14833
+ type: z13.literal("object"),
14834
+ properties: z13.record(propertyNameSchema, schemaPropertySchema).optional(),
14835
+ required: z13.array(z13.string()).optional(),
14875
14836
  "x-order": propertyOrderSchema,
14876
14837
  ...objectRulesSchema.shape
14877
14838
  }).superRefine((schema, context) => {
@@ -14891,23 +14852,88 @@ function objectJsonSchemaOf(bindings) {
14891
14852
  }
14892
14853
  var objectSchema = objectJsonSchemaOf();
14893
14854
  var EMPTY_OBJECT = { type: "object" };
14894
- var audienceSchema = z7.union([
14895
- z7.literal("all"),
14896
- z7.strictObject({ server: nameSchema }),
14897
- z7.strictObject({
14898
- agents: z7.array(nameSchema).min(1).refine((names) => new Set(names).size === names.length, "an agent repeats")
14899
- })
14900
- ]);
14901
- var MODEL_PROVIDER_LIMITS = { urlLength: 2048, modelLength: 200, models: 100 };
14902
- var modelSchema = z7.strictObject({
14903
- provider: nameSchema,
14904
- model: z7.string().trim().min(1).max(MODEL_PROVIDER_LIMITS.modelLength),
14905
- effort: z7.string().trim().min(1).max(64).optional()
14906
- });
14907
- var SERVICE_LIMITS = { descriptionLength: 4000 };
14908
- var localizedTextSchema = z7.record(localeSchema, z7.string().trim().min(1).max(SERVICE_LIMITS.descriptionLength));
14909
- var { tool: toolBounds } = SETTING_BOUNDS;
14910
- var { tool: toolRateLimits, datasetHost: datasetHostRateLimits } = RATE_LIMITS;
14855
+
14856
+ // ../../internal/contracts/src/manifest/tools.ts
14857
+ var toolTagsSchema = z14.array(z14.string().trim().min(1).max(60).regex(/^[^,]*$/, "a tag holds no comma")).max(20);
14858
+ var embedOriginSchema = tlsUrlSchema.overwrite((value) => new URL(value).origin);
14859
+ var soapActionSchema = z14.string().regex(/^[^"\\\u0000-\u001f\u007f]*$/);
14860
+ var envelopeTemplateSchema = z14.string().refine((template) => template.trim().length > 0);
14861
+ var toolConfigByType = {
14862
+ http: z14.object({
14863
+ responseWrap: z14.enum(RESPONSE_WRAPS).meta({ id: "ResponseWrap" }).optional(),
14864
+ requestMediaType: z14.enum(FORM_MEDIA_TYPES).meta({ id: "FormMediaType" }).optional(),
14865
+ resultPath: jsonPointerSchema.optional()
14866
+ }),
14867
+ embedded: z14.object({
14868
+ embedOrigin: embedOriginSchema,
14869
+ surface: z14.enum(TOOL_SURFACES).meta({ id: "ToolSurface" })
14870
+ }),
14871
+ soap: z14.object({
14872
+ soapVersion: z14.enum(SOAP_VERSIONS).meta({ id: "SoapVersion" }),
14873
+ soapAction: soapActionSchema,
14874
+ envelopeTemplate: envelopeTemplateSchema,
14875
+ tokenCall: z14.object({
14876
+ envelopeTemplate: envelopeTemplateSchema,
14877
+ soapAction: soapActionSchema,
14878
+ tokenPath: z14.string().trim().min(1)
14879
+ }).optional()
14880
+ }),
14881
+ native: z14.object({}),
14882
+ client: z14.object({})
14883
+ };
14884
+ var TOOL_TYPES = {
14885
+ http: {
14886
+ kind: "server",
14887
+ calls: true,
14888
+ approval: true,
14889
+ sources: true,
14890
+ targets: true,
14891
+ creatable: true
14892
+ },
14893
+ embedded: {
14894
+ kind: "client",
14895
+ calls: true,
14896
+ approval: false,
14897
+ sources: true,
14898
+ targets: false,
14899
+ creatable: true,
14900
+ readOnly: false
14901
+ },
14902
+ soap: {
14903
+ kind: "server",
14904
+ calls: true,
14905
+ approval: true,
14906
+ sources: true,
14907
+ targets: true,
14908
+ creatable: true,
14909
+ method: "POST"
14910
+ },
14911
+ native: {
14912
+ kind: "server",
14913
+ calls: true,
14914
+ approval: true,
14915
+ sources: false,
14916
+ targets: false,
14917
+ creatable: false,
14918
+ method: "POST"
14919
+ },
14920
+ client: {
14921
+ kind: "client",
14922
+ calls: false,
14923
+ approval: false,
14924
+ sources: false,
14925
+ targets: false,
14926
+ creatable: true,
14927
+ readOnly: true
14928
+ }
14929
+ };
14930
+ var CREATABLE_TOOL_TYPES = TOOL_TYPE_NAMES.filter((type) => TOOL_TYPES[type].creatable);
14931
+ function confinesEndpointParams(url) {
14932
+ const origin = /^[^:/?#]*:[/\\]*[^/\\?#]*/.exec(url)?.[0] ?? "";
14933
+ const hash = url.indexOf("#", origin.length);
14934
+ const fragment = hash < 0 ? "" : url.slice(hash);
14935
+ return ![origin, fragment].some((part) => part.match(ENDPOINT_PARAM_PATTERN));
14936
+ }
14911
14937
  function toolInputSchemaOf(type) {
14912
14938
  const { sources, targets } = TOOL_TYPES[type];
14913
14939
  return objectJsonSchemaOf([
@@ -14925,23 +14951,25 @@ var TOOL_OVERRIDABLES = [
14925
14951
  "tags"
14926
14952
  ];
14927
14953
  var CALLED_TOOL_OVERRIDABLES = [...TOOL_OVERRIDABLES, "headers"];
14928
- var toolBaseSchema = z7.strictObject({
14954
+ var { tool: toolBounds } = SETTING_BOUNDS;
14955
+ var { tool: toolRateLimits } = RATE_LIMITS;
14956
+ var toolBaseSchema = z14.strictObject({
14929
14957
  ...serverToolSchema.pick({ name: true, description: true }).shape,
14930
14958
  displayName: displayNameSchema.default({}),
14931
14959
  inputSchema: toolInputSchemaOf("client"),
14932
14960
  outputSchema: objectSchema.default(EMPTY_OBJECT),
14933
14961
  timeoutMs: setting(toolBounds.timeoutMs),
14934
14962
  maxResponseBytes: setting(toolBounds.maxResponseBytes),
14935
- rateLimits: z7.strictObject({
14936
- allUsers: z7.strictObject({
14963
+ rateLimits: z14.strictObject({
14964
+ allUsers: z14.strictObject({
14937
14965
  callsPerMinute: rateLimit(toolRateLimits.callsPerMinute, "allUsers")
14938
14966
  }).prefault({}),
14939
- perUser: z7.strictObject({
14967
+ perUser: z14.strictObject({
14940
14968
  callsPerMinute: rateLimit(toolRateLimits.callsPerMinute, "perUser")
14941
14969
  }).prefault({})
14942
14970
  }).prefault({}),
14943
- projectOutput: z7.boolean().default(false),
14944
- pinned: z7.boolean().default(false),
14971
+ projectOutput: z14.boolean().default(false),
14972
+ pinned: z14.boolean().default(false),
14945
14973
  tags: toolTagsSchema.default([]),
14946
14974
  audience: audienceSchema,
14947
14975
  overridable: overridable(TOOL_OVERRIDABLES)
@@ -14949,93 +14977,112 @@ var toolBaseSchema = z7.strictObject({
14949
14977
  var calledToolSchema = toolBaseSchema.extend({
14950
14978
  url: upstreamUrlSchema.refine(confinesEndpointParams, "a {parameter} outside the path or query"),
14951
14979
  headers: headersSchema,
14952
- requiresApproval: z7.boolean().default(false),
14980
+ requiresApproval: z14.boolean().default(false),
14953
14981
  overridable: overridable(CALLED_TOOL_OVERRIDABLES)
14954
14982
  });
14955
- var manifestToolSchema = z7.discriminatedUnion("type", [
14983
+ var manifestToolSchema = z14.discriminatedUnion("type", [
14956
14984
  calledToolSchema.extend({
14957
- type: z7.literal("http"),
14985
+ type: z14.literal("http"),
14958
14986
  inputSchema: toolInputSchemaOf("http"),
14959
- method: z7.enum(TOOL_METHODS),
14960
- readOnly: z7.boolean(),
14987
+ method: z14.enum(TOOL_METHODS),
14988
+ readOnly: z14.boolean(),
14961
14989
  ...toolConfigByType.http.shape
14962
14990
  }),
14963
14991
  calledToolSchema.omit({ requiresApproval: true }).extend({
14964
- type: z7.literal("embedded"),
14992
+ type: z14.literal("embedded"),
14965
14993
  inputSchema: toolInputSchemaOf("embedded"),
14966
- method: z7.enum(TOOL_METHODS),
14994
+ method: z14.enum(TOOL_METHODS),
14967
14995
  ...toolConfigByType.embedded.shape
14968
14996
  }),
14969
14997
  calledToolSchema.extend({
14970
- type: z7.literal("soap"),
14998
+ type: z14.literal("soap"),
14971
14999
  inputSchema: toolInputSchemaOf("soap"),
14972
- readOnly: z7.boolean(),
15000
+ readOnly: z14.boolean(),
14973
15001
  ...toolConfigByType.soap.shape
14974
15002
  }),
14975
- toolBaseSchema.extend({ type: z7.literal("client") })
15003
+ toolBaseSchema.extend({ type: z14.literal("client") })
14976
15004
  ]).superRefine((tool, context) => refuseBlockedApprovalTitle(tool, context, []));
14977
- var toolNamesSchema = z7.array(serverToolSchema.shape.name).max(500).default([]);
14978
- var manifestOpenApiSchema = z7.strictObject({
15005
+ var toolNamesSchema = z14.array(serverToolSchema.shape.name).max(500).default([]);
15006
+ var manifestOpenApiSchema = z14.strictObject({
14979
15007
  name: nameSchema,
14980
15008
  url: upstreamUrlSchema,
14981
15009
  headers: headersSchema,
14982
15010
  resultPath: jsonPointerSchema.optional(),
14983
15011
  pinned: toolNamesSchema,
14984
- approval: z7.strictObject({ never: toolNamesSchema, always: toolNamesSchema }).prefault({}).refine(({ never, always }) => !never.some((name) => always.includes(name)), "a tool both never and always needs approval"),
15012
+ approval: z14.strictObject({ never: toolNamesSchema, always: toolNamesSchema }).prefault({}).refine(({ never, always }) => !never.some((name) => always.includes(name)), "a tool both never and always needs approval"),
14985
15013
  audience: audienceSchema,
14986
15014
  overridable: overridable(CALLED_TOOL_OVERRIDABLES)
14987
15015
  });
14988
- var manifestServiceSchema = z7.strictObject({
14989
- name: nameSchema,
14990
- displayName: displayNameSchema.default({}),
14991
- description: localizedTextSchema,
14992
- audience: audienceSchema,
14993
- overridable: overridable(["displayName", "description"])
14994
- });
14995
- var SKILL_LIMITS = { descriptionLength: 500 };
14996
- var manifestSkillSchema = z7.strictObject({
14997
- name: nameSchema,
14998
- displayName: displayNameSchema.default({}),
14999
- description: z7.string().trim().min(1).max(SKILL_LIMITS.descriptionLength),
15000
- body: z7.string().trim().min(1),
15001
- service: nameSchema.optional(),
15002
- audience: audienceSchema,
15003
- overridable: overridable(["displayName", "description", "body"])
15004
- });
15005
- var triggerThreadPolicySchema = z7.discriminatedUnion("policy", [
15006
- z7.object({ policy: z7.literal("single") }),
15007
- z7.object({ policy: z7.literal("per-input") }),
15008
- z7.object({ policy: z7.literal("ephemeral") }),
15009
- z7.object({ policy: z7.literal("keyed"), key: jsonPointerSchema }),
15010
- z7.object({
15011
- policy: z7.literal("thread"),
15012
- key: jsonPointerSchema,
15013
- wake: z7.boolean()
15014
- })
15015
- ]);
15016
- function threadFromPayload(policy) {
15017
- return policy.policy === "keyed" || policy.policy === "thread";
15016
+
15017
+ // ../../internal/contracts/src/manifest/triggers.ts
15018
+ import { z as z16 } from "zod";
15019
+
15020
+ // ../../internal/contracts/src/schedule/index.ts
15021
+ var import_cron_parser = __toESM(require_dist(), 1);
15022
+ import { z as z15 } from "zod";
15023
+ function isTimeZone(timeZone) {
15024
+ try {
15025
+ new Intl.DateTimeFormat("en", { timeZone });
15026
+ return true;
15027
+ } catch {
15028
+ return false;
15029
+ }
15018
15030
  }
15019
- function scheduledTriggerIssues(trigger) {
15020
- if (!trigger.scheduled)
15021
- return [];
15022
- return [
15023
- trigger.inputFields > 0 && "input",
15031
+ function isCron(cron) {
15032
+ if (cron.split(/\s+/).length !== 5 || /\bH\b/i.test(cron))
15033
+ return false;
15034
+ try {
15035
+ import_cron_parser.CronExpressionParser.parse(cron);
15036
+ return true;
15037
+ } catch {
15038
+ return false;
15039
+ }
15040
+ }
15041
+ function triggerScheduleSchemaWith(messages) {
15042
+ return z15.object({
15043
+ cron: z15.string().trim().refine(isCron, { error: messages.cron }),
15044
+ timeZone: z15.string().trim().refine(isTimeZone, { error: messages.timeZone })
15045
+ });
15046
+ }
15047
+ var triggerScheduleSchema = triggerScheduleSchemaWith({
15048
+ cron: () => "is not a cron of five fields: minute, hour, day of month, month, day of week",
15049
+ timeZone: () => "is not an IANA time zone, such as Asia/Dubai"
15050
+ });
15051
+
15052
+ // ../../internal/contracts/src/manifest/triggers.ts
15053
+ var triggerThreadPolicySchema = z16.discriminatedUnion("policy", [
15054
+ z16.object({ policy: z16.literal("single") }),
15055
+ z16.object({ policy: z16.literal("per-input") }),
15056
+ z16.object({ policy: z16.literal("ephemeral") }),
15057
+ z16.object({ policy: z16.literal("keyed"), key: jsonPointerSchema }),
15058
+ z16.object({
15059
+ policy: z16.literal("thread"),
15060
+ key: jsonPointerSchema,
15061
+ wake: z16.boolean()
15062
+ })
15063
+ ]).meta({ id: "TriggerThreadPolicy" });
15064
+ function threadFromPayload(policy) {
15065
+ return policy.policy === "keyed" || policy.policy === "thread";
15066
+ }
15067
+ function scheduledTriggerIssues(trigger) {
15068
+ if (!trigger.scheduled)
15069
+ return [];
15070
+ return [
15071
+ trigger.inputFields > 0 && "input",
15024
15072
  trigger.fireCredential && "fireCredential",
15025
15073
  threadFromPayload(trigger.threadPolicy) && "threadPolicy"
15026
15074
  ].filter((issue) => issue !== false);
15027
15075
  }
15028
- var TRIGGER_LIMITS = { descriptionLength: 500, instructionsLength: 20000 };
15029
- var manifestTriggerSchema = z7.strictObject({
15076
+ var manifestTriggerSchema = z16.strictObject({
15030
15077
  name: nameSchema,
15031
15078
  displayName: displayNameSchema.default({}),
15032
- description: z7.string().trim().min(1).max(TRIGGER_LIMITS.descriptionLength),
15079
+ description: z16.string().trim().min(1).max(TRIGGER_LIMITS.descriptionLength),
15033
15080
  inputSchema: objectSchema.default(EMPTY_OBJECT),
15034
15081
  outputSchema: objectSchema.refine((schema) => Object.keys(schema.properties ?? {}).length > 0, "declares a property; leave it out for a free-text answer").optional(),
15035
- instructions: z7.string().trim().min(1).max(TRIGGER_LIMITS.instructionsLength),
15082
+ instructions: z16.string().trim().min(1).max(TRIGGER_LIMITS.instructionsLength),
15036
15083
  threadPolicy: triggerThreadPolicySchema.default({ policy: "single" }),
15037
- whileBusy: z7.enum(WHILE_BUSY).default("queue"),
15038
- budgetPerDay: z7.number().int().positive().optional(),
15084
+ whileBusy: z16.enum(WHILE_BUSY).default("queue"),
15085
+ budgetPerDay: z16.number().int().positive().optional(),
15039
15086
  disableAfterFailures: setting(SETTING_BOUNDS.trigger.disableAfterFailures),
15040
15087
  credential: nameSchema.optional(),
15041
15088
  fireCredential: nameSchema.optional(),
@@ -15075,327 +15122,454 @@ var manifestTriggerSchema = z7.strictObject({
15075
15122
  context.addIssue({ code: "custom", path: [path], message });
15076
15123
  }
15077
15124
  });
15078
- function unexposedPins(host) {
15079
- const exposed = new Set(host.expose);
15080
- return host.pinned.filter((name) => !exposed.has(name));
15081
- }
15082
- var manifestDatasetHostSchema = z7.strictObject({
15083
- name: datasetIdentifierSchema,
15125
+
15126
+ // ../../internal/contracts/src/manifest/webhooks.ts
15127
+ import { z as z17 } from "zod";
15128
+ var manifestWebhookSchema = z17.strictObject({
15129
+ name: nameSchema,
15084
15130
  displayName: displayNameSchema.default({}),
15131
+ description: z17.string().trim().max(500).default(""),
15132
+ event: z17.enum(SERVER_EVENTS),
15085
15133
  url: upstreamUrlSchema,
15086
- headers: headersSchema,
15087
- timeoutMs: setting(SETTING_BOUNDS.datasetHost.timeoutMs),
15088
- rateLimits: z7.strictObject({
15089
- allUsers: z7.strictObject({
15090
- queriesPerMinute: rateLimit(datasetHostRateLimits.queriesPerMinute, "allUsers")
15091
- }).prefault({}),
15092
- perUser: z7.strictObject({
15093
- queriesPerMinute: rateLimit(datasetHostRateLimits.queriesPerMinute, "perUser")
15094
- }).prefault({})
15095
- }).prefault({}),
15096
- expose: z7.array(datasetIdentifierSchema).min(1).max(500),
15097
- pinned: z7.array(datasetIdentifierSchema).max(50).default([]),
15134
+ headers: declaredHeadersSchema(presentedHeaderSchema.refine((name) => name.toLowerCase() !== EVENT_HEADER.toLowerCase(), "the header that names the event"), runlessHeaderSourceSchema),
15135
+ timeoutMs: setting(SETTING_BOUNDS.webhook.timeoutMs),
15098
15136
  audience: audienceSchema,
15099
- overridable: overridable(["displayName", "timeoutMs", "rateLimits", "headers"])
15100
- }).superRefine((host, context) => {
15101
- const unexposed = unexposedPins(host);
15102
- if (unexposed.length > 0) {
15103
- context.addIssue({
15104
- code: "custom",
15105
- path: ["pinned"],
15106
- message: `not exposed: ${unexposed.join(", ")}`
15107
- });
15108
- }
15137
+ overridable: overridable(["displayName", "description", "timeoutMs", "headers"])
15109
15138
  });
15110
- var mcpToolNamesSchema = z7.array(z7.string().trim().min(1).max(128).regex(/^[^,]*$/, "a tool name holds no comma")).max(200);
15111
- var MCP_CONNECTION_OWNERS = ["shared", "endUser"];
15112
- var mcpSignInSchema = z7.strictObject({
15113
- connects: z7.enum(MCP_CONNECTION_OWNERS),
15114
- scope: z7.string().trim().min(1).max(1000).optional(),
15115
- credential: nameSchema.optional()
15139
+
15140
+ // ../../internal/contracts/src/manifest/manifest.ts
15141
+ function listOf(entry) {
15142
+ return z18.array(entry).refine((entries) => new Set(entries.map((value) => value.name)).size === entries.length, "a name repeats").default([]);
15143
+ }
15144
+ var manifestSchema = z18.strictObject({
15145
+ id: nameSchema,
15146
+ agents: listOf(manifestAgentSchema),
15147
+ tools: listOf(manifestToolSchema),
15148
+ openapi: listOf(manifestOpenApiSchema),
15149
+ services: listOf(manifestServiceSchema),
15150
+ skills: listOf(manifestSkillSchema),
15151
+ triggers: listOf(manifestTriggerSchema),
15152
+ datasetHosts: listOf(manifestDatasetHostSchema),
15153
+ mcpServers: listOf(manifestMcpServerSchema),
15154
+ webhooks: listOf(manifestWebhookSchema),
15155
+ collections: listOf(manifestCollectionSchema)
15116
15156
  });
15117
- function authorizationBesideSignIn(server) {
15118
- return server.signIn ? server.headers.findIndex((entry) => entry.header.toLowerCase() === "authorization") : -1;
15157
+ var resolvedManifestSchema = manifestSchema.extend({
15158
+ collections: listOf(resolvedCollectionSchema)
15159
+ });
15160
+ var manifestKindSchema = z18.enum(MANIFEST_KINDS);
15161
+ var namesByKindSchema = z18.record(manifestKindSchema, z18.array(z18.string()));
15162
+ var manifestChangesSchema = z18.object({
15163
+ create: namesByKindSchema,
15164
+ update: namesByKindSchema,
15165
+ delete: namesByKindSchema
15166
+ });
15167
+ var manifestConflictSchema = z18.strictObject({
15168
+ kind: manifestKindSchema,
15169
+ name: z18.string(),
15170
+ field: z18.string(),
15171
+ key: z18.string().optional()
15172
+ });
15173
+ var conflictSideSchema = z18.enum(["live", "manifest"]);
15174
+ var manifestApplyInputSchema = resolvedManifestSchema.extend({
15175
+ prefer: conflictSideSchema.optional(),
15176
+ resolutions: z18.array(manifestConflictSchema.extend({ keep: conflictSideSchema })).default([])
15177
+ });
15178
+ var manifestPreviewSchema = manifestChangesSchema.extend({
15179
+ conflicts: z18.array(manifestConflictSchema)
15180
+ });
15181
+ var appliedManifestSchema = manifestChangesSchema.extend({
15182
+ triggerSecrets: z18.record(z18.string(), z18.string())
15183
+ });
15184
+ function defineManifest(manifest) {
15185
+ return manifest;
15186
+ }
15187
+ // src/triggers/trigger-client.ts
15188
+ class TriggerClientError extends Error {
15189
+ status;
15190
+ body;
15191
+ constructor(status, body) {
15192
+ super(`Cortex answered ${status}: ${body}`);
15193
+ this.status = status;
15194
+ this.body = body;
15195
+ this.name = "TriggerClientError";
15196
+ }
15197
+ }
15198
+ var READ_BUDGET_MS = 30000;
15199
+ function createTriggerClient(config) {
15200
+ if (config.url !== undefined && !upstreamUrlSchema.safeParse(config.url).success) {
15201
+ throw new Error("createTriggerClient needs an absolute http or https url, or none");
15202
+ }
15203
+ const origin = config.url?.replace(/\/+$/, "");
15204
+ const fetchFn = config.fetch ?? globalThis.fetch;
15205
+ function secretOf(trigger) {
15206
+ const { secrets = {} } = config;
15207
+ const own = Object.hasOwn(secrets, trigger) ? secrets[trigger] : undefined;
15208
+ const secret = own?.trim() ? own : config.secret;
15209
+ return secret?.trim() ? secret : undefined;
15210
+ }
15211
+ function runPath(runId) {
15212
+ return runRoute(config, config.agent, runId);
15213
+ }
15214
+ async function send(trigger, path, init, parse, acceptedErrors = [], wait = 0) {
15215
+ const secret = secretOf(trigger);
15216
+ if (!secret)
15217
+ throw new Error(`No secret configured for trigger "${trigger}"`);
15218
+ if (origin === undefined)
15219
+ throw new Error("No engine url configured");
15220
+ const headers = new Headers(init.headers);
15221
+ headers.set("Authorization", `Bearer ${secret}`);
15222
+ const deadline = AbortSignal.timeout(wait + READ_BUDGET_MS);
15223
+ const signal = init.signal ? AbortSignal.any([init.signal, deadline]) : deadline;
15224
+ const response = await fetchFn(`${origin}${path}`, { ...init, headers, signal });
15225
+ const body = await response.text();
15226
+ if (!response.ok && !acceptedErrors.includes(response.status))
15227
+ throw new TriggerClientError(response.status, body);
15228
+ try {
15229
+ return parse(JSON.parse(body));
15230
+ } catch {
15231
+ throw new TriggerClientError(response.status, body);
15232
+ }
15233
+ }
15234
+ async function post(trigger, path, payload, options) {
15235
+ const headers = new Headers({ "Content-Type": "application/json" });
15236
+ if (options.idempotencyKey !== undefined)
15237
+ headers.set("Idempotency-Key", options.idempotencyKey);
15238
+ return await send(trigger, `${path}${query(options)}`, { method: "POST", headers, body: JSON.stringify(payload), signal: options.signal }, (answer) => fireAnswerSchema.parse(answer), [409, 422, 429], options.wait);
15239
+ }
15240
+ function query(options) {
15241
+ const params = new URLSearchParams;
15242
+ if (options.wait !== undefined) {
15243
+ if (!Number.isInteger(options.wait) || options.wait < 0 || options.wait > 300000)
15244
+ throw new RangeError("wait must be an integer from 0 to 300000 milliseconds");
15245
+ params.set("wait", String(options.wait));
15246
+ }
15247
+ if (options.busy !== undefined)
15248
+ params.set("busy", options.busy);
15249
+ return params.size ? `?${params.toString()}` : "";
15250
+ }
15251
+ return {
15252
+ canFire(trigger) {
15253
+ return origin !== undefined && secretOf(trigger) !== undefined;
15254
+ },
15255
+ async fire(trigger, payload, options = {}) {
15256
+ return await post(trigger, triggerRoute(config, config.agent, trigger), payload, options);
15257
+ },
15258
+ async answer(trigger, runId, decision, options = {}) {
15259
+ return await post(trigger, `${runPath(runId)}/answer`, runAnswerSchema.parse(decision), options);
15260
+ },
15261
+ async read(trigger, runId, options = {}) {
15262
+ return await send(trigger, runPath(runId), { method: "GET", signal: options.signal }, (answer) => runRecordSchema.parse(answer));
15263
+ },
15264
+ async list(trigger, options = {}) {
15265
+ const query = new URLSearchParams;
15266
+ if (options.limit !== undefined) {
15267
+ if (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 200)
15268
+ throw new RangeError("limit must be an integer from 1 to 200");
15269
+ query.set("limit", String(options.limit));
15270
+ }
15271
+ if (options.before !== undefined)
15272
+ query.set("before", options.before);
15273
+ const suffix = query.size ? `?${query.toString()}` : "";
15274
+ return await send(trigger, `${triggerRoute(config, config.agent, trigger)}/runs${suffix}`, { method: "GET", signal: options.signal }, (answer) => runListSchema.parse(answer));
15275
+ },
15276
+ async cancel(trigger, runId, options = {}) {
15277
+ return await send(trigger, `${runPath(runId)}/cancel`, { method: "POST", signal: options.signal }, (answer) => runCancelSchema.parse(answer));
15278
+ }
15279
+ };
15280
+ }
15281
+ // ../../internal/contracts/src/management/index.ts
15282
+ import { z as z19 } from "zod";
15283
+
15284
+ // ../../internal/contracts/src/management/procedures.generated.ts
15285
+ var managementProcedureKinds = {
15286
+ "agents.addAlias": "mutation",
15287
+ "agents.create": "mutation",
15288
+ "agents.delete": "mutation",
15289
+ "agents.deleteAlias": "mutation",
15290
+ "agents.get": "query",
15291
+ "agents.list": "query",
15292
+ "agents.listAliases": "query",
15293
+ "agents.options": "query",
15294
+ "agents.publishPrompt": "mutation",
15295
+ "agents.rollbackPrompt": "mutation",
15296
+ "agents.savePrompt": "mutation",
15297
+ "agents.saveSettings": "mutation",
15298
+ "agents.subagentOptions": "query",
15299
+ "agents.update": "mutation",
15300
+ "audit.filters": "query",
15301
+ "audit.get": "query",
15302
+ "audit.list": "query",
15303
+ "collections.create": "mutation",
15304
+ "collections.delete": "mutation",
15305
+ "collections.get": "query",
15306
+ "collections.list": "query",
15307
+ "collections.setAudience": "mutation",
15308
+ "collections.testRetrieval": "mutation",
15309
+ "collections.update": "mutation",
15310
+ "credentials.create": "mutation",
15311
+ "credentials.delete": "mutation",
15312
+ "credentials.list": "query",
15313
+ "credentials.names": "query",
15314
+ "credentials.rotateKey": "mutation",
15315
+ "credentials.update": "mutation",
15316
+ "datasetHosts.create": "mutation",
15317
+ "datasetHosts.delete": "mutation",
15318
+ "datasetHosts.get": "query",
15319
+ "datasetHosts.list": "query",
15320
+ "datasetHosts.publish": "mutation",
15321
+ "datasetHosts.rollback": "mutation",
15322
+ "datasetHosts.setAudience": "mutation",
15323
+ "datasetHosts.sync": "mutation",
15324
+ "datasetHosts.test": "mutation",
15325
+ "datasetHosts.toggle": "mutation",
15326
+ "datasetHosts.update": "mutation",
15327
+ "documents.chunks": "query",
15328
+ "documents.completeUpload": "mutation",
15329
+ "documents.list": "query",
15330
+ "documents.prepareUpload": "mutation",
15331
+ "documents.remove": "mutation",
15332
+ "documents.retry": "mutation",
15333
+ "managementKeys.mine": "query",
15334
+ "manifests.preview": "mutation",
15335
+ "manifests.sync": "mutation",
15336
+ "mcpServers.create": "mutation",
15337
+ "mcpServers.delete": "mutation",
15338
+ "mcpServers.detectSignIn": "query",
15339
+ "mcpServers.disconnect": "mutation",
15340
+ "mcpServers.get": "query",
15341
+ "mcpServers.list": "query",
15342
+ "mcpServers.publish": "mutation",
15343
+ "mcpServers.rollback": "mutation",
15344
+ "mcpServers.setAudience": "mutation",
15345
+ "mcpServers.test": "mutation",
15346
+ "mcpServers.toggle": "mutation",
15347
+ "mcpServers.update": "mutation",
15348
+ "modelProviders.create": "mutation",
15349
+ "modelProviders.delete": "mutation",
15350
+ "modelProviders.inherited": "query",
15351
+ "modelProviders.list": "query",
15352
+ "modelProviders.options": "query",
15353
+ "modelProviders.update": "mutation",
15354
+ "observability.getExecution": "query",
15355
+ "observability.getExecutionSummary": "query",
15356
+ "observability.getRetrievalQuality": "query",
15357
+ "observability.getRun": "query",
15358
+ "observability.getUsage": "query",
15359
+ "observability.listDatasetReads": "query",
15360
+ "observability.listExecutions": "query",
15361
+ "observability.listRuns": "query",
15362
+ "observability.listSchemaDrifts": "query",
15363
+ "observability.listSkillLoads": "query",
15364
+ "observability.listSkillMisses": "query",
15365
+ "observability.listSkillUsage": "query",
15366
+ "observability.listToolHealth": "query",
15367
+ "observability.listUsageUsers": "query",
15368
+ "observability.unhealthyToolIds": "query",
15369
+ "observability.unusedSkillIds": "query",
15370
+ "observability.updateSchemaDrift": "mutation",
15371
+ "orgs.create": "mutation",
15372
+ "orgs.delete": "mutation",
15373
+ "orgs.deleteEnvironment": "mutation",
15374
+ "orgs.deleteProject": "mutation",
15375
+ "orgs.inviteOwner": "mutation",
15376
+ "orgs.list": "query",
15377
+ "orgs.options": "query",
15378
+ "orgs.rename": "mutation",
15379
+ "orgs.restore": "mutation",
15380
+ "orgs.suspend": "mutation",
15381
+ "orgs.updateProject": "mutation",
15382
+ "publishing.exclusive": "query",
15383
+ "publishing.history": "query",
15384
+ "publishing.latest": "query",
15385
+ "roles.create": "mutation",
15386
+ "roles.delete": "mutation",
15387
+ "roles.list": "query",
15388
+ "roles.update": "mutation",
15389
+ "secrets.delete": "mutation",
15390
+ "secrets.list": "query",
15391
+ "secrets.names": "query",
15392
+ "secrets.rotate": "mutation",
15393
+ "secrets.set": "mutation",
15394
+ "secrets.update": "mutation",
15395
+ "servers.create": "mutation",
15396
+ "servers.delete": "mutation",
15397
+ "servers.get": "query",
15398
+ "servers.list": "query",
15399
+ "servers.options": "query",
15400
+ "servers.sync": "mutation",
15401
+ "servers.update": "mutation",
15402
+ "services.create": "mutation",
15403
+ "services.delete": "mutation",
15404
+ "services.get": "query",
15405
+ "services.list": "query",
15406
+ "services.options": "query",
15407
+ "services.publish": "mutation",
15408
+ "services.rollback": "mutation",
15409
+ "services.setAudience": "mutation",
15410
+ "services.toggle": "mutation",
15411
+ "services.update": "mutation",
15412
+ "settings.get": "query",
15413
+ "settings.update": "mutation",
15414
+ "skills.countPublished": "query",
15415
+ "skills.create": "mutation",
15416
+ "skills.delete": "mutation",
15417
+ "skills.get": "query",
15418
+ "skills.list": "query",
15419
+ "skills.publish": "mutation",
15420
+ "skills.rollback": "mutation",
15421
+ "skills.setAudience": "mutation",
15422
+ "skills.toggle": "mutation",
15423
+ "skills.update": "mutation",
15424
+ "threads.get": "query",
15425
+ "threads.list": "query",
15426
+ "threads.llmRequests": "query",
15427
+ "threads.transcript": "query",
15428
+ "tools.applyDiff": "mutation",
15429
+ "tools.countPinned": "query",
15430
+ "tools.create": "mutation",
15431
+ "tools.createDrafts": "mutation",
15432
+ "tools.delete": "mutation",
15433
+ "tools.diff": "query",
15434
+ "tools.get": "query",
15435
+ "tools.list": "query",
15436
+ "tools.options": "query",
15437
+ "tools.preview": "mutation",
15438
+ "tools.publish": "mutation",
15439
+ "tools.rollback": "mutation",
15440
+ "tools.setAudience": "mutation",
15441
+ "tools.test": "mutation",
15442
+ "tools.toggle": "mutation",
15443
+ "tools.update": "mutation",
15444
+ "triggers.answerRun": "mutation",
15445
+ "triggers.create": "mutation",
15446
+ "triggers.delete": "mutation",
15447
+ "triggers.fire": "mutation",
15448
+ "triggers.get": "query",
15449
+ "triggers.list": "query",
15450
+ "triggers.publish": "mutation",
15451
+ "triggers.rollback": "mutation",
15452
+ "triggers.rotateSecret": "mutation",
15453
+ "triggers.setAudience": "mutation",
15454
+ "triggers.toggle": "mutation",
15455
+ "triggers.update": "mutation",
15456
+ "users.accounts": "query",
15457
+ "users.invite": "mutation",
15458
+ "users.list": "query",
15459
+ "users.listInvitations": "query",
15460
+ "users.remove": "mutation",
15461
+ "users.revokeInvitation": "mutation",
15462
+ "users.roleOptions": "query",
15463
+ "users.setAccountActive": "mutation",
15464
+ "users.setActive": "mutation",
15465
+ "users.setRoles": "mutation",
15466
+ "users.setTempPassword": "mutation",
15467
+ "webhooks.create": "mutation",
15468
+ "webhooks.delete": "mutation",
15469
+ "webhooks.get": "query",
15470
+ "webhooks.list": "query",
15471
+ "webhooks.listDeliveries": "query",
15472
+ "webhooks.setAudience": "mutation",
15473
+ "webhooks.test": "mutation",
15474
+ "webhooks.toggle": "mutation",
15475
+ "webhooks.update": "mutation"
15476
+ };
15477
+
15478
+ // ../../internal/contracts/src/management/index.ts
15479
+ var MANAGEMENT_BASE_PATH = "/api/management";
15480
+ function managementPath(procedure) {
15481
+ const kebab = procedure.replace(/[A-Z]/g, (upper) => `-${upper.toLowerCase()}`);
15482
+ return `/${kebab.replaceAll(".", "/")}`;
15483
+ }
15484
+ function isScalar(value) {
15485
+ return value === null || ["string", "number", "boolean"].includes(typeof value);
15119
15486
  }
15120
- var manifestMcpServerSchema = z7.strictObject({
15121
- name: identifierSchema,
15122
- displayName: displayNameSchema.default({}),
15123
- url: upstreamUrlSchema,
15124
- headers: declaredHeadersSchema(presentedHeaderSchema.refine((name) => !mcpTransportHeaders.has(name.toLowerCase()), "a header the MCP transport sets"), headerSourceSchema),
15125
- signIn: mcpSignInSchema.optional(),
15126
- include: mcpToolNamesSchema.default([]),
15127
- exclude: mcpToolNamesSchema.default([]),
15128
- audience: audienceSchema,
15129
- overridable: overridable(["displayName", "include", "exclude", "headers", "signIn"])
15130
- }).superRefine((server, context) => {
15131
- const index = authorizationBesideSignIn(server);
15132
- if (index >= 0) {
15133
- context.addIssue({
15134
- code: "custom",
15135
- path: ["headers", index, "header"],
15136
- message: "the sign-in's token travels under Authorization"
15137
- });
15487
+ function managementQuery(input) {
15488
+ const params = new URLSearchParams;
15489
+ for (const [name, value] of Object.entries(input)) {
15490
+ if (value === undefined)
15491
+ continue;
15492
+ if (isScalar(value))
15493
+ params.set(name, String(value));
15494
+ else if (Array.isArray(value) && value.length > 0 && value.every(isScalar)) {
15495
+ for (const item of value)
15496
+ params.append(name, String(item));
15497
+ } else
15498
+ params.set(name, JSON.stringify(value));
15138
15499
  }
15139
- });
15140
- var manifestWebhookSchema = z7.strictObject({
15141
- name: nameSchema,
15142
- displayName: displayNameSchema.default({}),
15143
- description: z7.string().trim().max(500).default(""),
15144
- event: z7.enum(SERVER_EVENTS),
15145
- url: upstreamUrlSchema,
15146
- headers: declaredHeadersSchema(presentedHeaderSchema.refine((name) => name.toLowerCase() !== EVENT_HEADER.toLowerCase(), "the header that names the event"), runlessHeaderSourceSchema),
15147
- timeoutMs: setting(SETTING_BOUNDS.webhook.timeoutMs),
15148
- audience: audienceSchema,
15149
- overridable: overridable(["displayName", "description", "timeoutMs", "headers"])
15150
- });
15151
- var COLLECTION_LIMITS = { descriptionLength: 2000, documents: 100 };
15152
- var DOCUMENT_LIMITS = { nameLength: 255, bytes: 10 * 1024 * 1024 };
15153
- var DOCX_MIME_TYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
15154
- var mimeTypeByExtension = new Map([
15155
- ["md", "text/markdown"],
15156
- ["txt", "text/plain"],
15157
- ["html", "text/html"],
15158
- ["htm", "text/html"],
15159
- ["pdf", "application/pdf"],
15160
- ["docx", DOCX_MIME_TYPE]
15161
- ]);
15162
- function documentType(name) {
15163
- const dot = name.lastIndexOf(".");
15164
- return dot === -1 ? undefined : mimeTypeByExtension.get(name.slice(dot + 1).toLowerCase());
15165
- }
15166
- function base64Bytes(data) {
15167
- const padding = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
15168
- return data.length / 4 * 3 - padding;
15500
+ const encoded = params.toString();
15501
+ return encoded === "" ? "" : `?${encoded}`;
15169
15502
  }
15170
- var documentNameSchema = z7.string().trim().min(1).max(DOCUMENT_LIMITS.nameLength);
15171
- var textDocumentSchema = z7.strictObject({
15172
- name: documentNameSchema,
15173
- text: z7.string().min(1).refine((text) => new TextEncoder().encode(text).byteLength <= DOCUMENT_LIMITS.bytes, `larger than ${DOCUMENT_LIMITS.bytes} bytes`)
15174
- });
15175
- var pathDocumentSchema = z7.strictObject({
15176
- path: z7.string().trim().min(1),
15177
- name: documentNameSchema.optional()
15178
- });
15179
- var urlDocumentSchema = z7.strictObject({
15180
- url: upstreamUrlSchema,
15181
- name: documentNameSchema.optional()
15182
- });
15183
- var dataDocumentSchema = z7.strictObject({
15184
- name: documentNameSchema,
15185
- data: z7.base64().refine((data) => base64Bytes(data) <= DOCUMENT_LIMITS.bytes, `larger than ${DOCUMENT_LIMITS.bytes} bytes`)
15503
+ var refusalBodySchema = z19.object({
15504
+ code: z19.string().optional().catch(undefined),
15505
+ message: z19.string().optional().catch(undefined),
15506
+ refusal: z19.string().optional().catch(undefined),
15507
+ cause: z19.record(z19.string(), z19.unknown()).optional().catch(undefined)
15186
15508
  });
15187
- function documentName(document) {
15188
- if (document.name !== undefined)
15189
- return document.name;
15190
- if (document.path !== undefined)
15191
- return document.path.split(/[/\\]/).pop() ?? "";
15192
- const segment = new URL(document.url ?? "", "https://x").pathname.split("/").pop() ?? "";
15193
- try {
15194
- return decodeURIComponent(segment);
15195
- } catch {
15196
- return segment;
15509
+
15510
+ class ManagementClientError extends Error {
15511
+ status;
15512
+ code;
15513
+ detail;
15514
+ refusal;
15515
+ constructor(status, code, message, detail, refusal) {
15516
+ super(message);
15517
+ this.status = status;
15518
+ this.code = code;
15519
+ this.detail = detail;
15520
+ this.refusal = refusal;
15521
+ this.name = "ManagementClientError";
15197
15522
  }
15198
15523
  }
15199
- function documentsSchema(document) {
15200
- return z7.array(document).max(COLLECTION_LIMITS.documents).superRefine((documents, ctx) => {
15201
- const names = documents.map(documentName);
15202
- names.forEach((name, index) => {
15203
- if (documentType(name) === undefined) {
15204
- ctx.addIssue({
15205
- code: "custom",
15206
- path: [index, "name"],
15207
- message: "a document's name ends in .md, .txt, .html, .htm, .pdf or .docx"
15208
- });
15209
- } else if (names.indexOf(name) !== index) {
15210
- ctx.addIssue({
15211
- code: "custom",
15212
- path: [index, "name"],
15213
- message: "a name repeats"
15214
- });
15215
- }
15216
- });
15217
- }).default([]);
15218
- }
15219
- function collectionSchema(document) {
15220
- return z7.strictObject({
15221
- name: nameSchema,
15222
- displayName: displayNameSchema.default({}),
15223
- description: z7.string().trim().max(COLLECTION_LIMITS.descriptionLength).default(""),
15224
- service: nameSchema.optional(),
15225
- citable: z7.boolean().default(true),
15226
- documents: documentsSchema(document),
15227
- audience: audienceSchema,
15228
- overridable: overridable(["displayName", "description", "documents"])
15524
+ var DEFAULT_TIMEOUT_MS2 = 1e5;
15525
+ async function callManagement(target, request) {
15526
+ const { method, path, input } = request;
15527
+ const query = method === "get" && isRecord(input) ? managementQuery(input) : "";
15528
+ const signals = [
15529
+ ...request.signal ? [request.signal] : [],
15530
+ ...target.timeoutMs === undefined ? [] : [AbortSignal.timeout(target.timeoutMs)]
15531
+ ];
15532
+ const url = `${target.url.replace(/\/+$/, "")}${MANAGEMENT_BASE_PATH}${path}${query}`;
15533
+ const response = await (target.fetch ?? globalThis.fetch)(url, {
15534
+ method: method.toUpperCase(),
15535
+ headers: {
15536
+ Authorization: `Bearer ${target.key}`,
15537
+ ...method === "post" ? { "Content-Type": "application/json" } : {},
15538
+ ...target.locale ? { "Accept-Language": target.locale } : {},
15539
+ ...target.timeZone ? { [TIMEZONE_HEADER]: target.timeZone } : {}
15540
+ },
15541
+ body: method === "post" && input !== undefined ? JSON.stringify(input) : undefined,
15542
+ signal: signals.length ? AbortSignal.any(signals) : undefined
15229
15543
  });
15544
+ if (response.ok) {
15545
+ const output = await response.json();
15546
+ return output;
15547
+ }
15548
+ const body = await response.json().catch(() => null);
15549
+ const refused = refusalBodySchema.safeParse(body).data ?? {};
15550
+ throw new ManagementClientError(response.status, refused.code ?? "error", refused.message ?? response.statusText, refused.cause, refused.refusal);
15230
15551
  }
15231
- var manifestDocumentSchema = z7.union([textDocumentSchema, pathDocumentSchema, urlDocumentSchema]);
15232
- var manifestCollectionSchema = collectionSchema(manifestDocumentSchema);
15233
- var resolvedCollectionSchema = collectionSchema(z7.union([textDocumentSchema, dataDocumentSchema, urlDocumentSchema]));
15234
- var AUTH_JWT_SECRET_ALGORITHMS = ["HS256", "HS384", "HS512"];
15235
- var issuerSchema = z7.string().trim().min(1).max(2048);
15236
- var tokenAudienceSchema = z7.string().trim().min(1).max(2048).optional();
15237
- var agentAuthSchema = z7.discriminatedUnion("kind", [
15238
- z7.strictObject({
15239
- kind: z7.literal("jwks"),
15240
- jwksUri: tlsUrlSchema,
15241
- issuer: issuerSchema,
15242
- audience: tokenAudienceSchema
15243
- }),
15244
- z7.strictObject({
15245
- kind: z7.literal("jwt-secret"),
15246
- secret: nameSchema,
15247
- algorithm: z7.enum(AUTH_JWT_SECRET_ALGORITHMS),
15248
- issuer: issuerSchema,
15249
- audience: tokenAudienceSchema
15250
- }),
15251
- z7.strictObject({
15252
- kind: z7.literal("anonymous"),
15253
- recaptcha: z7.strictObject({
15254
- siteKey: z7.string().trim().min(1).max(200),
15255
- projectId: z7.string().trim().min(1).max(200),
15256
- secret: nameSchema,
15257
- minScore: z7.number().min(SETTING_BOUNDS.recaptcha.minScore.min).max(SETTING_BOUNDS.recaptcha.minScore.max).default(SETTING_BOUNDS.recaptcha.minScore.default)
15258
- }).optional()
15259
- }),
15260
- z7.strictObject({ kind: z7.literal("server") })
15261
- ]);
15262
- var { agentContext, agentLimits } = SETTING_BOUNDS;
15263
- var { agent: agentRateLimits } = RATE_LIMITS;
15264
- var agentSettingsSchema = z7.strictObject({
15265
- ragEnabled: z7.boolean().default(false),
15266
- toolRegistryEnabled: z7.boolean().default(false),
15267
- serviceRegistryEnabled: z7.boolean().default(false),
15268
- subagentsEnabled: z7.boolean().default(false),
15269
- checkBacksEnabled: z7.boolean().default(false),
15270
- attachmentsEnabled: z7.boolean().default(true),
15271
- fetchImageHostnames: z7.array(z7.string().max(253).regex(HOSTNAME_PATTERN)).max(FETCH_IMAGE_HOSTS_LIMIT).default([]),
15272
- locationPicker: z7.boolean().default(false),
15273
- media: z7.array(z7.enum(MEDIA_FORMS)).default([...DEFAULT_MEDIA_FORMS]),
15274
- messages: z7.boolean().default(true),
15275
- whileBusy: z7.enum(WHILE_BUSY).default("refuse"),
15276
- a2a: z7.boolean().default(false),
15277
- a2aPushHostnames: z7.array(z7.string().max(253).regex(HOSTNAME_PATTERN)).max(A2A_PUSH_HOSTS_LIMIT).default([]),
15278
- description: z7.string().trim().max(1000).default(""),
15279
- defaultLocale: localeSchema.default(BASE_LOCALE),
15280
- context: z7.strictObject({
15281
- maxContextTokens: setting(agentContext.maxContextTokens),
15282
- summarizationThreshold: z7.number().min(agentContext.summarizationThreshold.min).max(agentContext.summarizationThreshold.max).default(agentContext.summarizationThreshold.default),
15283
- toolResultMaxTokens: setting(agentContext.toolResultMaxTokens),
15284
- recentMessagesToKeep: setting(agentContext.recentMessagesToKeep)
15285
- }).prefault({}),
15286
- limits: z7.strictObject({
15287
- resolveTokenBudget: setting(agentLimits.resolveTokenBudget),
15288
- executeTimeoutMs: setting(agentLimits.executeTimeoutMs),
15289
- maxResponseBytes: setting(agentLimits.maxResponseBytes)
15290
- }).prefault({})
15291
- });
15292
- var manifestAgentSchema = z7.strictObject({
15293
- name: nameSchema,
15294
- displayName: displayNameSchema.default({}),
15295
- server: nameSchema.optional(),
15296
- prompt: z7.string().trim().min(1),
15297
- auth: agentAuthSchema,
15298
- models: z7.strictObject({
15299
- chat: modelSchema.optional(),
15300
- vision: modelSchema.omit({ effort: true }).optional(),
15301
- summarization: modelSchema.omit({ effort: true }).optional()
15302
- }).default({}),
15303
- settings: agentSettingsSchema.prefault({}),
15304
- rateLimits: z7.strictObject({
15305
- allUsers: z7.strictObject({
15306
- messagesPerMinute: rateLimit(agentRateLimits.messagesPerMinute, "allUsers"),
15307
- tokensPerDay: rateLimit(agentRateLimits.tokensPerDay, "allUsers")
15308
- }).prefault({}),
15309
- perUser: z7.strictObject({
15310
- messagesPerMinute: rateLimit(agentRateLimits.messagesPerMinute, "perUser"),
15311
- tokensPerDay: rateLimit(agentRateLimits.tokensPerDay, "perUser")
15312
- }).prefault({})
15313
- }).prefault({}),
15314
- suggestions: suggestionsSchema.default(() => byLocale(() => [])),
15315
- greeting: greetingSchema.default(() => byLocale(() => "")),
15316
- overridable: overridable([
15317
- "displayName",
15318
- "prompt",
15319
- "models",
15320
- "settings",
15321
- "rateLimits",
15322
- "suggestions",
15323
- "greeting"
15324
- ])
15325
- }).superRefine((agent, context) => {
15326
- if (agent.server !== undefined)
15327
- return;
15328
- if (agent.auth.kind === "server") {
15329
- context.addIssue({
15330
- code: "custom",
15331
- path: ["auth"],
15332
- message: "server auth needs a server"
15333
- });
15552
+ function createManagementClient(options) {
15553
+ if (!upstreamUrlSchema.safeParse(options.url).success) {
15554
+ throw new Error("createManagementClient needs an absolute http or https url");
15334
15555
  }
15335
- if (agent.models.chat === undefined) {
15336
- context.addIssue({
15337
- code: "custom",
15338
- path: ["models", "chat"],
15339
- message: "an agent with no server names its own chat model"
15556
+ if (!options.key?.trim())
15557
+ throw new Error("createManagementClient needs a management key");
15558
+ if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1)) {
15559
+ throw new Error("createManagementClient needs a timeoutMs of whole milliseconds above 0");
15560
+ }
15561
+ const target = { ...options, timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS2 };
15562
+ const client = {};
15563
+ for (const [procedure, kind] of Object.entries(managementProcedureKinds)) {
15564
+ const [router = "", name = ""] = procedure.split(".");
15565
+ (client[router] ??= {})[name] = (input, options) => callManagement(target, {
15566
+ method: kind === "query" ? "get" : "post",
15567
+ path: managementPath(procedure),
15568
+ input,
15569
+ signal: options?.signal
15340
15570
  });
15341
15571
  }
15342
- });
15343
- var MANIFEST_KINDS = [
15344
- "agents",
15345
- "services",
15346
- "tools",
15347
- "skills",
15348
- "triggers",
15349
- "datasetHosts",
15350
- "mcpServers",
15351
- "webhooks",
15352
- "collections"
15353
- ];
15354
- function listOf(entry) {
15355
- return z7.array(entry).refine((entries) => new Set(entries.map((value) => value.name)).size === entries.length, "a name repeats").default([]);
15356
- }
15357
- var manifestSchema = z7.strictObject({
15358
- id: nameSchema,
15359
- agents: listOf(manifestAgentSchema),
15360
- tools: listOf(manifestToolSchema),
15361
- openapi: listOf(manifestOpenApiSchema),
15362
- services: listOf(manifestServiceSchema),
15363
- skills: listOf(manifestSkillSchema),
15364
- triggers: listOf(manifestTriggerSchema),
15365
- datasetHosts: listOf(manifestDatasetHostSchema),
15366
- mcpServers: listOf(manifestMcpServerSchema),
15367
- webhooks: listOf(manifestWebhookSchema),
15368
- collections: listOf(manifestCollectionSchema)
15369
- });
15370
- var resolvedManifestSchema = manifestSchema.extend({
15371
- collections: listOf(resolvedCollectionSchema)
15372
- });
15373
- var manifestKindSchema = z7.enum(MANIFEST_KINDS);
15374
- var namesByKindSchema = z7.record(manifestKindSchema, z7.array(z7.string()));
15375
- var manifestChangesSchema = z7.object({
15376
- create: namesByKindSchema,
15377
- update: namesByKindSchema,
15378
- delete: namesByKindSchema
15379
- });
15380
- var manifestConflictSchema = z7.strictObject({
15381
- kind: manifestKindSchema,
15382
- name: z7.string(),
15383
- field: z7.string(),
15384
- key: z7.string().optional()
15385
- });
15386
- var conflictSideSchema = z7.enum(["live", "manifest"]);
15387
- var manifestApplyInputSchema = resolvedManifestSchema.extend({
15388
- prefer: conflictSideSchema.optional(),
15389
- resolutions: z7.array(manifestConflictSchema.extend({ keep: conflictSideSchema })).default([])
15390
- });
15391
- var manifestPreviewSchema = manifestChangesSchema.extend({
15392
- conflicts: z7.array(manifestConflictSchema)
15393
- });
15394
- var appliedManifestSchema = manifestChangesSchema.extend({
15395
- triggerSecrets: z7.record(z7.string(), z7.string())
15396
- });
15397
- function defineManifest(manifest) {
15398
- return manifest;
15572
+ return client;
15399
15573
  }
15400
15574
  export {
15401
15575
  CortexError2 as CortexError,
@@ -15405,5 +15579,6 @@ export {
15405
15579
  createTriggerClient,
15406
15580
  defineDatasetHost,
15407
15581
  defineManifest,
15408
- defineServer
15582
+ defineServer,
15583
+ unverifiedJwtSubject
15409
15584
  };