@m6d/cortex 0.1.0 → 0.3.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
@@ -9,8 +9,10 @@ import {
9
9
  datasetIdentifierSchema,
10
10
  datasetRequestSchema,
11
11
  envelopeOf,
12
- errorEnvelope
13
- } from "./index-ncc61ew6.js";
12
+ errorEnvelope,
13
+ isRecord,
14
+ unescapePointerToken
15
+ } from "./index-dck60t84.js";
14
16
 
15
17
  // src/server.ts
16
18
  import { createHash, timingSafeEqual } from "node:crypto";
@@ -7034,6 +7036,7 @@ var DEFAULT_MEDIA_FORMS = [
7034
7036
  "map"
7035
7037
  ];
7036
7038
  var ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024;
7039
+ var APPROVAL_TITLE_FIELD = "approvalTitle";
7037
7040
 
7038
7041
  // ../../internal/contracts/src/server/index.ts
7039
7042
  var END_USER_TOKEN_HEADER = "X-End-User-Token";
@@ -7082,17 +7085,16 @@ var BUILT_IN_TOOL_NAMES = [
7082
7085
  "queryDataset",
7083
7086
  "readAttachment",
7084
7087
  "readReport",
7085
- "searchKnowledge",
7086
- "searchServices",
7088
+ "searchRegistries",
7087
7089
  "searchThreadHistory",
7088
- "searchTools",
7089
7090
  REQUEST_LOCATION_TOOL,
7090
7091
  TRIGGER_ANSWER_TOOL_NAME
7091
7092
  ];
7092
7093
  function isBuiltInToolName(name) {
7093
7094
  return BUILT_IN_TOOL_NAMES.some((builtIn) => builtIn === name);
7094
7095
  }
7095
- var declaredToolNameSchema = z2.string().regex(IDENTIFIER_PATTERN).max(64).refine((name) => !isBuiltInToolName(name), "the name of a built-in tool");
7096
+ var TOOL_NAME_MAX_LENGTH = 64;
7097
+ var declaredToolNameSchema = z2.string().regex(IDENTIFIER_PATTERN).max(TOOL_NAME_MAX_LENGTH).refine((name) => !isBuiltInToolName(name), "the name of a built-in tool");
7096
7098
  var jsonSchemaSchema = z2.record(z2.string(), z2.unknown());
7097
7099
  var serverVariableSchema = z2.object({
7098
7100
  name: z2.string().regex(IDENTIFIER_PATTERN).max(64).refine((name) => !BUILT_IN_VARIABLES.some((builtIn) => builtIn.name === name), "the name of a built-in variable"),
@@ -7106,7 +7108,7 @@ var serverToolSchema = z2.object({
7106
7108
  inputSchema: jsonSchemaSchema.refine((schema) => schema.type === "object", "a tool's input is an object"),
7107
7109
  outputSchema: jsonSchemaSchema.optional(),
7108
7110
  readOnly: z2.boolean(),
7109
- approval: z2.record(localeSchema, z2.string().trim().min(1).max(500)).optional()
7111
+ requiresApproval: z2.boolean().optional()
7110
7112
  });
7111
7113
  var SERVER_EVENTS = ["approval_requested"];
7112
7114
  var EVENT_HEADER = "X-Cortex-Event";
@@ -7122,13 +7124,74 @@ var approvalRequestedEventSchema = z2.object({
7122
7124
  approvals: z2.array(pendingApprovalSchema.partial({ input: true })),
7123
7125
  occurredAt: z2.iso.datetime()
7124
7126
  });
7127
+ function pointerKey(token) {
7128
+ try {
7129
+ return unescapePointerToken(decodeURIComponent(token));
7130
+ } catch {
7131
+ return;
7132
+ }
7133
+ }
7134
+ function pointedAt(root, ref) {
7135
+ if (!ref.startsWith("#"))
7136
+ return;
7137
+ let node = root;
7138
+ for (const token of ref.slice(1).split("/").slice(1)) {
7139
+ const key = pointerKey(token);
7140
+ node = key !== undefined && (isRecord(node) || Array.isArray(node)) ? new Map(Object.entries(node)).get(key) : undefined;
7141
+ }
7142
+ return node;
7143
+ }
7144
+ function namesApprovalTitle(node) {
7145
+ const required = node.required;
7146
+ return isRecord(node.properties) && Object.hasOwn(node.properties, APPROVAL_TITLE_FIELD) || Array.isArray(required) && required.includes(APPROVAL_TITLE_FIELD);
7147
+ }
7148
+ function sameObjectSchemas(node, root) {
7149
+ const schemas = typeof node.$ref === "string" ? [pointedAt(root, node.$ref)] : [];
7150
+ for (const keyword of ["allOf", "anyOf", "oneOf"]) {
7151
+ const members = node[keyword];
7152
+ if (!Array.isArray(members))
7153
+ continue;
7154
+ const listed = members;
7155
+ schemas.push(...listed);
7156
+ }
7157
+ return schemas;
7158
+ }
7159
+ function sameObjectNodes(inputSchema) {
7160
+ const nodes = new Array;
7161
+ const pending = [inputSchema];
7162
+ while (pending.length > 0) {
7163
+ const node = pending.pop();
7164
+ if (!isRecord(node) || nodes.includes(node))
7165
+ continue;
7166
+ nodes.push(node);
7167
+ pending.push(...sameObjectSchemas(node, inputSchema));
7168
+ }
7169
+ return nodes;
7170
+ }
7171
+ function closed(node) {
7172
+ return node.additionalProperties === false || node.unevaluatedProperties === false;
7173
+ }
7174
+ function blocksApprovalTitle(inputSchema) {
7175
+ return sameObjectNodes(inputSchema).some((node) => namesApprovalTitle(node) || node !== inputSchema && closed(node));
7176
+ }
7177
+ function refuseBlockedApprovalTitle(tool, context, path) {
7178
+ if (!tool.requiresApproval || !blocksApprovalTitle(tool.inputSchema))
7179
+ return;
7180
+ context.addIssue({
7181
+ code: "custom",
7182
+ path: [...path, "inputSchema"],
7183
+ message: `a tool that needs approval cannot take an input named ${APPROVAL_TITLE_FIELD}, nor one a closed sub-schema describes: Cortex adds the approval card's title to it`
7184
+ });
7185
+ }
7125
7186
  function uniqueNames(entries) {
7126
7187
  return new Set(entries.map((entry) => entry.name)).size === entries.length;
7127
7188
  }
7128
7189
  var serverManifestSchema = z2.object({
7129
7190
  version: z2.string().min(1).max(128),
7130
7191
  variables: z2.array(serverVariableSchema).max(100).refine(uniqueNames, "variable names repeat"),
7131
- tools: z2.array(serverToolSchema).max(500).refine(uniqueNames, "tool names repeat"),
7192
+ tools: z2.array(serverToolSchema).max(500).refine(uniqueNames, "tool names repeat").superRefine((tools, context) => {
7193
+ tools.forEach((tool, index) => refuseBlockedApprovalTitle(tool, context, [index]));
7194
+ }),
7132
7195
  verify: z2.boolean(),
7133
7196
  events: z2.array(z2.enum(SERVER_EVENTS))
7134
7197
  });
@@ -7202,7 +7265,7 @@ function manifestOf(options) {
7202
7265
  }),
7203
7266
  ...tool.output ? { outputSchema: z3.toJSONSchema(tool.output, { io: "output" }) } : {},
7204
7267
  readOnly: tool.readOnly,
7205
- ...tool.approval ? { approval: tool.approval } : {}
7268
+ ...tool.requiresApproval ? { requiresApproval: true } : {}
7206
7269
  })),
7207
7270
  verify: options.verify !== undefined,
7208
7271
  events: SERVER_EVENTS.filter((event) => options.events?.[event])
@@ -7466,7 +7529,10 @@ function canCarrySecret(url, allowed = egressAllowedHosts()) {
7466
7529
  // ../../internal/contracts/src/manifest/index.ts
7467
7530
  var TOOL_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
7468
7531
  var RESPONSE_WRAPS = ["items", "value"];
7532
+ var QUERY_STYLES = ["form", "spaceDelimited", "pipeDelimited", "deepObject"];
7533
+ var PATH_STYLES = ["simple", "label", "matrix"];
7469
7534
  var SOAP_VERSIONS = ["1.1", "1.2"];
7535
+ var jsonPointerSchema = z4.string().regex(/^\//).max(256);
7470
7536
  var SETTING_BOUNDS = {
7471
7537
  tool: {
7472
7538
  timeoutMs: { min: 100, max: 120000, default: 30000 },
@@ -7497,6 +7563,9 @@ var SETTING_BOUNDS = {
7497
7563
  function setting({ min, max, default: fallback }) {
7498
7564
  return z4.number().int().min(min).max(max).default(fallback);
7499
7565
  }
7566
+ function overridable(fields) {
7567
+ return z4.array(z4.enum(fields)).refine(uniqueBy((field) => field), "a field repeats").default([]);
7568
+ }
7500
7569
  var SLUG_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
7501
7570
  var slugSchema = z4.string().regex(SLUG_PATTERN).max(64);
7502
7571
  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])?)*$/;
@@ -7514,8 +7583,16 @@ var tlsUrlSchema = z4.url().refine((url) => canCarrySecret(url, []));
7514
7583
  var embedOriginSchema = tlsUrlSchema.transform((value) => new URL(value).origin);
7515
7584
  var soapActionSchema = z4.string().regex(/^[^"\\\u0000-\u001f\u007f]*$/);
7516
7585
  var envelopeTemplateSchema = z4.string().refine((template) => template.trim().length > 0);
7586
+ var FORM_MEDIA_TYPES = [
7587
+ "application/x-www-form-urlencoded",
7588
+ "multipart/form-data"
7589
+ ];
7517
7590
  var toolConfigByType = {
7518
- http: z4.object({ responseWrap: z4.enum(RESPONSE_WRAPS).optional() }),
7591
+ http: z4.object({
7592
+ responseWrap: z4.enum(RESPONSE_WRAPS).optional(),
7593
+ requestMediaType: z4.enum(FORM_MEDIA_TYPES).optional(),
7594
+ resultPath: jsonPointerSchema.optional()
7595
+ }),
7519
7596
  embedded: z4.object({ embedOrigin: embedOriginSchema, surface: z4.enum(TOOL_SURFACES) }),
7520
7597
  soap: z4.object({
7521
7598
  soapVersion: z4.enum(SOAP_VERSIONS),
@@ -7614,11 +7691,30 @@ function sourceFits(source, field) {
7614
7691
  }
7615
7692
  }
7616
7693
  var fieldTargetSchema = z4.discriminatedUnion("kind", [
7617
- z4.object({ kind: z4.literal("body") }),
7618
- z4.object({ kind: z4.literal("query"), name: z4.string().trim().min(1).max(120).optional() }),
7619
- z4.object({ kind: z4.literal("path") }),
7620
- z4.object({ kind: z4.literal("header"), name: headerNameSchema.optional() }),
7621
- z4.object({ kind: z4.literal("cookie"), name: headerNameSchema.optional() })
7694
+ z4.strictObject({
7695
+ kind: z4.literal("body"),
7696
+ contentType: z4.enum(["application/json", "text/plain"]).optional(),
7697
+ style: z4.enum(QUERY_STYLES).optional(),
7698
+ explode: z4.boolean().optional()
7699
+ }),
7700
+ z4.strictObject({
7701
+ kind: z4.literal("query"),
7702
+ name: z4.string().trim().min(1).max(120).optional(),
7703
+ style: z4.enum(QUERY_STYLES).optional(),
7704
+ explode: z4.boolean().optional()
7705
+ }),
7706
+ z4.strictObject({
7707
+ kind: z4.literal("path"),
7708
+ name: z4.string().trim().min(1).max(120).optional(),
7709
+ style: z4.enum(PATH_STYLES).optional(),
7710
+ explode: z4.boolean().optional()
7711
+ }),
7712
+ z4.strictObject({
7713
+ kind: z4.literal("header"),
7714
+ name: headerNameSchema.optional(),
7715
+ explode: z4.boolean().optional()
7716
+ }),
7717
+ z4.strictObject({ kind: z4.literal("cookie"), name: headerNameSchema.optional() })
7622
7718
  ]);
7623
7719
  var SCALAR_TYPES = ["string", "number", "integer", "boolean"];
7624
7720
  var schemaTypeSchema = z4.enum([...SCALAR_TYPES, "object", "array"]);
@@ -7689,13 +7785,17 @@ function propertyIssues(property, bindable) {
7689
7785
  });
7690
7786
  }
7691
7787
  const binds = bindable && SCALAR_TYPES.some((scalar) => scalar === type);
7692
- for (const binding of ["x-source", "x-target"]) {
7693
- if (property[binding] !== undefined && !binds) {
7694
- issues.push({
7695
- at: [binding],
7696
- message: "only a top-level scalar field of a tool's input has it"
7697
- });
7698
- }
7788
+ if (property["x-source"] !== undefined && !binds) {
7789
+ issues.push({
7790
+ at: ["x-source"],
7791
+ message: "only a top-level scalar field of a tool's input has it"
7792
+ });
7793
+ }
7794
+ if (property["x-target"] !== undefined && !bindable) {
7795
+ issues.push({
7796
+ at: ["x-target"],
7797
+ message: "only a top-level field of a tool's input has it"
7798
+ });
7699
7799
  }
7700
7800
  const source = property["x-source"];
7701
7801
  if (binds && source && !sourceFits(source, { type, enum: property.enum })) {
@@ -7753,13 +7853,22 @@ var toolBaseSchema = z4.strictObject({
7753
7853
  projectOutput: z4.boolean().default(false),
7754
7854
  pinned: z4.boolean().default(false),
7755
7855
  tags: toolTagsSchema.default([]),
7756
- audience: audienceSchema
7856
+ audience: audienceSchema,
7857
+ overridable: overridable([
7858
+ "description",
7859
+ "timeoutMs",
7860
+ "maxResponseBytes",
7861
+ "rateLimitRequests",
7862
+ "rateLimitWindowSeconds",
7863
+ "pinned",
7864
+ "tags"
7865
+ ])
7757
7866
  });
7758
7867
  var calledToolSchema = toolBaseSchema.extend({
7759
7868
  inputSchema: objectSchemaOf(true).default(EMPTY_OBJECT),
7760
7869
  url: upstreamUrlSchema.refine(confinesEndpointParams, "a {parameter} outside the path or query"),
7761
7870
  credentials: credentialsSchema,
7762
- approval: serverToolSchema.shape.approval
7871
+ requiresApproval: z4.boolean().default(false)
7763
7872
  });
7764
7873
  var manifestToolSchema = z4.discriminatedUnion("type", [
7765
7874
  calledToolSchema.extend({
@@ -7779,25 +7888,40 @@ var manifestToolSchema = z4.discriminatedUnion("type", [
7779
7888
  ...toolConfigByType.soap.shape
7780
7889
  }),
7781
7890
  toolBaseSchema.extend({ type: z4.literal("client") })
7782
- ]);
7891
+ ]).superRefine((tool, context) => {
7892
+ if (tool.type !== "client")
7893
+ refuseBlockedApprovalTitle(tool, context, []);
7894
+ });
7895
+ var toolNamesSchema = z4.array(serverToolSchema.shape.name).max(500).default([]);
7896
+ var manifestOpenApiSchema = z4.strictObject({
7897
+ name: nameSchema,
7898
+ url: upstreamUrlSchema,
7899
+ credentials: credentialsSchema,
7900
+ resultPath: jsonPointerSchema.optional(),
7901
+ pinned: toolNamesSchema,
7902
+ approval: z4.strictObject({ never: toolNamesSchema, always: toolNamesSchema }).prefault({}).refine(({ never, always }) => !never.some((name) => always.includes(name)), "a tool both never and always needs approval"),
7903
+ audience: audienceSchema
7904
+ });
7783
7905
  var manifestServiceSchema = z4.strictObject({
7784
7906
  key: slugSchema,
7785
7907
  name: localizedLineSchema,
7786
7908
  description: localizedTextSchema,
7787
- audience: audienceSchema
7909
+ audience: audienceSchema,
7910
+ overridable: overridable(["description"])
7788
7911
  });
7789
7912
  var manifestSkillSchema = z4.strictObject({
7790
7913
  name: slugSchema,
7791
7914
  description: z4.string().trim().min(1).max(500),
7792
7915
  body: z4.string().trim().min(1),
7793
7916
  service: slugSchema.optional(),
7794
- audience: audienceSchema
7917
+ audience: audienceSchema,
7918
+ overridable: overridable(["description", "body"])
7795
7919
  });
7796
7920
  var triggerThreadPolicySchema = z4.discriminatedUnion("policy", [
7797
7921
  z4.object({ policy: z4.literal("single") }),
7798
7922
  z4.object({ policy: z4.literal("per-firing") }),
7799
7923
  z4.object({ policy: z4.literal("ephemeral") }),
7800
- z4.object({ policy: z4.literal("keyed"), key: z4.string().regex(/^\//).max(256) })
7924
+ z4.object({ policy: z4.literal("keyed"), key: jsonPointerSchema })
7801
7925
  ]);
7802
7926
  var manifestTriggerSchema = z4.strictObject({
7803
7927
  name: slugSchema.refine((name) => name !== MESSAGE_TRIGGER_NAME, "the built-in trigger's name"),
@@ -7811,7 +7935,15 @@ var manifestTriggerSchema = z4.strictObject({
7811
7935
  credential: nameSchema.optional(),
7812
7936
  fireCredential: nameSchema.optional(),
7813
7937
  model: modelSchema.optional(),
7814
- audience: audienceSchema
7938
+ audience: audienceSchema,
7939
+ overridable: overridable([
7940
+ "description",
7941
+ "instructions",
7942
+ "threadPolicy",
7943
+ "budgetPerDay",
7944
+ "disableAfterFailures",
7945
+ "model"
7946
+ ])
7815
7947
  });
7816
7948
  function unexposedPins(host) {
7817
7949
  const exposed = new Set(host.expose);
@@ -7824,7 +7956,8 @@ var manifestDatasetHostSchema = z4.strictObject({
7824
7956
  timeoutMs: setting(SETTING_BOUNDS.datasetHost.timeoutMs),
7825
7957
  expose: z4.array(datasetIdentifierSchema).min(1).max(500),
7826
7958
  pinned: z4.array(datasetIdentifierSchema).max(50).default([]),
7827
- audience: audienceSchema
7959
+ audience: audienceSchema,
7960
+ overridable: overridable(["timeoutMs"])
7828
7961
  }).superRefine((host, context) => {
7829
7962
  const unexposed = unexposedPins(host);
7830
7963
  if (unexposed.length > 0) {
@@ -7842,7 +7975,8 @@ var manifestMcpServerSchema = z4.strictObject({
7842
7975
  credentials: presentationsSchema(presentedHeaderSchema.refine((name) => !mcpTransportHeaders.has(name.toLowerCase()), "a header the MCP transport sets"), nameSchema.nullable()),
7843
7976
  include: mcpToolNamesSchema.default([]),
7844
7977
  exclude: mcpToolNamesSchema.default([]),
7845
- audience: audienceSchema
7978
+ audience: audienceSchema,
7979
+ overridable: overridable(["include", "exclude"])
7846
7980
  });
7847
7981
  var manifestWebhookSchema = z4.strictObject({
7848
7982
  name: slugSchema,
@@ -7851,13 +7985,16 @@ var manifestWebhookSchema = z4.strictObject({
7851
7985
  url: upstreamUrlSchema,
7852
7986
  credentials: presentationsSchema(presentedHeaderSchema.refine((name) => name.toLowerCase() !== EVENT_HEADER.toLowerCase(), "the header that names the event"), nameSchema),
7853
7987
  timeoutMs: setting(SETTING_BOUNDS.webhook.timeoutMs),
7854
- audience: audienceSchema
7988
+ audience: audienceSchema,
7989
+ overridable: overridable(["description", "timeoutMs"])
7855
7990
  });
7856
7991
  var manifestCollectionSchema = z4.strictObject({
7857
7992
  name: z4.string().trim().min(1).max(80),
7858
7993
  description: z4.string().trim().max(2000).default(""),
7859
7994
  service: slugSchema.optional(),
7860
- audience: audienceSchema
7995
+ citable: z4.boolean().default(true),
7996
+ audience: audienceSchema,
7997
+ overridable: overridable(["description"])
7861
7998
  });
7862
7999
  var AUTH_JWT_SECRET_ALGORITHMS = ["HS256", "HS384", "HS512"];
7863
8000
  var issuerSchema = z4.string().trim().min(1).max(2048);
@@ -7918,7 +8055,8 @@ var manifestAgentSchema = z4.strictObject({
7918
8055
  }).default({}),
7919
8056
  settings: agentSettingsSchema.prefault({}),
7920
8057
  suggestions: suggestionsSchema.default({ en: [], ar: [] }),
7921
- greeting: greetingSchema.default({ en: "", ar: "" })
8058
+ greeting: greetingSchema.default({ en: "", ar: "" }),
8059
+ overridable: overridable(["name", "prompt", "models", "settings", "suggestions", "greeting"])
7922
8060
  });
7923
8061
  function uniqueBy(key) {
7924
8062
  return (entries) => new Set(entries.map(key)).size === entries.length;
@@ -7931,6 +8069,7 @@ var manifestSchema = z4.strictObject({
7931
8069
  id: slugSchema,
7932
8070
  agents: listOf(manifestAgentSchema, (agent) => agent.slug),
7933
8071
  tools: listOf(manifestToolSchema, byName),
8072
+ openapi: listOf(manifestOpenApiSchema, byName),
7934
8073
  services: listOf(manifestServiceSchema, (service) => service.key),
7935
8074
  skills: listOf(manifestSkillSchema, byName),
7936
8075
  triggers: listOf(manifestTriggerSchema, byName),
@@ -7939,12 +8078,26 @@ var manifestSchema = z4.strictObject({
7939
8078
  webhooks: listOf(manifestWebhookSchema, byName),
7940
8079
  collections: listOf(manifestCollectionSchema, byName)
7941
8080
  });
7942
- var namesByKindSchema = z4.record(manifestSchema.keyof().exclude(["id"]), z4.array(z4.string()));
8081
+ var manifestKindSchema = manifestSchema.keyof().exclude(["id", "openapi"]);
8082
+ var namesByKindSchema = z4.record(manifestKindSchema, z4.array(z4.string()));
7943
8083
  var manifestChangesSchema = z4.object({
7944
8084
  create: namesByKindSchema,
7945
8085
  update: namesByKindSchema,
7946
8086
  delete: namesByKindSchema
7947
8087
  });
8088
+ var manifestConflictSchema = z4.strictObject({
8089
+ kind: manifestKindSchema,
8090
+ name: z4.string(),
8091
+ field: z4.string()
8092
+ });
8093
+ var conflictSideSchema = z4.enum(["live", "manifest"]);
8094
+ var manifestApplyInputSchema = manifestSchema.extend({
8095
+ prefer: conflictSideSchema.optional(),
8096
+ resolutions: z4.array(manifestConflictSchema.extend({ keep: conflictSideSchema })).default([])
8097
+ });
8098
+ var manifestPreviewSchema = manifestChangesSchema.extend({
8099
+ conflicts: z4.array(manifestConflictSchema)
8100
+ });
7948
8101
  var appliedManifestSchema = manifestChangesSchema.extend({
7949
8102
  triggerSecrets: z4.record(z4.string(), z4.string())
7950
8103
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@m6d/cortex",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Cortex for TypeScript backends: serve the server protocol and dataset hosts, and fire triggers",
5
5
  "license": "MIT",
6
6
  "type": "module",