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