@exulu/backend 5.9.0 → 5.10.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.
@@ -659,7 +659,7 @@ var ExuluTool = class _ExuluTool {
659
659
  if (!agent) {
660
660
  throw new Error("Agent not found.");
661
661
  }
662
- const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-PEZCQBM5.js");
662
+ const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-56EULD5M.js");
663
663
  const tools = await convertExuluToolsToAiSdkTools2(
664
664
  [this],
665
665
  [],
@@ -846,7 +846,7 @@ var createSessionItemsRetrievalTool = async ({
846
846
  };
847
847
 
848
848
  // ee/agentic-retrieval/pipeline/index.ts
849
- import { z as z7 } from "zod";
849
+ import { z as z8 } from "zod";
850
850
 
851
851
  // src/exulu/resolve-reranker.ts
852
852
  var ResolveRerankerError = class extends Error {
@@ -2320,6 +2320,324 @@ ${glossary.map((g) => `${g.term} : ${g.meaning}`).join("\n")}` : "";
2320
2320
  }
2321
2321
  }
2322
2322
 
2323
+ // src/exulu/json-field-schema.ts
2324
+ import { z as z7 } from "zod";
2325
+ function unwrap(schema) {
2326
+ let current = schema;
2327
+ for (; ; ) {
2328
+ const def = current.def;
2329
+ if (def.type === "optional" || def.type === "nullable" || def.type === "default") {
2330
+ current = def.innerType;
2331
+ continue;
2332
+ }
2333
+ return current;
2334
+ }
2335
+ }
2336
+ function isPlainObject(value) {
2337
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2338
+ }
2339
+ function hasOwn(target, key) {
2340
+ return Object.prototype.hasOwnProperty.call(target, key);
2341
+ }
2342
+ function schemaPaths(schema) {
2343
+ const base = unwrap(schema);
2344
+ const def = base.def;
2345
+ if (def.type === "union") {
2346
+ const seen = /* @__PURE__ */ new Set();
2347
+ for (const option of def.options) {
2348
+ for (const path3 of schemaPaths(option)) seen.add(path3);
2349
+ }
2350
+ return [...seen];
2351
+ }
2352
+ if (def.type === "record") {
2353
+ const subPaths = schemaPaths(def.valueType);
2354
+ return subPaths.length > 0 ? subPaths.map((path3) => `<key>.${path3}`) : ["<key>"];
2355
+ }
2356
+ if (def.type !== "object") {
2357
+ return [];
2358
+ }
2359
+ const shape = def.shape;
2360
+ const paths = [];
2361
+ for (const key of Object.keys(shape)) {
2362
+ const child = shape[key];
2363
+ if (!child) continue;
2364
+ const childDef = unwrap(child).def;
2365
+ if (childDef.type === "object") {
2366
+ for (const subKey of Object.keys(childDef.shape)) {
2367
+ paths.push(`${key}.${subKey}`);
2368
+ }
2369
+ } else {
2370
+ paths.push(key);
2371
+ }
2372
+ }
2373
+ return paths;
2374
+ }
2375
+ function unknownChildPaths(child, value, key) {
2376
+ const childDef = unwrap(child).def;
2377
+ if (childDef.type === "object") {
2378
+ if (!isPlainObject(value)) {
2379
+ return [key];
2380
+ }
2381
+ const childShape = childDef.shape;
2382
+ const unknown = [];
2383
+ for (const subKey of Object.keys(value)) {
2384
+ if (!hasOwn(childShape, subKey)) unknown.push(`${key}.${subKey}`);
2385
+ }
2386
+ return unknown;
2387
+ }
2388
+ if (childDef.type === "record" && !isPlainObject(value)) {
2389
+ return [key];
2390
+ }
2391
+ return [];
2392
+ }
2393
+ function unknownPaths(schema, value) {
2394
+ if (!isPlainObject(value)) return [];
2395
+ const base = unwrap(schema);
2396
+ const def = base.def;
2397
+ if (def.type === "record") {
2398
+ const valueType = def.valueType;
2399
+ const unknown2 = [];
2400
+ for (const [key, inner] of Object.entries(value)) {
2401
+ unknown2.push(...unknownChildPaths(valueType, inner, key));
2402
+ }
2403
+ return unknown2;
2404
+ }
2405
+ if (def.type !== "object") {
2406
+ return [];
2407
+ }
2408
+ const shape = def.shape;
2409
+ const unknown = [];
2410
+ for (const [key, inner] of Object.entries(value)) {
2411
+ const child = hasOwn(shape, key) ? shape[key] : void 0;
2412
+ if (!child) {
2413
+ unknown.push(key);
2414
+ continue;
2415
+ }
2416
+ unknown.push(...unknownChildPaths(child, inner, key));
2417
+ }
2418
+ return unknown;
2419
+ }
2420
+ function valueAtPath(value, path3) {
2421
+ let current = value;
2422
+ for (const segment of path3) {
2423
+ if (current === null || typeof current !== "object") return void 0;
2424
+ current = current[segment];
2425
+ }
2426
+ return current;
2427
+ }
2428
+ function leafViolations(schema, value) {
2429
+ if (!isPlainObject(value)) return [];
2430
+ const base = unwrap(schema);
2431
+ const def = base.def;
2432
+ let subSchemaFor;
2433
+ if (def.type === "record") {
2434
+ const valueType = def.valueType;
2435
+ subSchemaFor = () => valueType;
2436
+ } else if (def.type === "object") {
2437
+ const shape = def.shape;
2438
+ subSchemaFor = (key) => hasOwn(shape, key) ? shape[key] : void 0;
2439
+ } else {
2440
+ return [];
2441
+ }
2442
+ const violations = [];
2443
+ for (const [key, inner] of Object.entries(value)) {
2444
+ const subSchema = subSchemaFor(key);
2445
+ if (!subSchema) continue;
2446
+ const result = subSchema.safeParse(inner);
2447
+ if (result.success) continue;
2448
+ for (const issue of result.error.issues) {
2449
+ const issuePath = issue.path.map(String);
2450
+ const expectedSet = describeExpectedValues(issue);
2451
+ violations.push({
2452
+ path: [key, ...issuePath].join("."),
2453
+ expected: expectedSet ? `expected one of ${expectedSet}` : issue.message,
2454
+ received: issue.path.length > 0 ? valueAtPath(inner, issue.path) : inner
2455
+ });
2456
+ }
2457
+ }
2458
+ return violations;
2459
+ }
2460
+ function describeExpectedValues(issue) {
2461
+ const anyIssue = issue;
2462
+ if (anyIssue.code === "invalid_value" && Array.isArray(anyIssue.values) && anyIssue.values.length > 0) {
2463
+ return anyIssue.values.map((value) => JSON.stringify(value)).join(" | ");
2464
+ }
2465
+ if (anyIssue.code === "invalid_union" && Array.isArray(anyIssue.errors)) {
2466
+ const parts = [];
2467
+ for (const branchIssues of anyIssue.errors) {
2468
+ const branchArray = branchIssues;
2469
+ const first = branchArray[0];
2470
+ if (!first || !Array.isArray(first.values) || first.values.length === 0) return void 0;
2471
+ parts.push(...first.values.map((value) => JSON.stringify(value)));
2472
+ }
2473
+ return parts.length > 0 ? parts.join(" | ") : void 0;
2474
+ }
2475
+ return void 0;
2476
+ }
2477
+ function missingRequiredKeys(schema, value) {
2478
+ if (!isPlainObject(value)) return [];
2479
+ const def = unwrap(schema).def;
2480
+ if (def.type !== "object") return [];
2481
+ const shape = def.shape;
2482
+ const missing = [];
2483
+ for (const key of Object.keys(shape)) {
2484
+ const child = shape[key];
2485
+ if (!child) continue;
2486
+ if (hasOwn(value, key)) continue;
2487
+ if (!child.safeParse(void 0).success) missing.push(key);
2488
+ }
2489
+ return missing;
2490
+ }
2491
+ function requiresPlainObject(schema) {
2492
+ const def = unwrap(schema).def;
2493
+ return def.type === "object" || def.type === "record";
2494
+ }
2495
+ function preserveDescription(original, rebuilt) {
2496
+ return original.description ? rebuilt.describe(original.description) : rebuilt;
2497
+ }
2498
+ function loosenForTransport(schema) {
2499
+ const def = schema.def;
2500
+ switch (def.type) {
2501
+ case "optional":
2502
+ return preserveDescription(schema, z7.optional(loosenForTransport(def.innerType)));
2503
+ case "nullable":
2504
+ return preserveDescription(schema, z7.nullable(loosenForTransport(def.innerType)));
2505
+ case "default":
2506
+ return preserveDescription(
2507
+ schema,
2508
+ loosenForTransport(def.innerType).default(
2509
+ def.defaultValue
2510
+ )
2511
+ );
2512
+ case "array":
2513
+ return preserveDescription(schema, z7.array(loosenForTransport(def.element)));
2514
+ case "record": {
2515
+ const loosenedValue = loosenForTransport(def.valueType);
2516
+ return preserveDescription(
2517
+ schema,
2518
+ schema.clone({ ...def, valueType: loosenedValue })
2519
+ );
2520
+ }
2521
+ case "union":
2522
+ return preserveDescription(
2523
+ schema,
2524
+ z7.union(def.options.map((option) => loosenForTransport(option)))
2525
+ );
2526
+ case "object": {
2527
+ const shape = def.shape;
2528
+ const loosenedShape = {};
2529
+ for (const key of Object.keys(shape)) {
2530
+ const child = shape[key];
2531
+ if (!child) continue;
2532
+ loosenedShape[key] = loosenForTransport(child);
2533
+ }
2534
+ return preserveDescription(
2535
+ schema,
2536
+ z7.object(loosenedShape).passthrough()
2537
+ );
2538
+ }
2539
+ default:
2540
+ return schema;
2541
+ }
2542
+ }
2543
+ function mergeJson(stored, patch) {
2544
+ const merged = isPlainObject(stored) ? { ...stored } : {};
2545
+ for (const [key, value] of Object.entries(patch)) {
2546
+ if (value === null) {
2547
+ delete merged[key];
2548
+ } else {
2549
+ Object.defineProperty(merged, key, { value, writable: true, enumerable: true, configurable: true });
2550
+ }
2551
+ }
2552
+ return merged;
2553
+ }
2554
+
2555
+ // src/graphql/utilities/convert-graphql-filter-operator-to-pg-query.ts
2556
+ var UnknownFilterPathError = class extends Error {
2557
+ field;
2558
+ offendingPaths;
2559
+ validPaths;
2560
+ constructor(field, offendingPaths, validPaths) {
2561
+ const plural = offendingPaths.length > 1;
2562
+ const badList = offendingPaths.map((path3) => `"${path3}"`).join(", ");
2563
+ const validList = validPaths.length > 0 ? validPaths.join(", ") : "(the schema declares no paths)";
2564
+ super(
2565
+ `Filter on field "${field}" rejected: ${plural ? "paths" : "path"} ${badList} ${plural ? "do" : "does"} not match the shape declared for "${field}". A filter on a path the schema does not define would silently match zero rows instead of erroring, which looks identical to "there are none" \u2014 so it is refused instead. Valid paths for "${field}": ${validList}.`
2566
+ );
2567
+ this.name = "UnknownFilterPathError";
2568
+ this.field = field;
2569
+ this.offendingPaths = offendingPaths;
2570
+ this.validPaths = validPaths;
2571
+ }
2572
+ };
2573
+ var convertGraphqlOperatorToPostgresQuery = (query, fieldName, operators, table, field_prefix) => {
2574
+ const field = table?.fields.find((f) => f.name === fieldName);
2575
+ const isJsonField = field?.type === "json";
2576
+ const prefix = field_prefix ? field_prefix + "." : "";
2577
+ fieldName = prefix + fieldName;
2578
+ console.log("[EXULU] operators", operators);
2579
+ if (isJsonField && field?.schema) {
2580
+ const filterValues = [];
2581
+ if (operators.eq !== void 0) filterValues.push(operators.eq);
2582
+ if (operators.ne !== void 0) filterValues.push(operators.ne);
2583
+ if (Array.isArray(operators.in)) filterValues.push(...operators.in);
2584
+ if (operators.contains !== void 0) filterValues.push(operators.contains);
2585
+ const badPaths = /* @__PURE__ */ new Set();
2586
+ for (const value of filterValues) {
2587
+ for (const path3 of unknownPaths(field.schema, value)) badPaths.add(path3);
2588
+ }
2589
+ if (badPaths.size > 0) {
2590
+ throw new UnknownFilterPathError(field.name, [...badPaths], schemaPaths(field.schema));
2591
+ }
2592
+ }
2593
+ if (operators.eq !== void 0) {
2594
+ if (isJsonField) {
2595
+ query = query.whereRaw(`?? = ?::jsonb`, [fieldName, JSON.stringify(operators.eq)]);
2596
+ } else {
2597
+ query = query.where(fieldName, operators.eq);
2598
+ }
2599
+ }
2600
+ if (operators.ne !== void 0) {
2601
+ if (isJsonField) {
2602
+ query = query.whereRaw(`?? IS DISTINCT FROM ?::jsonb`, [
2603
+ fieldName,
2604
+ JSON.stringify(operators.ne)
2605
+ ]);
2606
+ } else {
2607
+ query = query.whereRaw(`?? IS DISTINCT FROM ?`, [fieldName, operators.ne]);
2608
+ }
2609
+ }
2610
+ if (operators.in !== void 0) {
2611
+ if (isJsonField) {
2612
+ const conditions = operators.in.map(() => `?? = ?::jsonb`).join(" OR ");
2613
+ const bindings = operators.in.flatMap((val) => [fieldName, JSON.stringify(val)]);
2614
+ query = query.whereRaw(`(${conditions})`, bindings);
2615
+ } else {
2616
+ query = query.whereIn(fieldName, operators.in);
2617
+ }
2618
+ }
2619
+ if (operators.contains !== void 0) {
2620
+ if (isJsonField) {
2621
+ query = query.whereRaw(`?? @> ?::jsonb`, [fieldName, JSON.stringify(operators.contains)]);
2622
+ } else {
2623
+ query = query.where(fieldName, "ilike", `%${operators.contains}%`);
2624
+ }
2625
+ }
2626
+ if (operators.lte !== void 0) {
2627
+ console.log("[EXULU] operators.lte", operators.lte);
2628
+ console.log("[EXULU] fieldName", fieldName);
2629
+ if (operators.lte === 0 || operators.lte === "0") {
2630
+ query = query.whereNull(fieldName).orWhere(fieldName, "=", 0);
2631
+ } else {
2632
+ query = query.where(fieldName, "<=", operators.lte);
2633
+ }
2634
+ }
2635
+ if (operators.gte !== void 0) {
2636
+ query = query.where(fieldName, ">=", operators.gte);
2637
+ }
2638
+ return query;
2639
+ };
2640
+
2323
2641
  // ee/agentic-retrieval/pipeline/multi-query.ts
2324
2642
  async function singleSearch({
2325
2643
  query,
@@ -2350,6 +2668,7 @@ async function singleSearch({
2350
2668
  });
2351
2669
  return results.chunks || [];
2352
2670
  } catch (e) {
2671
+ if (e instanceof UnknownFilterPathError) throw e;
2353
2672
  console.warn("[EXULU] singleSearch failed for query:", query, e);
2354
2673
  return [];
2355
2674
  }
@@ -2589,6 +2908,7 @@ async function searchContexts(opts) {
2589
2908
  }
2590
2909
  return [];
2591
2910
  } catch (err3) {
2911
+ if (err3 instanceof UnknownFilterPathError) throw err3;
2592
2912
  if (isEmbedderNotConfigured(err3)) {
2593
2913
  console.warn(
2594
2914
  `[EXULU pipeline] context "${ctxId}" is not searchable: ${err3.message}`
@@ -3098,11 +3418,11 @@ function createAgenticRetrievalTool(opts) {
3098
3418
  default: '{"enabled":false,"model":"","fidelity":"fast","thresholds":{"warn":0.1,"alert":0.3}}'
3099
3419
  }
3100
3420
  ],
3101
- inputSchema: z7.object({
3102
- userQuery: z7.string().describe("The original unaltered question from the user"),
3103
- relevantKeywords: z7.array(z7.string()).describe("Keywords extracted from the user's question relevant to the search"),
3104
- importantKeyword: z7.string().describe("The single most important keyword from the user's question"),
3105
- confirmedContextIds: z7.array(z7.string()).optional().describe(
3421
+ inputSchema: z8.object({
3422
+ userQuery: z8.string().describe("The original unaltered question from the user"),
3423
+ relevantKeywords: z8.array(z8.string()).describe("Keywords extracted from the user's question relevant to the search"),
3424
+ importantKeyword: z8.string().describe("The single most important keyword from the user's question"),
3425
+ confirmedContextIds: z8.array(z8.string()).optional().describe(
3106
3426
  "Knowledge base IDs explicitly confirmed by the user to be used in the retrieval. When present, only searches these contexts."
3107
3427
  )
3108
3428
  }),
@@ -3520,6 +3840,18 @@ Verified answer:
3520
3840
  yield { result: serializeOutput(result, hideSources) };
3521
3841
  return { result: serializeOutput(result, hideSources) };
3522
3842
  } catch (err3) {
3843
+ if (err3 instanceof UnknownFilterPathError) {
3844
+ console.warn("[EXULU pipeline] retrieval refused an unknown json filter path:", err3.message);
3845
+ result.steps.push({
3846
+ stepNumber: 1,
3847
+ text: err3.message,
3848
+ toolCalls: [],
3849
+ chunks: [],
3850
+ tokens: 0
3851
+ });
3852
+ yield { result: serializeOutput(result, hideSources) };
3853
+ return;
3854
+ }
3523
3855
  console.warn("[EXULU pipeline] retrieval pipeline failed:", err3);
3524
3856
  result.steps.push({
3525
3857
  stepNumber: 1,
@@ -3572,7 +3904,7 @@ var STATISTICS_TYPE_ENUM = {
3572
3904
  };
3573
3905
 
3574
3906
  // src/exulu/memory/tools.ts
3575
- import { z as z9 } from "zod";
3907
+ import { z as z10 } from "zod";
3576
3908
 
3577
3909
  // src/exulu/memory/creator-id.ts
3578
3910
  function creatorId(value) {
@@ -5351,6 +5683,166 @@ var defaultChunker = async (item, maxChunkSize) => {
5351
5683
  return { item, chunks };
5352
5684
  };
5353
5685
 
5686
+ // src/exulu/item-write.ts
5687
+ function isPlainObject2(value) {
5688
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5689
+ }
5690
+ function describeKind(value) {
5691
+ if (value === null) return "null";
5692
+ if (value === void 0) return "undefined";
5693
+ if (Array.isArray(value)) return "an array";
5694
+ const kind = typeof value;
5695
+ return /^[aeiou]/.test(kind) ? `an ${kind}` : `a ${kind}`;
5696
+ }
5697
+ function hasOwnKey(target, key) {
5698
+ return Object.prototype.hasOwnProperty.call(target, key);
5699
+ }
5700
+ function safeStringify(value) {
5701
+ try {
5702
+ return JSON.stringify(value);
5703
+ } catch {
5704
+ return String(value);
5705
+ }
5706
+ }
5707
+ function omitNullEntries(value) {
5708
+ const filtered = /* @__PURE__ */ Object.create(null);
5709
+ for (const [key, inner] of Object.entries(value)) {
5710
+ if (inner !== null) filtered[key] = inner;
5711
+ }
5712
+ return filtered;
5713
+ }
5714
+ function mergeClearRefusalMessage(fieldName) {
5715
+ return `Write to field "${fieldName}" rejected: a merge patch's own value cannot be null. A bare null here would clear the entire field, and clearing a field is a replace, not a merge. To clear "${fieldName}" entirely, resend it WITHOUT "merge". To delete specific keys instead, keep merging and set only those keys' values to null.`;
5716
+ }
5717
+ function requiredNullRefusalMessage(fieldName) {
5718
+ return `Write to field "${fieldName}" rejected: this field is required and cannot be null. Send a value for "${fieldName}", or omit it from this write to leave it unchanged.`;
5719
+ }
5720
+ function mergeNonObjectRefusalMessage(fieldName, value) {
5721
+ const kind = describeKind(value);
5722
+ return `Write to field "${fieldName}" rejected: a merge patch must be a JSON object with named keys, but ${kind} was sent (${safeStringify(value)}). A merge patch cannot be ${kind} \u2014 only its object keys are merged. To replace "${fieldName}" entirely with ${kind}, resend it WITHOUT "merge".`;
5723
+ }
5724
+ function mergeStoredNonObjectRefusalMessage(fieldName, stored) {
5725
+ const kind = describeKind(stored);
5726
+ return `Write to field "${fieldName}" rejected: the STORED value is ${kind}, not a JSON object with named keys (${safeStringify(stored)}), so a merge patch cannot be combined into it. A merge combines keys into an EXISTING object; "${fieldName}" does not currently hold one. To replace "${fieldName}" entirely, resend it WITHOUT "merge".`;
5727
+ }
5728
+ function stringParseFailedMessage(fieldName, raw, schema) {
5729
+ const base = `Write to field "${fieldName}" rejected: the value is a string, but it does not parse as JSON (${safeStringify(raw)}). A json field may be sent as a serialized JSON string, but the string itself must be valid JSON.`;
5730
+ if (!schema) return base;
5731
+ const validPaths = schemaPaths(schema);
5732
+ const validList = validPaths.length > 0 ? validPaths.join(", ") : "(the schema declares no paths)";
5733
+ return `${base} Valid paths for "${fieldName}": ${validList}.`;
5734
+ }
5735
+ function shapeRefusalMessage(fieldName, value, schema) {
5736
+ const kind = describeKind(value);
5737
+ const validPaths = schemaPaths(schema);
5738
+ const validList = validPaths.length > 0 ? validPaths.join(", ") : "(the schema declares no paths)";
5739
+ return `Write to field "${fieldName}" rejected: the value must be a JSON object with named keys, but ${kind} was sent (${safeStringify(value)}). Valid paths for "${fieldName}": ${validList}.`;
5740
+ }
5741
+ function mergeUnknownFieldMessage(name, reason, mergeableNames) {
5742
+ const availableList = mergeableNames.length > 0 ? mergeableNames.map((mergeable) => `"${mergeable}"`).join(", ") : "(none \u2014 this write sends no json field, so there is nothing to merge into)";
5743
+ const why = reason === "not-json" ? `"${name}" is not a json field of this item` : `"${name}" is a json field but this write sends no value for it`;
5744
+ return `Write rejected: "merge" names "${name}", but ${why}. Every name in "merge" must be a json field that this same write sends a value for \u2014 an unmatched name would otherwise silently REPLACE that field instead of merging into it, deleting every stored key the value sent does not mention. json fields this write can merge into: ${availableList}.`;
5745
+ }
5746
+ function missingKeysRefusalMessage(fieldName, missing, schema) {
5747
+ const plural = missing.length > 1;
5748
+ const missingList = missing.map((key) => `"${key}"`).join(", ");
5749
+ const validPaths = schemaPaths(schema);
5750
+ const validList = validPaths.length > 0 ? validPaths.join(", ") : "(the schema declares no paths)";
5751
+ return `Write to field "${fieldName}" rejected: required ${plural ? "keys" : "key"} ${missingList} ${plural ? "are" : "is"} missing. This write REPLACES "${fieldName}" (it is not named in "merge"), so the value sent must be complete. To change only some keys and keep the rest, resend this write with "merge": ["${fieldName}"]. To clear "${fieldName}" entirely, send {}. Valid paths for "${fieldName}": ${validList}.`;
5752
+ }
5753
+ function refusalMessage(fieldName, badPaths, schema) {
5754
+ const plural = badPaths.length > 1;
5755
+ const badList = badPaths.map((path3) => `"${path3}"`).join(", ");
5756
+ const validPaths = schemaPaths(schema);
5757
+ const validList = validPaths.length > 0 ? validPaths.join(", ") : "(the schema declares no paths)";
5758
+ return `Write to field "${fieldName}" rejected: ${plural ? "paths" : "path"} ${badList} ${plural ? "do" : "does"} not match the shape declared for "${fieldName}". Valid paths for "${fieldName}": ${validList}.`;
5759
+ }
5760
+ function leafRefusalMessage(fieldName, violations) {
5761
+ const parts = violations.map((violation) => {
5762
+ const got = safeStringify(violation.received);
5763
+ return `"${fieldName}.${violation.path}": ${violation.expected} (got ${got})`;
5764
+ });
5765
+ return `Write to field "${fieldName}" rejected: ${parts.join("; ")}.`;
5766
+ }
5767
+ function prepareItemWrite(args) {
5768
+ const { fields, existing, input, merge } = args;
5769
+ const fieldsByName = new Map(fields.map((field) => [field.name, field]));
5770
+ const values = {};
5771
+ if (merge && merge.length > 0) {
5772
+ const mergeableNames = Object.keys(input).filter((name) => fieldsByName.get(name)?.type === "json");
5773
+ for (const name of merge) {
5774
+ if (fieldsByName.get(name)?.type !== "json") {
5775
+ return { ok: false, message: mergeUnknownFieldMessage(String(name), "not-json", mergeableNames) };
5776
+ }
5777
+ if (!hasOwnKey(input, name)) {
5778
+ return { ok: false, message: mergeUnknownFieldMessage(String(name), "absent", mergeableNames) };
5779
+ }
5780
+ }
5781
+ }
5782
+ for (const [key, value] of Object.entries(input)) {
5783
+ const field = fieldsByName.get(key);
5784
+ const schema = field?.type === "json" ? field.schema : void 0;
5785
+ const isMergeField = field?.type === "json" && (merge?.includes(key) ?? false);
5786
+ let checkValue = value;
5787
+ let stringParseFailed = false;
5788
+ if (field?.type === "json" && typeof value === "string") {
5789
+ try {
5790
+ checkValue = JSON.parse(value);
5791
+ } catch {
5792
+ stringParseFailed = true;
5793
+ }
5794
+ }
5795
+ if (isMergeField && checkValue === null) {
5796
+ return { ok: false, message: mergeClearRefusalMessage(key) };
5797
+ }
5798
+ if (!isMergeField && field?.type === "json" && checkValue === null) {
5799
+ if (schema && field.required === true) {
5800
+ return { ok: false, message: requiredNullRefusalMessage(key) };
5801
+ }
5802
+ Object.defineProperty(values, key, { value, writable: true, enumerable: true, configurable: true });
5803
+ continue;
5804
+ }
5805
+ if (stringParseFailed && (isMergeField || schema && requiresPlainObject(schema))) {
5806
+ return { ok: false, message: stringParseFailedMessage(key, value, schema) };
5807
+ }
5808
+ if (isMergeField && (!schema || !requiresPlainObject(schema)) && !isPlainObject2(checkValue)) {
5809
+ return { ok: false, message: mergeNonObjectRefusalMessage(key, checkValue) };
5810
+ }
5811
+ if (isMergeField && isPlainObject2(checkValue)) {
5812
+ const stored = existing?.[key];
5813
+ if (stored !== null && stored !== void 0 && !isPlainObject2(stored)) {
5814
+ return { ok: false, message: mergeStoredNonObjectRefusalMessage(key, stored) };
5815
+ }
5816
+ }
5817
+ if (schema) {
5818
+ if (requiresPlainObject(schema) && !isPlainObject2(checkValue) && !schema.safeParse(checkValue).success) {
5819
+ return { ok: false, message: shapeRefusalMessage(key, checkValue, schema) };
5820
+ }
5821
+ const toValidate = isMergeField && isPlainObject2(checkValue) ? omitNullEntries(checkValue) : checkValue;
5822
+ const badPaths = unknownPaths(schema, toValidate);
5823
+ if (badPaths.length > 0) {
5824
+ return { ok: false, message: refusalMessage(key, badPaths, schema) };
5825
+ }
5826
+ const violations = leafViolations(schema, toValidate);
5827
+ if (violations.length > 0) {
5828
+ return { ok: false, message: leafRefusalMessage(key, violations) };
5829
+ }
5830
+ if (!isMergeField && isPlainObject2(checkValue) && Object.keys(checkValue).length > 0) {
5831
+ const missing = missingRequiredKeys(schema, checkValue);
5832
+ if (missing.length > 0) {
5833
+ return { ok: false, message: missingKeysRefusalMessage(key, missing, schema) };
5834
+ }
5835
+ }
5836
+ }
5837
+ if (isMergeField && isPlainObject2(checkValue)) {
5838
+ Object.defineProperty(values, key, { value: mergeJson(existing?.[key], checkValue), writable: true, enumerable: true, configurable: true });
5839
+ } else {
5840
+ Object.defineProperty(values, key, { value, writable: true, enumerable: true, configurable: true });
5841
+ }
5842
+ }
5843
+ return { ok: true, values };
5844
+ }
5845
+
5354
5846
  // src/exulu/litellm/parse-embedding-models.ts
5355
5847
  import { existsSync, readFileSync } from "fs";
5356
5848
  import { resolve } from "path";
@@ -5633,14 +6125,14 @@ function randomizedPCA(rows, dims, k, seed, iterations) {
5633
6125
  for (const row of rows) {
5634
6126
  const centered = new Float64Array(dims);
5635
6127
  for (let d = 0; d < dims; d += 1) centered[d] = (row[d] ?? 0) - (mean[d] ?? 0);
5636
- const z17 = new Float64Array(basis.length);
6128
+ const z18 = new Float64Array(basis.length);
5637
6129
  for (const [b, vec] of basis.entries()) {
5638
6130
  let dot = 0;
5639
6131
  for (let d = 0; d < dims; d += 1) dot += (centered[d] ?? 0) * (vec[d] ?? 0);
5640
- z17[b] = dot;
6132
+ z18[b] = dot;
5641
6133
  }
5642
6134
  for (const [b, target] of next.entries()) {
5643
- const scale = z17[b] ?? 0;
6135
+ const scale = z18[b] ?? 0;
5644
6136
  if (scale === 0) continue;
5645
6137
  for (let d = 0; d < dims; d += 1) target[d] = (target[d] ?? 0) + (centered[d] ?? 0) * scale;
5646
6138
  }
@@ -5738,12 +6230,12 @@ function ridgeFit(Z, Y, lambda) {
5738
6230
  });
5739
6231
  return { map, intercept };
5740
6232
  }
5741
- function applyMap(z17, map, intercept) {
6233
+ function applyMap(z18, map, intercept) {
5742
6234
  const out = [];
5743
6235
  for (let j = 0; j < 3; j += 1) {
5744
6236
  let v = intercept[j] ?? 0;
5745
6237
  const row = map[j] ?? [];
5746
- for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z17[d] ?? 0);
6238
+ for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z18[d] ?? 0);
5747
6239
  out.push(Number.isFinite(v) ? v : 0);
5748
6240
  }
5749
6241
  return [out[0] ?? 0, out[1] ?? 0, out[2] ?? 0];
@@ -5766,8 +6258,8 @@ function fitResidual(Z, Y, map, intercept) {
5766
6258
  for (let i = 0; i < Z.length; i += 1) {
5767
6259
  const zi = Z[i] ?? [];
5768
6260
  const yi = Y[i] ?? [];
5769
- const [x, y, z17] = applyMap(zi, map, intercept);
5770
- total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z17 - finite(yi[2]));
6261
+ const [x, y, z18] = applyMap(zi, map, intercept);
6262
+ total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z18 - finite(yi[2]));
5771
6263
  }
5772
6264
  return finite(total / Z.length);
5773
6265
  }
@@ -5907,8 +6399,8 @@ async function chunkCoordinates({
5907
6399
  }
5908
6400
  return null;
5909
6401
  }
5910
- const [x, y, z17] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
5911
- return { x, y, z: z17 };
6402
+ const [x, y, z18] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
6403
+ return { x, y, z: z18 };
5912
6404
  });
5913
6405
  } catch (e) {
5914
6406
  console.error("[EXULU] could not compute chunk coordinates", e instanceof Error ? e.message : String(e));
@@ -6348,61 +6840,6 @@ var applyAccessControl = (table, query, user, field_prefix) => {
6348
6840
  return query;
6349
6841
  };
6350
6842
 
6351
- // src/graphql/utilities/convert-graphql-filter-operator-to-pg-query.ts
6352
- var convertGraphqlOperatorToPostgresQuery = (query, fieldName, operators, table, field_prefix) => {
6353
- const field = table?.fields.find((f) => f.name === fieldName);
6354
- const isJsonField = field?.type === "json";
6355
- const prefix = field_prefix ? field_prefix + "." : "";
6356
- fieldName = prefix + fieldName;
6357
- console.log("[EXULU] operators", operators);
6358
- if (operators.eq !== void 0) {
6359
- if (isJsonField) {
6360
- query = query.whereRaw(`?? = ?::jsonb`, [fieldName, JSON.stringify(operators.eq)]);
6361
- } else {
6362
- query = query.where(fieldName, operators.eq);
6363
- }
6364
- }
6365
- if (operators.ne !== void 0) {
6366
- if (isJsonField) {
6367
- query = query.whereRaw(`?? IS DISTINCT FROM ?::jsonb`, [
6368
- fieldName,
6369
- JSON.stringify(operators.ne)
6370
- ]);
6371
- } else {
6372
- query = query.whereRaw(`?? IS DISTINCT FROM ?`, [fieldName, operators.ne]);
6373
- }
6374
- }
6375
- if (operators.in !== void 0) {
6376
- if (isJsonField) {
6377
- const conditions = operators.in.map(() => `?? = ?::jsonb`).join(" OR ");
6378
- const bindings = operators.in.flatMap((val) => [fieldName, JSON.stringify(val)]);
6379
- query = query.whereRaw(`(${conditions})`, bindings);
6380
- } else {
6381
- query = query.whereIn(fieldName, operators.in);
6382
- }
6383
- }
6384
- if (operators.contains !== void 0) {
6385
- if (isJsonField) {
6386
- query = query.whereRaw(`?? @> ?::jsonb`, [fieldName, JSON.stringify(operators.contains)]);
6387
- } else {
6388
- query = query.where(fieldName, "ilike", `%${operators.contains}%`);
6389
- }
6390
- }
6391
- if (operators.lte !== void 0) {
6392
- console.log("[EXULU] operators.lte", operators.lte);
6393
- console.log("[EXULU] fieldName", fieldName);
6394
- if (operators.lte === 0 || operators.lte === "0") {
6395
- query = query.whereNull(fieldName).orWhere(fieldName, "=", 0);
6396
- } else {
6397
- query = query.where(fieldName, "<=", operators.lte);
6398
- }
6399
- }
6400
- if (operators.gte !== void 0) {
6401
- query = query.where(fieldName, ">=", operators.gte);
6402
- }
6403
- return query;
6404
- };
6405
-
6406
6843
  // src/graphql/resolvers/apply-filters.ts
6407
6844
  var applyFilters = (query, filters, table, field_prefix) => {
6408
6845
  if (!filters) {
@@ -6575,29 +7012,29 @@ var resolveEntityModel = async (context) => {
6575
7012
 
6576
7013
  // src/exulu/entities/extractor.ts
6577
7014
  import { generateText as generateText2, Output as Output2 } from "ai";
6578
- import { z as z8 } from "zod";
7015
+ import { z as z9 } from "zod";
6579
7016
  var CHUNK_BATCH_SIZE = 30;
6580
7017
  var MAX_SUGGESTIONS = 5;
6581
- var mentionSchema = z8.object({
6582
- entities: z8.array(
6583
- z8.object({
6584
- chunkIndex: z8.number().int().describe("Index of the chunk this entity was found in."),
6585
- type: z8.string().describe("One of the provided entity type names."),
6586
- mention: z8.string().describe("The exact surface form as it appears in the text."),
6587
- canonical: z8.string().describe("The canonical, language-normalized name used to merge variants."),
6588
- confidence: z8.number().min(0).max(1).describe("Confidence 0..1 that this is a valid entity.")
7018
+ var mentionSchema = z9.object({
7019
+ entities: z9.array(
7020
+ z9.object({
7021
+ chunkIndex: z9.number().int().describe("Index of the chunk this entity was found in."),
7022
+ type: z9.string().describe("One of the provided entity type names."),
7023
+ mention: z9.string().describe("The exact surface form as it appears in the text."),
7024
+ canonical: z9.string().describe("The canonical, language-normalized name used to merge variants."),
7025
+ confidence: z9.number().min(0).max(1).describe("Confidence 0..1 that this is a valid entity.")
6589
7026
  })
6590
7027
  ),
6591
- suggestedTypes: z8.array(
6592
- z8.object({
6593
- name: z8.string().describe("A concise NEW entity type name, e.g. 'Error Code', 'Component'."),
6594
- description: z8.string().describe("What this type captures, one sentence."),
6595
- mentions: z8.array(
6596
- z8.object({
6597
- chunkIndex: z8.number().int().describe("Index of the chunk this mention was found in."),
6598
- mention: z8.string().describe("The exact surface form as it appears in the text."),
6599
- canonical: z8.string().describe("Canonical, language-normalized name."),
6600
- confidence: z8.number().min(0).max(1).describe("Confidence 0..1.")
7028
+ suggestedTypes: z9.array(
7029
+ z9.object({
7030
+ name: z9.string().describe("A concise NEW entity type name, e.g. 'Error Code', 'Component'."),
7031
+ description: z9.string().describe("What this type captures, one sentence."),
7032
+ mentions: z9.array(
7033
+ z9.object({
7034
+ chunkIndex: z9.number().int().describe("Index of the chunk this mention was found in."),
7035
+ mention: z9.string().describe("The exact surface form as it appears in the text."),
7036
+ canonical: z9.string().describe("Canonical, language-normalized name."),
7037
+ confidence: z9.number().min(0).max(1).describe("Confidence 0..1.")
6601
7038
  })
6602
7039
  ).describe("Every mention of this new type found in the provided chunks.")
6603
7040
  })
@@ -8159,6 +8596,10 @@ var ExuluContext2 = class {
8159
8596
  }
8160
8597
  item.rights_mode = sanitizeItemRightsMode(item.rights_mode, this.configuration.defaultRightsMode);
8161
8598
  const { db } = await postgresClient();
8599
+ const createValidation = prepareItemWrite({ fields: this.fields, existing: null, input: item });
8600
+ if (!createValidation.ok) {
8601
+ throw new Error(createValidation.message);
8602
+ }
8162
8603
  Object.keys(item).forEach((key) => {
8163
8604
  if (this.fields.find((field) => field.name === key)?.type === "json") {
8164
8605
  if (typeof item[key] === "object" || Array.isArray(item[key])) {
@@ -8235,7 +8676,7 @@ var ExuluContext2 = class {
8235
8676
  job: jobs.length > 0 ? jobs.join(",") : void 0
8236
8677
  };
8237
8678
  };
8238
- updateItem = async (item, config, user, role, generateEmbeddingsOverwrite, runProcessorOverwrite) => {
8679
+ updateItem = async (item, config, user, role, generateEmbeddingsOverwrite, runProcessorOverwrite, merge) => {
8239
8680
  console.log("[EXULU] updating item", item);
8240
8681
  const { db } = await postgresClient();
8241
8682
  if (item.field) {
@@ -8245,16 +8686,26 @@ var ExuluContext2 = class {
8245
8686
  if (!record) {
8246
8687
  throw new Error("Item not found.");
8247
8688
  }
8248
- Object.keys(item).forEach((key) => {
8689
+ const prepared = prepareItemWrite({
8690
+ fields: this.fields,
8691
+ existing: record,
8692
+ input: item,
8693
+ merge
8694
+ });
8695
+ if (!prepared.ok) {
8696
+ throw new Error(prepared.message);
8697
+ }
8698
+ const values = prepared.values;
8699
+ Object.keys(values).forEach((key) => {
8249
8700
  if (this.fields.find((field) => field.name === key)?.type === "json") {
8250
- if (typeof item[key] === "object" || Array.isArray(item[key])) {
8251
- item[key] = JSON.stringify(item[key]);
8701
+ if (typeof values[key] === "object" || Array.isArray(values[key])) {
8702
+ values[key] = JSON.stringify(values[key]);
8252
8703
  }
8253
8704
  }
8254
8705
  });
8255
8706
  const mutation = db.from(getTableName(this.id)).where({ id: record.id }).update({
8256
- ...item,
8257
- tags: item.tags ? Array.isArray(item.tags) ? item.tags.join(",") : item.tags : void 0
8707
+ ...values,
8708
+ tags: values.tags ? Array.isArray(values.tags) ? values.tags.join(",") : values.tags : void 0
8258
8709
  }).returning("id");
8259
8710
  await mutation;
8260
8711
  let jobs = [];
@@ -8265,7 +8716,17 @@ var ExuluContext2 = class {
8265
8716
  const { job: processorJob, result: processorResult } = await this.processField(
8266
8717
  "api",
8267
8718
  {
8268
- ...item,
8719
+ // `values`, not `item` (coordinator ruling, Task 4 fix round 1):
8720
+ // the fence on "don't change processor behaviour" is about WHEN
8721
+ // a processor fires, not WHAT it sees once it does. Before
8722
+ // merge existed, the patch WAS the result, so this was never a
8723
+ // live distinction; `mv_pitches`'s processor (trigger: "always")
8724
+ // is the first real consumer of a merge-listed json field, so a
8725
+ // processor seeing a bare patch instead of the full merged
8726
+ // object is live, not latent. `values` carries the SAME keys
8727
+ // `item` did -- unchanged values pass through by reference --
8728
+ // so this is a no-op for every call that doesn't use `merge`.
8729
+ ...values,
8269
8730
  id: record.id
8270
8731
  },
8271
8732
  config,
@@ -10332,7 +10793,20 @@ var convertContextToTableDefinition = (context) => {
10332
10793
  index: field.index,
10333
10794
  enumValues: field.enumValues,
10334
10795
  allowedFileTypes: field.allowedFileTypes,
10335
- unique: field.unique
10796
+ unique: field.unique,
10797
+ // Task 4 fix round 2, Critical: without this, every context item
10798
+ // table's fields lose their declared json schema on the way into
10799
+ // createMutations/createQueries -- the GraphQL write path (and
10800
+ // vector-search.ts's filter path, Task 5) would see `schema:
10801
+ // undefined` for every field, no matter what the context declares.
10802
+ // This is an explicit allowlist with NO spread (by design, so a
10803
+ // write-only secret like `hidden` doesn't leak into read-side SDL by
10804
+ // accident) -- which also means every new ExuluContextFieldDefinition
10805
+ // property has to be added here deliberately. `hidden` itself is a
10806
+ // known, still-open instance of exactly this failure mode (not fixed
10807
+ // here -- out of this task's scope); `schema` must not become a
10808
+ // second one.
10809
+ schema: field.schema
10336
10810
  }))
10337
10811
  };
10338
10812
  definition.fields.push({
@@ -10622,7 +11096,7 @@ async function findVisible(context, id, user) {
10622
11096
  }
10623
11097
  function createMemoryTools({ agent, context, user }) {
10624
11098
  const types = memoryTypeValues(context);
10625
- const typeSchema = types.length > 0 ? z9.enum(types) : z9.string();
11099
+ const typeSchema = types.length > 0 ? z10.enum(types) : z10.string();
10626
11100
  const category = `${agent.name}_memory`;
10627
11101
  const remember = new ExuluTool({
10628
11102
  id: "memory_remember",
@@ -10632,12 +11106,12 @@ function createMemoryTools({ agent, context, user }) {
10632
11106
  config: [],
10633
11107
  needsApproval: true,
10634
11108
  description: `Propose saving ONE fact, preference, decision or instruction the user shared to ${agent.name}'s long-term memory. The user reviews the wording and who can see it on a card before anything is saved; never ask about visibility yourself unless the user raised it, and never claim something was saved until this tool returns memory_saved. Call it once per fact, in the user's own words.`,
10635
- inputSchema: z9.object({
10636
- title: z9.string().describe("Short title, max 80 characters"),
10637
- information: z9.string().describe("The fact in one or two sentences, in the user's own words"),
11109
+ inputSchema: z10.object({
11110
+ title: z10.string().describe("Short title, max 80 characters"),
11111
+ information: z10.string().describe("The fact in one or two sentences, in the user's own words"),
10638
11112
  type: typeSchema.describe(`Memory type. One of: ${types.join(", ")}`),
10639
- whySaved: z9.string().describe("Why this is worth remembering: the question or topic that triggered it"),
10640
- visibility: z9.enum(["private", "public"]).optional().describe("Only when the user explicitly said who may see it")
11113
+ whySaved: z10.string().describe("Why this is worth remembering: the question or topic that triggered it"),
11114
+ visibility: z10.enum(["private", "public"]).optional().describe("Only when the user explicitly said who may see it")
10641
11115
  }),
10642
11116
  execute: async (params) => {
10643
11117
  const { user: u, exuluConfig, memoryDecision } = params;
@@ -10721,12 +11195,12 @@ function createMemoryTools({ agent, context, user }) {
10721
11195
  config: [],
10722
11196
  needsApproval: true,
10723
11197
  description: `Propose a correction to an existing memory of ${agent.name} (use the item_id from the memory block). Only the person who saved it, people with write access, or admins can change it; otherwise the result names the creator so you can suggest asking them. The user confirms on a card before anything changes.`,
10724
- inputSchema: z9.object({
10725
- memoryId: z9.string().describe("item_id of the memory to change"),
10726
- information: z9.string().optional().describe("New wording, if it changes"),
10727
- title: z9.string().optional(),
11198
+ inputSchema: z10.object({
11199
+ memoryId: z10.string().describe("item_id of the memory to change"),
11200
+ information: z10.string().optional().describe("New wording, if it changes"),
11201
+ title: z10.string().optional(),
10728
11202
  type: typeSchema.optional(),
10729
- reason: z9.string().describe("What the user said that contradicts or refines the memory")
11203
+ reason: z10.string().describe("What the user said that contradicts or refines the memory")
10730
11204
  }),
10731
11205
  execute: async (params) => {
10732
11206
  const { user: u, exuluConfig, memoryDecision } = params;
@@ -10765,9 +11239,9 @@ function createMemoryTools({ agent, context, user }) {
10765
11239
  config: [],
10766
11240
  needsApproval: true,
10767
11241
  description: `Propose deleting one of ${agent.name}'s memories when the user asks to forget it (use the item_id from the memory block). Same access rule as update_memory; the user confirms on a card before anything is deleted.`,
10768
- inputSchema: z9.object({
10769
- memoryId: z9.string().describe("item_id of the memory to delete"),
10770
- reason: z9.string().describe("What the user said")
11242
+ inputSchema: z10.object({
11243
+ memoryId: z10.string().describe("item_id of the memory to delete"),
11244
+ reason: z10.string().describe("What the user said")
10771
11245
  }),
10772
11246
  execute: async (params) => {
10773
11247
  const { user: u } = params;
@@ -10863,7 +11337,7 @@ function collectMemoryDecisions(messages) {
10863
11337
  }
10864
11338
 
10865
11339
  // src/templates/tools/context-write-tools.ts
10866
- import { z as z11 } from "zod";
11340
+ import { z as z12 } from "zod";
10867
11341
  import { randomUUID as randomUUID3 } from "crypto";
10868
11342
 
10869
11343
  // src/exulu/session-files.ts
@@ -10947,11 +11421,11 @@ var checkItemWriteAccess = async (context, record, user) => {
10947
11421
  };
10948
11422
 
10949
11423
  // src/templates/tools/kb-editor-config.ts
10950
- import { z as z10 } from "zod";
11424
+ import { z as z11 } from "zod";
10951
11425
  var KB_EDITOR_TOOL_ID = "knowledge_base_editor";
10952
- var permissionsSchema = z10.object({
10953
- create: z10.boolean().catch(false).default(false),
10954
- update: z10.boolean().catch(false).default(false)
11426
+ var permissionsSchema = z11.object({
11427
+ create: z11.boolean().catch(false).default(false),
11428
+ update: z11.boolean().catch(false).default(false)
10955
11429
  });
10956
11430
  var emptyConfig = () => ({
10957
11431
  enabled: false,
@@ -11022,21 +11496,22 @@ var buildWriteSchema = (context, mode) => {
11022
11496
  const shape = {};
11023
11497
  const contentKeys = [];
11024
11498
  const fileFields = [];
11499
+ const jsonFieldNames = [];
11025
11500
  const addContent = (key, schema, required) => {
11026
11501
  shape[key] = required && mode === "create" ? schema : schema.optional();
11027
11502
  contentKeys.push(key);
11028
11503
  };
11029
11504
  if (mode === "update") {
11030
- shape["id"] = z11.string().optional().describe("The id of the item to update.");
11031
- shape["external_id"] = z11.string().optional().describe("The external_id of the item to update, if the id is unknown. Lookup only \u2014 it is never changed.");
11505
+ shape["id"] = z12.string().optional().describe("The id of the item to update.");
11506
+ shape["external_id"] = z12.string().optional().describe("The external_id of the item to update, if the id is unknown. Lookup only \u2014 it is never changed.");
11032
11507
  }
11033
- addContent("name", z11.string().describe("The name of the item."), true);
11034
- addContent("description", z11.string().describe("A description of the item."), false);
11035
- addContent("tags", z11.array(z11.string()).describe("Tags for the item."), false);
11508
+ addContent("name", z12.string().describe("The name of the item."), true);
11509
+ addContent("description", z12.string().describe("A description of the item."), false);
11510
+ addContent("tags", z12.array(z12.string()).describe("Tags for the item."), false);
11036
11511
  if (mode === "create") {
11037
11512
  addContent(
11038
11513
  "external_id",
11039
- z11.string().describe("An optional external identifier for the item, e.g. an id from a source system."),
11514
+ z12.string().describe("An optional external identifier for the item, e.g. an id from a source system."),
11040
11515
  false
11041
11516
  );
11042
11517
  }
@@ -11049,7 +11524,7 @@ var buildWriteSchema = (context, mode) => {
11049
11524
  const allowed = (field.allowedFileTypes ?? []).map((ext) => ext.toLowerCase());
11050
11525
  const column = `${field.name}_s3key`;
11051
11526
  const allowedNote = allowed.length ? ` Allowed types: ${allowed.join(", ")}.` : "";
11052
- shape[field.name] = (field.required === true && mode === "create" ? z11.string() : z11.string().optional()).describe(
11527
+ shape[field.name] = (field.required === true && mode === "create" ? z12.string() : z12.string().optional()).describe(
11053
11528
  `The ${field.name} file: the bare name of a file from this session's files (as listed there, no path).${allowedNote}` + (mode === "update" ? " Omit to keep the current file." : "")
11054
11529
  );
11055
11530
  contentKeys.push(column);
@@ -11059,32 +11534,38 @@ var buildWriteSchema = (context, mode) => {
11059
11534
  let schema;
11060
11535
  switch (field.type) {
11061
11536
  case "enum":
11062
- schema = z11.string().describe(
11537
+ schema = z12.string().describe(
11063
11538
  `The ${field.name} of the item. Must be one of: ${(field.enumValues ?? []).join(", ")}`
11064
11539
  );
11065
11540
  break;
11066
11541
  case "json":
11067
- schema = z11.string().describe(`The ${field.name} of the item, as a valid JSON string.`);
11542
+ jsonFieldNames.push(field.name);
11543
+ schema = field.schema ? loosenForTransport(field.schema).describe(`The ${field.name} of the item.`) : z12.string().describe(`The ${field.name} of the item, as a valid JSON string.`);
11068
11544
  break;
11069
11545
  case "markdown":
11070
- schema = z11.string().describe(`The ${field.name} of the item, as a valid Markdown string.`);
11546
+ schema = z12.string().describe(`The ${field.name} of the item, as a valid Markdown string.`);
11071
11547
  break;
11072
11548
  case "date":
11073
- schema = z11.string().describe(`The ${field.name} of the item, as an ISO-8601 date string.`);
11549
+ schema = z12.string().describe(`The ${field.name} of the item, as an ISO-8601 date string.`);
11074
11550
  break;
11075
11551
  case "number":
11076
- schema = z11.number().describe(`The ${field.name} of the item.`);
11552
+ schema = z12.number().describe(`The ${field.name} of the item.`);
11077
11553
  break;
11078
11554
  case "boolean":
11079
- schema = z11.boolean().describe(`The ${field.name} of the item.`);
11555
+ schema = z12.boolean().describe(`The ${field.name} of the item.`);
11080
11556
  break;
11081
11557
  default:
11082
- schema = z11.string().describe(`The ${field.name} of the item.`);
11558
+ schema = z12.string().describe(`The ${field.name} of the item.`);
11083
11559
  break;
11084
11560
  }
11085
11561
  addContent(field.name, schema, field.required === true);
11086
11562
  }
11087
- return { shape, contentKeys, fileFields };
11563
+ if (mode === "update" && jsonFieldNames.length > 0 && !shape["merge"]) {
11564
+ shape["merge"] = z12.array(z12.string()).optional().describe(
11565
+ `Names of json fields in THIS call (choose from: ${jsonFieldNames.join(", ")}) whose given value should be merged into the stored value instead of replacing it: only the keys given are changed, every other stored key is kept, and giving a key an explicit null value deletes just that key. Omit a field's name here (or omit "merge" entirely) to replace its whole value, as normal. Every name must be spelled exactly as listed above AND be a field you are sending a value for in this same call; a name that is neither is refused, not ignored. Do not run two merges on the same item at once: a merge reads the stored value and writes the combined result in two steps with no lock, so overlapping merges can lose one of them.`
11566
+ );
11567
+ }
11568
+ return { shape, contentKeys, fileFields, jsonFieldNames };
11088
11569
  };
11089
11570
  var BARE_FILENAME = /^[^/\\]+$/;
11090
11571
  var attachSessionFiles = async (params, fileFields, deps) => {
@@ -11162,7 +11643,7 @@ var createContextWriteTools = (context, perms, skipApproval, deps = {}) => {
11162
11643
  category: "knowledge_base_editing",
11163
11644
  description: `Create a new item in the "${context.name}" knowledge base.${contextLabel}${fileNote}`,
11164
11645
  type: "function",
11165
- inputSchema: z11.object(shape),
11646
+ inputSchema: z12.object(shape),
11166
11647
  config: [],
11167
11648
  needsApproval: !skipApproval,
11168
11649
  execute: async (params) => {
@@ -11215,7 +11696,7 @@ var createContextWriteTools = (context, perms, skipApproval, deps = {}) => {
11215
11696
  category: "knowledge_base_editing",
11216
11697
  description: `Update an existing item in the "${context.name}" knowledge base. Provide the item's id (or external_id) plus only the fields to change; omitted fields keep their values.${fileNote}`,
11217
11698
  type: "function",
11218
- inputSchema: z11.object(shape),
11699
+ inputSchema: z12.object(shape),
11219
11700
  config: [],
11220
11701
  needsApproval: !skipApproval,
11221
11702
  execute: async (params) => {
@@ -11250,7 +11731,16 @@ var createContextWriteTools = (context, perms, skipApproval, deps = {}) => {
11250
11731
  return { result: "No fields to update were provided." };
11251
11732
  }
11252
11733
  patch.id = existing.id;
11253
- const { job } = await context.updateItem(patch, exuluConfig, user?.id, user?.role?.id);
11734
+ const merge = Array.isArray(params.merge) ? params.merge : void 0;
11735
+ const { job } = await context.updateItem(
11736
+ patch,
11737
+ exuluConfig,
11738
+ user?.id,
11739
+ user?.role?.id,
11740
+ void 0,
11741
+ void 0,
11742
+ merge
11743
+ );
11254
11744
  const fresh = await context.getItem({ item: { id: existing.id } });
11255
11745
  const summary = { id: existing.id };
11256
11746
  for (const key of contentKeys) {
@@ -11280,7 +11770,7 @@ var createKbEditorPickerTool = () => new ExuluTool({
11280
11770
  category: "default",
11281
11771
  description: "Let this agent create or update items in selected knowledge bases during chat, including attaching files from the session's files to file fields. Configure per knowledge base whether the agent may create and/or update items.",
11282
11772
  type: "function",
11283
- inputSchema: z11.object({}),
11773
+ inputSchema: z12.object({}),
11284
11774
  config: [
11285
11775
  {
11286
11776
  name: "knowledge_bases",
@@ -11319,7 +11809,7 @@ var collectKbWriteTools = (agent, contexts, deps = {}) => {
11319
11809
 
11320
11810
  // src/templates/tools/skill-author-tools.ts
11321
11811
  import { randomUUID as randomUUID4 } from "crypto";
11322
- import { z as z12 } from "zod";
11812
+ import { z as z13 } from "zod";
11323
11813
 
11324
11814
  // ee/rbac-resolver.ts
11325
11815
  var RBACResolver = async (db, entityName, resourceId, rights_mode) => {
@@ -11623,7 +12113,7 @@ var createSkillAuthorTools = (agent, deps = {}) => {
11623
12113
  config: [],
11624
12114
  needsApproval: false,
11625
12115
  description: "List the skills in this instance's library that the current user may read: name, description and current version. Use it before creating a skill to avoid duplicates, and before updating one.",
11626
- inputSchema: z12.object({ query: z12.string().optional().describe("Optional substring to filter by name or description") }),
12116
+ inputSchema: z13.object({ query: z13.string().optional().describe("Optional substring to filter by name or description") }),
11627
12117
  execute: async (params) => {
11628
12118
  const { user } = params;
11629
12119
  if (!user?.id) return err2("Skills require a signed-in user.");
@@ -11649,9 +12139,9 @@ var createSkillAuthorTools = (agent, deps = {}) => {
11649
12139
  config: [],
11650
12140
  needsApproval: false,
11651
12141
  description: "Read a skill the user may access: its file list and the content of SKILL.md, or of one file by path. Use it before updating a skill so you change only what must change.",
11652
- inputSchema: z12.object({
11653
- skill: z12.string().describe("The skill's name or id"),
11654
- path: z12.string().optional().describe("A file path inside the skill to read instead of SKILL.md")
12142
+ inputSchema: z13.object({
12143
+ skill: z13.string().describe("The skill's name or id"),
12144
+ path: z13.string().optional().describe("A file path inside the skill to read instead of SKILL.md")
11655
12145
  }),
11656
12146
  execute: async (params) => {
11657
12147
  const { user, exuluConfig } = params;
@@ -11696,10 +12186,10 @@ ${content}`
11696
12186
  needsApproval: !config.skipApproval,
11697
12187
  needsApprovalFn: approvalFn,
11698
12188
  description: "Propose a NEW skill from a procedure the user just completed. Give it a short name, a one-line description, and its files: a SKILL.md with frontmatter and clear steps, plus reference files only where useful. The user confirms name, description and visibility on a card before anything is created; never claim it exists until this tool returns skill_created.",
11699
- inputSchema: z12.object({
11700
- name: z12.string().describe("Short, specific skill name (e.g. 'quarterly-report-from-crm')"),
11701
- description: z12.string().describe("One line: what the skill does and when to use it"),
11702
- files: z12.array(z12.object({ path: z12.string().describe("Relative path inside the skill, e.g. SKILL.md or references/checklist.md"), content: z12.string() })).min(1).describe("The skill's files; SKILL.md is required")
12189
+ inputSchema: z13.object({
12190
+ name: z13.string().describe("Short, specific skill name (e.g. 'quarterly-report-from-crm')"),
12191
+ description: z13.string().describe("One line: what the skill does and when to use it"),
12192
+ files: z13.array(z13.object({ path: z13.string().describe("Relative path inside the skill, e.g. SKILL.md or references/checklist.md"), content: z13.string() })).min(1).describe("The skill's files; SKILL.md is required")
11703
12193
  }),
11704
12194
  execute: async (params) => {
11705
12195
  const { user, exuluConfig } = params;
@@ -11765,12 +12255,12 @@ ${content}`
11765
12255
  needsApproval: !config.skipApproval,
11766
12256
  needsApprovalFn: approvalFn,
11767
12257
  description: "Publish a new version of an existing skill the user may write: pass only the files to add or replace (full content each) and, optionally, paths to remove. Unchanged files carry over. Read the skill first with skill_read. The user confirms on a card; never claim the change happened until this tool returns skill_updated.",
11768
- inputSchema: z12.object({
11769
- skill: z12.string().describe("The skill's name or id"),
11770
- files: z12.array(z12.object({ path: z12.string(), content: z12.string() })).optional().describe("Files to add or replace, full content each"),
11771
- deletePaths: z12.array(z12.string()).optional().describe("Paths to remove in the new version"),
11772
- description: z12.string().optional().describe("A new one-line description, if it changed"),
11773
- label: z12.string().optional().describe("A short label for this version, e.g. 'Added the review checklist'")
12258
+ inputSchema: z13.object({
12259
+ skill: z13.string().describe("The skill's name or id"),
12260
+ files: z13.array(z13.object({ path: z13.string(), content: z13.string() })).optional().describe("Files to add or replace, full content each"),
12261
+ deletePaths: z13.array(z13.string()).optional().describe("Paths to remove in the new version"),
12262
+ description: z13.string().optional().describe("A new one-line description, if it changed"),
12263
+ label: z13.string().optional().describe("A short label for this version, e.g. 'Added the review checklist'")
11774
12264
  }),
11775
12265
  execute: async (params) => {
11776
12266
  const { user, exuluConfig } = params;
@@ -11847,7 +12337,7 @@ var createSkillAuthorPickerTool = () => new ExuluTool({
11847
12337
  category: "default",
11848
12338
  description: "Let this agent create skills and publish new versions of existing ones from the chat, with the user's consent on a card. Adds a system-prompt hint to offer a skill only after complex, recurring, multi-step work \u2014 never for a single question or correction.",
11849
12339
  type: "function",
11850
- inputSchema: z12.object({}),
12340
+ inputSchema: z13.object({}),
11851
12341
  config: [
11852
12342
  { name: "create", description: "The agent may propose new skills.", type: "boolean", default: true },
11853
12343
  { name: "update", description: "The agent may publish new versions of skills the user can write.", type: "boolean", default: true },
@@ -12816,7 +13306,7 @@ var buildSkillSandboxEvent = (ctx, opts = {}) => {
12816
13306
  // ee/invoke-skills/create-sandbox.ts
12817
13307
  import { createBashTool } from "bash-tool";
12818
13308
  import { tool as tool2 } from "ai";
12819
- import { z as z13 } from "zod";
13309
+ import { z as z14 } from "zod";
12820
13310
  import CryptoJS3 from "crypto-js";
12821
13311
  var getAllExuluVariables = async () => {
12822
13312
  const { db } = await postgresClient();
@@ -13340,9 +13830,9 @@ Probe error: ${probe.reason ?? "(no detail)"}`
13340
13830
  });
13341
13831
  const writeFileTool = tool2({
13342
13832
  description: 'Write content to a file in the sandbox. Creates parent directories if needed. Paths are always resolved against the session sandbox root \u2014 both relative paths ("skills/<Skill name>/SKILL.md") and leading-slash paths ("/skills/<Skill name>/SKILL.md") work and reach the same file. When the path is under the session artifact tree, the file is also uploaded to S3 and a short-lived presigned URL is returned in the tool output.',
13343
- inputSchema: z13.object({
13344
- path: z13.string().describe("The path where the file should be written. Relative paths and leading-slash paths are both resolved against the session sandbox root."),
13345
- content: z13.string().describe("The content to write to the file")
13833
+ inputSchema: z14.object({
13834
+ path: z14.string().describe("The path where the file should be written. Relative paths and leading-slash paths are both resolved against the session sandbox root."),
13835
+ content: z14.string().describe("The content to write to the file")
13346
13836
  }),
13347
13837
  execute: async ({ path: path3, content }) => {
13348
13838
  const resolvedPath = resolveSessionPath(path3, sessionDir);
@@ -13361,8 +13851,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
13361
13851
  });
13362
13852
  const readFileTool = tool2({
13363
13853
  description: 'Read the contents of a file from the sandbox. Paths are always resolved against the session sandbox root \u2014 both relative paths ("skills/<Skill name>/SKILL.md") and leading-slash paths ("/skills/<Skill name>/SKILL.md") work and reach the same file. Skills live in a folder per skill: "skills/<Skill name>/SKILL.md", never "skills/<Skill name>.md". If the file does not exist, the error message is surfaced verbatim.',
13364
- inputSchema: z13.object({
13365
- path: z13.string().describe("The path of the file to read. Relative paths and leading-slash paths are both resolved against the session sandbox root.")
13854
+ inputSchema: z14.object({
13855
+ path: z14.string().describe("The path of the file to read. Relative paths and leading-slash paths are both resolved against the session sandbox root.")
13366
13856
  }),
13367
13857
  execute: async ({ path: path3 }) => {
13368
13858
  const resolvedPath = resolveSessionPath(path3, sessionDir);
@@ -13379,8 +13869,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
13379
13869
  const originalBashTool = tools.bash;
13380
13870
  const bashTool = tool2({
13381
13871
  description: originalBashTool.description ?? "",
13382
- inputSchema: z13.object({
13383
- command: z13.string().describe("The bash command to execute.")
13872
+ inputSchema: z14.object({
13873
+ command: z14.string().describe("The bash command to execute.")
13384
13874
  }),
13385
13875
  execute: async (args, opts) => {
13386
13876
  const before = persistenceEnabled ? await snapshotSessionArtifacts() : null;
@@ -13652,7 +14142,7 @@ var buildAuthToolModelOutput = (tool3) => ({ output }) => {
13652
14142
  };
13653
14143
 
13654
14144
  // src/templates/tools/session-file-read-tool.ts
13655
- import { z as z14 } from "zod";
14145
+ import { z as z15 } from "zod";
13656
14146
  var DEFAULT_LIMIT = 250;
13657
14147
  var MAX_CONTENT_CHARS = 16e3;
13658
14148
  var SESSION_FILE_READ_TOOL_NAME = "read_session_file";
@@ -13705,10 +14195,10 @@ var createSessionFileReadTool = ({
13705
14195
  name: SESSION_FILE_READ_TOOL_NAME,
13706
14196
  needsApproval: false,
13707
14197
  description: "Read a line range from a file stored in this session's files \u2014 including offloaded tool outputs (tool-output-*.txt) and uploaded documents. Use offset (1-based line number) and limit to page through large files instead of reading everything at once.",
13708
- inputSchema: z14.object({
13709
- filename: z14.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
13710
- offset: z14.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
13711
- limit: z14.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT})`)
14198
+ inputSchema: z15.object({
14199
+ filename: z15.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
14200
+ offset: z15.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
14201
+ limit: z15.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT})`)
13712
14202
  }),
13713
14203
  type: "function",
13714
14204
  category: "session",
@@ -13721,7 +14211,7 @@ var createSessionFileReadTool = ({
13721
14211
  };
13722
14212
 
13723
14213
  // src/templates/tools/parse-document-tool.ts
13724
- import { z as z15 } from "zod";
14214
+ import { z as z16 } from "zod";
13725
14215
  import { extname } from "path";
13726
14216
  import { parseOfficeAsync as parseOfficeAsync2 } from "officeparser";
13727
14217
 
@@ -14090,11 +14580,11 @@ ${text.trim()}`).join("\n");
14090
14580
  name: PARSE_DOCUMENT_TOOL_NAME,
14091
14581
  needsApproval: false,
14092
14582
  description: `Extract the text of an uploaded PDF or Office document from this session's files, with "--- page N ---" markers for PDFs so you can locate content by page. Free and fast (no OCR): works only on documents with a real text layer. To SEE a page or an image inside a document, use view_document_page.`,
14093
- inputSchema: z15.object({
14094
- filename: z15.string().describe('Exact session file name, e.g. "report.pdf"'),
14095
- pages: z15.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
14096
- offset: z15.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
14097
- limit: z15.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT2})`)
14583
+ inputSchema: z16.object({
14584
+ filename: z16.string().describe('Exact session file name, e.g. "report.pdf"'),
14585
+ pages: z16.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
14586
+ offset: z16.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
14587
+ limit: z16.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT2})`)
14098
14588
  }),
14099
14589
  type: "function",
14100
14590
  category: "session",
@@ -14107,7 +14597,7 @@ ${text.trim()}`).join("\n");
14107
14597
  };
14108
14598
 
14109
14599
  // src/templates/tools/view-document-page-tool.ts
14110
- import { z as z16 } from "zod";
14600
+ import { z as z17 } from "zod";
14111
14601
  import { extname as extname3 } from "path";
14112
14602
 
14113
14603
  // src/sessions/pdf-preview-cache.ts
@@ -14378,9 +14868,9 @@ var createViewDocumentPageTool = ({
14378
14868
  name: VIEW_DOCUMENT_PAGE_TOOL_NAME,
14379
14869
  needsApproval: false,
14380
14870
  description: "LOOK at a page of an uploaded PDF/Office document, or at an uploaded image, from this session's files. The rendered image is attached as a user message directly after this tool result so you can visually analyze photos, charts, scans, and layouts. Use parse_document first to find which page you need. Requires a vision-capable model.",
14381
- inputSchema: z16.object({
14382
- filename: z16.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
14383
- page: z16.number().int().min(1).optional().describe("Page number to render (default 1; ignored for image files)")
14871
+ inputSchema: z17.object({
14872
+ filename: z17.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
14873
+ page: z17.number().int().min(1).optional().describe("Page number to render (default 1; ignored for image files)")
14384
14874
  }),
14385
14875
  type: "function",
14386
14876
  category: "session",
@@ -14972,6 +15462,7 @@ export {
14972
15462
  BaseChunker,
14973
15463
  SentenceChunker,
14974
15464
  defaultChunker,
15465
+ prepareItemWrite,
14975
15466
  resolveEmbedder,
14976
15467
  PROJECTION_VERSION,
14977
15468
  PROJECTION_METHOD,