@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/README.md CHANGED
@@ -38,8 +38,9 @@ export const cortexServer = defineServer({
38
38
  description: "Cancel one of the user's open orders.",
39
39
  input: z.object({ orderId: z.string() }),
40
40
  readOnly: false,
41
- // Every call parks until the end user approves this action, the card's only text.
42
- approval: { en: "Cancel this order", ar: "إلغاء هذا الطلب" },
41
+ // Every call parks until the end user approves it, on a card titled with
42
+ // what the model says that call will do.
43
+ requiresApproval: true,
43
44
  run: async ({ orderId }, { user }) => {
44
45
  if (!user)
45
46
  throw new CortexError("forbidden", "Only a signed-in user can cancel an order");
@@ -62,7 +63,7 @@ app.route("/cortex", cortexServer);
62
63
 
63
64
  Cortex reads `GET /` (the manifest, versioned by its own content) on every sync, and calls `POST /variables`, `POST /tools/:name`, `POST /verify` and `POST /events/approval_requested` behind it. A run-scoped call carries the run's token, which `resolve` and `run` receive as `token`: the end user's bearer in a chat, the trigger's credential in a trigger run. A tool's input is an object schema (any other fails at startup, since every call's `input` is an object), parsed before `run` sees it. A refusal answers as described in [Errors](#errors).
64
65
 
65
- A name Cortex would refuse fails `defineServer` at startup: a tool or variable name that is no identifier, and Cortex's built-in names (`utcTime`, `locale`, `timezone`, and the built-in tools such as `executeCode` and `requestLocation`). The protocol is described in full in `apps/cortex/docs/cortex-integration.md`.
66
+ A name Cortex would refuse fails `defineServer` at startup: a tool or variable name that is no identifier, and Cortex's built-in names (`utcTime`, `locale`, `timezone`, and the built-in tools such as `executeCode` and `requestLocation`), and so does an input of a tool that needs approval that names `approvalTitle` or closes a sub-schema to it (`additionalProperties: false` inside `allOf`, `anyOf` or `oneOf`), since Cortex adds the card's title to it. The protocol is described in full in `apps/cortex/docs/cortex-integration.md`.
66
67
 
67
68
  ## Dataset hosts
68
69
 
package/dist/drizzle.d.ts CHANGED
@@ -22,6 +22,7 @@ declare const datasetDefinitionSchema: z.ZodObject<{
22
22
  date: "date";
23
23
  }>;
24
24
  description: z.ZodDefault<z.ZodString>;
25
+ values: z.ZodOptional<z.ZodArray<z.ZodString>>;
25
26
  }, z.core.$strip>>;
26
27
  relations: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
27
28
  dataset: z.ZodString;
@@ -648,6 +649,11 @@ export type DrizzleDatasetOptions<TUser> = {
648
649
  exclude?: readonly string[];
649
650
  };
650
651
  descriptions?: Record<string, string>;
652
+ /**
653
+ * Every value a string column can hold, which the agent reads and a query
654
+ * may only compare it to; a column drizzle knows as an enum lists its own.
655
+ */
656
+ values?: Record<string, readonly string[]>;
651
657
  /** The dataset type of a column the table cannot describe, such as a date kept as ISO text. */
652
658
  types?: Record<string, DatasetColumnType>;
653
659
  /** Read late, so datasets may refer to each other and to themselves. */
package/dist/drizzle.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  filterRefs,
5
5
  groupKeyName,
6
6
  isColumnValue
7
- } from "./index-ncc61ew6.js";
7
+ } from "./index-dck60t84.js";
8
8
 
9
9
  // src/datasets/drizzle.ts
10
10
  import {
@@ -38,6 +38,10 @@ import {
38
38
  SQL
39
39
  } from "drizzle-orm";
40
40
  import { SQLiteTimestamp } from "drizzle-orm/sqlite-core";
41
+ function enumValuesOf(column) {
42
+ const values = column.enumValues;
43
+ return values && values.length >= 1 && values.length <= 100 && values.every((value) => value.length >= 1 && value.length <= 200) ? values : undefined;
44
+ }
41
45
  function columnTypeOf(column) {
42
46
  const dataType = column.dataType;
43
47
  if (dataType.startsWith("boolean"))
@@ -123,13 +127,21 @@ function drizzleDataset(options) {
123
127
  });
124
128
  const columns = picked.flatMap(([name, column]) => {
125
129
  const type = options.types?.[name] ?? columnTypeOf(column);
126
- return type ? [
130
+ if (!type)
131
+ return [];
132
+ const declared = options.values?.[name];
133
+ if (declared && type !== "string") {
134
+ throw new Error(`Dataset "${options.name}": only a string column lists its values, and ${name} is a ${type}`);
135
+ }
136
+ const values = declared ?? enumValuesOf(column);
137
+ return [
127
138
  {
128
139
  name,
129
140
  type,
130
- description: options.descriptions?.[name] ?? ""
141
+ description: options.descriptions?.[name] ?? "",
142
+ ...type === "string" && values && { values: [...values] }
131
143
  }
132
- ] : [];
144
+ ];
133
145
  });
134
146
  const columnsByName = new Map(picked.map(([name, column]) => [name, column]));
135
147
  let definition;
@@ -52,6 +52,9 @@ import { z as z2 } from "zod";
52
52
  function isRecord(value) {
53
53
  return typeof value === "object" && value !== null && !Array.isArray(value);
54
54
  }
55
+ function unescapePointerToken(token) {
56
+ return token.replaceAll("~1", "/").replaceAll("~0", "~");
57
+ }
55
58
 
56
59
  // ../../internal/contracts/src/datasets/datasets.ts
57
60
  var DATASET_IDENTIFIER_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/;
@@ -63,7 +66,11 @@ var DATASET_COLUMN_TYPES = ["string", "number", "boolean", "date"];
63
66
  var datasetColumnSchema = z2.object({
64
67
  name: datasetIdentifierSchema,
65
68
  type: z2.enum(DATASET_COLUMN_TYPES),
66
- description: z2.string().max(200).default("")
69
+ description: z2.string().max(200).default(""),
70
+ values: z2.array(z2.string().min(1).max(200)).min(1).max(100).optional()
71
+ }).refine((column) => column.values === undefined || column.type === "string", {
72
+ message: "only a string column lists its values",
73
+ path: ["values"]
67
74
  });
68
75
  var datasetRelationSchema = z2.object({
69
76
  dataset: datasetIdentifierSchema,
@@ -245,9 +252,31 @@ function resolveDatasetColumn(catalog, from, ref) {
245
252
  }
246
253
  const column = dataset.columns.find((candidate) => candidate.name === columnName);
247
254
  if (!column)
248
- return missing(`"${dataset.name}" has no column "${columnName}"`);
255
+ return missing(unknownColumnError(dataset, columnName));
249
256
  return { ok: true, column, path: segments.join(".") };
250
257
  }
258
+ function unknownColumnError(dataset, name) {
259
+ const columns = dataset.columns.map((column) => column.name);
260
+ const wanted = name.toLowerCase();
261
+ const containing = columns.filter((column) => {
262
+ const lower = column.toLowerCase();
263
+ return wanted.length > 2 && lower.includes(wanted) || lower.length > 2 && wanted.includes(lower);
264
+ });
265
+ const closest = (containing.length > 0 ? containing : columns.filter((column) => Math.abs(column.length - wanted.length) <= 2 && editDistance(column.toLowerCase(), wanted) <= 2)).slice(0, 3);
266
+ const hint = closest.length > 0 ? ` Closest: ${closest.join(", ")}.` : "";
267
+ return `${dataset.name} has no column "${name}".${hint} Columns: ${columns.join(", ")}.`;
268
+ }
269
+ function editDistance(a, b) {
270
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
271
+ for (let i = 1;i <= a.length; i++) {
272
+ const current = [i];
273
+ for (let j = 1;j <= b.length; j++) {
274
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
275
+ }
276
+ previous = current;
277
+ }
278
+ return previous[b.length];
279
+ }
251
280
  function refError(kind, ref, reason) {
252
281
  return `${kind} "${ref}": ${reason}`;
253
282
  }
@@ -446,6 +475,12 @@ function validateDatasetQuery(catalog, query) {
446
475
  };
447
476
  for (const filter of query.filter)
448
477
  checkFilter(check, filter);
478
+ const row = checkAnsweredRow(check, catalog, query);
479
+ checkFinishedRow(check, query, row);
480
+ checkExpansion(check, query, catalog.get(query.from)?.columns.length ?? 0);
481
+ return issues;
482
+ }
483
+ function checkAnsweredRow(check, catalog, query) {
449
484
  const groupKeys = checkGroupBy(check, query.groupBy);
450
485
  const aliases = checkAggregates(check, query.aggregate);
451
486
  for (const alias of aliases.keys()) {
@@ -462,10 +497,15 @@ function validateDatasetQuery(catalog, query) {
462
497
  check.issue("a grouped query answers the group keys, the aggregate aliases and the computed aliases; put computed values in aggregate or compute and leave select out");
463
498
  }
464
499
  const selectAliases = checkSelect(check, query.select ?? []);
465
- const row = grouped ? { names: new Map([...groupKeys, ...aliases]), kind: "grouped" } : { names: selectAliases, kind: "plain" };
466
- checkFinishedRow(check, query, row);
467
- checkExpansion(check, query, catalog.get(query.from)?.columns.length ?? 0);
468
- return issues;
500
+ return grouped ? {
501
+ names: new Map([...groupKeys, ...aliases]),
502
+ kind: "grouped",
503
+ columns: passedColumns(catalog, query, query.groupBy)
504
+ } : {
505
+ names: selectAliases,
506
+ kind: "plain",
507
+ columns: passedColumns(catalog, query, query.select ?? [])
508
+ };
469
509
  }
470
510
  var DATASET_EXPANSION_BUDGET = 2000;
471
511
  function checkExpansion(check, query, columnCount) {
@@ -583,7 +623,7 @@ function rowScope(check, row) {
583
623
  columnOf(kind, ref) {
584
624
  const type = row.names.get(ref);
585
625
  if (type)
586
- return { name: ref, type, description: "" };
626
+ return row.columns.get(ref) ?? { name: ref, type, description: "" };
587
627
  if (row.kind === "plain")
588
628
  return check.columnOf(kind, ref);
589
629
  check.issue(refError(kind, ref, `${kind} names a group key, an aggregate alias, a window alias or a computed alias`));
@@ -800,10 +840,23 @@ function checkFilter(check, filter, kind = "filter") {
800
840
  check.issue(refError(kind, shown, `${filter.op} is not valid on a ${type} column`));
801
841
  return;
802
842
  }
803
- const issue = isColumnValue(filter.value) ? columnValueIssue(check, kind, type, filter.op, filter.value.col) : filterValueIssue(filter) ?? filterValueTypeIssue(type, filter) ?? truncatedDateIssue(filter);
843
+ const issue = isColumnValue(filter.value) ? columnValueIssue(check, kind, type, filter.op, filter.value.col) : filterValueIssue(filter) ?? filterValueTypeIssue(type, filter) ?? truncatedDateIssue(filter) ?? listedValueIssue(check, kind, filter);
804
844
  if (issue)
805
845
  check.issue(refError(kind, shown, issue));
806
846
  }
847
+ var LISTED_VALUE_OPS = new Set(["=", "!=", "in", "notIn"]);
848
+ function listedValueIssue(check, kind, filter) {
849
+ if (typeof filter.col !== "string" || !LISTED_VALUE_OPS.has(filter.op))
850
+ return;
851
+ if (filter.value === undefined || isColumnValue(filter.value))
852
+ return;
853
+ const listed = check.columnOf(kind, filter.col)?.values;
854
+ if (!listed)
855
+ return;
856
+ const values = Array.isArray(filter.value) ? filter.value : [filter.value];
857
+ const odd = values.find((value) => !listed.includes(String(value)));
858
+ return odd === undefined ? undefined : `${JSON.stringify(odd)} is not one of its values: ${listed.join(", ")}`;
859
+ }
807
860
  function truncatedDateIssue(filter) {
808
861
  const truncated = typeof filter.col === "object" && "fn" in filter.col && filter.col.fn === "dateTrunc";
809
862
  if (!truncated || filter.value === undefined || isColumnValue(filter.value))
@@ -877,6 +930,15 @@ function aggregateType(check, aggregate, label = `aggregate "${aggregate.as}"`)
877
930
  const counts = aggregate.fn === "count" || aggregate.fn === "countDistinct";
878
931
  return counts || numeric ? "number" : type ?? "number";
879
932
  }
933
+ function passedColumns(catalog, query, entries) {
934
+ return new Map(entries.flatMap((entry) => {
935
+ const [name, ref] = typeof entry === "string" ? [entry, entry] : [entry.as, entry.expr];
936
+ if (typeof ref !== "string")
937
+ return [];
938
+ const resolved = resolveDatasetColumn(catalog, query.from, ref);
939
+ return resolved.ok ? [[name, resolved.column]] : [];
940
+ }));
941
+ }
880
942
  function checkSort(check, sort, kind, row) {
881
943
  for (const { col } of sort)
882
944
  checkRowName(check, kind, col, row);
@@ -1039,6 +1101,9 @@ class Sources {
1039
1101
  if (isLink(source)) {
1040
1102
  throw new DatasetSqlError(`"${qualifier}" is a link table; read its columns from the datasets it links.`);
1041
1103
  }
1104
+ if (!source.dataset.columns.some((c) => c.name === column)) {
1105
+ throw new DatasetSqlError(unknownColumnError(source.dataset, column));
1106
+ }
1042
1107
  return source.path ? `${source.path}.${column}` : column;
1043
1108
  }
1044
1109
  name(qualifier, source) {
@@ -1104,8 +1169,8 @@ class Sources {
1104
1169
  if (owners.length > 1) {
1105
1170
  throw new DatasetSqlError(`"${column}" is a column of ${owners.map((o) => o.dataset.name).join(" and ")}; qualify it as dataset.column.`);
1106
1171
  }
1107
- const joined = this.paths.length ? " or of the joined datasets" : "";
1108
- throw new DatasetSqlError(`"${column}" is not a column of ${this.root.dataset.name}${joined}.`);
1172
+ const joined = this.paths.length ? " Nor does any joined dataset." : "";
1173
+ throw new DatasetSqlError(unknownColumnError(this.root.dataset, column) + joined);
1109
1174
  }
1110
1175
  sources() {
1111
1176
  const seen = new Set;
@@ -1143,4 +1208,4 @@ class Sources {
1143
1208
  }
1144
1209
  // ../../internal/contracts/src/datasets/dataset-sql-guide.ts
1145
1210
  var DATASET_SQL_GRAMMAR = "One SELECT over one dataset. LEFT JOIN related datasets exactly as the dataset's description lists them (LEFT JOIN keeps rows without a match; JOIN or INNER JOIN drops them); reference dataset.column. " + "SELECT: columns, DATE_TRUNC('unit', column), EXTRACT(part FROM column), CASE WHEN ... END, LOWER/UPPER/TRIM/LENGTH/ABS/ROUND/COALESCE, COUNT/SUM/AVG/MIN/MAX over a column or arithmetic each with an optional FILTER (WHERE ...), and named arithmetic between aggregates (SUM(a) / COUNT(*) AS avg). " + "WHERE and HAVING: AND, OR, NOT, parentheses, comparisons with literals or other columns, IN, BETWEEN, LIKE, IS NULL; CURRENT_DATE and INTERVAL arithmetic on it. " + "GROUP BY columns or select aliases. An aggregate with OVER () or OVER (PARTITION BY ...) is a window: that aggregate over the rows sharing the partition, on every row (SUM(COUNT(*)) OVER () is the grand total); name it AS, use it in arithmetic, and QUALIFY filters the finished rows. " + "QUALIFY RANK() OVER (PARTITION BY ... ORDER BY ...) <= n for the top n per group (rows tied on every ORDER BY key share a rank and all stay); ORDER BY; LIMIT; OFFSET. " + "Rows nest qualified columns under the qualifier as written (pets.name comes back as row.pets.name); aliases and aggregates are top-level.";
1146
- export { BACKEND_ERROR_STATUS, backendErrorSchema, CortexError, errorEnvelope, envelopeOf, datasetIdentifierSchema, datasetDefinitionSchema, datasetRequestSchema, datasetCatalogOf, groupKeyName, filterRefs, isColumnValue, checkDatasetQuery, boundDatasetResult, FUNCTION_SIGNATURES };
1211
+ export { BACKEND_ERROR_STATUS, backendErrorSchema, isRecord, unescapePointerToken, CortexError, errorEnvelope, envelopeOf, datasetIdentifierSchema, datasetDefinitionSchema, datasetRequestSchema, datasetCatalogOf, groupKeyName, filterRefs, isColumnValue, checkDatasetQuery, boundDatasetResult, FUNCTION_SIGNATURES };