@m6d/cortex 0.14.0 → 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-4n21s4ns.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
  });
@@ -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,623 +13970,282 @@ 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";
14031
-
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));
14246
- }
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
- });
14256
-
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/manifest.ts
14308
- import { z as z19 } from "zod";
14309
-
14310
- // ../../internal/contracts/src/manifest/agents.ts
14311
- import { z as z7 } from "zod";
14312
-
14313
- // ../../internal/contracts/src/manifest/bounds.ts
14314
- var TOOL_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
14315
- var SETTING_BOUNDS = {
14316
- tool: {
14317
- timeoutMs: { min: 100, max: 120000, default: 30000 },
14318
- maxResponseBytes: { min: 1024, max: 1048576, default: 262144 }
14319
- },
14320
- agentContext: {
14321
- maxContextTokens: { min: 4000, max: 2000000, default: 120000 },
14322
- summarizationThreshold: { min: 0.1, max: 0.95, default: 0.75 },
14323
- toolResultMaxTokens: { min: 500, max: 200000, default: 1e4 },
14324
- recentMessagesToKeep: { min: 0, max: 100, default: 6 }
14325
- },
14326
- agentLimits: {
14327
- resolveTokenBudget: { min: 500, max: 64000, default: 4000 },
14328
- executeTimeoutMs: { min: 1000, max: 300000, default: 30000 },
14329
- maxResponseBytes: { min: 1024, max: 1048576, default: 262144 }
14330
- },
14331
- trigger: { disableAfterFailures: { min: 1, max: 1000, default: 5 } },
14332
- datasetHost: { timeoutMs: { min: 100, max: 120000, default: 30000 } },
14333
- webhook: { timeoutMs: { min: 1000, max: 30000, default: 1e4 } },
14334
- recaptcha: { minScore: { min: 0.1, max: 0.9, default: 0.5 } },
14335
- server: {
14336
- signInChecksPerMinute: { min: 1, max: 1e5, default: 600 },
14337
- triggerChecksPerMinute: { min: 1, max: 1e4, default: 60 }
14338
- }
14339
- };
14340
- var RATE_LIMITS = {
14341
- agent: {
14342
- messagesPerMinute: { max: 1e4, allUsers: 600, perUser: 20 },
14343
- tokensPerDay: { max: 1000000000000, allUsers: null, perUser: 1e6 }
14344
- },
14345
- tool: { callsPerMinute: { max: 1e4, allUsers: 60, perUser: 20 } },
14346
- datasetHost: { queriesPerMinute: { max: 1e4, allUsers: 60, perUser: 20 } }
14347
- };
14348
- var TOOL_TYPE_NAMES = ["http", "embedded", "soap", "native", "client"];
14349
- var MCP_CONNECTION_OWNERS = ["shared", "endUser"];
14350
- var RESPONSE_WRAPS = ["items", "value"];
14351
- var QUERY_STYLES = ["form", "spaceDelimited", "pipeDelimited", "deepObject"];
14352
- var PATH_STYLES = ["simple", "label", "matrix"];
14353
- var SOAP_VERSIONS = ["1.1", "1.2"];
14354
- 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])?)*$/;
14355
- var FETCH_IMAGE_HOSTS_LIMIT = 20;
14356
- var A2A_PUSH_HOSTS_LIMIT = 20;
14357
- var SUGGESTION_LIMITS = { perLocale: 6, titleLength: 120, promptLength: 2000 };
14358
- var GREETING_MAX_LENGTH = 200;
14359
- var FORM_MEDIA_TYPES = [
14360
- "application/x-www-form-urlencoded",
14361
- "multipart/form-data"
14362
- ];
14363
- var ENDPOINT_PARAM_PATTERN = /\{([^{}]+)\}/g;
14364
- var HEADER_LIMITS = { headerLength: 120, prefixLength: 40, headers: 8 };
14365
- var HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
14366
- var HEADER_VALUE_PATTERN = /^[\t\x20-\x7e\x80-\xff]*$/;
14367
- var transportSetHeaders = ["accept", "content-type", "content-length", "host"];
14368
- var transportForbiddenHeaders = [
14369
- "connection",
14370
- "transfer-encoding",
14371
- "upgrade",
14372
- "expect",
14373
- "te",
14374
- "trailer",
14375
- "proxy-authorization"
14376
- ];
14377
- var mcpTransportHeaders = new Set([
14378
- "mcp-session-id",
14379
- "mcp-protocol-version",
14380
- "last-event-id"
14381
- ]);
14382
- var transportOwnedHeaders = new Set([
14383
- ...transportSetHeaders,
14384
- ...transportForbiddenHeaders
14385
- ]);
14386
- var SCALAR_TYPES = ["string", "number", "integer", "boolean"];
14387
- var FIELD_LIMITS = { nameLength: 120, descriptionLength: 500, enumValues: 50 };
14388
- var MODEL_PROVIDER_LIMITS = { urlLength: 2048, modelLength: 200, models: 100 };
14389
- var SERVICE_LIMITS = { descriptionLength: 4000 };
14390
- var SKILL_LIMITS = { descriptionLength: 500 };
14391
- var TRIGGER_LIMITS = { descriptionLength: 500, instructionsLength: 20000 };
14392
- var COLLECTION_LIMITS = { descriptionLength: 2000, documents: 100 };
14393
- var DOCUMENT_LIMITS = { nameLength: 255, bytes: 10 * 1024 * 1024 };
14394
- var DOCX_MIME_TYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
14395
- var AUTH_JWT_SECRET_ALGORITHMS = ["HS256", "HS384", "HS512"];
14396
- var MANIFEST_KINDS = [
14397
- "agents",
14398
- "services",
14399
- "tools",
14400
- "skills",
14401
- "triggers",
14402
- "datasetHosts",
14403
- "mcpServers",
14404
- "webhooks",
14405
- "collections"
14406
- ];
14407
-
14408
- // ../../internal/contracts/src/manifest/fields.ts
14409
- import { z as z6 } from "zod";
14410
-
14411
- // ../../internal/contracts/src/egress-policy/url.ts
14412
- function isLoopback(hostname) {
14413
- return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
14414
- }
14415
- function normalizeHost(hostname) {
14416
- const bare = hostname.toLowerCase().replace(/\.$/, "").replace(/^\[(.*)]$/, "$1");
14417
- if (!bare.includes(":"))
14418
- return bare;
14419
- try {
14420
- return new URL(`http://[${bare}]`).hostname.replace(/^\[(.*)]$/, "$1");
14421
- } catch {
14422
- return bare;
14423
- }
14424
- }
14425
- function egressAllowedHosts() {
14426
- return (globalThis.process?.env?.EGRESS_ALLOWED_HOSTS ?? "").split(",").map((host) => host.trim()).filter(Boolean);
14427
- }
14428
- function isEgressAllowedHost(hostname, allowed = egressAllowedHosts()) {
14429
- const wanted = normalizeHost(hostname);
14430
- return allowed.some((host) => host === "*" || normalizeHost(host) === wanted);
14431
- }
14432
- function canCarrySecret(url, allowed = egressAllowedHosts()) {
14433
- try {
14434
- const { protocol, hostname } = new URL(url);
14435
- if (protocol === "https:")
14436
- return true;
14437
- if (protocol !== "http:")
14438
- return false;
14439
- return isLoopback(normalizeHost(hostname)) || isEgressAllowedHost(hostname, allowed);
14440
- } catch {
14441
- return false;
14442
- }
14443
- }
14444
- // ../../internal/contracts/src/manifest/fields.ts
14445
- var jsonPointerSchema = z6.string().regex(/^\//).max(256);
14446
- function setting({ min, max, default: fallback }) {
14447
- return z6.number().int().min(min).max(max).default(fallback);
14448
- }
14449
- function rateLimit(bound, users) {
14450
- return z6.number().int().min(1).max(bound.max).nullable().default(bound[users]);
14451
- }
14452
- function overridable(fields) {
14453
- return z6.array(z6.enum(fields)).refine((listed) => new Set(listed).size === listed.length, "a field repeats").default([]);
14454
- }
14455
- var tlsUrlSchema = z6.url().refine((url) => canCarrySecret(url, []));
14456
- var upstreamUrlSchema = z6.url({ protocol: /^https?$/ });
14457
- var audienceSchema = z6.union([
14458
- z6.literal("all"),
14459
- z6.strictObject({ server: nameSchema }),
14460
- z6.strictObject({
14461
- agents: z6.array(nameSchema).min(1).refine((names) => new Set(names).size === names.length, "an agent repeats")
14462
- })
14463
- ]);
14464
- var modelSchema = z6.strictObject({
14465
- provider: nameSchema,
14466
- model: z6.string().trim().min(1).max(MODEL_PROVIDER_LIMITS.modelLength),
14467
- effort: z6.string().trim().min(1).max(64).optional()
14468
- });
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";
14469
14152
 
14470
14153
  // ../../internal/contracts/src/manifest/agents.ts
14471
- var trimmedText = (max) => z7.string().min(1).max(max).refine((text) => text === text.trim(), "text has surrounding whitespace");
14472
- var suggestionsSchema = z7.record(localeSchema, z7.array(z7.object({
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({
14473
14157
  title: trimmedText(SUGGESTION_LIMITS.titleLength),
14474
14158
  prompt: trimmedText(SUGGESTION_LIMITS.promptLength)
14475
14159
  })).max(SUGGESTION_LIMITS.perLocale));
14476
- var greetingSchema = z7.record(localeSchema, z7.string().max(GREETING_MAX_LENGTH).refine((text) => text === text.trim(), "greeting has surrounding whitespace"));
14477
- var issuerSchema = z7.string().trim().min(1).max(2048);
14478
- var tokenAudienceSchema = z7.string().trim().min(1).max(2048).optional();
14479
- var agentAuthSchema = z7.discriminatedUnion("kind", [
14480
- z7.strictObject({
14481
- kind: z7.literal("jwks"),
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"),
14482
14173
  jwksUri: tlsUrlSchema,
14483
14174
  issuer: issuerSchema,
14484
14175
  audience: tokenAudienceSchema
14485
14176
  }),
14486
- z7.strictObject({
14487
- kind: z7.literal("jwt-secret"),
14177
+ z6.strictObject({
14178
+ kind: z6.literal("jwt-secret"),
14488
14179
  secret: nameSchema,
14489
- algorithm: z7.enum(AUTH_JWT_SECRET_ALGORITHMS),
14180
+ algorithm: z6.enum(AUTH_JWT_SECRET_ALGORITHMS).meta({ id: "JwtSecretAlgorithm" }),
14490
14181
  issuer: issuerSchema,
14491
14182
  audience: tokenAudienceSchema
14492
14183
  }),
14493
- z7.strictObject({
14494
- kind: z7.literal("anonymous"),
14495
- recaptcha: z7.strictObject({
14496
- siteKey: z7.string().trim().min(1).max(200),
14497
- projectId: z7.string().trim().min(1).max(200),
14184
+ z6.strictObject({
14185
+ kind: z6.literal("anonymous"),
14186
+ recaptcha: z6.strictObject({
14187
+ keys: recaptchaKeysSchema,
14188
+ projectId: z6.string().trim().min(1).max(200),
14498
14189
  secret: nameSchema,
14499
- minScore: z7.number().min(SETTING_BOUNDS.recaptcha.minScore.min).max(SETTING_BOUNDS.recaptcha.minScore.max).default(SETTING_BOUNDS.recaptcha.minScore.default)
14190
+ minScore: z6.number().min(SETTING_BOUNDS.recaptcha.minScore.min).max(SETTING_BOUNDS.recaptcha.minScore.max).default(SETTING_BOUNDS.recaptcha.minScore.default)
14500
14191
  }).optional()
14501
14192
  }),
14502
- z7.strictObject({ kind: z7.literal("server") })
14193
+ z6.strictObject({ kind: z6.literal("server") })
14503
14194
  ]);
14504
14195
  var { agentContext, agentLimits } = SETTING_BOUNDS;
14196
+ var SUBAGENT_WHEN_MAX = 1000;
14505
14197
  var { agent: agentRateLimits } = RATE_LIMITS;
14506
- var agentSettingsSchema = z7.strictObject({
14507
- ragEnabled: z7.boolean().default(false),
14508
- toolRegistryEnabled: z7.boolean().default(false),
14509
- serviceRegistryEnabled: z7.boolean().default(false),
14510
- subagentsEnabled: z7.boolean().default(false),
14511
- checkBacksEnabled: z7.boolean().default(false),
14512
- attachmentsEnabled: z7.boolean().default(true),
14513
- fetchImageHostnames: z7.array(z7.string().max(253).regex(HOSTNAME_PATTERN)).max(FETCH_IMAGE_HOSTS_LIMIT).default([]),
14514
- locationPicker: z7.boolean().default(false),
14515
- media: z7.array(z7.enum(MEDIA_FORMS)).default([...DEFAULT_MEDIA_FORMS]),
14516
- messages: z7.boolean().default(true),
14517
- whileBusy: z7.enum(WHILE_BUSY).default("refuse"),
14518
- a2a: z7.boolean().default(false),
14519
- a2aPushHostnames: z7.array(z7.string().max(253).regex(HOSTNAME_PATTERN)).max(A2A_PUSH_HOSTS_LIMIT).default([]),
14520
- description: z7.string().trim().max(1000).default(""),
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(""),
14521
14216
  defaultLocale: localeSchema.default(BASE_LOCALE),
14522
- context: z7.strictObject({
14217
+ context: z6.strictObject({
14523
14218
  maxContextTokens: setting(agentContext.maxContextTokens),
14524
- summarizationThreshold: z7.number().min(agentContext.summarizationThreshold.min).max(agentContext.summarizationThreshold.max).default(agentContext.summarizationThreshold.default),
14219
+ summarizationThreshold: z6.number().min(agentContext.summarizationThreshold.min).max(agentContext.summarizationThreshold.max).default(agentContext.summarizationThreshold.default),
14525
14220
  toolResultMaxTokens: setting(agentContext.toolResultMaxTokens),
14526
14221
  recentMessagesToKeep: setting(agentContext.recentMessagesToKeep)
14527
14222
  }).prefault({}),
14528
- limits: z7.strictObject({
14223
+ limits: z6.strictObject({
14529
14224
  resolveTokenBudget: setting(agentLimits.resolveTokenBudget),
14530
14225
  executeTimeoutMs: setting(agentLimits.executeTimeoutMs),
14531
- maxResponseBytes: setting(agentLimits.maxResponseBytes)
14226
+ maxResponseBytes: setting(agentLimits.maxResponseBytes),
14227
+ subagentDepth: setting(agentLimits.subagentDepth),
14228
+ subagentsAtOnce: setting(agentLimits.subagentsAtOnce)
14532
14229
  }).prefault({})
14533
14230
  });
14534
- var manifestAgentSchema = z7.strictObject({
14231
+ var manifestAgentSchema = z6.strictObject({
14535
14232
  name: nameSchema,
14536
14233
  displayName: displayNameSchema.default({}),
14537
14234
  server: nameSchema.optional(),
14538
- prompt: z7.string().trim().min(1),
14235
+ prompt: z6.string().trim().min(1),
14539
14236
  auth: agentAuthSchema,
14540
- models: z7.strictObject({
14237
+ models: z6.strictObject({
14541
14238
  chat: modelSchema.optional(),
14542
14239
  vision: modelSchema.omit({ effort: true }).optional(),
14543
14240
  summarization: modelSchema.omit({ effort: true }).optional()
14544
14241
  }).default({}),
14545
14242
  settings: agentSettingsSchema.prefault({}),
14546
- rateLimits: z7.strictObject({
14547
- allUsers: z7.strictObject({
14243
+ rateLimits: z6.strictObject({
14244
+ allUsers: z6.strictObject({
14548
14245
  messagesPerMinute: rateLimit(agentRateLimits.messagesPerMinute, "allUsers"),
14549
14246
  tokensPerDay: rateLimit(agentRateLimits.tokensPerDay, "allUsers")
14550
14247
  }).prefault({}),
14551
- perUser: z7.strictObject({
14248
+ perUser: z6.strictObject({
14552
14249
  messagesPerMinute: rateLimit(agentRateLimits.messagesPerMinute, "perUser"),
14553
14250
  tokensPerDay: rateLimit(agentRateLimits.tokensPerDay, "perUser")
14554
14251
  }).prefault({})
@@ -14584,11 +14281,11 @@ var manifestAgentSchema = z7.strictObject({
14584
14281
  });
14585
14282
 
14586
14283
  // ../../internal/contracts/src/manifest/datasets.ts
14587
- import { z as z9 } from "zod";
14284
+ import { z as z8 } from "zod";
14588
14285
 
14589
14286
  // ../../internal/contracts/src/manifest/headers.ts
14590
- import { z as z8 } from "zod";
14591
- var headerNameSchema = z8.string().trim().min(1).max(HEADER_LIMITS.headerLength).regex(HEADER_NAME_PATTERN);
14287
+ import { z as z7 } from "zod";
14288
+ var headerNameSchema = z7.string().trim().min(1).max(HEADER_LIMITS.headerLength).regex(HEADER_NAME_PATTERN);
14592
14289
  function repeatedHeaders(entries) {
14593
14290
  const seen = new Set;
14594
14291
  return entries.flatMap((entry, index) => {
@@ -14600,7 +14297,7 @@ function repeatedHeaders(entries) {
14600
14297
  }
14601
14298
  var presentedHeaderSchema = headerNameSchema.refine((name) => !transportOwnedHeaders.has(name.toLowerCase()), "a header the transport sets");
14602
14299
  function headerListSchema(entry, repeated) {
14603
- return z8.array(entry).max(HEADER_LIMITS.headers).superRefine((entries, context) => {
14300
+ return z7.array(entry).max(HEADER_LIMITS.headers).superRefine((entries, context) => {
14604
14301
  for (const index of repeatedHeaders(entries)) {
14605
14302
  context.addIssue({
14606
14303
  code: "custom",
@@ -14610,32 +14307,32 @@ function headerListSchema(entry, repeated) {
14610
14307
  }
14611
14308
  });
14612
14309
  }
14613
- var variableSourceSchema = z8.object({
14614
- kind: z8.literal("variable"),
14615
- name: z8.string().trim().min(1).max(64)
14310
+ var variableSourceSchema = z7.object({
14311
+ kind: z7.literal("variable"),
14312
+ name: z7.string().trim().min(1).max(64)
14616
14313
  });
14617
- var credentialSourceSchema = z8.object({
14618
- kind: z8.literal("credential"),
14314
+ var credentialSourceSchema = z7.object({
14315
+ kind: z7.literal("credential"),
14619
14316
  name: nameSchema
14620
14317
  });
14621
- var constantHeaderSourceSchema = z8.object({
14622
- kind: z8.literal("constant"),
14623
- value: z8.string().max(4000)
14318
+ var constantHeaderSourceSchema = z7.object({
14319
+ kind: z7.literal("constant"),
14320
+ value: z7.string().max(4000)
14624
14321
  });
14625
- var headerSourceSchema = z8.discriminatedUnion("kind", [
14322
+ var headerSourceSchema = z7.discriminatedUnion("kind", [
14626
14323
  credentialSourceSchema,
14627
- z8.object({ kind: z8.literal("runToken") }),
14324
+ z7.object({ kind: z7.literal("runToken") }),
14628
14325
  variableSourceSchema,
14629
14326
  constantHeaderSourceSchema
14630
- ]);
14631
- var runlessHeaderSourceSchema = z8.discriminatedUnion("kind", [
14327
+ ]).meta({ id: "HeaderSource" });
14328
+ var runlessHeaderSourceSchema = z7.discriminatedUnion("kind", [
14632
14329
  credentialSourceSchema,
14633
14330
  constantHeaderSourceSchema
14634
14331
  ]);
14635
14332
  function declaredHeadersSchema(header, from) {
14636
- return headerListSchema(z8.strictObject({
14333
+ return headerListSchema(z7.strictObject({
14637
14334
  header,
14638
- prefix: z8.string().max(HEADER_LIMITS.prefixLength).regex(HEADER_VALUE_PATTERN, "a prefix a header cannot carry").default(""),
14335
+ prefix: z7.string().max(HEADER_LIMITS.prefixLength).regex(HEADER_VALUE_PATTERN, "a prefix a header cannot carry").default(""),
14639
14336
  from
14640
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([]);
14641
14338
  }
@@ -14647,22 +14344,22 @@ function unexposedPins(host) {
14647
14344
  return host.pinned.filter((name) => !exposed.has(name));
14648
14345
  }
14649
14346
  var { datasetHost: datasetHostRateLimits } = RATE_LIMITS;
14650
- var manifestDatasetHostSchema = z9.strictObject({
14347
+ var manifestDatasetHostSchema = z8.strictObject({
14651
14348
  name: datasetIdentifierSchema,
14652
14349
  displayName: displayNameSchema.default({}),
14653
14350
  url: upstreamUrlSchema,
14654
14351
  headers: headersSchema,
14655
14352
  timeoutMs: setting(SETTING_BOUNDS.datasetHost.timeoutMs),
14656
- rateLimits: z9.strictObject({
14657
- allUsers: z9.strictObject({
14353
+ rateLimits: z8.strictObject({
14354
+ allUsers: z8.strictObject({
14658
14355
  queriesPerMinute: rateLimit(datasetHostRateLimits.queriesPerMinute, "allUsers")
14659
14356
  }).prefault({}),
14660
- perUser: z9.strictObject({
14357
+ perUser: z8.strictObject({
14661
14358
  queriesPerMinute: rateLimit(datasetHostRateLimits.queriesPerMinute, "perUser")
14662
14359
  }).prefault({})
14663
14360
  }).prefault({}),
14664
- expose: z9.array(datasetIdentifierSchema).min(1).max(500),
14665
- pinned: z9.array(datasetIdentifierSchema).max(50).default([]),
14361
+ expose: z8.array(datasetIdentifierSchema).min(1).max(500),
14362
+ pinned: z8.array(datasetIdentifierSchema).max(50).default([]),
14666
14363
  audience: audienceSchema,
14667
14364
  overridable: overridable(["displayName", "timeoutMs", "rateLimits", "headers"])
14668
14365
  }).superRefine((host, context) => {
@@ -14677,7 +14374,7 @@ var manifestDatasetHostSchema = z9.strictObject({
14677
14374
  });
14678
14375
 
14679
14376
  // ../../internal/contracts/src/manifest/knowledge.ts
14680
- import { z as z10 } from "zod";
14377
+ import { z as z9 } from "zod";
14681
14378
  var mimeTypeByExtension = new Map([
14682
14379
  ["md", "text/markdown"],
14683
14380
  ["txt", "text/plain"],
@@ -14694,22 +14391,22 @@ function base64Bytes(data) {
14694
14391
  const padding = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
14695
14392
  return data.length / 4 * 3 - padding;
14696
14393
  }
14697
- var documentNameSchema = z10.string().trim().min(1).max(DOCUMENT_LIMITS.nameLength);
14698
- var textDocumentSchema = z10.strictObject({
14394
+ var documentNameSchema = z9.string().trim().min(1).max(DOCUMENT_LIMITS.nameLength);
14395
+ var textDocumentSchema = z9.strictObject({
14699
14396
  name: documentNameSchema,
14700
- text: z10.string().min(1).refine((text) => new TextEncoder().encode(text).byteLength <= DOCUMENT_LIMITS.bytes, `larger than ${DOCUMENT_LIMITS.bytes} bytes`)
14397
+ text: z9.string().min(1).refine((text) => new TextEncoder().encode(text).byteLength <= DOCUMENT_LIMITS.bytes, `larger than ${DOCUMENT_LIMITS.bytes} bytes`)
14701
14398
  });
14702
- var pathDocumentSchema = z10.strictObject({
14703
- path: z10.string().trim().min(1),
14399
+ var pathDocumentSchema = z9.strictObject({
14400
+ path: z9.string().trim().min(1),
14704
14401
  name: documentNameSchema.optional()
14705
14402
  });
14706
- var urlDocumentSchema = z10.strictObject({
14403
+ var urlDocumentSchema = z9.strictObject({
14707
14404
  url: upstreamUrlSchema,
14708
14405
  name: documentNameSchema.optional()
14709
14406
  });
14710
- var dataDocumentSchema = z10.strictObject({
14407
+ var dataDocumentSchema = z9.strictObject({
14711
14408
  name: documentNameSchema,
14712
- data: z10.base64().refine((data) => base64Bytes(data) <= DOCUMENT_LIMITS.bytes, `larger than ${DOCUMENT_LIMITS.bytes} bytes`)
14409
+ data: z9.base64().refine((data) => base64Bytes(data) <= DOCUMENT_LIMITS.bytes, `larger than ${DOCUMENT_LIMITS.bytes} bytes`)
14713
14410
  });
14714
14411
  function documentName(document) {
14715
14412
  if (document.name !== undefined)
@@ -14724,7 +14421,7 @@ function documentName(document) {
14724
14421
  }
14725
14422
  }
14726
14423
  function documentsSchema(document) {
14727
- return z10.array(document).max(COLLECTION_LIMITS.documents).superRefine((documents, ctx) => {
14424
+ return z9.array(document).max(COLLECTION_LIMITS.documents).superRefine((documents, ctx) => {
14728
14425
  const names = documents.map(documentName);
14729
14426
  names.forEach((name, index) => {
14730
14427
  if (documentType(name) === undefined) {
@@ -14744,33 +14441,62 @@ function documentsSchema(document) {
14744
14441
  }).default([]);
14745
14442
  }
14746
14443
  function collectionSchema(document) {
14747
- return z10.strictObject({
14444
+ return z9.strictObject({
14748
14445
  name: nameSchema,
14749
14446
  displayName: displayNameSchema.default({}),
14750
- description: z10.string().trim().max(COLLECTION_LIMITS.descriptionLength).default(""),
14447
+ description: z9.string().trim().max(COLLECTION_LIMITS.descriptionLength).default(""),
14751
14448
  service: nameSchema.optional(),
14752
- citable: z10.boolean().default(true),
14449
+ citable: z9.boolean().default(true),
14753
14450
  documents: documentsSchema(document),
14754
14451
  audience: audienceSchema,
14755
14452
  overridable: overridable(["displayName", "description", "documents"])
14756
14453
  });
14757
14454
  }
14758
- var manifestDocumentSchema = z10.union([textDocumentSchema, pathDocumentSchema, urlDocumentSchema]);
14455
+ var manifestDocumentSchema = z9.union([textDocumentSchema, pathDocumentSchema, urlDocumentSchema]);
14759
14456
  var manifestCollectionSchema = collectionSchema(manifestDocumentSchema);
14760
- var resolvedCollectionSchema = collectionSchema(z10.union([textDocumentSchema, dataDocumentSchema, urlDocumentSchema]));
14457
+ var resolvedCollectionSchema = collectionSchema(z9.union([textDocumentSchema, dataDocumentSchema, urlDocumentSchema]));
14761
14458
 
14762
14459
  // ../../internal/contracts/src/manifest/mcp-servers.ts
14763
- import { z as z11 } from "zod";
14764
- var mcpToolNamesSchema = z11.array(z11.string().trim().min(1).max(128).regex(/^[^,]*$/, "a tool name holds no comma")).max(200);
14765
- var mcpSignInSchema = z11.strictObject({
14766
- connects: z11.enum(MCP_CONNECTION_OWNERS),
14767
- scope: z11.string().trim().min(1).max(1000).optional(),
14768
- credential: nameSchema.optional()
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()
14769
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
+ }
14770
14496
  function authorizationBesideSignIn(server) {
14771
14497
  return server.signIn ? server.headers.findIndex((entry) => entry.header.toLowerCase() === "authorization") : -1;
14772
14498
  }
14773
- var manifestMcpServerSchema = z11.strictObject({
14499
+ var manifestMcpServerSchema = z10.strictObject({
14774
14500
  name: identifierSchema,
14775
14501
  displayName: displayNameSchema.default({}),
14776
14502
  url: upstreamUrlSchema,
@@ -14789,12 +14515,20 @@ var manifestMcpServerSchema = z11.strictObject({
14789
14515
  message: "the sign-in's token travels under Authorization"
14790
14516
  });
14791
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
+ }
14792
14526
  });
14793
14527
 
14794
14528
  // ../../internal/contracts/src/manifest/services.ts
14795
- import { z as z12 } from "zod";
14796
- var localizedTextSchema = z12.record(localeSchema, z12.string().trim().min(1).max(SERVICE_LIMITS.descriptionLength));
14797
- var manifestServiceSchema = z12.strictObject({
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({
14798
14532
  name: nameSchema,
14799
14533
  displayName: displayNameSchema.default({}),
14800
14534
  description: localizedTextSchema,
@@ -14803,30 +14537,30 @@ var manifestServiceSchema = z12.strictObject({
14803
14537
  });
14804
14538
 
14805
14539
  // ../../internal/contracts/src/manifest/skills.ts
14806
- import { z as z13 } from "zod";
14807
- var manifestSkillSchema = z13.strictObject({
14540
+ import { z as z12 } from "zod";
14541
+ var manifestSkillSchema = z12.strictObject({
14808
14542
  name: nameSchema,
14809
14543
  displayName: displayNameSchema.default({}),
14810
- description: z13.string().trim().min(1).max(SKILL_LIMITS.descriptionLength),
14811
- body: z13.string().trim().min(1),
14544
+ description: z12.string().trim().min(1).max(SKILL_LIMITS.descriptionLength),
14545
+ body: z12.string().trim().min(1),
14812
14546
  service: nameSchema.optional(),
14813
14547
  audience: audienceSchema,
14814
14548
  overridable: overridable(["displayName", "description", "body"])
14815
14549
  });
14816
14550
 
14817
14551
  // ../../internal/contracts/src/manifest/tools.ts
14818
- import { z as z15 } from "zod";
14552
+ import { z as z14 } from "zod";
14819
14553
 
14820
14554
  // ../../internal/contracts/src/manifest/json-schema.ts
14821
- import { z as z14 } from "zod";
14822
- var fieldSourceSchema = z14.discriminatedUnion("kind", [
14555
+ import { z as z13 } from "zod";
14556
+ var fieldSourceSchema = z13.discriminatedUnion("kind", [
14823
14557
  variableSourceSchema,
14824
- z14.object({ kind: z14.literal("secret"), name: nameSchema }),
14825
- z14.object({
14826
- kind: z14.literal("constant"),
14827
- value: z14.union([z14.string().max(4000), z14.number(), z14.boolean()])
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()])
14828
14562
  }),
14829
- z14.object({ kind: z14.literal("endUserToken") })
14563
+ z13.object({ kind: z13.literal("endUserToken") })
14830
14564
  ]);
14831
14565
  function sourceFits(source, field) {
14832
14566
  switch (source.kind) {
@@ -14849,50 +14583,50 @@ function sourceFits(source, field) {
14849
14583
  }
14850
14584
  }
14851
14585
  }
14852
- var fieldTargetSchema = z14.discriminatedUnion("kind", [
14853
- z14.strictObject({
14854
- kind: z14.literal("body"),
14855
- contentType: z14.enum(["application/json", "text/plain"]).optional(),
14856
- style: z14.enum(QUERY_STYLES).optional(),
14857
- explode: z14.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()
14858
14592
  }),
14859
- z14.strictObject({
14860
- kind: z14.literal("query"),
14861
- name: z14.string().trim().min(1).max(120).optional(),
14862
- style: z14.enum(QUERY_STYLES).optional(),
14863
- explode: z14.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()
14864
14598
  }),
14865
- z14.strictObject({
14866
- kind: z14.literal("path"),
14867
- name: z14.string().trim().min(1).max(120).optional(),
14868
- style: z14.enum(PATH_STYLES).optional(),
14869
- explode: z14.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()
14870
14604
  }),
14871
- z14.strictObject({
14872
- kind: z14.literal("header"),
14605
+ z13.strictObject({
14606
+ kind: z13.literal("header"),
14873
14607
  name: headerNameSchema.optional(),
14874
- explode: z14.boolean().optional()
14608
+ explode: z13.boolean().optional()
14875
14609
  }),
14876
- z14.strictObject({ kind: z14.literal("cookie"), name: headerNameSchema.optional() })
14610
+ z13.strictObject({ kind: z13.literal("cookie"), name: headerNameSchema.optional() })
14877
14611
  ]);
14878
- var schemaTypeSchema = z14.enum([...SCALAR_TYPES, "object", "array"]);
14879
- var propertyNameSchema = z14.string().min(1).max(FIELD_LIMITS.nameLength).refine((name) => name === name.trim(), "no surrounding spaces");
14880
- var propertyOrderSchema = z14.array(z14.string()).refine((names) => new Set(names).size === names.length, "a name repeats").optional();
14881
- var countSchema = z14.number().int().min(0).optional();
14882
- var valueKeywordsSchema = z14.strictObject({
14883
- pattern: z14.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(),
14884
14618
  minLength: countSchema,
14885
14619
  maxLength: countSchema,
14886
- format: z14.string().trim().min(1).max(100).optional(),
14887
- minimum: z14.number().optional(),
14888
- maximum: z14.number().optional(),
14889
- exclusiveMinimum: z14.number().optional(),
14890
- exclusiveMaximum: z14.number().optional(),
14891
- multipleOf: z14.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(),
14892
14626
  minItems: countSchema,
14893
14627
  maxItems: countSchema,
14894
- uniqueItems: z14.boolean().optional(),
14895
- const: z14.union([z14.string().max(4000), z14.number(), z14.boolean()]).optional()
14628
+ uniqueItems: z13.boolean().optional(),
14629
+ const: z13.union([z13.string().max(4000), z13.number(), z13.boolean()]).optional()
14896
14630
  });
14897
14631
  var NUMERIC_TYPES = ["number", "integer"];
14898
14632
  var VALUE_KEYWORD_TYPES = {
@@ -14910,18 +14644,18 @@ var VALUE_KEYWORD_TYPES = {
14910
14644
  uniqueItems: ["array"],
14911
14645
  const: SCALAR_TYPES
14912
14646
  };
14913
- var ruleTypeSchema = z14.enum([...SCALAR_TYPES, "object", "array", "null"]);
14914
- var conditionSchema = z14.lazy(() => z14.strictObject({
14915
- type: z14.union([ruleTypeSchema, z14.array(ruleTypeSchema).min(1)]).optional(),
14916
- enum: z14.array(z14.union([z14.string(), z14.number(), z14.boolean(), z14.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(),
14917
14651
  ...valueKeywordsSchema.shape,
14918
- required: z14.array(z14.string()).optional(),
14919
- properties: z14.record(z14.string(), conditionSchema).optional(),
14652
+ required: z13.array(z13.string()).optional(),
14653
+ properties: z13.record(z13.string(), conditionSchema).optional(),
14920
14654
  items: conditionSchema.optional(),
14921
14655
  ...objectRulesSchema.shape
14922
14656
  })).meta({ id: "SchemaCondition" });
14923
- var conditionsSchema = z14.array(conditionSchema).min(1).meta({ id: "SchemaConditions" });
14924
- var objectRulesSchema = z14.strictObject({
14657
+ var conditionsSchema = z13.array(conditionSchema).min(1).meta({ id: "SchemaConditions" });
14658
+ var objectRulesSchema = z13.strictObject({
14925
14659
  anyOf: conditionsSchema.optional(),
14926
14660
  oneOf: conditionsSchema.optional(),
14927
14661
  allOf: conditionsSchema.optional(),
@@ -14929,8 +14663,8 @@ var objectRulesSchema = z14.strictObject({
14929
14663
  if: conditionSchema.optional(),
14930
14664
  then: conditionSchema.optional(),
14931
14665
  else: conditionSchema.optional(),
14932
- dependentRequired: z14.record(z14.string(), z14.array(z14.string())).optional(),
14933
- dependentSchemas: z14.record(z14.string(), conditionSchema).optional(),
14666
+ dependentRequired: z13.record(z13.string(), z13.array(z13.string())).optional(),
14667
+ dependentSchemas: z13.record(z13.string(), conditionSchema).optional(),
14934
14668
  minProperties: countSchema,
14935
14669
  maxProperties: countSchema
14936
14670
  });
@@ -14967,32 +14701,32 @@ function ruleNames(rule) {
14967
14701
  ...Object.keys(keyed(node.dependentSchemas))
14968
14702
  ]).filter((name) => typeof name === "string");
14969
14703
  }
14970
- var itemTypeSchema = z14.enum([...SCALAR_TYPES, "object"]);
14971
- var enumSchema = z14.array(z14.union([z14.string().trim().min(1), z14.null()])).min(1).max(FIELD_LIMITS.enumValues + 1).optional();
14972
- var itemsSchema = z14.lazy(() => z14.strictObject({
14973
- type: z14.union([itemTypeSchema, z14.tuple([itemTypeSchema, z14.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")])]),
14974
14708
  enum: enumSchema,
14975
- properties: z14.record(propertyNameSchema, schemaPropertySchema).optional(),
14976
- required: z14.array(z14.string()).optional(),
14709
+ properties: z13.record(propertyNameSchema, schemaPropertySchema).optional(),
14710
+ required: z13.array(z13.string()).optional(),
14977
14711
  "x-order": propertyOrderSchema,
14978
14712
  ...valueKeywordsSchema.shape,
14979
14713
  ...objectRulesSchema.shape
14980
- }));
14981
- var schemaPropertySchema = z14.lazy(() => z14.strictObject({
14982
- type: z14.union([schemaTypeSchema, z14.tuple([schemaTypeSchema, z14.literal("null")])]),
14983
- description: z14.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(),
14984
14718
  enum: enumSchema,
14985
- properties: z14.record(propertyNameSchema, schemaPropertySchema).optional(),
14986
- required: z14.array(z14.string()).optional(),
14719
+ properties: z13.record(propertyNameSchema, schemaPropertySchema).optional(),
14720
+ required: z13.array(z13.string()).optional(),
14987
14721
  "x-order": propertyOrderSchema,
14988
14722
  items: itemsSchema.optional(),
14989
- "x-sensitive": z14.boolean().optional(),
14723
+ "x-sensitive": z13.boolean().optional(),
14990
14724
  "x-displayName": displayNameSchema.optional(),
14991
14725
  "x-source": fieldSourceSchema.optional(),
14992
14726
  "x-target": fieldTargetSchema.optional(),
14993
14727
  ...valueKeywordsSchema.shape,
14994
14728
  ...objectRulesSchema.shape
14995
- }));
14729
+ })).meta({ id: "SchemaProperty" });
14996
14730
  function typeOf(node) {
14997
14731
  return [node.type].flat()[0];
14998
14732
  }
@@ -15095,10 +14829,10 @@ function heldByRows(node, context, path, bindings) {
15095
14829
  }
15096
14830
  }
15097
14831
  function objectJsonSchemaOf(bindings) {
15098
- return z14.strictObject({
15099
- type: z14.literal("object"),
15100
- properties: z14.record(propertyNameSchema, schemaPropertySchema).optional(),
15101
- required: z14.array(z14.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(),
15102
14836
  "x-order": propertyOrderSchema,
15103
14837
  ...objectRulesSchema.shape
15104
14838
  }).superRefine((schema, context) => {
@@ -15120,29 +14854,32 @@ var objectSchema = objectJsonSchemaOf();
15120
14854
  var EMPTY_OBJECT = { type: "object" };
15121
14855
 
15122
14856
  // ../../internal/contracts/src/manifest/tools.ts
15123
- var toolTagsSchema = z15.array(z15.string().trim().min(1).max(60).regex(/^[^,]*$/, "a tag holds no comma")).max(20);
15124
- var embedOriginSchema = tlsUrlSchema.transform((value) => new URL(value).origin);
15125
- var soapActionSchema = z15.string().regex(/^[^"\\\u0000-\u001f\u007f]*$/);
15126
- var envelopeTemplateSchema = z15.string().refine((template) => template.trim().length > 0);
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);
15127
14861
  var toolConfigByType = {
15128
- http: z15.object({
15129
- responseWrap: z15.enum(RESPONSE_WRAPS).optional(),
15130
- requestMediaType: z15.enum(FORM_MEDIA_TYPES).optional(),
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(),
15131
14865
  resultPath: jsonPointerSchema.optional()
15132
14866
  }),
15133
- embedded: z15.object({ embedOrigin: embedOriginSchema, surface: z15.enum(TOOL_SURFACES) }),
15134
- soap: z15.object({
15135
- soapVersion: z15.enum(SOAP_VERSIONS),
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" }),
15136
14873
  soapAction: soapActionSchema,
15137
14874
  envelopeTemplate: envelopeTemplateSchema,
15138
- tokenCall: z15.object({
14875
+ tokenCall: z14.object({
15139
14876
  envelopeTemplate: envelopeTemplateSchema,
15140
14877
  soapAction: soapActionSchema,
15141
- tokenPath: z15.string().trim().min(1)
14878
+ tokenPath: z14.string().trim().min(1)
15142
14879
  }).optional()
15143
14880
  }),
15144
- native: z15.object({}),
15145
- client: z15.object({})
14881
+ native: z14.object({}),
14882
+ client: z14.object({})
15146
14883
  };
15147
14884
  var TOOL_TYPES = {
15148
14885
  http: {
@@ -15216,23 +14953,23 @@ var TOOL_OVERRIDABLES = [
15216
14953
  var CALLED_TOOL_OVERRIDABLES = [...TOOL_OVERRIDABLES, "headers"];
15217
14954
  var { tool: toolBounds } = SETTING_BOUNDS;
15218
14955
  var { tool: toolRateLimits } = RATE_LIMITS;
15219
- var toolBaseSchema = z15.strictObject({
14956
+ var toolBaseSchema = z14.strictObject({
15220
14957
  ...serverToolSchema.pick({ name: true, description: true }).shape,
15221
14958
  displayName: displayNameSchema.default({}),
15222
14959
  inputSchema: toolInputSchemaOf("client"),
15223
14960
  outputSchema: objectSchema.default(EMPTY_OBJECT),
15224
14961
  timeoutMs: setting(toolBounds.timeoutMs),
15225
14962
  maxResponseBytes: setting(toolBounds.maxResponseBytes),
15226
- rateLimits: z15.strictObject({
15227
- allUsers: z15.strictObject({
14963
+ rateLimits: z14.strictObject({
14964
+ allUsers: z14.strictObject({
15228
14965
  callsPerMinute: rateLimit(toolRateLimits.callsPerMinute, "allUsers")
15229
14966
  }).prefault({}),
15230
- perUser: z15.strictObject({
14967
+ perUser: z14.strictObject({
15231
14968
  callsPerMinute: rateLimit(toolRateLimits.callsPerMinute, "perUser")
15232
14969
  }).prefault({})
15233
14970
  }).prefault({}),
15234
- projectOutput: z15.boolean().default(false),
15235
- pinned: z15.boolean().default(false),
14971
+ projectOutput: z14.boolean().default(false),
14972
+ pinned: z14.boolean().default(false),
15236
14973
  tags: toolTagsSchema.default([]),
15237
14974
  audience: audienceSchema,
15238
14975
  overridable: overridable(TOOL_OVERRIDABLES)
@@ -15240,212 +14977,599 @@ var toolBaseSchema = z15.strictObject({
15240
14977
  var calledToolSchema = toolBaseSchema.extend({
15241
14978
  url: upstreamUrlSchema.refine(confinesEndpointParams, "a {parameter} outside the path or query"),
15242
14979
  headers: headersSchema,
15243
- requiresApproval: z15.boolean().default(false),
14980
+ requiresApproval: z14.boolean().default(false),
15244
14981
  overridable: overridable(CALLED_TOOL_OVERRIDABLES)
15245
14982
  });
15246
- var manifestToolSchema = z15.discriminatedUnion("type", [
14983
+ var manifestToolSchema = z14.discriminatedUnion("type", [
15247
14984
  calledToolSchema.extend({
15248
- type: z15.literal("http"),
14985
+ type: z14.literal("http"),
15249
14986
  inputSchema: toolInputSchemaOf("http"),
15250
- method: z15.enum(TOOL_METHODS),
15251
- readOnly: z15.boolean(),
14987
+ method: z14.enum(TOOL_METHODS),
14988
+ readOnly: z14.boolean(),
15252
14989
  ...toolConfigByType.http.shape
15253
14990
  }),
15254
14991
  calledToolSchema.omit({ requiresApproval: true }).extend({
15255
- type: z15.literal("embedded"),
14992
+ type: z14.literal("embedded"),
15256
14993
  inputSchema: toolInputSchemaOf("embedded"),
15257
- method: z15.enum(TOOL_METHODS),
14994
+ method: z14.enum(TOOL_METHODS),
15258
14995
  ...toolConfigByType.embedded.shape
15259
14996
  }),
15260
14997
  calledToolSchema.extend({
15261
- type: z15.literal("soap"),
14998
+ type: z14.literal("soap"),
15262
14999
  inputSchema: toolInputSchemaOf("soap"),
15263
- readOnly: z15.boolean(),
15000
+ readOnly: z14.boolean(),
15264
15001
  ...toolConfigByType.soap.shape
15265
15002
  }),
15266
- toolBaseSchema.extend({ type: z15.literal("client") })
15003
+ toolBaseSchema.extend({ type: z14.literal("client") })
15267
15004
  ]).superRefine((tool, context) => refuseBlockedApprovalTitle(tool, context, []));
15268
- var toolNamesSchema = z15.array(serverToolSchema.shape.name).max(500).default([]);
15269
- var manifestOpenApiSchema = z15.strictObject({
15005
+ var toolNamesSchema = z14.array(serverToolSchema.shape.name).max(500).default([]);
15006
+ var manifestOpenApiSchema = z14.strictObject({
15007
+ name: nameSchema,
15008
+ url: upstreamUrlSchema,
15009
+ headers: headersSchema,
15010
+ resultPath: jsonPointerSchema.optional(),
15011
+ pinned: toolNamesSchema,
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"),
15013
+ audience: audienceSchema,
15014
+ overridable: overridable(CALLED_TOOL_OVERRIDABLES)
15015
+ });
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
+ }
15030
+ }
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",
15072
+ trigger.fireCredential && "fireCredential",
15073
+ threadFromPayload(trigger.threadPolicy) && "threadPolicy"
15074
+ ].filter((issue) => issue !== false);
15075
+ }
15076
+ var manifestTriggerSchema = z16.strictObject({
15077
+ name: nameSchema,
15078
+ displayName: displayNameSchema.default({}),
15079
+ description: z16.string().trim().min(1).max(TRIGGER_LIMITS.descriptionLength),
15080
+ inputSchema: objectSchema.default(EMPTY_OBJECT),
15081
+ outputSchema: objectSchema.refine((schema) => Object.keys(schema.properties ?? {}).length > 0, "declares a property; leave it out for a free-text answer").optional(),
15082
+ instructions: z16.string().trim().min(1).max(TRIGGER_LIMITS.instructionsLength),
15083
+ threadPolicy: triggerThreadPolicySchema.default({ policy: "single" }),
15084
+ whileBusy: z16.enum(WHILE_BUSY).default("queue"),
15085
+ budgetPerDay: z16.number().int().positive().optional(),
15086
+ disableAfterFailures: setting(SETTING_BOUNDS.trigger.disableAfterFailures),
15087
+ credential: nameSchema.optional(),
15088
+ fireCredential: nameSchema.optional(),
15089
+ model: modelSchema.optional(),
15090
+ schedule: triggerScheduleSchema.optional(),
15091
+ audience: audienceSchema,
15092
+ overridable: overridable([
15093
+ "displayName",
15094
+ "description",
15095
+ "instructions",
15096
+ "threadPolicy",
15097
+ "whileBusy",
15098
+ "budgetPerDay",
15099
+ "disableAfterFailures",
15100
+ "model",
15101
+ "schedule"
15102
+ ])
15103
+ }).superRefine((trigger, context) => {
15104
+ const issues = {
15105
+ input: [
15106
+ "inputSchema",
15107
+ "a scheduled trigger fires with no payload, so it takes no input fields"
15108
+ ],
15109
+ fireCredential: ["fireCredential", "a scheduled trigger has no caller to fire it"],
15110
+ threadPolicy: [
15111
+ "threadPolicy",
15112
+ "a scheduled trigger has no payload to read its thread from"
15113
+ ]
15114
+ };
15115
+ for (const issue of scheduledTriggerIssues({
15116
+ scheduled: trigger.schedule !== undefined,
15117
+ inputFields: Object.keys(trigger.inputSchema.properties ?? {}).length,
15118
+ fireCredential: trigger.fireCredential !== undefined,
15119
+ threadPolicy: trigger.threadPolicy
15120
+ })) {
15121
+ const [path, message] = issues[issue];
15122
+ context.addIssue({ code: "custom", path: [path], message });
15123
+ }
15124
+ });
15125
+
15126
+ // ../../internal/contracts/src/manifest/webhooks.ts
15127
+ import { z as z17 } from "zod";
15128
+ var manifestWebhookSchema = z17.strictObject({
15270
15129
  name: nameSchema,
15130
+ displayName: displayNameSchema.default({}),
15131
+ description: z17.string().trim().max(500).default(""),
15132
+ event: z17.enum(SERVER_EVENTS),
15271
15133
  url: upstreamUrlSchema,
15272
- headers: headersSchema,
15273
- resultPath: jsonPointerSchema.optional(),
15274
- pinned: toolNamesSchema,
15275
- approval: z15.strictObject({ never: toolNamesSchema, always: toolNamesSchema }).prefault({}).refine(({ never, always }) => !never.some((name) => always.includes(name)), "a tool both never and always needs approval"),
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),
15276
15136
  audience: audienceSchema,
15277
- overridable: overridable(CALLED_TOOL_OVERRIDABLES)
15137
+ overridable: overridable(["displayName", "description", "timeoutMs", "headers"])
15278
15138
  });
15279
15139
 
15280
- // ../../internal/contracts/src/manifest/triggers.ts
15281
- import { z as z17 } from "zod";
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)
15156
+ });
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
+ };
15282
15477
 
15283
- // ../../internal/contracts/src/schedule/index.ts
15284
- var import_cron_parser = __toESM(require_dist(), 1);
15285
- import { z as z16 } from "zod";
15286
- function isTimeZone(timeZone) {
15287
- try {
15288
- new Intl.DateTimeFormat("en", { timeZone });
15289
- return true;
15290
- } catch {
15291
- return false;
15292
- }
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(".", "/")}`;
15293
15483
  }
15294
- function isCron(cron) {
15295
- if (cron.split(/\s+/).length !== 5 || /\bH\b/i.test(cron))
15296
- return false;
15297
- try {
15298
- import_cron_parser.CronExpressionParser.parse(cron);
15299
- return true;
15300
- } catch {
15301
- return false;
15302
- }
15484
+ function isScalar(value) {
15485
+ return value === null || ["string", "number", "boolean"].includes(typeof value);
15303
15486
  }
15304
- function triggerScheduleSchemaWith(messages) {
15305
- return z16.object({
15306
- cron: z16.string().trim().refine(isCron, { error: messages.cron }),
15307
- timeZone: z16.string().trim().refine(isTimeZone, { error: messages.timeZone })
15308
- });
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));
15499
+ }
15500
+ const encoded = params.toString();
15501
+ return encoded === "" ? "" : `?${encoded}`;
15309
15502
  }
15310
- var triggerScheduleSchema = triggerScheduleSchemaWith({
15311
- cron: () => "is not a cron of five fields: minute, hour, day of month, month, day of week",
15312
- timeZone: () => "is not an IANA time zone, such as Asia/Dubai"
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)
15313
15508
  });
15314
15509
 
15315
- // ../../internal/contracts/src/manifest/triggers.ts
15316
- var triggerThreadPolicySchema = z17.discriminatedUnion("policy", [
15317
- z17.object({ policy: z17.literal("single") }),
15318
- z17.object({ policy: z17.literal("per-input") }),
15319
- z17.object({ policy: z17.literal("ephemeral") }),
15320
- z17.object({ policy: z17.literal("keyed"), key: jsonPointerSchema }),
15321
- z17.object({
15322
- policy: z17.literal("thread"),
15323
- key: jsonPointerSchema,
15324
- wake: z17.boolean()
15325
- })
15326
- ]);
15327
- function threadFromPayload(policy) {
15328
- return policy.policy === "keyed" || policy.policy === "thread";
15329
- }
15330
- function scheduledTriggerIssues(trigger) {
15331
- if (!trigger.scheduled)
15332
- return [];
15333
- return [
15334
- trigger.inputFields > 0 && "input",
15335
- trigger.fireCredential && "fireCredential",
15336
- threadFromPayload(trigger.threadPolicy) && "threadPolicy"
15337
- ].filter((issue) => issue !== false);
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";
15522
+ }
15338
15523
  }
15339
- var manifestTriggerSchema = z17.strictObject({
15340
- name: nameSchema,
15341
- displayName: displayNameSchema.default({}),
15342
- description: z17.string().trim().min(1).max(TRIGGER_LIMITS.descriptionLength),
15343
- inputSchema: objectSchema.default(EMPTY_OBJECT),
15344
- outputSchema: objectSchema.refine((schema) => Object.keys(schema.properties ?? {}).length > 0, "declares a property; leave it out for a free-text answer").optional(),
15345
- instructions: z17.string().trim().min(1).max(TRIGGER_LIMITS.instructionsLength),
15346
- threadPolicy: triggerThreadPolicySchema.default({ policy: "single" }),
15347
- whileBusy: z17.enum(WHILE_BUSY).default("queue"),
15348
- budgetPerDay: z17.number().int().positive().optional(),
15349
- disableAfterFailures: setting(SETTING_BOUNDS.trigger.disableAfterFailures),
15350
- credential: nameSchema.optional(),
15351
- fireCredential: nameSchema.optional(),
15352
- model: modelSchema.optional(),
15353
- schedule: triggerScheduleSchema.optional(),
15354
- audience: audienceSchema,
15355
- overridable: overridable([
15356
- "displayName",
15357
- "description",
15358
- "instructions",
15359
- "threadPolicy",
15360
- "whileBusy",
15361
- "budgetPerDay",
15362
- "disableAfterFailures",
15363
- "model",
15364
- "schedule"
15365
- ])
15366
- }).superRefine((trigger, context) => {
15367
- const issues = {
15368
- input: [
15369
- "inputSchema",
15370
- "a scheduled trigger fires with no payload, so it takes no input fields"
15371
- ],
15372
- fireCredential: ["fireCredential", "a scheduled trigger has no caller to fire it"],
15373
- threadPolicy: [
15374
- "threadPolicy",
15375
- "a scheduled trigger has no payload to read its thread from"
15376
- ]
15377
- };
15378
- for (const issue of scheduledTriggerIssues({
15379
- scheduled: trigger.schedule !== undefined,
15380
- inputFields: Object.keys(trigger.inputSchema.properties ?? {}).length,
15381
- fireCredential: trigger.fireCredential !== undefined,
15382
- threadPolicy: trigger.threadPolicy
15383
- })) {
15384
- const [path, message] = issues[issue];
15385
- context.addIssue({ code: "custom", path: [path], message });
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
15543
+ });
15544
+ if (response.ok) {
15545
+ const output = await response.json();
15546
+ return output;
15386
15547
  }
15387
- });
15388
-
15389
- // ../../internal/contracts/src/manifest/webhooks.ts
15390
- import { z as z18 } from "zod";
15391
- var manifestWebhookSchema = z18.strictObject({
15392
- name: nameSchema,
15393
- displayName: displayNameSchema.default({}),
15394
- description: z18.string().trim().max(500).default(""),
15395
- event: z18.enum(SERVER_EVENTS),
15396
- url: upstreamUrlSchema,
15397
- headers: declaredHeadersSchema(presentedHeaderSchema.refine((name) => name.toLowerCase() !== EVENT_HEADER.toLowerCase(), "the header that names the event"), runlessHeaderSourceSchema),
15398
- timeoutMs: setting(SETTING_BOUNDS.webhook.timeoutMs),
15399
- audience: audienceSchema,
15400
- overridable: overridable(["displayName", "description", "timeoutMs", "headers"])
15401
- });
15402
-
15403
- // ../../internal/contracts/src/manifest/manifest.ts
15404
- function listOf(entry) {
15405
- return z19.array(entry).refine((entries) => new Set(entries.map((value) => value.name)).size === entries.length, "a name repeats").default([]);
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);
15406
15551
  }
15407
- var manifestSchema = z19.strictObject({
15408
- id: nameSchema,
15409
- agents: listOf(manifestAgentSchema),
15410
- tools: listOf(manifestToolSchema),
15411
- openapi: listOf(manifestOpenApiSchema),
15412
- services: listOf(manifestServiceSchema),
15413
- skills: listOf(manifestSkillSchema),
15414
- triggers: listOf(manifestTriggerSchema),
15415
- datasetHosts: listOf(manifestDatasetHostSchema),
15416
- mcpServers: listOf(manifestMcpServerSchema),
15417
- webhooks: listOf(manifestWebhookSchema),
15418
- collections: listOf(manifestCollectionSchema)
15419
- });
15420
- var resolvedManifestSchema = manifestSchema.extend({
15421
- collections: listOf(resolvedCollectionSchema)
15422
- });
15423
- var manifestKindSchema = z19.enum(MANIFEST_KINDS);
15424
- var namesByKindSchema = z19.record(manifestKindSchema, z19.array(z19.string()));
15425
- var manifestChangesSchema = z19.object({
15426
- create: namesByKindSchema,
15427
- update: namesByKindSchema,
15428
- delete: namesByKindSchema
15429
- });
15430
- var manifestConflictSchema = z19.strictObject({
15431
- kind: manifestKindSchema,
15432
- name: z19.string(),
15433
- field: z19.string(),
15434
- key: z19.string().optional()
15435
- });
15436
- var conflictSideSchema = z19.enum(["live", "manifest"]);
15437
- var manifestApplyInputSchema = resolvedManifestSchema.extend({
15438
- prefer: conflictSideSchema.optional(),
15439
- resolutions: z19.array(manifestConflictSchema.extend({ keep: conflictSideSchema })).default([])
15440
- });
15441
- var manifestPreviewSchema = manifestChangesSchema.extend({
15442
- conflicts: z19.array(manifestConflictSchema)
15443
- });
15444
- var appliedManifestSchema = manifestChangesSchema.extend({
15445
- triggerSecrets: z19.record(z19.string(), z19.string())
15446
- });
15447
- function defineManifest(manifest) {
15448
- return manifest;
15552
+ function createManagementClient(options) {
15553
+ if (!upstreamUrlSchema.safeParse(options.url).success) {
15554
+ throw new Error("createManagementClient needs an absolute http or https url");
15555
+ }
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
15570
+ });
15571
+ }
15572
+ return client;
15449
15573
  }
15450
15574
  export {
15451
15575
  CortexError2 as CortexError,
@@ -15455,5 +15579,6 @@ export {
15455
15579
  createTriggerClient,
15456
15580
  defineDatasetHost,
15457
15581
  defineManifest,
15458
- defineServer
15582
+ defineServer,
15583
+ unverifiedJwtSubject
15459
15584
  };