@exulu/backend 5.9.0 → 5.10.1

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.cjs CHANGED
@@ -2134,6 +2134,412 @@ var init_chunker = __esm({
2134
2134
  }
2135
2135
  });
2136
2136
 
2137
+ // src/exulu/json-field-schema.ts
2138
+ function unwrap(schema7) {
2139
+ let current = schema7;
2140
+ for (; ; ) {
2141
+ const def = current.def;
2142
+ if (def.type === "optional" || def.type === "nullable" || def.type === "default") {
2143
+ current = def.innerType;
2144
+ continue;
2145
+ }
2146
+ return current;
2147
+ }
2148
+ }
2149
+ function isPlainObject(value) {
2150
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2151
+ }
2152
+ function hasOwn(target, key) {
2153
+ return Object.prototype.hasOwnProperty.call(target, key);
2154
+ }
2155
+ function schemaPaths(schema7) {
2156
+ const base = unwrap(schema7);
2157
+ const def = base.def;
2158
+ if (def.type === "union") {
2159
+ const seen = /* @__PURE__ */ new Set();
2160
+ for (const option of def.options) {
2161
+ for (const path4 of schemaPaths(option)) seen.add(path4);
2162
+ }
2163
+ return [...seen];
2164
+ }
2165
+ if (def.type === "record") {
2166
+ const subPaths = schemaPaths(def.valueType);
2167
+ return subPaths.length > 0 ? subPaths.map((path4) => `<key>.${path4}`) : ["<key>"];
2168
+ }
2169
+ if (def.type !== "object") {
2170
+ return [];
2171
+ }
2172
+ const shape = def.shape;
2173
+ const paths = [];
2174
+ for (const key of Object.keys(shape)) {
2175
+ const child = shape[key];
2176
+ if (!child) continue;
2177
+ const childDef = unwrap(child).def;
2178
+ if (childDef.type === "object") {
2179
+ for (const subKey of Object.keys(childDef.shape)) {
2180
+ paths.push(`${key}.${subKey}`);
2181
+ }
2182
+ } else {
2183
+ paths.push(key);
2184
+ }
2185
+ }
2186
+ return paths;
2187
+ }
2188
+ function unknownChildPaths(child, value, key) {
2189
+ const childDef = unwrap(child).def;
2190
+ if (childDef.type === "object") {
2191
+ if (!isPlainObject(value)) {
2192
+ return [key];
2193
+ }
2194
+ const childShape = childDef.shape;
2195
+ const unknown = [];
2196
+ for (const subKey of Object.keys(value)) {
2197
+ if (!hasOwn(childShape, subKey)) unknown.push(`${key}.${subKey}`);
2198
+ }
2199
+ return unknown;
2200
+ }
2201
+ if (childDef.type === "record" && !isPlainObject(value)) {
2202
+ return [key];
2203
+ }
2204
+ return [];
2205
+ }
2206
+ function unknownPaths(schema7, value) {
2207
+ if (!isPlainObject(value)) return [];
2208
+ const base = unwrap(schema7);
2209
+ const def = base.def;
2210
+ if (def.type === "record") {
2211
+ const valueType = def.valueType;
2212
+ const unknown2 = [];
2213
+ for (const [key, inner] of Object.entries(value)) {
2214
+ unknown2.push(...unknownChildPaths(valueType, inner, key));
2215
+ }
2216
+ return unknown2;
2217
+ }
2218
+ if (def.type !== "object") {
2219
+ return [];
2220
+ }
2221
+ const shape = def.shape;
2222
+ const unknown = [];
2223
+ for (const [key, inner] of Object.entries(value)) {
2224
+ const child = hasOwn(shape, key) ? shape[key] : void 0;
2225
+ if (!child) {
2226
+ unknown.push(key);
2227
+ continue;
2228
+ }
2229
+ unknown.push(...unknownChildPaths(child, inner, key));
2230
+ }
2231
+ return unknown;
2232
+ }
2233
+ function valueAtPath(value, path4) {
2234
+ let current = value;
2235
+ for (const segment of path4) {
2236
+ if (current === null || typeof current !== "object") return void 0;
2237
+ current = current[segment];
2238
+ }
2239
+ return current;
2240
+ }
2241
+ function leafViolations(schema7, value) {
2242
+ if (!isPlainObject(value)) return [];
2243
+ const base = unwrap(schema7);
2244
+ const def = base.def;
2245
+ let subSchemaFor;
2246
+ if (def.type === "record") {
2247
+ const valueType = def.valueType;
2248
+ subSchemaFor = () => valueType;
2249
+ } else if (def.type === "object") {
2250
+ const shape = def.shape;
2251
+ subSchemaFor = (key) => hasOwn(shape, key) ? shape[key] : void 0;
2252
+ } else {
2253
+ return [];
2254
+ }
2255
+ const violations = [];
2256
+ for (const [key, inner] of Object.entries(value)) {
2257
+ const subSchema = subSchemaFor(key);
2258
+ if (!subSchema) continue;
2259
+ const result = subSchema.safeParse(inner);
2260
+ if (result.success) continue;
2261
+ for (const issue of result.error.issues) {
2262
+ const issuePath = issue.path.map(String);
2263
+ const expectedSet = describeExpectedValues(issue);
2264
+ violations.push({
2265
+ path: [key, ...issuePath].join("."),
2266
+ expected: expectedSet ? `expected one of ${expectedSet}` : issue.message,
2267
+ received: issue.path.length > 0 ? valueAtPath(inner, issue.path) : inner
2268
+ });
2269
+ }
2270
+ }
2271
+ return violations;
2272
+ }
2273
+ function describeExpectedValues(issue) {
2274
+ const anyIssue = issue;
2275
+ if (anyIssue.code === "invalid_value" && Array.isArray(anyIssue.values) && anyIssue.values.length > 0) {
2276
+ return anyIssue.values.map((value) => JSON.stringify(value)).join(" | ");
2277
+ }
2278
+ if (anyIssue.code === "invalid_union" && Array.isArray(anyIssue.errors)) {
2279
+ const parts = [];
2280
+ for (const branchIssues of anyIssue.errors) {
2281
+ const branchArray = branchIssues;
2282
+ const first = branchArray[0];
2283
+ if (!first || !Array.isArray(first.values) || first.values.length === 0) return void 0;
2284
+ parts.push(...first.values.map((value) => JSON.stringify(value)));
2285
+ }
2286
+ return parts.length > 0 ? parts.join(" | ") : void 0;
2287
+ }
2288
+ return void 0;
2289
+ }
2290
+ function missingRequiredKeys(schema7, value) {
2291
+ if (!isPlainObject(value)) return [];
2292
+ const def = unwrap(schema7).def;
2293
+ if (def.type !== "object") return [];
2294
+ const shape = def.shape;
2295
+ const missing = [];
2296
+ for (const key of Object.keys(shape)) {
2297
+ const child = shape[key];
2298
+ if (!child) continue;
2299
+ if (hasOwn(value, key)) continue;
2300
+ if (!child.safeParse(void 0).success) missing.push(key);
2301
+ }
2302
+ return missing;
2303
+ }
2304
+ function requiresPlainObject(schema7) {
2305
+ const def = unwrap(schema7).def;
2306
+ return def.type === "object" || def.type === "record";
2307
+ }
2308
+ function preserveDescription(original, rebuilt) {
2309
+ return original.description ? rebuilt.describe(original.description) : rebuilt;
2310
+ }
2311
+ function loosenForTransport(schema7) {
2312
+ const def = schema7.def;
2313
+ switch (def.type) {
2314
+ case "optional":
2315
+ return preserveDescription(schema7, import_zod.z.optional(loosenForTransport(def.innerType)));
2316
+ case "nullable":
2317
+ return preserveDescription(schema7, import_zod.z.nullable(loosenForTransport(def.innerType)));
2318
+ case "default":
2319
+ return preserveDescription(
2320
+ schema7,
2321
+ loosenForTransport(def.innerType).default(
2322
+ def.defaultValue
2323
+ )
2324
+ );
2325
+ case "array":
2326
+ return preserveDescription(schema7, import_zod.z.array(loosenForTransport(def.element)));
2327
+ case "record": {
2328
+ const loosenedValue = loosenForTransport(def.valueType);
2329
+ return preserveDescription(
2330
+ schema7,
2331
+ schema7.clone({ ...def, valueType: loosenedValue })
2332
+ );
2333
+ }
2334
+ case "union":
2335
+ return preserveDescription(
2336
+ schema7,
2337
+ import_zod.z.union(def.options.map((option) => loosenForTransport(option)))
2338
+ );
2339
+ case "object": {
2340
+ const shape = def.shape;
2341
+ const loosenedShape = {};
2342
+ for (const key of Object.keys(shape)) {
2343
+ const child = shape[key];
2344
+ if (!child) continue;
2345
+ loosenedShape[key] = loosenForTransport(child);
2346
+ }
2347
+ return preserveDescription(
2348
+ schema7,
2349
+ import_zod.z.object(loosenedShape).passthrough()
2350
+ );
2351
+ }
2352
+ default:
2353
+ return schema7;
2354
+ }
2355
+ }
2356
+ function mergeJson(stored, patch) {
2357
+ const merged = isPlainObject(stored) ? { ...stored } : {};
2358
+ for (const [key, value] of Object.entries(patch)) {
2359
+ if (value === null) {
2360
+ delete merged[key];
2361
+ } else {
2362
+ Object.defineProperty(merged, key, { value, writable: true, enumerable: true, configurable: true });
2363
+ }
2364
+ }
2365
+ return merged;
2366
+ }
2367
+ var import_zod;
2368
+ var init_json_field_schema = __esm({
2369
+ "src/exulu/json-field-schema.ts"() {
2370
+ "use strict";
2371
+ init_cjs_shims();
2372
+ import_zod = require("zod");
2373
+ }
2374
+ });
2375
+
2376
+ // src/exulu/item-write.ts
2377
+ function isPlainObject2(value) {
2378
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2379
+ }
2380
+ function describeKind(value) {
2381
+ if (value === null) return "null";
2382
+ if (value === void 0) return "undefined";
2383
+ if (Array.isArray(value)) return "an array";
2384
+ const kind = typeof value;
2385
+ return /^[aeiou]/.test(kind) ? `an ${kind}` : `a ${kind}`;
2386
+ }
2387
+ function hasOwnKey(target, key) {
2388
+ return Object.prototype.hasOwnProperty.call(target, key);
2389
+ }
2390
+ function safeStringify(value) {
2391
+ try {
2392
+ return JSON.stringify(value);
2393
+ } catch {
2394
+ return String(value);
2395
+ }
2396
+ }
2397
+ function omitNullEntries(value) {
2398
+ const filtered = /* @__PURE__ */ Object.create(null);
2399
+ for (const [key, inner] of Object.entries(value)) {
2400
+ if (inner !== null) filtered[key] = inner;
2401
+ }
2402
+ return filtered;
2403
+ }
2404
+ function mergeClearRefusalMessage(fieldName) {
2405
+ 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.`;
2406
+ }
2407
+ function requiredNullRefusalMessage(fieldName) {
2408
+ 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.`;
2409
+ }
2410
+ function mergeNonObjectRefusalMessage(fieldName, value) {
2411
+ const kind = describeKind(value);
2412
+ 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".`;
2413
+ }
2414
+ function mergeStoredNonObjectRefusalMessage(fieldName, stored) {
2415
+ const kind = describeKind(stored);
2416
+ 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".`;
2417
+ }
2418
+ function stringParseFailedMessage(fieldName, raw, schema7) {
2419
+ 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.`;
2420
+ if (!schema7) return base;
2421
+ const validPaths = schemaPaths(schema7);
2422
+ const validList = validPaths.length > 0 ? validPaths.join(", ") : "(the schema declares no paths)";
2423
+ return `${base} Valid paths for "${fieldName}": ${validList}.`;
2424
+ }
2425
+ function shapeRefusalMessage(fieldName, value, schema7) {
2426
+ const kind = describeKind(value);
2427
+ const validPaths = schemaPaths(schema7);
2428
+ const validList = validPaths.length > 0 ? validPaths.join(", ") : "(the schema declares no paths)";
2429
+ 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}.`;
2430
+ }
2431
+ function mergeUnknownFieldMessage(name, reason, mergeableNames) {
2432
+ 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)";
2433
+ 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`;
2434
+ 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}.`;
2435
+ }
2436
+ function missingKeysRefusalMessage(fieldName, missing, schema7) {
2437
+ const plural = missing.length > 1;
2438
+ const missingList = missing.map((key) => `"${key}"`).join(", ");
2439
+ const validPaths = schemaPaths(schema7);
2440
+ const validList = validPaths.length > 0 ? validPaths.join(", ") : "(the schema declares no paths)";
2441
+ 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}.`;
2442
+ }
2443
+ function refusalMessage(fieldName, badPaths, schema7) {
2444
+ const plural = badPaths.length > 1;
2445
+ const badList = badPaths.map((path4) => `"${path4}"`).join(", ");
2446
+ const validPaths = schemaPaths(schema7);
2447
+ const validList = validPaths.length > 0 ? validPaths.join(", ") : "(the schema declares no paths)";
2448
+ 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}.`;
2449
+ }
2450
+ function leafRefusalMessage(fieldName, violations) {
2451
+ const parts = violations.map((violation) => {
2452
+ const got = safeStringify(violation.received);
2453
+ return `"${fieldName}.${violation.path}": ${violation.expected} (got ${got})`;
2454
+ });
2455
+ return `Write to field "${fieldName}" rejected: ${parts.join("; ")}.`;
2456
+ }
2457
+ function prepareItemWrite(args) {
2458
+ const { fields, existing, input, merge } = args;
2459
+ const fieldsByName = new Map(fields.map((field) => [field.name, field]));
2460
+ const values = {};
2461
+ if (merge && merge.length > 0) {
2462
+ const mergeableNames = Object.keys(input).filter((name) => fieldsByName.get(name)?.type === "json");
2463
+ for (const name of merge) {
2464
+ if (fieldsByName.get(name)?.type !== "json") {
2465
+ return { ok: false, message: mergeUnknownFieldMessage(String(name), "not-json", mergeableNames) };
2466
+ }
2467
+ if (!hasOwnKey(input, name)) {
2468
+ return { ok: false, message: mergeUnknownFieldMessage(String(name), "absent", mergeableNames) };
2469
+ }
2470
+ }
2471
+ }
2472
+ for (const [key, value] of Object.entries(input)) {
2473
+ const field = fieldsByName.get(key);
2474
+ const schema7 = field?.type === "json" ? field.schema : void 0;
2475
+ const isMergeField = field?.type === "json" && (merge?.includes(key) ?? false);
2476
+ let checkValue = value;
2477
+ let stringParseFailed = false;
2478
+ if (field?.type === "json" && typeof value === "string") {
2479
+ try {
2480
+ checkValue = JSON.parse(value);
2481
+ } catch {
2482
+ stringParseFailed = true;
2483
+ }
2484
+ }
2485
+ if (isMergeField && checkValue === null) {
2486
+ return { ok: false, message: mergeClearRefusalMessage(key) };
2487
+ }
2488
+ if (!isMergeField && field?.type === "json" && checkValue === null) {
2489
+ if (schema7 && field.required === true) {
2490
+ return { ok: false, message: requiredNullRefusalMessage(key) };
2491
+ }
2492
+ Object.defineProperty(values, key, { value, writable: true, enumerable: true, configurable: true });
2493
+ continue;
2494
+ }
2495
+ if (stringParseFailed && (isMergeField || schema7 && requiresPlainObject(schema7))) {
2496
+ return { ok: false, message: stringParseFailedMessage(key, value, schema7) };
2497
+ }
2498
+ if (isMergeField && (!schema7 || !requiresPlainObject(schema7)) && !isPlainObject2(checkValue)) {
2499
+ return { ok: false, message: mergeNonObjectRefusalMessage(key, checkValue) };
2500
+ }
2501
+ if (isMergeField && isPlainObject2(checkValue)) {
2502
+ const stored = existing?.[key];
2503
+ if (stored !== null && stored !== void 0 && !isPlainObject2(stored)) {
2504
+ return { ok: false, message: mergeStoredNonObjectRefusalMessage(key, stored) };
2505
+ }
2506
+ }
2507
+ if (schema7) {
2508
+ if (requiresPlainObject(schema7) && !isPlainObject2(checkValue) && !schema7.safeParse(checkValue).success) {
2509
+ return { ok: false, message: shapeRefusalMessage(key, checkValue, schema7) };
2510
+ }
2511
+ const toValidate = isMergeField && isPlainObject2(checkValue) ? omitNullEntries(checkValue) : checkValue;
2512
+ const badPaths = unknownPaths(schema7, toValidate);
2513
+ if (badPaths.length > 0) {
2514
+ return { ok: false, message: refusalMessage(key, badPaths, schema7) };
2515
+ }
2516
+ const violations = leafViolations(schema7, toValidate);
2517
+ if (violations.length > 0) {
2518
+ return { ok: false, message: leafRefusalMessage(key, violations) };
2519
+ }
2520
+ if (!isMergeField && isPlainObject2(checkValue) && Object.keys(checkValue).length > 0) {
2521
+ const missing = missingRequiredKeys(schema7, checkValue);
2522
+ if (missing.length > 0) {
2523
+ return { ok: false, message: missingKeysRefusalMessage(key, missing, schema7) };
2524
+ }
2525
+ }
2526
+ }
2527
+ if (isMergeField && isPlainObject2(checkValue)) {
2528
+ Object.defineProperty(values, key, { value: mergeJson(existing?.[key], checkValue), writable: true, enumerable: true, configurable: true });
2529
+ } else {
2530
+ Object.defineProperty(values, key, { value, writable: true, enumerable: true, configurable: true });
2531
+ }
2532
+ }
2533
+ return { ok: true, values };
2534
+ }
2535
+ var init_item_write = __esm({
2536
+ "src/exulu/item-write.ts"() {
2537
+ "use strict";
2538
+ init_cjs_shims();
2539
+ init_json_field_schema();
2540
+ }
2541
+ });
2542
+
2137
2543
  // src/exulu/litellm/env.ts
2138
2544
  function litellmBase() {
2139
2545
  const host = process.env.LITELLM_HOST ?? "127.0.0.1";
@@ -3300,14 +3706,14 @@ function randomizedPCA(rows, dims, k, seed, iterations) {
3300
3706
  for (const row of rows) {
3301
3707
  const centered = new Float64Array(dims);
3302
3708
  for (let d = 0; d < dims; d += 1) centered[d] = (row[d] ?? 0) - (mean[d] ?? 0);
3303
- const z36 = new Float64Array(basis.length);
3709
+ const z37 = new Float64Array(basis.length);
3304
3710
  for (const [b, vec] of basis.entries()) {
3305
3711
  let dot = 0;
3306
3712
  for (let d = 0; d < dims; d += 1) dot += (centered[d] ?? 0) * (vec[d] ?? 0);
3307
- z36[b] = dot;
3713
+ z37[b] = dot;
3308
3714
  }
3309
3715
  for (const [b, target] of next.entries()) {
3310
- const scale = z36[b] ?? 0;
3716
+ const scale = z37[b] ?? 0;
3311
3717
  if (scale === 0) continue;
3312
3718
  for (let d = 0; d < dims; d += 1) target[d] = (target[d] ?? 0) + (centered[d] ?? 0) * scale;
3313
3719
  }
@@ -3405,12 +3811,12 @@ function ridgeFit(Z, Y, lambda) {
3405
3811
  });
3406
3812
  return { map, intercept };
3407
3813
  }
3408
- function applyMap(z36, map, intercept) {
3814
+ function applyMap(z37, map, intercept) {
3409
3815
  const out = [];
3410
3816
  for (let j = 0; j < 3; j += 1) {
3411
3817
  let v = intercept[j] ?? 0;
3412
3818
  const row = map[j] ?? [];
3413
- for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z36[d] ?? 0);
3819
+ for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z37[d] ?? 0);
3414
3820
  out.push(Number.isFinite(v) ? v : 0);
3415
3821
  }
3416
3822
  return [out[0] ?? 0, out[1] ?? 0, out[2] ?? 0];
@@ -3433,8 +3839,8 @@ function fitResidual(Z, Y, map, intercept) {
3433
3839
  for (let i = 0; i < Z.length; i += 1) {
3434
3840
  const zi = Z[i] ?? [];
3435
3841
  const yi = Y[i] ?? [];
3436
- const [x, y, z36] = applyMap(zi, map, intercept);
3437
- total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z36 - finite(yi[2]));
3842
+ const [x, y, z37] = applyMap(zi, map, intercept);
3843
+ total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z37 - finite(yi[2]));
3438
3844
  }
3439
3845
  return finite(total / Z.length);
3440
3846
  }
@@ -3578,8 +3984,8 @@ async function chunkCoordinates({
3578
3984
  }
3579
3985
  return null;
3580
3986
  }
3581
- const [x, y, z36] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
3582
- return { x, y, z: z36 };
3987
+ const [x, y, z37] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
3988
+ return { x, y, z: z37 };
3583
3989
  });
3584
3990
  } catch (e) {
3585
3991
  console.error("[EXULU] could not compute chunk coordinates", e instanceof Error ? e.message : String(e));
@@ -4155,17 +4561,49 @@ var init_access_control = __esm({
4155
4561
  });
4156
4562
 
4157
4563
  // src/graphql/utilities/convert-graphql-filter-operator-to-pg-query.ts
4158
- var convertGraphqlOperatorToPostgresQuery;
4564
+ var UnknownFilterPathError, convertGraphqlOperatorToPostgresQuery;
4159
4565
  var init_convert_graphql_filter_operator_to_pg_query = __esm({
4160
4566
  "src/graphql/utilities/convert-graphql-filter-operator-to-pg-query.ts"() {
4161
4567
  "use strict";
4162
4568
  init_cjs_shims();
4569
+ init_json_field_schema();
4570
+ UnknownFilterPathError = class extends Error {
4571
+ field;
4572
+ offendingPaths;
4573
+ validPaths;
4574
+ constructor(field, offendingPaths, validPaths) {
4575
+ const plural = offendingPaths.length > 1;
4576
+ const badList = offendingPaths.map((path4) => `"${path4}"`).join(", ");
4577
+ const validList = validPaths.length > 0 ? validPaths.join(", ") : "(the schema declares no paths)";
4578
+ super(
4579
+ `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}.`
4580
+ );
4581
+ this.name = "UnknownFilterPathError";
4582
+ this.field = field;
4583
+ this.offendingPaths = offendingPaths;
4584
+ this.validPaths = validPaths;
4585
+ }
4586
+ };
4163
4587
  convertGraphqlOperatorToPostgresQuery = (query, fieldName, operators, table, field_prefix) => {
4164
4588
  const field = table?.fields.find((f) => f.name === fieldName);
4165
4589
  const isJsonField = field?.type === "json";
4166
4590
  const prefix = field_prefix ? field_prefix + "." : "";
4167
4591
  fieldName = prefix + fieldName;
4168
4592
  console.log("[EXULU] operators", operators);
4593
+ if (isJsonField && field?.schema) {
4594
+ const filterValues = [];
4595
+ if (operators.eq !== void 0) filterValues.push(operators.eq);
4596
+ if (operators.ne !== void 0) filterValues.push(operators.ne);
4597
+ if (Array.isArray(operators.in)) filterValues.push(...operators.in);
4598
+ if (operators.contains !== void 0) filterValues.push(operators.contains);
4599
+ const badPaths = /* @__PURE__ */ new Set();
4600
+ for (const value of filterValues) {
4601
+ for (const path4 of unknownPaths(field.schema, value)) badPaths.add(path4);
4602
+ }
4603
+ if (badPaths.size > 0) {
4604
+ throw new UnknownFilterPathError(field.name, [...badPaths], schemaPaths(field.schema));
4605
+ }
4606
+ }
4169
4607
  if (operators.eq !== void 0) {
4170
4608
  if (isJsonField) {
4171
4609
  query = query.whereRaw(`?? = ?::jsonb`, [fieldName, JSON.stringify(operators.eq)]);
@@ -6054,7 +6492,20 @@ var init_convert_context_to_table_definition = __esm({
6054
6492
  index: field.index,
6055
6493
  enumValues: field.enumValues,
6056
6494
  allowedFileTypes: field.allowedFileTypes,
6057
- unique: field.unique
6495
+ unique: field.unique,
6496
+ // Task 4 fix round 2, Critical: without this, every context item
6497
+ // table's fields lose their declared json schema on the way into
6498
+ // createMutations/createQueries -- the GraphQL write path (and
6499
+ // vector-search.ts's filter path, Task 5) would see `schema:
6500
+ // undefined` for every field, no matter what the context declares.
6501
+ // This is an explicit allowlist with NO spread (by design, so a
6502
+ // write-only secret like `hidden` doesn't leak into read-side SDL by
6503
+ // accident) -- which also means every new ExuluContextFieldDefinition
6504
+ // property has to be added here deliberately. `hidden` itself is a
6505
+ // known, still-open instance of exactly this failure mode (not fixed
6506
+ // here -- out of this task's scope); `schema` must not become a
6507
+ // second one.
6508
+ schema: field.schema
6058
6509
  }))
6059
6510
  };
6060
6511
  definition.fields.push({
@@ -6368,38 +6819,38 @@ var init_resolve_model = __esm({
6368
6819
  });
6369
6820
 
6370
6821
  // src/exulu/entities/extractor.ts
6371
- var import_ai, import_zod, CHUNK_BATCH_SIZE, MAX_SUGGESTIONS, mentionSchema, buildSystemPrompt, buildUserPrompt, extractEntitiesForItem;
6822
+ var import_ai, import_zod2, CHUNK_BATCH_SIZE, MAX_SUGGESTIONS, mentionSchema, buildSystemPrompt, buildUserPrompt, extractEntitiesForItem;
6372
6823
  var init_extractor = __esm({
6373
6824
  "src/exulu/entities/extractor.ts"() {
6374
6825
  "use strict";
6375
6826
  init_cjs_shims();
6376
6827
  import_ai = require("ai");
6377
- import_zod = require("zod");
6828
+ import_zod2 = require("zod");
6378
6829
  init_resolve_model();
6379
6830
  init_singleton();
6380
6831
  init_config();
6381
6832
  CHUNK_BATCH_SIZE = 30;
6382
6833
  MAX_SUGGESTIONS = 5;
6383
- mentionSchema = import_zod.z.object({
6384
- entities: import_zod.z.array(
6385
- import_zod.z.object({
6386
- chunkIndex: import_zod.z.number().int().describe("Index of the chunk this entity was found in."),
6387
- type: import_zod.z.string().describe("One of the provided entity type names."),
6388
- mention: import_zod.z.string().describe("The exact surface form as it appears in the text."),
6389
- canonical: import_zod.z.string().describe("The canonical, language-normalized name used to merge variants."),
6390
- confidence: import_zod.z.number().min(0).max(1).describe("Confidence 0..1 that this is a valid entity.")
6834
+ mentionSchema = import_zod2.z.object({
6835
+ entities: import_zod2.z.array(
6836
+ import_zod2.z.object({
6837
+ chunkIndex: import_zod2.z.number().int().describe("Index of the chunk this entity was found in."),
6838
+ type: import_zod2.z.string().describe("One of the provided entity type names."),
6839
+ mention: import_zod2.z.string().describe("The exact surface form as it appears in the text."),
6840
+ canonical: import_zod2.z.string().describe("The canonical, language-normalized name used to merge variants."),
6841
+ confidence: import_zod2.z.number().min(0).max(1).describe("Confidence 0..1 that this is a valid entity.")
6391
6842
  })
6392
6843
  ),
6393
- suggestedTypes: import_zod.z.array(
6394
- import_zod.z.object({
6395
- name: import_zod.z.string().describe("A concise NEW entity type name, e.g. 'Error Code', 'Component'."),
6396
- description: import_zod.z.string().describe("What this type captures, one sentence."),
6397
- mentions: import_zod.z.array(
6398
- import_zod.z.object({
6399
- chunkIndex: import_zod.z.number().int().describe("Index of the chunk this mention was found in."),
6400
- mention: import_zod.z.string().describe("The exact surface form as it appears in the text."),
6401
- canonical: import_zod.z.string().describe("Canonical, language-normalized name."),
6402
- confidence: import_zod.z.number().min(0).max(1).describe("Confidence 0..1.")
6844
+ suggestedTypes: import_zod2.z.array(
6845
+ import_zod2.z.object({
6846
+ name: import_zod2.z.string().describe("A concise NEW entity type name, e.g. 'Error Code', 'Component'."),
6847
+ description: import_zod2.z.string().describe("What this type captures, one sentence."),
6848
+ mentions: import_zod2.z.array(
6849
+ import_zod2.z.object({
6850
+ chunkIndex: import_zod2.z.number().int().describe("Index of the chunk this mention was found in."),
6851
+ mention: import_zod2.z.string().describe("The exact surface form as it appears in the text."),
6852
+ canonical: import_zod2.z.string().describe("Canonical, language-normalized name."),
6853
+ confidence: import_zod2.z.number().min(0).max(1).describe("Confidence 0..1.")
6403
6854
  })
6404
6855
  ).describe("Every mention of this new type found in the provided chunks.")
6405
6856
  })
@@ -7746,6 +8197,7 @@ var init_context = __esm({
7746
8197
  init_table_names();
7747
8198
  import_knex4 = __toESM(require("pgvector/knex"), 1);
7748
8199
  init_chunker();
8200
+ init_item_write();
7749
8201
  init_resolve_embedder();
7750
8202
  init_store();
7751
8203
  init_parse_embedding_models();
@@ -8084,6 +8536,10 @@ var init_context = __esm({
8084
8536
  }
8085
8537
  item.rights_mode = sanitizeItemRightsMode(item.rights_mode, this.configuration.defaultRightsMode);
8086
8538
  const { db: db2 } = await postgresClient();
8539
+ const createValidation = prepareItemWrite({ fields: this.fields, existing: null, input: item });
8540
+ if (!createValidation.ok) {
8541
+ throw new Error(createValidation.message);
8542
+ }
8087
8543
  Object.keys(item).forEach((key) => {
8088
8544
  if (this.fields.find((field) => field.name === key)?.type === "json") {
8089
8545
  if (typeof item[key] === "object" || Array.isArray(item[key])) {
@@ -8160,7 +8616,7 @@ var init_context = __esm({
8160
8616
  job: jobs.length > 0 ? jobs.join(",") : void 0
8161
8617
  };
8162
8618
  };
8163
- updateItem = async (item, config, user, role, generateEmbeddingsOverwrite, runProcessorOverwrite) => {
8619
+ updateItem = async (item, config, user, role, generateEmbeddingsOverwrite, runProcessorOverwrite, merge) => {
8164
8620
  console.log("[EXULU] updating item", item);
8165
8621
  const { db: db2 } = await postgresClient();
8166
8622
  if (item.field) {
@@ -8170,16 +8626,26 @@ var init_context = __esm({
8170
8626
  if (!record) {
8171
8627
  throw new Error("Item not found.");
8172
8628
  }
8173
- Object.keys(item).forEach((key) => {
8629
+ const prepared = prepareItemWrite({
8630
+ fields: this.fields,
8631
+ existing: record,
8632
+ input: item,
8633
+ merge
8634
+ });
8635
+ if (!prepared.ok) {
8636
+ throw new Error(prepared.message);
8637
+ }
8638
+ const values = prepared.values;
8639
+ Object.keys(values).forEach((key) => {
8174
8640
  if (this.fields.find((field) => field.name === key)?.type === "json") {
8175
- if (typeof item[key] === "object" || Array.isArray(item[key])) {
8176
- item[key] = JSON.stringify(item[key]);
8641
+ if (typeof values[key] === "object" || Array.isArray(values[key])) {
8642
+ values[key] = JSON.stringify(values[key]);
8177
8643
  }
8178
8644
  }
8179
8645
  });
8180
8646
  const mutation = db2.from(getTableName(this.id)).where({ id: record.id }).update({
8181
- ...item,
8182
- tags: item.tags ? Array.isArray(item.tags) ? item.tags.join(",") : item.tags : void 0
8647
+ ...values,
8648
+ tags: values.tags ? Array.isArray(values.tags) ? values.tags.join(",") : values.tags : void 0
8183
8649
  }).returning("id");
8184
8650
  await mutation;
8185
8651
  let jobs = [];
@@ -8190,7 +8656,17 @@ var init_context = __esm({
8190
8656
  const { job: processorJob, result: processorResult } = await this.processField(
8191
8657
  "api",
8192
8658
  {
8193
- ...item,
8659
+ // `values`, not `item` (coordinator ruling, Task 4 fix round 1):
8660
+ // the fence on "don't change processor behaviour" is about WHEN
8661
+ // a processor fires, not WHAT it sees once it does. Before
8662
+ // merge existed, the patch WAS the result, so this was never a
8663
+ // live distinction; `mv_pitches`'s processor (trigger: "always")
8664
+ // is the first real consumer of a merge-listed json field, so a
8665
+ // processor seeing a bare patch instead of the full merged
8666
+ // object is live, not latent. `values` carries the SAME keys
8667
+ // `item` did -- unchanged values pass through by reference --
8668
+ // so this is a no-op for every call that doesn't use `merge`.
8669
+ ...values,
8194
8670
  id: record.id
8195
8671
  },
8196
8672
  config,
@@ -9250,14 +9726,14 @@ var init_wrap_execute = __esm({
9250
9726
  });
9251
9727
 
9252
9728
  // src/templates/tools/session-items-retrieval-tool.ts
9253
- var import_zod2, SESSION_ITEMS_RETRIEVAL_TOOL_NAME, createSessionItemsRetrievalTool;
9729
+ var import_zod3, SESSION_ITEMS_RETRIEVAL_TOOL_NAME, createSessionItemsRetrievalTool;
9254
9730
  var init_session_items_retrieval_tool = __esm({
9255
9731
  "src/templates/tools/session-items-retrieval-tool.ts"() {
9256
9732
  "use strict";
9257
9733
  init_cjs_shims();
9258
9734
  init_tool();
9259
9735
  init_embedder_not_configured();
9260
- import_zod2 = require("zod");
9736
+ import_zod3 = require("zod");
9261
9737
  SESSION_ITEMS_RETRIEVAL_TOOL_NAME = "context_search in knowledge items added to session.";
9262
9738
  createSessionItemsRetrievalTool = async ({
9263
9739
  user,
@@ -9270,8 +9746,8 @@ var init_session_items_retrieval_tool = __esm({
9270
9746
  id: "session_items_information_context_search",
9271
9747
  name: SESSION_ITEMS_RETRIEVAL_TOOL_NAME,
9272
9748
  description: "Context search in knowledge items added to session.",
9273
- inputSchema: import_zod2.z.object({
9274
- query: import_zod2.z.string().describe("The query to retrieve information from knowledge items added to the session.")
9749
+ inputSchema: import_zod3.z.object({
9750
+ query: import_zod3.z.string().describe("The query to retrieve information from knowledge items added to the session.")
9275
9751
  }),
9276
9752
  type: "context",
9277
9753
  category: "session",
@@ -9350,6 +9826,40 @@ var init_session_items_retrieval_tool = __esm({
9350
9826
  }
9351
9827
  });
9352
9828
 
9829
+ // src/exulu/approval-revalidation.ts
9830
+ function answeredApprovalToolCallIds(messages) {
9831
+ const toolCallByApproval = /* @__PURE__ */ new Map();
9832
+ for (const message of messages ?? []) {
9833
+ if (message.role !== "assistant" || typeof message.content === "string") continue;
9834
+ for (const part of message.content) {
9835
+ if (part?.type === "tool-approval-request" && typeof part.approvalId === "string" && typeof part.toolCallId === "string") {
9836
+ toolCallByApproval.set(part.approvalId, part.toolCallId);
9837
+ }
9838
+ }
9839
+ }
9840
+ const answered = /* @__PURE__ */ new Set();
9841
+ for (const message of messages ?? []) {
9842
+ if (message.role !== "tool" || typeof message.content === "string") continue;
9843
+ for (const part of message.content) {
9844
+ if (part?.type !== "tool-approval-response" || typeof part.approvalId !== "string") continue;
9845
+ const toolCallId = toolCallByApproval.get(part.approvalId);
9846
+ if (toolCallId) answered.add(toolCallId);
9847
+ }
9848
+ }
9849
+ return answered;
9850
+ }
9851
+ function needsApprovalForCall(args) {
9852
+ if (!args.requiresApproval) return false;
9853
+ if (answeredApprovalToolCallIds(args.messages).has(args.toolCallId)) return true;
9854
+ return !args.approvedForSession;
9855
+ }
9856
+ var init_approval_revalidation = __esm({
9857
+ "src/exulu/approval-revalidation.ts"() {
9858
+ "use strict";
9859
+ init_cjs_shims();
9860
+ }
9861
+ });
9862
+
9353
9863
  // ee/agentic-retrieval/pipeline/global-ids.ts
9354
9864
  function parsePreselectedItems(globalIds) {
9355
9865
  const map = /* @__PURE__ */ new Map();
@@ -9728,7 +10238,7 @@ async function findVisible(context, id, user) {
9728
10238
  }
9729
10239
  function createMemoryTools({ agent, context, user }) {
9730
10240
  const types = memoryTypeValues(context);
9731
- const typeSchema = types.length > 0 ? import_zod3.z.enum(types) : import_zod3.z.string();
10241
+ const typeSchema = types.length > 0 ? import_zod4.z.enum(types) : import_zod4.z.string();
9732
10242
  const category = `${agent.name}_memory`;
9733
10243
  const remember = new ExuluTool({
9734
10244
  id: "memory_remember",
@@ -9738,12 +10248,12 @@ function createMemoryTools({ agent, context, user }) {
9738
10248
  config: [],
9739
10249
  needsApproval: true,
9740
10250
  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.`,
9741
- inputSchema: import_zod3.z.object({
9742
- title: import_zod3.z.string().describe("Short title, max 80 characters"),
9743
- information: import_zod3.z.string().describe("The fact in one or two sentences, in the user's own words"),
10251
+ inputSchema: import_zod4.z.object({
10252
+ title: import_zod4.z.string().describe("Short title, max 80 characters"),
10253
+ information: import_zod4.z.string().describe("The fact in one or two sentences, in the user's own words"),
9744
10254
  type: typeSchema.describe(`Memory type. One of: ${types.join(", ")}`),
9745
- whySaved: import_zod3.z.string().describe("Why this is worth remembering: the question or topic that triggered it"),
9746
- visibility: import_zod3.z.enum(["private", "public"]).optional().describe("Only when the user explicitly said who may see it")
10255
+ whySaved: import_zod4.z.string().describe("Why this is worth remembering: the question or topic that triggered it"),
10256
+ visibility: import_zod4.z.enum(["private", "public"]).optional().describe("Only when the user explicitly said who may see it")
9747
10257
  }),
9748
10258
  execute: async (params) => {
9749
10259
  const { user: u, exuluConfig, memoryDecision } = params;
@@ -9827,12 +10337,12 @@ function createMemoryTools({ agent, context, user }) {
9827
10337
  config: [],
9828
10338
  needsApproval: true,
9829
10339
  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.`,
9830
- inputSchema: import_zod3.z.object({
9831
- memoryId: import_zod3.z.string().describe("item_id of the memory to change"),
9832
- information: import_zod3.z.string().optional().describe("New wording, if it changes"),
9833
- title: import_zod3.z.string().optional(),
10340
+ inputSchema: import_zod4.z.object({
10341
+ memoryId: import_zod4.z.string().describe("item_id of the memory to change"),
10342
+ information: import_zod4.z.string().optional().describe("New wording, if it changes"),
10343
+ title: import_zod4.z.string().optional(),
9834
10344
  type: typeSchema.optional(),
9835
- reason: import_zod3.z.string().describe("What the user said that contradicts or refines the memory")
10345
+ reason: import_zod4.z.string().describe("What the user said that contradicts or refines the memory")
9836
10346
  }),
9837
10347
  execute: async (params) => {
9838
10348
  const { user: u, exuluConfig, memoryDecision } = params;
@@ -9871,9 +10381,9 @@ function createMemoryTools({ agent, context, user }) {
9871
10381
  config: [],
9872
10382
  needsApproval: true,
9873
10383
  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.`,
9874
- inputSchema: import_zod3.z.object({
9875
- memoryId: import_zod3.z.string().describe("item_id of the memory to delete"),
9876
- reason: import_zod3.z.string().describe("What the user said")
10384
+ inputSchema: import_zod4.z.object({
10385
+ memoryId: import_zod4.z.string().describe("item_id of the memory to delete"),
10386
+ reason: import_zod4.z.string().describe("What the user said")
9877
10387
  }),
9878
10388
  execute: async (params) => {
9879
10389
  const { user: u } = params;
@@ -9892,12 +10402,12 @@ function createMemoryTools({ agent, context, user }) {
9892
10402
  forget.needsApprovalFn = needsWriteApproval;
9893
10403
  return [remember, update, forget];
9894
10404
  }
9895
- var import_zod3, err, resolveType;
10405
+ var import_zod4, err, resolveType;
9896
10406
  var init_tools = __esm({
9897
10407
  "src/exulu/memory/tools.ts"() {
9898
10408
  "use strict";
9899
10409
  init_cjs_shims();
9900
- import_zod3 = require("zod");
10410
+ import_zod4 = require("zod");
9901
10411
  init_creator_id();
9902
10412
  init_tool();
9903
10413
  init_client();
@@ -10095,16 +10605,16 @@ var init_check_item_write_access = __esm({
10095
10605
  });
10096
10606
 
10097
10607
  // src/templates/tools/kb-editor-config.ts
10098
- var import_zod4, KB_EDITOR_TOOL_ID, permissionsSchema, emptyConfig, parseKbEditorConfig;
10608
+ var import_zod5, KB_EDITOR_TOOL_ID, permissionsSchema, emptyConfig, parseKbEditorConfig;
10099
10609
  var init_kb_editor_config = __esm({
10100
10610
  "src/templates/tools/kb-editor-config.ts"() {
10101
10611
  "use strict";
10102
10612
  init_cjs_shims();
10103
- import_zod4 = require("zod");
10613
+ import_zod5 = require("zod");
10104
10614
  KB_EDITOR_TOOL_ID = "knowledge_base_editor";
10105
- permissionsSchema = import_zod4.z.object({
10106
- create: import_zod4.z.boolean().catch(false).default(false),
10107
- update: import_zod4.z.boolean().catch(false).default(false)
10615
+ permissionsSchema = import_zod5.z.object({
10616
+ create: import_zod5.z.boolean().catch(false).default(false),
10617
+ update: import_zod5.z.boolean().catch(false).default(false)
10108
10618
  });
10109
10619
  emptyConfig = () => ({
10110
10620
  enabled: false,
@@ -10156,19 +10666,20 @@ var init_kb_editor_config = __esm({
10156
10666
  });
10157
10667
 
10158
10668
  // src/templates/tools/context-write-tools.ts
10159
- var import_zod5, import_node_crypto3, MAX_CONTEXT_SEGMENT, RESERVED_INPUT_KEYS, buildWriteSchema, BARE_FILENAME, attachSessionFiles, canonicalizeEnumFields, pickContent, jobNote, createContextWriteTools, createKbEditorPickerTool, collectKbWriteTools;
10669
+ var import_zod6, import_node_crypto3, MAX_CONTEXT_SEGMENT, RESERVED_INPUT_KEYS, buildWriteSchema, BARE_FILENAME, attachSessionFiles, canonicalizeEnumFields, pickContent, jobNote, createContextWriteTools, createKbEditorPickerTool, collectKbWriteTools;
10160
10670
  var init_context_write_tools = __esm({
10161
10671
  "src/templates/tools/context-write-tools.ts"() {
10162
10672
  "use strict";
10163
10673
  init_cjs_shims();
10164
10674
  init_tool();
10165
- import_zod5 = require("zod");
10675
+ import_zod6 = require("zod");
10166
10676
  import_node_crypto3 = require("crypto");
10167
10677
  init_session_files();
10168
10678
  init_uppy();
10169
10679
  init_sanitize_name();
10170
10680
  init_check_item_write_access();
10171
10681
  init_kb_editor_config();
10682
+ init_json_field_schema();
10172
10683
  MAX_CONTEXT_SEGMENT = 68;
10173
10684
  RESERVED_INPUT_KEYS = /* @__PURE__ */ new Set([
10174
10685
  "model",
@@ -10190,21 +10701,22 @@ var init_context_write_tools = __esm({
10190
10701
  const shape = {};
10191
10702
  const contentKeys = [];
10192
10703
  const fileFields = [];
10704
+ const jsonFieldNames = [];
10193
10705
  const addContent = (key, schema7, required) => {
10194
10706
  shape[key] = required && mode === "create" ? schema7 : schema7.optional();
10195
10707
  contentKeys.push(key);
10196
10708
  };
10197
10709
  if (mode === "update") {
10198
- shape["id"] = import_zod5.z.string().optional().describe("The id of the item to update.");
10199
- shape["external_id"] = import_zod5.z.string().optional().describe("The external_id of the item to update, if the id is unknown. Lookup only \u2014 it is never changed.");
10710
+ shape["id"] = import_zod6.z.string().optional().describe("The id of the item to update.");
10711
+ shape["external_id"] = import_zod6.z.string().optional().describe("The external_id of the item to update, if the id is unknown. Lookup only \u2014 it is never changed.");
10200
10712
  }
10201
- addContent("name", import_zod5.z.string().describe("The name of the item."), true);
10202
- addContent("description", import_zod5.z.string().describe("A description of the item."), false);
10203
- addContent("tags", import_zod5.z.array(import_zod5.z.string()).describe("Tags for the item."), false);
10713
+ addContent("name", import_zod6.z.string().describe("The name of the item."), true);
10714
+ addContent("description", import_zod6.z.string().describe("A description of the item."), false);
10715
+ addContent("tags", import_zod6.z.array(import_zod6.z.string()).describe("Tags for the item."), false);
10204
10716
  if (mode === "create") {
10205
10717
  addContent(
10206
10718
  "external_id",
10207
- import_zod5.z.string().describe("An optional external identifier for the item, e.g. an id from a source system."),
10719
+ import_zod6.z.string().describe("An optional external identifier for the item, e.g. an id from a source system."),
10208
10720
  false
10209
10721
  );
10210
10722
  }
@@ -10217,7 +10729,7 @@ var init_context_write_tools = __esm({
10217
10729
  const allowed = (field.allowedFileTypes ?? []).map((ext) => ext.toLowerCase());
10218
10730
  const column = `${field.name}_s3key`;
10219
10731
  const allowedNote = allowed.length ? ` Allowed types: ${allowed.join(", ")}.` : "";
10220
- shape[field.name] = (field.required === true && mode === "create" ? import_zod5.z.string() : import_zod5.z.string().optional()).describe(
10732
+ shape[field.name] = (field.required === true && mode === "create" ? import_zod6.z.string() : import_zod6.z.string().optional()).describe(
10221
10733
  `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." : "")
10222
10734
  );
10223
10735
  contentKeys.push(column);
@@ -10227,32 +10739,38 @@ var init_context_write_tools = __esm({
10227
10739
  let schema7;
10228
10740
  switch (field.type) {
10229
10741
  case "enum":
10230
- schema7 = import_zod5.z.string().describe(
10742
+ schema7 = import_zod6.z.string().describe(
10231
10743
  `The ${field.name} of the item. Must be one of: ${(field.enumValues ?? []).join(", ")}`
10232
10744
  );
10233
10745
  break;
10234
10746
  case "json":
10235
- schema7 = import_zod5.z.string().describe(`The ${field.name} of the item, as a valid JSON string.`);
10747
+ jsonFieldNames.push(field.name);
10748
+ schema7 = field.schema ? loosenForTransport(field.schema).describe(`The ${field.name} of the item.`) : import_zod6.z.string().describe(`The ${field.name} of the item, as a valid JSON string.`);
10236
10749
  break;
10237
10750
  case "markdown":
10238
- schema7 = import_zod5.z.string().describe(`The ${field.name} of the item, as a valid Markdown string.`);
10751
+ schema7 = import_zod6.z.string().describe(`The ${field.name} of the item, as a valid Markdown string.`);
10239
10752
  break;
10240
10753
  case "date":
10241
- schema7 = import_zod5.z.string().describe(`The ${field.name} of the item, as an ISO-8601 date string.`);
10754
+ schema7 = import_zod6.z.string().describe(`The ${field.name} of the item, as an ISO-8601 date string.`);
10242
10755
  break;
10243
10756
  case "number":
10244
- schema7 = import_zod5.z.number().describe(`The ${field.name} of the item.`);
10757
+ schema7 = import_zod6.z.number().describe(`The ${field.name} of the item.`);
10245
10758
  break;
10246
10759
  case "boolean":
10247
- schema7 = import_zod5.z.boolean().describe(`The ${field.name} of the item.`);
10760
+ schema7 = import_zod6.z.boolean().describe(`The ${field.name} of the item.`);
10248
10761
  break;
10249
10762
  default:
10250
- schema7 = import_zod5.z.string().describe(`The ${field.name} of the item.`);
10763
+ schema7 = import_zod6.z.string().describe(`The ${field.name} of the item.`);
10251
10764
  break;
10252
10765
  }
10253
10766
  addContent(field.name, schema7, field.required === true);
10254
10767
  }
10255
- return { shape, contentKeys, fileFields };
10768
+ if (mode === "update" && jsonFieldNames.length > 0 && !shape["merge"]) {
10769
+ shape["merge"] = import_zod6.z.array(import_zod6.z.string()).optional().describe(
10770
+ `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.`
10771
+ );
10772
+ }
10773
+ return { shape, contentKeys, fileFields, jsonFieldNames };
10256
10774
  };
10257
10775
  BARE_FILENAME = /^[^/\\]+$/;
10258
10776
  attachSessionFiles = async (params, fileFields, deps) => {
@@ -10330,7 +10848,7 @@ var init_context_write_tools = __esm({
10330
10848
  category: "knowledge_base_editing",
10331
10849
  description: `Create a new item in the "${context.name}" knowledge base.${contextLabel}${fileNote}`,
10332
10850
  type: "function",
10333
- inputSchema: import_zod5.z.object(shape),
10851
+ inputSchema: import_zod6.z.object(shape),
10334
10852
  config: [],
10335
10853
  needsApproval: !skipApproval,
10336
10854
  execute: async (params) => {
@@ -10383,7 +10901,7 @@ var init_context_write_tools = __esm({
10383
10901
  category: "knowledge_base_editing",
10384
10902
  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}`,
10385
10903
  type: "function",
10386
- inputSchema: import_zod5.z.object(shape),
10904
+ inputSchema: import_zod6.z.object(shape),
10387
10905
  config: [],
10388
10906
  needsApproval: !skipApproval,
10389
10907
  execute: async (params) => {
@@ -10418,7 +10936,16 @@ var init_context_write_tools = __esm({
10418
10936
  return { result: "No fields to update were provided." };
10419
10937
  }
10420
10938
  patch.id = existing.id;
10421
- const { job } = await context.updateItem(patch, exuluConfig, user?.id, user?.role?.id);
10939
+ const merge = Array.isArray(params.merge) ? params.merge : void 0;
10940
+ const { job } = await context.updateItem(
10941
+ patch,
10942
+ exuluConfig,
10943
+ user?.id,
10944
+ user?.role?.id,
10945
+ void 0,
10946
+ void 0,
10947
+ merge
10948
+ );
10422
10949
  const fresh = await context.getItem({ item: { id: existing.id } });
10423
10950
  const summary = { id: existing.id };
10424
10951
  for (const key of contentKeys) {
@@ -10448,7 +10975,7 @@ Current item: ${JSON.stringify(summary)}`
10448
10975
  category: "default",
10449
10976
  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.",
10450
10977
  type: "function",
10451
- inputSchema: import_zod5.z.object({}),
10978
+ inputSchema: import_zod6.z.object({}),
10452
10979
  config: [
10453
10980
  {
10454
10981
  name: "knowledge_bases",
@@ -10656,13 +11183,13 @@ async function resolveSkill(db2, ref) {
10656
11183
  const byId = /^[0-9a-f-]{36}$/i.test(value) ? await db2("skills").where({ id: value }).first() : null;
10657
11184
  return byId ?? await resolveSkillByName(db2, value);
10658
11185
  }
10659
- var import_node_crypto4, import_zod6, MAX_FILES, MAX_FILE_BYTES, MAX_READ_BYTES, defaultIo, err2, safeSkillPath, contentTypeFor, yamlString, ensureFrontmatter, generalPrefix, relativePaths, normalizeFiles, createSkillAuthorTools, createSkillAuthorPickerTool, collectSkillAuthorTools;
11186
+ var import_node_crypto4, import_zod7, MAX_FILES, MAX_FILE_BYTES, MAX_READ_BYTES, defaultIo, err2, safeSkillPath, contentTypeFor, yamlString, ensureFrontmatter, generalPrefix, relativePaths, normalizeFiles, createSkillAuthorTools, createSkillAuthorPickerTool, collectSkillAuthorTools;
10660
11187
  var init_skill_author_tools = __esm({
10661
11188
  "src/templates/tools/skill-author-tools.ts"() {
10662
11189
  "use strict";
10663
11190
  init_cjs_shims();
10664
11191
  import_node_crypto4 = require("crypto");
10665
- import_zod6 = require("zod");
11192
+ import_zod7 = require("zod");
10666
11193
  init_tool();
10667
11194
  init_client();
10668
11195
  init_skill_access();
@@ -10749,7 +11276,7 @@ ${content.replace(/^\s+/, "")}`;
10749
11276
  config: [],
10750
11277
  needsApproval: false,
10751
11278
  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.",
10752
- inputSchema: import_zod6.z.object({ query: import_zod6.z.string().optional().describe("Optional substring to filter by name or description") }),
11279
+ inputSchema: import_zod7.z.object({ query: import_zod7.z.string().optional().describe("Optional substring to filter by name or description") }),
10753
11280
  execute: async (params) => {
10754
11281
  const { user } = params;
10755
11282
  if (!user?.id) return err2("Skills require a signed-in user.");
@@ -10775,9 +11302,9 @@ ${content.replace(/^\s+/, "")}`;
10775
11302
  config: [],
10776
11303
  needsApproval: false,
10777
11304
  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.",
10778
- inputSchema: import_zod6.z.object({
10779
- skill: import_zod6.z.string().describe("The skill's name or id"),
10780
- path: import_zod6.z.string().optional().describe("A file path inside the skill to read instead of SKILL.md")
11305
+ inputSchema: import_zod7.z.object({
11306
+ skill: import_zod7.z.string().describe("The skill's name or id"),
11307
+ path: import_zod7.z.string().optional().describe("A file path inside the skill to read instead of SKILL.md")
10781
11308
  }),
10782
11309
  execute: async (params) => {
10783
11310
  const { user, exuluConfig } = params;
@@ -10822,10 +11349,10 @@ ${content}`
10822
11349
  needsApproval: !config.skipApproval,
10823
11350
  needsApprovalFn: approvalFn,
10824
11351
  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.",
10825
- inputSchema: import_zod6.z.object({
10826
- name: import_zod6.z.string().describe("Short, specific skill name (e.g. 'quarterly-report-from-crm')"),
10827
- description: import_zod6.z.string().describe("One line: what the skill does and when to use it"),
10828
- files: import_zod6.z.array(import_zod6.z.object({ path: import_zod6.z.string().describe("Relative path inside the skill, e.g. SKILL.md or references/checklist.md"), content: import_zod6.z.string() })).min(1).describe("The skill's files; SKILL.md is required")
11352
+ inputSchema: import_zod7.z.object({
11353
+ name: import_zod7.z.string().describe("Short, specific skill name (e.g. 'quarterly-report-from-crm')"),
11354
+ description: import_zod7.z.string().describe("One line: what the skill does and when to use it"),
11355
+ files: import_zod7.z.array(import_zod7.z.object({ path: import_zod7.z.string().describe("Relative path inside the skill, e.g. SKILL.md or references/checklist.md"), content: import_zod7.z.string() })).min(1).describe("The skill's files; SKILL.md is required")
10829
11356
  }),
10830
11357
  execute: async (params) => {
10831
11358
  const { user, exuluConfig } = params;
@@ -10891,12 +11418,12 @@ ${content}`
10891
11418
  needsApproval: !config.skipApproval,
10892
11419
  needsApprovalFn: approvalFn,
10893
11420
  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.",
10894
- inputSchema: import_zod6.z.object({
10895
- skill: import_zod6.z.string().describe("The skill's name or id"),
10896
- files: import_zod6.z.array(import_zod6.z.object({ path: import_zod6.z.string(), content: import_zod6.z.string() })).optional().describe("Files to add or replace, full content each"),
10897
- deletePaths: import_zod6.z.array(import_zod6.z.string()).optional().describe("Paths to remove in the new version"),
10898
- description: import_zod6.z.string().optional().describe("A new one-line description, if it changed"),
10899
- label: import_zod6.z.string().optional().describe("A short label for this version, e.g. 'Added the review checklist'")
11421
+ inputSchema: import_zod7.z.object({
11422
+ skill: import_zod7.z.string().describe("The skill's name or id"),
11423
+ files: import_zod7.z.array(import_zod7.z.object({ path: import_zod7.z.string(), content: import_zod7.z.string() })).optional().describe("Files to add or replace, full content each"),
11424
+ deletePaths: import_zod7.z.array(import_zod7.z.string()).optional().describe("Paths to remove in the new version"),
11425
+ description: import_zod7.z.string().optional().describe("A new one-line description, if it changed"),
11426
+ label: import_zod7.z.string().optional().describe("A short label for this version, e.g. 'Added the review checklist'")
10900
11427
  }),
10901
11428
  execute: async (params) => {
10902
11429
  const { user, exuluConfig } = params;
@@ -10973,7 +11500,7 @@ ${content}`
10973
11500
  category: "default",
10974
11501
  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.",
10975
11502
  type: "function",
10976
- inputSchema: import_zod6.z.object({}),
11503
+ inputSchema: import_zod7.z.object({}),
10977
11504
  config: [
10978
11505
  { name: "create", description: "The agent may propose new skills.", type: "boolean", default: true },
10979
11506
  { name: "update", description: "The agent may publish new versions of skills the user can write.", type: "boolean", default: true },
@@ -12752,9 +13279,9 @@ Probe error: ${probe.reason ?? "(no detail)"}`
12752
13279
  });
12753
13280
  const writeFileTool = (0, import_ai2.tool)({
12754
13281
  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.',
12755
- inputSchema: import_zod7.z.object({
12756
- path: import_zod7.z.string().describe("The path where the file should be written. Relative paths and leading-slash paths are both resolved against the session sandbox root."),
12757
- content: import_zod7.z.string().describe("The content to write to the file")
13282
+ inputSchema: import_zod8.z.object({
13283
+ path: import_zod8.z.string().describe("The path where the file should be written. Relative paths and leading-slash paths are both resolved against the session sandbox root."),
13284
+ content: import_zod8.z.string().describe("The content to write to the file")
12758
13285
  }),
12759
13286
  execute: async ({ path: path4, content }) => {
12760
13287
  const resolvedPath = resolveSessionPath(path4, sessionDir);
@@ -12773,8 +13300,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
12773
13300
  });
12774
13301
  const readFileTool = (0, import_ai2.tool)({
12775
13302
  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.',
12776
- inputSchema: import_zod7.z.object({
12777
- path: import_zod7.z.string().describe("The path of the file to read. Relative paths and leading-slash paths are both resolved against the session sandbox root.")
13303
+ inputSchema: import_zod8.z.object({
13304
+ path: import_zod8.z.string().describe("The path of the file to read. Relative paths and leading-slash paths are both resolved against the session sandbox root.")
12778
13305
  }),
12779
13306
  execute: async ({ path: path4 }) => {
12780
13307
  const resolvedPath = resolveSessionPath(path4, sessionDir);
@@ -12791,8 +13318,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
12791
13318
  const originalBashTool = tools.bash;
12792
13319
  const bashTool = (0, import_ai2.tool)({
12793
13320
  description: originalBashTool.description ?? "",
12794
- inputSchema: import_zod7.z.object({
12795
- command: import_zod7.z.string().describe("The bash command to execute.")
13321
+ inputSchema: import_zod8.z.object({
13322
+ command: import_zod8.z.string().describe("The bash command to execute.")
12796
13323
  }),
12797
13324
  execute: async (args, opts) => {
12798
13325
  const before = persistenceEnabled ? await snapshotSessionArtifacts() : null;
@@ -12867,7 +13394,7 @@ ${lines.join("\n")}`;
12867
13394
  sandboxCache.set(sessionId, { handle, installedSkills });
12868
13395
  return handle;
12869
13396
  }
12870
- var import_sandbox_runtime, import_promises2, import_node_fs6, import_node_path5, import_node_child_process4, import_node_util3, import_bash_tool, import_ai2, import_zod7, import_crypto_js3, getAllExuluVariables, execAsync3, backendSecretFiles, EXEC_MAX_BUFFER, litellmSecretNamesCache, litellmConfigSecretNames, sandboxProbePromise, SANDBOX_FALLBACK_INSTRUCTIONS, degradedModeLogged, sandboxCache;
13397
+ var import_sandbox_runtime, import_promises2, import_node_fs6, import_node_path5, import_node_child_process4, import_node_util3, import_bash_tool, import_ai2, import_zod8, import_crypto_js3, getAllExuluVariables, execAsync3, backendSecretFiles, EXEC_MAX_BUFFER, litellmSecretNamesCache, litellmConfigSecretNames, sandboxProbePromise, SANDBOX_FALLBACK_INSTRUCTIONS, degradedModeLogged, sandboxCache;
12871
13398
  var init_create_sandbox = __esm({
12872
13399
  "ee/invoke-skills/create-sandbox.ts"() {
12873
13400
  "use strict";
@@ -12889,7 +13416,7 @@ var init_create_sandbox = __esm({
12889
13416
  init_skill_sandbox();
12890
13417
  import_bash_tool = require("bash-tool");
12891
13418
  import_ai2 = require("ai");
12892
- import_zod7 = require("zod");
13419
+ import_zod8 = require("zod");
12893
13420
  init_variable();
12894
13421
  import_crypto_js3 = __toESM(require("crypto-js"), 1);
12895
13422
  init_client();
@@ -13177,12 +13704,12 @@ var init_auth_tool_model_output = __esm({
13177
13704
  });
13178
13705
 
13179
13706
  // src/templates/tools/session-file-read-tool.ts
13180
- var import_zod8, DEFAULT_LIMIT, MAX_CONTENT_CHARS, SESSION_FILE_READ_TOOL_NAME, createSessionFileReadTool;
13707
+ var import_zod9, DEFAULT_LIMIT, MAX_CONTENT_CHARS, SESSION_FILE_READ_TOOL_NAME, createSessionFileReadTool;
13181
13708
  var init_session_file_read_tool = __esm({
13182
13709
  "src/templates/tools/session-file-read-tool.ts"() {
13183
13710
  "use strict";
13184
13711
  init_cjs_shims();
13185
- import_zod8 = require("zod");
13712
+ import_zod9 = require("zod");
13186
13713
  init_session_files();
13187
13714
  init_tool();
13188
13715
  init_uppy();
@@ -13238,10 +13765,10 @@ var init_session_file_read_tool = __esm({
13238
13765
  name: SESSION_FILE_READ_TOOL_NAME,
13239
13766
  needsApproval: false,
13240
13767
  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.",
13241
- inputSchema: import_zod8.z.object({
13242
- filename: import_zod8.z.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
13243
- offset: import_zod8.z.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
13244
- limit: import_zod8.z.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT})`)
13768
+ inputSchema: import_zod9.z.object({
13769
+ filename: import_zod9.z.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
13770
+ offset: import_zod9.z.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
13771
+ limit: import_zod9.z.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT})`)
13245
13772
  }),
13246
13773
  type: "function",
13247
13774
  category: "session",
@@ -13845,15 +14372,15 @@ If the page contains a flow-chart, schematic, technical drawing or control board
13845
14372
  const result = await (0, import_ai3.generateText)({
13846
14373
  model,
13847
14374
  output: import_ai3.Output.object({
13848
- schema: import_zod9.z.object({
13849
- needs_correction: import_zod9.z.boolean(),
13850
- corrected_text: import_zod9.z.string().nullable(),
13851
- current_page_table: import_zod9.z.object({
13852
- headers: import_zod9.z.array(import_zod9.z.string()),
13853
- is_continuation: import_zod9.z.boolean()
14375
+ schema: import_zod10.z.object({
14376
+ needs_correction: import_zod10.z.boolean(),
14377
+ corrected_text: import_zod10.z.string().nullable(),
14378
+ current_page_table: import_zod10.z.object({
14379
+ headers: import_zod10.z.array(import_zod10.z.string()),
14380
+ is_continuation: import_zod10.z.boolean()
13854
14381
  }).nullable(),
13855
- confidence: import_zod9.z.enum(["high", "medium", "low"]),
13856
- reasoning: import_zod9.z.string()
14382
+ confidence: import_zod10.z.enum(["high", "medium", "low"]),
14383
+ reasoning: import_zod10.z.string()
13857
14384
  })
13858
14385
  }),
13859
14386
  messages: [
@@ -14290,7 +14817,7 @@ async function documentProcessor({
14290
14817
  }
14291
14818
  }
14292
14819
  }
14293
- var fs2, path3, import_ai3, import_zod9, import_p_limit, import_crypto3, mammoth, import_turndown, import_word_extractor, import_officeparser, import_liteparse, loadFile;
14820
+ var fs2, path3, import_ai3, import_zod10, import_p_limit, import_crypto3, mammoth, import_turndown, import_word_extractor, import_officeparser, import_liteparse, loadFile;
14294
14821
  var init_doc_processor = __esm({
14295
14822
  "ee/python/documents/processing/doc_processor.ts"() {
14296
14823
  "use strict";
@@ -14298,7 +14825,7 @@ var init_doc_processor = __esm({
14298
14825
  fs2 = __toESM(require("fs"), 1);
14299
14826
  path3 = __toESM(require("path"), 1);
14300
14827
  import_ai3 = require("ai");
14301
- import_zod9 = require("zod");
14828
+ import_zod10 = require("zod");
14302
14829
  import_p_limit = __toESM(require("p-limit"), 1);
14303
14830
  import_crypto3 = require("crypto");
14304
14831
  init_with_retry();
@@ -14489,12 +15016,12 @@ function binaryDocumentBashHint(command, stdout, stderr) {
14489
15016
  const [, file] = match;
14490
15017
  return `Note: "${file}" is a binary document \u2014 grep/cat/text tools cannot read the text inside it, so a silent or garbled result does not mean the content isn't there. Use parse_document to extract its text first, then search or read within that extracted text instead of the original file.`;
14491
15018
  }
14492
- var import_zod10, import_node_path7, import_officeparser3, DEFAULT_LIMIT2, MAX_CONTENT_CHARS2, PARSE_DOCUMENT_TOOL_NAME, MIN_CHARS_PER_PAGE, OFFICE_EXTENSIONS, pagesPattern, BINARY_DOCUMENT_EXTENSION_PATTERN, createParseDocumentTool;
15019
+ var import_zod11, import_node_path7, import_officeparser3, DEFAULT_LIMIT2, MAX_CONTENT_CHARS2, PARSE_DOCUMENT_TOOL_NAME, MIN_CHARS_PER_PAGE, OFFICE_EXTENSIONS, pagesPattern, BINARY_DOCUMENT_EXTENSION_PATTERN, createParseDocumentTool;
14493
15020
  var init_parse_document_tool = __esm({
14494
15021
  "src/templates/tools/parse-document-tool.ts"() {
14495
15022
  "use strict";
14496
15023
  init_cjs_shims();
14497
- import_zod10 = require("zod");
15024
+ import_zod11 = require("zod");
14498
15025
  import_node_path7 = require("path");
14499
15026
  import_officeparser3 = require("officeparser");
14500
15027
  init_tool();
@@ -14630,11 +15157,11 @@ ${text.trim()}`).join("\n");
14630
15157
  name: PARSE_DOCUMENT_TOOL_NAME,
14631
15158
  needsApproval: false,
14632
15159
  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.`,
14633
- inputSchema: import_zod10.z.object({
14634
- filename: import_zod10.z.string().describe('Exact session file name, e.g. "report.pdf"'),
14635
- pages: import_zod10.z.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
14636
- offset: import_zod10.z.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
14637
- limit: import_zod10.z.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT2})`)
15160
+ inputSchema: import_zod11.z.object({
15161
+ filename: import_zod11.z.string().describe('Exact session file name, e.g. "report.pdf"'),
15162
+ pages: import_zod11.z.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
15163
+ offset: import_zod11.z.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
15164
+ limit: import_zod11.z.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT2})`)
14638
15165
  }),
14639
15166
  type: "function",
14640
15167
  category: "session",
@@ -14906,12 +15433,12 @@ var init_tool_image_attachments = __esm({
14906
15433
  });
14907
15434
 
14908
15435
  // src/templates/tools/view-document-page-tool.ts
14909
- var import_zod11, import_node_path9, VIEW_DOCUMENT_PAGE_TOOL_NAME, MAX_IMAGE_BYTES, SCALE_PRIMARY, SCALE_FALLBACK, IMAGE_MEDIA_TYPES, OFFICE_EXTENSIONS2, createViewDocumentPageTool;
15436
+ var import_zod12, import_node_path9, VIEW_DOCUMENT_PAGE_TOOL_NAME, MAX_IMAGE_BYTES, SCALE_PRIMARY, SCALE_FALLBACK, IMAGE_MEDIA_TYPES, OFFICE_EXTENSIONS2, createViewDocumentPageTool;
14910
15437
  var init_view_document_page_tool = __esm({
14911
15438
  "src/templates/tools/view-document-page-tool.ts"() {
14912
15439
  "use strict";
14913
15440
  init_cjs_shims();
14914
- import_zod11 = require("zod");
15441
+ import_zod12 = require("zod");
14915
15442
  init_session_files();
14916
15443
  import_node_path9 = require("path");
14917
15444
  init_tool();
@@ -15039,9 +15566,9 @@ var init_view_document_page_tool = __esm({
15039
15566
  name: VIEW_DOCUMENT_PAGE_TOOL_NAME,
15040
15567
  needsApproval: false,
15041
15568
  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.",
15042
- inputSchema: import_zod11.z.object({
15043
- filename: import_zod11.z.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
15044
- page: import_zod11.z.number().int().min(1).optional().describe("Page number to render (default 1; ignored for image files)")
15569
+ inputSchema: import_zod12.z.object({
15570
+ filename: import_zod12.z.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
15571
+ page: import_zod12.z.number().int().min(1).optional().describe("Page number to render (default 1; ignored for image files)")
15045
15572
  }),
15046
15573
  type: "function",
15047
15574
  category: "session",
@@ -15117,6 +15644,7 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
15117
15644
  init_client();
15118
15645
  import_crypto_js4 = __toESM(require("crypto-js"), 1);
15119
15646
  init_session_items_retrieval_tool();
15647
+ init_approval_revalidation();
15120
15648
  init_pipeline();
15121
15649
  init_project_scope();
15122
15650
  init_sanitize_tool_name();
@@ -15463,11 +15991,12 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
15463
15991
  )?.default;
15464
15992
  const toolDescription = cur.description;
15465
15993
  const description = userDefinedConfigDescription || defaultConfigDescription || toolDescription;
15994
+ const approvedForSession = approvedTools?.includes("tool-" + cur.name) ?? false;
15466
15995
  console.log(
15467
15996
  "[EXULU] Tool",
15468
15997
  cur.name,
15469
15998
  "needs approval",
15470
- approvedTools?.includes(cur.name) ? false : true
15999
+ cur.needsApprovalFn ? "per call" : isMemoryToolId(cur.id) ? true : approvedForSession ? "only answered calls" : !!cur.needsApproval
15471
16000
  );
15472
16001
  return {
15473
16002
  ...prev,
@@ -15476,8 +16005,16 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
15476
16005
  description,
15477
16006
  // The approvedTools array uses the tool.name lookup as the frontend
15478
16007
  // Vercel AI SDK uses the sanitized tool name as the key, so this matches.
15479
- needsApproval: cur.needsApprovalFn ? (input, opts) => cur.needsApprovalFn(input, opts) : isMemoryToolId(cur.id) ? true : approvedTools?.includes("tool-" + cur.name) || !cur.needsApproval ? false : true,
15480
- // todo make configurable
16008
+ // Never a plain `false` for a tool the user allowed for this chat: the
16009
+ // SDK re-validates an ANSWERED approval by calling needsApproval again
16010
+ // and reads `false` as "deny" — see approval-revalidation.ts.
16011
+ needsApproval: cur.needsApprovalFn ? (input, opts) => cur.needsApprovalFn(input, opts) : isMemoryToolId(cur.id) ? true : (_input, opts) => needsApprovalForCall({
16012
+ toolCallId: opts.toolCallId,
16013
+ messages: opts.messages,
16014
+ approvedForSession,
16015
+ requiresApproval: !!cur.needsApproval
16016
+ // todo make configurable
16017
+ }),
15481
16018
  // Auth-wrapped tools: the model sees scrub text instead of the
15482
16019
  // credentialRequest/oauth payload; the UI stream keeps the raw
15483
16020
  // output (spec 2026-07-22 §1.2).
@@ -15662,13 +16199,13 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
15662
16199
  });
15663
16200
 
15664
16201
  // src/exulu/tool.ts
15665
- var import_ai4, import_zod12, import_node_crypto7, PUBLIC_TOOL_TYPES, ExuluTool;
16202
+ var import_ai4, import_zod13, import_node_crypto7, PUBLIC_TOOL_TYPES, ExuluTool;
15666
16203
  var init_tool = __esm({
15667
16204
  "src/exulu/tool.ts"() {
15668
16205
  "use strict";
15669
16206
  init_cjs_shims();
15670
16207
  import_ai4 = require("ai");
15671
- import_zod12 = require("zod");
16208
+ import_zod13 = require("zod");
15672
16209
  init_sanitize_name();
15673
16210
  import_node_crypto7 = require("crypto");
15674
16211
  init_singleton();
@@ -15733,7 +16270,7 @@ var init_tool = __esm({
15733
16270
  this.type = type;
15734
16271
  this.tool = (0, import_ai4.tool)({
15735
16272
  description,
15736
- inputSchema: inputSchema || import_zod12.z.object({}),
16273
+ inputSchema: inputSchema || import_zod13.z.object({}),
15737
16274
  execute: authentication2 ? wrapExecuteWithAuth(id, authentication2, execute2) : execute2
15738
16275
  });
15739
16276
  }
@@ -16027,92 +16564,92 @@ function effectiveKbSettings(profile, ctx) {
16027
16564
  keywordPrefilter: preset.keywordPrefilter
16028
16565
  };
16029
16566
  }
16030
- var import_zod13, KB_KINDS, DEFAULT_PREFILTER_CUTOFF, RRF_K, CHUNK_GROUP_MAX, kbProfileSchema, knowledgeBasesSchema, routingRuleSchema, routingSchema, identifierSetSchema, vocabularySchema, memorySchema, tuningSchema, claimCheckSchema, boolVal, strVal, KIND_PRESETS;
16567
+ var import_zod14, KB_KINDS, DEFAULT_PREFILTER_CUTOFF, RRF_K, CHUNK_GROUP_MAX, kbProfileSchema, knowledgeBasesSchema, routingRuleSchema, routingSchema, identifierSetSchema, vocabularySchema, memorySchema, tuningSchema, claimCheckSchema, boolVal, strVal, KIND_PRESETS;
16031
16568
  var init_config3 = __esm({
16032
16569
  "ee/agentic-retrieval/pipeline/config.ts"() {
16033
16570
  "use strict";
16034
16571
  init_cjs_shims();
16035
- import_zod13 = require("zod");
16572
+ import_zod14 = require("zod");
16036
16573
  init_types2();
16037
16574
  KB_KINDS = ["documents", "conversations", "records"];
16038
16575
  DEFAULT_PREFILTER_CUTOFF = 2.5;
16039
16576
  RRF_K = 60;
16040
16577
  CHUNK_GROUP_MAX = 10;
16041
- kbProfileSchema = import_zod13.z.object({
16042
- enabled: import_zod13.z.boolean().default(true),
16043
- kind: import_zod13.z.enum(KB_KINDS).default("documents"),
16044
- instructions: import_zod13.z.string().default(""),
16045
- overrides: import_zod13.z.object({
16046
- limit: import_zod13.z.number().int().positive().optional(),
16047
- expand: import_zod13.z.number().int().min(0).optional(),
16048
- multiQuery: import_zod13.z.boolean().optional(),
16049
- hyde: import_zod13.z.boolean().optional()
16578
+ kbProfileSchema = import_zod14.z.object({
16579
+ enabled: import_zod14.z.boolean().default(true),
16580
+ kind: import_zod14.z.enum(KB_KINDS).default("documents"),
16581
+ instructions: import_zod14.z.string().default(""),
16582
+ overrides: import_zod14.z.object({
16583
+ limit: import_zod14.z.number().int().positive().optional(),
16584
+ expand: import_zod14.z.number().int().min(0).optional(),
16585
+ multiQuery: import_zod14.z.boolean().optional(),
16586
+ hyde: import_zod14.z.boolean().optional()
16050
16587
  }).default({})
16051
16588
  });
16052
- knowledgeBasesSchema = import_zod13.z.record(import_zod13.z.string(), kbProfileSchema);
16053
- routingRuleSchema = import_zod13.z.object({
16054
- id: import_zod13.z.string(),
16055
- label: import_zod13.z.string(),
16056
- description: import_zod13.z.string(),
16057
- main: import_zod13.z.array(import_zod13.z.string()),
16058
- fallback: import_zod13.z.array(import_zod13.z.string()).default([])
16589
+ knowledgeBasesSchema = import_zod14.z.record(import_zod14.z.string(), kbProfileSchema);
16590
+ routingRuleSchema = import_zod14.z.object({
16591
+ id: import_zod14.z.string(),
16592
+ label: import_zod14.z.string(),
16593
+ description: import_zod14.z.string(),
16594
+ main: import_zod14.z.array(import_zod14.z.string()),
16595
+ fallback: import_zod14.z.array(import_zod14.z.string()).default([])
16059
16596
  });
16060
- routingSchema = import_zod13.z.object({ rules: import_zod13.z.array(routingRuleSchema).default([]) });
16061
- identifierSetSchema = import_zod13.z.object({
16062
- name: import_zod13.z.string(),
16063
- description: import_zod13.z.string().default(""),
16064
- examples: import_zod13.z.array(import_zod13.z.string()).default([]),
16065
- strategy: import_zod13.z.enum(["fuzzy", "exact"]),
16066
- contexts: import_zod13.z.array(import_zod13.z.string()).default([])
16597
+ routingSchema = import_zod14.z.object({ rules: import_zod14.z.array(routingRuleSchema).default([]) });
16598
+ identifierSetSchema = import_zod14.z.object({
16599
+ name: import_zod14.z.string(),
16600
+ description: import_zod14.z.string().default(""),
16601
+ examples: import_zod14.z.array(import_zod14.z.string()).default([]),
16602
+ strategy: import_zod14.z.enum(["fuzzy", "exact"]),
16603
+ contexts: import_zod14.z.array(import_zod14.z.string()).default([])
16067
16604
  });
16068
- vocabularySchema = import_zod13.z.object({
16069
- glossary: import_zod13.z.array(import_zod13.z.object({ term: import_zod13.z.string(), meaning: import_zod13.z.string() })).default([]),
16070
- identifiers: import_zod13.z.array(identifierSetSchema).default([]),
16071
- rewrites: import_zod13.z.array(import_zod13.z.object({ find: import_zod13.z.string(), replace: import_zod13.z.string() })).default([]),
16072
- styleHint: import_zod13.z.string().default("")
16605
+ vocabularySchema = import_zod14.z.object({
16606
+ glossary: import_zod14.z.array(import_zod14.z.object({ term: import_zod14.z.string(), meaning: import_zod14.z.string() })).default([]),
16607
+ identifiers: import_zod14.z.array(identifierSetSchema).default([]),
16608
+ rewrites: import_zod14.z.array(import_zod14.z.object({ find: import_zod14.z.string(), replace: import_zod14.z.string() })).default([]),
16609
+ styleHint: import_zod14.z.string().default("")
16073
16610
  });
16074
- memorySchema = import_zod13.z.object({
16075
- enabled: import_zod13.z.boolean().default(true),
16076
- override: import_zod13.z.boolean().default(false),
16077
- filePrioritization: import_zod13.z.boolean().default(false),
16078
- queryAugmentation: import_zod13.z.boolean().default(true)
16611
+ memorySchema = import_zod14.z.object({
16612
+ enabled: import_zod14.z.boolean().default(true),
16613
+ override: import_zod14.z.boolean().default(false),
16614
+ filePrioritization: import_zod14.z.boolean().default(false),
16615
+ queryAugmentation: import_zod14.z.boolean().default(true)
16079
16616
  });
16080
- tuningSchema = import_zod13.z.object({
16081
- topK: import_zod13.z.number().int().positive().default(5),
16082
- fallbackThreshold: import_zod13.z.number().min(0).max(1).default(0.95),
16083
- pinBoost: import_zod13.z.number().min(0).max(1).default(0.15),
16084
- identifierBoost: import_zod13.z.number().min(0).max(1).default(0.15),
16085
- pageWindow: import_zod13.z.number().int().min(0).default(1),
16086
- maxQueriesPerContext: import_zod13.z.number().int().positive().default(5),
16617
+ tuningSchema = import_zod14.z.object({
16618
+ topK: import_zod14.z.number().int().positive().default(5),
16619
+ fallbackThreshold: import_zod14.z.number().min(0).max(1).default(0.95),
16620
+ pinBoost: import_zod14.z.number().min(0).max(1).default(0.15),
16621
+ identifierBoost: import_zod14.z.number().min(0).max(1).default(0.15),
16622
+ pageWindow: import_zod14.z.number().int().min(0).default(1),
16623
+ maxQueriesPerContext: import_zod14.z.number().int().positive().default(5),
16087
16624
  /**
16088
16625
  * Orchestration engine. "v1" is the sequential flow every agent ran before 2026-09;
16089
16626
  * "v2" merges the phase-1 LLM hops and runs identifier pins in parallel. Per agent,
16090
16627
  * so a candidate agent can run v2 while the production agent stays on v1.
16091
16628
  */
16092
- engine: import_zod13.z.enum(["v1", "v2"]).default("v1"),
16629
+ engine: import_zod14.z.enum(["v1", "v2"]).default("v1"),
16093
16630
  /** v2 sub-features; each can be switched off on its own to bisect a regression. */
16094
- v2: import_zod13.z.object({
16095
- mergedMemoryCall: import_zod13.z.boolean().default(true),
16096
- mergedRoutingCall: import_zod13.z.boolean().default(true),
16097
- parallelPins: import_zod13.z.boolean().default(true)
16631
+ v2: import_zod14.z.object({
16632
+ mergedMemoryCall: import_zod14.z.boolean().default(true),
16633
+ mergedRoutingCall: import_zod14.z.boolean().default(true),
16634
+ parallelPins: import_zod14.z.boolean().default(true)
16098
16635
  }).default({ mergedMemoryCall: true, mergedRoutingCall: true, parallelPins: true })
16099
16636
  });
16100
- claimCheckSchema = import_zod13.z.object({
16101
- enabled: import_zod13.z.boolean().default(false),
16637
+ claimCheckSchema = import_zod14.z.object({
16638
+ enabled: import_zod14.z.boolean().default(false),
16102
16639
  /** Empty = fall back to the agent's utility model, then the agent's model. */
16103
- model: import_zod13.z.string().default(""),
16104
- fidelity: import_zod13.z.enum(["fast", "paper"]).default(CLAIM_CHECK_DEFAULTS.fidelity),
16105
- completions: import_zod13.z.number().int().min(1).max(3).default(CLAIM_CHECK_DEFAULTS.completions),
16106
- reRetrieve: import_zod13.z.boolean().default(CLAIM_CHECK_DEFAULTS.reRetrieve),
16107
- thresholds: import_zod13.z.object({
16108
- warn: import_zod13.z.number().min(0).max(1).default(CLAIM_CHECK_DEFAULTS.thresholds.warn),
16109
- alert: import_zod13.z.number().min(0).max(1).default(CLAIM_CHECK_DEFAULTS.thresholds.alert)
16640
+ model: import_zod14.z.string().default(""),
16641
+ fidelity: import_zod14.z.enum(["fast", "paper"]).default(CLAIM_CHECK_DEFAULTS.fidelity),
16642
+ completions: import_zod14.z.number().int().min(1).max(3).default(CLAIM_CHECK_DEFAULTS.completions),
16643
+ reRetrieve: import_zod14.z.boolean().default(CLAIM_CHECK_DEFAULTS.reRetrieve),
16644
+ thresholds: import_zod14.z.object({
16645
+ warn: import_zod14.z.number().min(0).max(1).default(CLAIM_CHECK_DEFAULTS.thresholds.warn),
16646
+ alert: import_zod14.z.number().min(0).max(1).default(CLAIM_CHECK_DEFAULTS.thresholds.alert)
16110
16647
  }).default(CLAIM_CHECK_DEFAULTS.thresholds),
16111
- showToExternalUsers: import_zod13.z.boolean().default(false),
16112
- caps: import_zod13.z.object({
16113
- maxSentences: import_zod13.z.number().int().positive().default(CLAIM_CHECK_DEFAULTS.caps.maxSentences),
16114
- maxClaims: import_zod13.z.number().int().positive().default(CLAIM_CHECK_DEFAULTS.caps.maxClaims),
16115
- maxReRetrievals: import_zod13.z.number().int().min(0).default(CLAIM_CHECK_DEFAULTS.caps.maxReRetrievals)
16648
+ showToExternalUsers: import_zod14.z.boolean().default(false),
16649
+ caps: import_zod14.z.object({
16650
+ maxSentences: import_zod14.z.number().int().positive().default(CLAIM_CHECK_DEFAULTS.caps.maxSentences),
16651
+ maxClaims: import_zod14.z.number().int().positive().default(CLAIM_CHECK_DEFAULTS.caps.maxClaims),
16652
+ maxReRetrievals: import_zod14.z.number().int().min(0).default(CLAIM_CHECK_DEFAULTS.caps.maxReRetrievals)
16116
16653
  }).default(CLAIM_CHECK_DEFAULTS.caps)
16117
16654
  });
16118
16655
  boolVal = (v) => v === true || v === "true" || v === 1;
@@ -16448,9 +16985,9 @@ async function resolveIdentifierPins({
16448
16985
  model,
16449
16986
  system: set.strategy === "exact" ? EXACT_EXTRACTION_PROMPT(set) : FUZZY_EXTRACTION_PROMPT(set),
16450
16987
  messages: [{ role: "user", content: question }],
16451
- schema: import_zod14.z.object({
16452
- hasMatches: import_zod14.z.boolean(),
16453
- matches: import_zod14.z.array(import_zod14.z.string()).optional()
16988
+ schema: import_zod15.z.object({
16989
+ hasMatches: import_zod15.z.boolean(),
16990
+ matches: import_zod15.z.array(import_zod15.z.string()).optional()
16454
16991
  })
16455
16992
  });
16456
16993
  if (!output?.hasMatches || !output.matches?.length) return;
@@ -16498,13 +17035,13 @@ async function resolveIdentifierPins({
16498
17035
  );
16499
17036
  return { pinsByContext, exactPinsByContext, steps };
16500
17037
  }
16501
- var import_fuse, import_zod14, SUPPLEMENT_MIN_TOKEN_LENGTH, SUPPLEMENT_BUDGET, SUPPLEMENT_BUDGET_WIDE, itemCaches, ensureItemsCache, FUZZY_EXTRACTION_PROMPT, EXACT_EXTRACTION_PROMPT;
17038
+ var import_fuse, import_zod15, SUPPLEMENT_MIN_TOKEN_LENGTH, SUPPLEMENT_BUDGET, SUPPLEMENT_BUDGET_WIDE, itemCaches, ensureItemsCache, FUZZY_EXTRACTION_PROMPT, EXACT_EXTRACTION_PROMPT;
16502
17039
  var init_prefilter = __esm({
16503
17040
  "ee/agentic-retrieval/pipeline/prefilter.ts"() {
16504
17041
  "use strict";
16505
17042
  init_cjs_shims();
16506
17043
  import_fuse = __toESM(require("fuse.js"), 1);
16507
- import_zod14 = require("zod");
17044
+ import_zod15 = require("zod");
16508
17045
  init_micro_call();
16509
17046
  init_text_utils();
16510
17047
  init_config3();
@@ -16588,18 +17125,18 @@ ${rulesLines}` + (extraInstructions ? `
16588
17125
  ${extraInstructions}
16589
17126
  </instructions>` : "") : "");
16590
17127
  const ids = enabledContexts.map((c) => c.id);
16591
- const schema7 = import_zod15.z.object({
16592
- docPage: import_zod15.z.object({
16593
- hasFilenameHint: import_zod15.z.boolean(),
16594
- filenameHints: import_zod15.z.array(import_zod15.z.string()).optional(),
16595
- hasPageHint: import_zod15.z.boolean(),
16596
- pageNumber: import_zod15.z.number().int().nullable().optional()
17128
+ const schema7 = import_zod16.z.object({
17129
+ docPage: import_zod16.z.object({
17130
+ hasFilenameHint: import_zod16.z.boolean(),
17131
+ filenameHints: import_zod16.z.array(import_zod16.z.string()).optional(),
17132
+ hasPageHint: import_zod16.z.boolean(),
17133
+ pageNumber: import_zod16.z.number().int().nullable().optional()
16597
17134
  }),
16598
- explicitlyRequestedKnowledgeBases: import_zod15.z.array(import_zod15.z.enum(ids)),
17135
+ explicitlyRequestedKnowledgeBases: import_zod16.z.array(import_zod16.z.enum(ids)),
16599
17136
  ...routingRules.length ? {
16600
- classification: import_zod15.z.object({
16601
- ruleId: import_zod15.z.enum(routingRules.map((r) => r.id)),
16602
- reason: import_zod15.z.string()
17137
+ classification: import_zod16.z.object({
17138
+ ruleId: import_zod16.z.enum(routingRules.map((r) => r.id)),
17139
+ reason: import_zod16.z.string()
16603
17140
  })
16604
17141
  } : {}
16605
17142
  });
@@ -16658,11 +17195,11 @@ If explicit, return the knowledge base ids. If not, return an empty array.`;
16658
17195
  model,
16659
17196
  system: buildDocPagePrompt(knownIdentifiers),
16660
17197
  messages: [{ role: "user", content: question }],
16661
- schema: import_zod15.z.object({
16662
- hasFilenameHint: import_zod15.z.boolean(),
16663
- filenameHints: import_zod15.z.array(import_zod15.z.string()).optional(),
16664
- hasPageHint: import_zod15.z.boolean(),
16665
- pageNumber: import_zod15.z.number().int().nullable().optional()
17198
+ schema: import_zod16.z.object({
17199
+ hasFilenameHint: import_zod16.z.boolean(),
17200
+ filenameHints: import_zod16.z.array(import_zod16.z.string()).optional(),
17201
+ hasPageHint: import_zod16.z.boolean(),
17202
+ pageNumber: import_zod16.z.number().int().nullable().optional()
16666
17203
  })
16667
17204
  });
16668
17205
  } catch (err4) {
@@ -16682,9 +17219,9 @@ If explicit, return the knowledge base ids. If not, return an empty array.`;
16682
17219
  return await microCall({
16683
17220
  model,
16684
17221
  system: kbSystemPrompt,
16685
- schema: import_zod15.z.object({
16686
- explicitlyRequestedKnowledgeBases: import_zod15.z.array(
16687
- import_zod15.z.enum(enabledContexts.map((c) => c.id))
17222
+ schema: import_zod16.z.object({
17223
+ explicitlyRequestedKnowledgeBases: import_zod16.z.array(
17224
+ import_zod16.z.enum(enabledContexts.map((c) => c.id))
16688
17225
  )
16689
17226
  }),
16690
17227
  messages: [{ role: "user", content: question }]
@@ -16775,9 +17312,9 @@ ${extraInstructions}
16775
17312
  model,
16776
17313
  system: classifyPrompt,
16777
17314
  messages: [{ role: "user", content: question }],
16778
- schema: import_zod15.z.object({
16779
- ruleId: import_zod15.z.enum(ruleIds),
16780
- reason: import_zod15.z.string()
17315
+ schema: import_zod16.z.object({
17316
+ ruleId: import_zod16.z.enum(ruleIds),
17317
+ reason: import_zod16.z.string()
16781
17318
  })
16782
17319
  }));
16783
17320
  const matchedRule = routingRules.find((r) => r.id === classified.ruleId);
@@ -16832,12 +17369,12 @@ ${extraInstructions}
16832
17369
  };
16833
17370
  }
16834
17371
  }
16835
- var import_zod15, MAX_USER_PIN_MATCHES, buildDocPagePrompt;
17372
+ var import_zod16, MAX_USER_PIN_MATCHES, buildDocPagePrompt;
16836
17373
  var init_routing = __esm({
16837
17374
  "ee/agentic-retrieval/pipeline/routing.ts"() {
16838
17375
  "use strict";
16839
17376
  init_cjs_shims();
16840
- import_zod15 = require("zod");
17377
+ import_zod16 = require("zod");
16841
17378
  init_micro_call();
16842
17379
  init_timing();
16843
17380
  init_prefilter();
@@ -16942,22 +17479,22 @@ ${glossary.map((g) => `${g.term} : ${g.meaning}`).join("\n")}` : "";
16942
17479
  `
16943
17480
  }
16944
17481
  ],
16945
- schema: import_zod16.z.object({
16946
- relevantChunkIds: import_zod16.z.array(import_zod16.z.string()).describe("chunk_ids (UUIDs at the start of each bullet) of relevant chunks; empty array if none."),
16947
- override: import_zod16.z.object({
16948
- overrides: import_zod16.z.boolean().describe("True ONLY if a chunk directly and sufficiently answers the question."),
16949
- confidence: import_zod16.z.enum(["high", "medium", "low"]),
16950
- authoritativeChunkIds: import_zod16.z.array(import_zod16.z.string()).describe("chunk_ids that directly answer the question; empty if overrides is false."),
16951
- reason: import_zod16.z.string().describe("One short sentence.")
17482
+ schema: import_zod17.z.object({
17483
+ relevantChunkIds: import_zod17.z.array(import_zod17.z.string()).describe("chunk_ids (UUIDs at the start of each bullet) of relevant chunks; empty array if none."),
17484
+ override: import_zod17.z.object({
17485
+ overrides: import_zod17.z.boolean().describe("True ONLY if a chunk directly and sufficiently answers the question."),
17486
+ confidence: import_zod17.z.enum(["high", "medium", "low"]),
17487
+ authoritativeChunkIds: import_zod17.z.array(import_zod17.z.string()).describe("chunk_ids that directly answer the question; empty if overrides is false."),
17488
+ reason: import_zod17.z.string().describe("One short sentence.")
16952
17489
  }),
16953
- filePrioritization: import_zod16.z.object({
16954
- shouldPrioritizeFiles: import_zod16.z.boolean(),
16955
- fileNameHints: import_zod16.z.array(import_zod16.z.string()).optional()
17490
+ filePrioritization: import_zod17.z.object({
17491
+ shouldPrioritizeFiles: import_zod17.z.boolean(),
17492
+ fileNameHints: import_zod17.z.array(import_zod17.z.string()).optional()
16956
17493
  }),
16957
- augmentation: import_zod16.z.object({
16958
- updatedUserQuestion: import_zod16.z.string(),
16959
- updatedRelevantKeywords: import_zod16.z.array(import_zod16.z.string()),
16960
- updatedImportantKeyword: import_zod16.z.string()
17494
+ augmentation: import_zod17.z.object({
17495
+ updatedUserQuestion: import_zod17.z.string(),
17496
+ updatedRelevantKeywords: import_zod17.z.array(import_zod17.z.string()),
17497
+ updatedImportantKeyword: import_zod17.z.string()
16961
17498
  })
16962
17499
  })
16963
17500
  });
@@ -17040,8 +17577,8 @@ async function runMemoryPhase({
17040
17577
  `
17041
17578
  }
17042
17579
  ],
17043
- schema: import_zod16.z.object({
17044
- relevantChunkIds: import_zod16.z.array(import_zod16.z.string()).describe(
17580
+ schema: import_zod17.z.object({
17581
+ relevantChunkIds: import_zod17.z.array(import_zod17.z.string()).describe(
17045
17582
  "The chunk_ids (UUIDs at the start of each bullet) of chunks containing information relevant to the user's question. Empty array if none are relevant."
17046
17583
  )
17047
17584
  })
@@ -17150,17 +17687,17 @@ ${glossary.map((g) => `${g.term} : ${g.meaning}`).join("\n")}` : "";
17150
17687
  `
17151
17688
  }
17152
17689
  ],
17153
- schema: import_zod16.z.object({
17154
- overrides: import_zod16.z.boolean().describe(
17690
+ schema: import_zod17.z.object({
17691
+ overrides: import_zod17.z.boolean().describe(
17155
17692
  "True ONLY if a memory chunk directly and sufficiently answers the user's question and should be authoritative over the documents. Be strict; when unsure, false."
17156
17693
  ),
17157
- confidence: import_zod16.z.enum(["high", "medium", "low"]).describe(
17694
+ confidence: import_zod17.z.enum(["high", "medium", "low"]).describe(
17158
17695
  "Confidence that the selected memory chunk(s) fully and directly answer the question."
17159
17696
  ),
17160
- authoritativeChunkIds: import_zod16.z.array(import_zod16.z.string()).describe(
17697
+ authoritativeChunkIds: import_zod17.z.array(import_zod17.z.string()).describe(
17161
17698
  "The chunk_ids of the memory chunk(s) that directly answer the question. Empty if overrides is false."
17162
17699
  ),
17163
- reason: import_zod16.z.string().describe(
17700
+ reason: import_zod17.z.string().describe(
17164
17701
  "One short sentence: why this memory does or does not directly answer the question."
17165
17702
  )
17166
17703
  })
@@ -17184,9 +17721,9 @@ ${glossary.map((g) => `${g.term} : ${g.meaning}`).join("\n")}` : "";
17184
17721
  model,
17185
17722
  system: "You are a helpful assistant that will strictly follow the user's instructions.",
17186
17723
  messages: [{ role: "user", content: PROMPT_EXTRACT_PRIORITIZED_FILES }],
17187
- schema: import_zod16.z.object({
17188
- shouldPrioritizeFiles: import_zod16.z.boolean(),
17189
- fileNameHints: import_zod16.z.array(import_zod16.z.string()).optional()
17724
+ schema: import_zod17.z.object({
17725
+ shouldPrioritizeFiles: import_zod17.z.boolean(),
17726
+ fileNameHints: import_zod17.z.array(import_zod17.z.string()).optional()
17190
17727
  })
17191
17728
  }).catch(() => ({
17192
17729
  output: { shouldPrioritizeFiles: false, fileNameHints: [] }
@@ -17198,10 +17735,10 @@ ${glossary.map((g) => `${g.term} : ${g.meaning}`).join("\n")}` : "";
17198
17735
  model,
17199
17736
  system: "You are a helpful assistant that will strictly follow the user's instructions.",
17200
17737
  messages: [{ role: "user", content: QUERY_AUGMENTATION_PROMPT }],
17201
- schema: import_zod16.z.object({
17202
- updatedUserQuestion: import_zod16.z.string(),
17203
- updatedRelevantKeywords: import_zod16.z.array(import_zod16.z.string()),
17204
- updatedImportantKeyword: import_zod16.z.string()
17738
+ schema: import_zod17.z.object({
17739
+ updatedUserQuestion: import_zod17.z.string(),
17740
+ updatedRelevantKeywords: import_zod17.z.array(import_zod17.z.string()),
17741
+ updatedImportantKeyword: import_zod17.z.string()
17205
17742
  })
17206
17743
  }).catch(() => ({
17207
17744
  output: {
@@ -17288,12 +17825,12 @@ ${glossary.map((g) => `${g.term} : ${g.meaning}`).join("\n")}` : "";
17288
17825
  return neutralResult(question, keywords, importantKeyword);
17289
17826
  }
17290
17827
  }
17291
- var import_zod16, MEMORY_OVERRIDE_MIN_CONFIDENCE, MEMORY_SYNTHETIC_RERANK_SCORE;
17828
+ var import_zod17, MEMORY_OVERRIDE_MIN_CONFIDENCE, MEMORY_SYNTHETIC_RERANK_SCORE;
17292
17829
  var init_memory = __esm({
17293
17830
  "ee/agentic-retrieval/pipeline/memory.ts"() {
17294
17831
  "use strict";
17295
17832
  init_cjs_shims();
17296
- import_zod16 = require("zod");
17833
+ import_zod17 = require("zod");
17297
17834
  init_micro_call();
17298
17835
  init_timing();
17299
17836
  init_prefilter();
@@ -17333,6 +17870,7 @@ async function singleSearch({
17333
17870
  });
17334
17871
  return results.chunks || [];
17335
17872
  } catch (e) {
17873
+ if (e instanceof UnknownFilterPathError) throw e;
17336
17874
  console.warn("[EXULU] singleSearch failed for query:", query, e);
17337
17875
  return [];
17338
17876
  }
@@ -17394,6 +17932,7 @@ var init_multi_query = __esm({
17394
17932
  "ee/agentic-retrieval/pipeline/multi-query.ts"() {
17395
17933
  "use strict";
17396
17934
  init_cjs_shims();
17935
+ init_convert_graphql_filter_operator_to_pg_query();
17397
17936
  init_config3();
17398
17937
  }
17399
17938
  });
@@ -17587,6 +18126,7 @@ async function searchContexts(opts) {
17587
18126
  }
17588
18127
  return [];
17589
18128
  } catch (err4) {
18129
+ if (err4 instanceof UnknownFilterPathError) throw err4;
17590
18130
  if (isEmbedderNotConfigured(err4)) {
17591
18131
  console.warn(
17592
18132
  `[EXULU pipeline] context "${ctxId}" is not searchable: ${err4.message}`
@@ -17612,6 +18152,7 @@ var init_search = __esm({
17612
18152
  init_timing();
17613
18153
  init_text_utils();
17614
18154
  init_embedder_not_configured();
18155
+ init_convert_graphql_filter_operator_to_pg_query();
17615
18156
  tagContext = (chunks, ctx) => chunks.map((c) => ({ ...c, context: { id: ctx.id, name: ctx.name ?? ctx.id } }));
17616
18157
  }
17617
18158
  });
@@ -18136,11 +18677,11 @@ function createAgenticRetrievalTool(opts) {
18136
18677
  default: '{"enabled":false,"model":"","fidelity":"fast","thresholds":{"warn":0.1,"alert":0.3}}'
18137
18678
  }
18138
18679
  ],
18139
- inputSchema: import_zod17.z.object({
18140
- userQuery: import_zod17.z.string().describe("The original unaltered question from the user"),
18141
- relevantKeywords: import_zod17.z.array(import_zod17.z.string()).describe("Keywords extracted from the user's question relevant to the search"),
18142
- importantKeyword: import_zod17.z.string().describe("The single most important keyword from the user's question"),
18143
- confirmedContextIds: import_zod17.z.array(import_zod17.z.string()).optional().describe(
18680
+ inputSchema: import_zod18.z.object({
18681
+ userQuery: import_zod18.z.string().describe("The original unaltered question from the user"),
18682
+ relevantKeywords: import_zod18.z.array(import_zod18.z.string()).describe("Keywords extracted from the user's question relevant to the search"),
18683
+ importantKeyword: import_zod18.z.string().describe("The single most important keyword from the user's question"),
18684
+ confirmedContextIds: import_zod18.z.array(import_zod18.z.string()).optional().describe(
18144
18685
  "Knowledge base IDs explicitly confirmed by the user to be used in the retrieval. When present, only searches these contexts."
18145
18686
  )
18146
18687
  }),
@@ -18558,6 +19099,18 @@ Verified answer:
18558
19099
  yield { result: serializeOutput(result, hideSources) };
18559
19100
  return { result: serializeOutput(result, hideSources) };
18560
19101
  } catch (err4) {
19102
+ if (err4 instanceof UnknownFilterPathError) {
19103
+ console.warn("[EXULU pipeline] retrieval refused an unknown json filter path:", err4.message);
19104
+ result.steps.push({
19105
+ stepNumber: 1,
19106
+ text: err4.message,
19107
+ toolCalls: [],
19108
+ chunks: [],
19109
+ tokens: 0
19110
+ });
19111
+ yield { result: serializeOutput(result, hideSources) };
19112
+ return;
19113
+ }
18561
19114
  console.warn("[EXULU pipeline] retrieval pipeline failed:", err4);
18562
19115
  result.steps.push({
18563
19116
  stepNumber: 1,
@@ -18572,12 +19125,12 @@ Verified answer:
18572
19125
  }
18573
19126
  });
18574
19127
  }
18575
- var import_zod17, AGENTIC_RETRIEVAL_TOOL_NAME;
19128
+ var import_zod18, AGENTIC_RETRIEVAL_TOOL_NAME;
18576
19129
  var init_pipeline = __esm({
18577
19130
  "ee/agentic-retrieval/pipeline/index.ts"() {
18578
19131
  "use strict";
18579
19132
  init_cjs_shims();
18580
- import_zod17 = require("zod");
19133
+ import_zod18 = require("zod");
18581
19134
  init_tool();
18582
19135
  init_entitlements();
18583
19136
  init_resolve_reranker();
@@ -18595,6 +19148,7 @@ var init_pipeline = __esm({
18595
19148
  init_pin_rerun();
18596
19149
  init_global_ids();
18597
19150
  init_resolve_max_steps();
19151
+ init_convert_graphql_filter_operator_to_pg_query();
18598
19152
  init_global_ids();
18599
19153
  AGENTIC_RETRIEVAL_TOOL_NAME = "Context Search";
18600
19154
  }
@@ -20025,6 +20579,7 @@ async function getJobsByQueueName(queueName, statusses, page, limit) {
20025
20579
  // src/graphql/mutations/index.ts
20026
20580
  init_cjs_shims();
20027
20581
  init_context();
20582
+ init_item_write();
20028
20583
  init_entities();
20029
20584
  init_statistics2();
20030
20585
  init_access_control();
@@ -21725,6 +22280,10 @@ function createMutations(table, contexts, tools, config) {
21725
22280
  if (table.name.singular === "agent") {
21726
22281
  input = await applyAgentGuestFieldTransforms(input);
21727
22282
  }
22283
+ const createValidation = prepareItemWrite({ fields: table.fields, existing: null, input });
22284
+ if (!createValidation.ok) {
22285
+ throw new Error(createValidation.message);
22286
+ }
21728
22287
  Object.keys(input).forEach((key) => {
21729
22288
  if (table.fields.find((field) => field.name === key)?.type === "json") {
21730
22289
  if (typeof input[key] === "object" || Array.isArray(input[key])) {
@@ -21800,13 +22359,6 @@ function createMutations(table, contexts, tools, config) {
21800
22359
  if (table.name.singular === "agent") {
21801
22360
  input = await applyAgentGuestFieldTransforms(input);
21802
22361
  }
21803
- Object.keys(input).forEach((key) => {
21804
- if (table.fields.find((field) => field.name === key)?.type === "json") {
21805
- if (typeof input[key] === "object" || Array.isArray(input[key])) {
21806
- input[key] = JSON.stringify(input[key]);
21807
- }
21808
- }
21809
- });
21810
22362
  const requestedFields = getRequestedFields(info);
21811
22363
  const sanitizedFields = sanitizeRequestedFields(table, requestedFields);
21812
22364
  let itemQuery = db2.from(tableNamePlural).select(sanitizedFields);
@@ -21816,6 +22368,24 @@ function createMutations(table, contexts, tools, config) {
21816
22368
  throw new Error("Record not found");
21817
22369
  }
21818
22370
  await validateWriteAccess(item.id, context);
22371
+ const existingRow = args.merge?.length ? await db2.from(tableNamePlural).where({ id: item.id }).first() : null;
22372
+ const prepared = prepareItemWrite({
22373
+ fields: table.fields,
22374
+ existing: existingRow ?? null,
22375
+ input,
22376
+ merge: args.merge
22377
+ });
22378
+ if (!prepared.ok) {
22379
+ throw new Error(prepared.message);
22380
+ }
22381
+ input = prepared.values;
22382
+ Object.keys(input).forEach((key) => {
22383
+ if (table.fields.find((field) => field.name === key)?.type === "json") {
22384
+ if (typeof input[key] === "object" || Array.isArray(input[key])) {
22385
+ input[key] = JSON.stringify(input[key]);
22386
+ }
22387
+ }
22388
+ });
21819
22389
  const columns = await db2(tableNamePlural).columnInfo();
21820
22390
  const [result] = await db2(tableNamePlural).where({ id: item.id }).update({
21821
22391
  ...input,
@@ -21876,6 +22446,17 @@ function createMutations(table, contexts, tools, config) {
21876
22446
  if (table.name.singular === "agent") {
21877
22447
  input = await applyAgentGuestFieldTransforms(input);
21878
22448
  }
22449
+ const existingRow = args.merge?.length ? await db2.from(tableNamePlural).where({ id }).first() : null;
22450
+ const prepared = prepareItemWrite({
22451
+ fields: table.fields,
22452
+ existing: existingRow ?? null,
22453
+ input,
22454
+ merge: args.merge
22455
+ });
22456
+ if (!prepared.ok) {
22457
+ throw new Error(prepared.message);
22458
+ }
22459
+ input = prepared.values;
21879
22460
  Object.keys(input).forEach((key) => {
21880
22461
  if (table.fields.find((field) => field.name === key)?.type === "json") {
21881
22462
  if (typeof input[key] === "object" || Array.isArray(input[key])) {
@@ -22610,7 +23191,7 @@ init_cjs_shims();
22610
23191
  init_entitlements();
22611
23192
  init_singleton();
22612
23193
  init_tool();
22613
- var import_zod18 = require("zod");
23194
+ var import_zod19 = require("zod");
22614
23195
  init_check_record_access();
22615
23196
  init_resolve_model();
22616
23197
  init_statistics2();
@@ -23027,10 +23608,10 @@ function resolveProviderOptions(agent) {
23027
23608
  // src/exulu/stream-error.ts
23028
23609
  init_cjs_shims();
23029
23610
  function onChatStreamError({ error }) {
23030
- const detail = error instanceof Error ? error.message : error === void 0 ? "unknown error" : safeStringify(error);
23611
+ const detail = error instanceof Error ? error.message : error === void 0 ? "unknown error" : safeStringify2(error);
23031
23612
  console.error("[EXULU] chat stream error.", detail);
23032
23613
  }
23033
- function safeStringify(value) {
23614
+ function safeStringify2(value) {
23034
23615
  try {
23035
23616
  return JSON.stringify(value) ?? String(value);
23036
23617
  } catch {
@@ -24090,9 +24671,9 @@ var createAgentTool = async (instance2, contexts) => {
24090
24671
  name: `${agent.name}`,
24091
24672
  type: "agent",
24092
24673
  category: "agents",
24093
- inputSchema: import_zod18.z.object({
24094
- prompt: import_zod18.z.string().describe("The prompt (usually a question for the agent) to send to the agent."),
24095
- information: import_zod18.z.string().describe("A summary of relevant context / information from the current session")
24674
+ inputSchema: import_zod19.z.object({
24675
+ prompt: import_zod19.z.string().describe("The prompt (usually a question for the agent) to send to the agent."),
24676
+ information: import_zod19.z.string().describe("A summary of relevant context / information from the current session")
24096
24677
  }),
24097
24678
  description: `This tool calls an agent named: ${agent.name}. The agent does the following: ${agent.description}.`,
24098
24679
  config: [],
@@ -29479,12 +30060,12 @@ async function runScan({ db: db2, context, user, judge, now = /* @__PURE__ */ ne
29479
30060
  // src/exulu/memory/conflicts/judge.ts
29480
30061
  init_cjs_shims();
29481
30062
  var import_ai10 = require("ai");
29482
- var import_zod19 = require("zod");
30063
+ var import_zod20 = require("zod");
29483
30064
  init_resolve_model();
29484
- var schema = import_zod19.z.object({
29485
- verdict: import_zod19.z.enum(["same", "contradict", "compatible"]),
30065
+ var schema = import_zod20.z.object({
30066
+ verdict: import_zod20.z.enum(["same", "contradict", "compatible"]),
29486
30067
  // No .max(160) here: an over-long reason must not fail the whole call — truncate after.
29487
- reason: import_zod19.z.string()
30068
+ reason: import_zod20.z.string()
29488
30069
  });
29489
30070
  var SYSTEM = `You compare two short memories an assistant saved from conversations.
29490
30071
  Answer with JSON: verdict = "same" when both state the same fact or instruction (wording may differ),
@@ -29519,7 +30100,7 @@ async function makeMergeSuggester({ modelId, agent, user }) {
29519
30100
  prompt: members.map((m, i) => `Memory ${i + 1}:
29520
30101
  ${m.information}`).join("\n\n"),
29521
30102
  maxRetries: 1,
29522
- output: import_ai10.Output.object({ schema: import_zod19.z.object({ information: import_zod19.z.string().min(1).max(400) }) })
30103
+ output: import_ai10.Output.object({ schema: import_zod20.z.object({ information: import_zod20.z.string().min(1).max(400) }) })
29523
30104
  });
29524
30105
  const types = members.map((m) => m.type).filter((t) => !!t);
29525
30106
  const type = types.length ? [...types].sort((x, y) => types.filter((t) => t === y).length - types.filter((t) => t === x).length)[0] ?? null : null;
@@ -30114,8 +30695,34 @@ function createSDL(tables, contexts, tools, config, evals) {
30114
30695
  ${tableNamePlural}CreateOne(input: ${tableNameSingular}Input!, upsert: Boolean, generateEmbeddings: Boolean): ${tableNameSingular}MutationPayload
30115
30696
  ${tableNamePlural}CopyOneById(id: ID!): ${tableNameSingular}MutationPayload
30116
30697
 
30117
- ${tableNamePlural}UpdateOne(where: [Filter${tableNameSingularUpperCaseFirst}], input: ${tableNameSingular}Input!, generateEmbeddings: Boolean): ${tableNameSingular}MutationPayload
30118
- ${tableNamePlural}UpdateOneById(id: ID!, input: ${tableNameSingular}Input!, generateEmbeddings: Boolean): ${tableNameSingular}MutationPayload
30698
+ """
30699
+ merge: names of json fields in \`input\` whose value is a merge patch
30700
+ (only the keys given are changed, other stored keys are kept, and an
30701
+ explicit null deletes a key) rather than a full replacement. Omit to
30702
+ replace the whole field, as normal (spec 2026-11-09-typed-json-fields).
30703
+ Every name given must be a json field this same call sends a value for;
30704
+ one that is not is refused, not ignored. NOT concurrency-safe: a merge
30705
+ reads the stored value and writes the combined result as two separate
30706
+ statements, with no transaction or row lock, so two merges that OVERLAP
30707
+ in time can still lose one of them. Merges that are serialized (each
30708
+ awaited before the next) both land; overlapping edits to one item need
30709
+ to be serialized by the caller.
30710
+ """
30711
+ ${tableNamePlural}UpdateOne(where: [Filter${tableNameSingularUpperCaseFirst}], input: ${tableNameSingular}Input!, generateEmbeddings: Boolean, merge: [String]): ${tableNameSingular}MutationPayload
30712
+ """
30713
+ merge: names of json fields in \`input\` whose value is a merge patch
30714
+ (only the keys given are changed, other stored keys are kept, and an
30715
+ explicit null deletes a key) rather than a full replacement. Omit to
30716
+ replace the whole field, as normal (spec 2026-11-09-typed-json-fields).
30717
+ Every name given must be a json field this same call sends a value for;
30718
+ one that is not is refused, not ignored. NOT concurrency-safe: a merge
30719
+ reads the stored value and writes the combined result as two separate
30720
+ statements, with no transaction or row lock, so two merges that OVERLAP
30721
+ in time can still lose one of them. Merges that are serialized (each
30722
+ awaited before the next) both land; overlapping edits to one item need
30723
+ to be serialized by the caller.
30724
+ """
30725
+ ${tableNamePlural}UpdateOneById(id: ID!, input: ${tableNameSingular}Input!, generateEmbeddings: Boolean, merge: [String]): ${tableNameSingular}MutationPayload
30119
30726
  ${tableNamePlural}RemoveOneById(id: ID!): ${tableNameSingular}
30120
30727
  ${tableNamePlural}RemoveOne(where: JSON!): ${tableNameSingular}
30121
30728
  `;
@@ -32546,12 +33153,12 @@ init_statistics2();
32546
33153
  // src/exulu/suggestions.ts
32547
33154
  init_cjs_shims();
32548
33155
  var import_ai11 = require("ai");
32549
- var import_zod20 = require("zod");
33156
+ var import_zod21 = require("zod");
32550
33157
  var SUGGESTIONS_SYSTEM_PROMPT = "You generate short follow-up message suggestions for the user. You are NOT continuing the conversation as the assistant \u2014 you are predicting what the user might want to say next. Suggest up to 3 short follow-up questions or messages the user might want to send next. Each suggestion must be written from the user's perspective (first person) and be 12 words or fewer. You MUST submit your answer by calling the `submit_suggestions` tool exactly once. Do not emit any plain text \u2014 only the tool call.";
32551
33158
  var submitSuggestionsTool = (0, import_ai11.tool)({
32552
33159
  description: "Submit the final list of follow-up message suggestions for the user. Must be called exactly once. Each suggestion is written from the user's perspective (first person) and is 12 words or fewer.",
32553
- inputSchema: import_zod20.z.object({
32554
- suggestions: import_zod20.z.array(import_zod20.z.string()).max(3)
33160
+ inputSchema: import_zod21.z.object({
33161
+ suggestions: import_zod21.z.array(import_zod21.z.string()).max(3)
32555
33162
  })
32556
33163
  });
32557
33164
  var MAX_CHARS_PER_MESSAGE = 1e4;
@@ -32782,16 +33389,16 @@ init_view_document_page_tool();
32782
33389
  // src/templates/tools/perplexity.ts
32783
33390
  init_cjs_shims();
32784
33391
  init_tool();
32785
- var import_zod21 = __toESM(require("zod"), 1);
33392
+ var import_zod22 = __toESM(require("zod"), 1);
32786
33393
  var import_perplexity_ai = __toESM(require("@perplexity-ai/perplexity_ai"), 1);
32787
33394
  var INTERNET_SEARCH_TOOL_NAME = "Internet Search";
32788
33395
  var internetSearchTool = new ExuluTool({
32789
33396
  id: "internet_search",
32790
33397
  name: INTERNET_SEARCH_TOOL_NAME,
32791
33398
  description: "Search the internet for information.",
32792
- inputSchema: import_zod21.default.object({
32793
- query: import_zod21.default.string().describe("The query to the tool."),
32794
- search_recency_filter: import_zod21.default.enum(["day", "week", "month", "year"]).optional().describe("The recency filter for the search, can be day, week, month or year.")
33399
+ inputSchema: import_zod22.default.object({
33400
+ query: import_zod22.default.string().describe("The query to the tool."),
33401
+ search_recency_filter: import_zod22.default.enum(["day", "week", "month", "year"]).optional().describe("The recency filter for the search, can be day, week, month or year.")
32795
33402
  }),
32796
33403
  category: "internet_search",
32797
33404
  type: "web_search",
@@ -33549,7 +34156,7 @@ function registerViewerIdentityRoutes(app, deps) {
33549
34156
 
33550
34157
  // ee/claim-check/routes.ts
33551
34158
  init_cjs_shims();
33552
- var import_zod22 = require("zod");
34159
+ var import_zod23 = require("zod");
33553
34160
  init_resolve_max_steps();
33554
34161
  init_types2();
33555
34162
 
@@ -33612,13 +34219,13 @@ var SOURCE_TYPES = [
33612
34219
  "session_item",
33613
34220
  "other"
33614
34221
  ];
33615
- var requestSchema = import_zod22.z.object({
33616
- question: import_zod22.z.string().min(1),
33617
- answer: import_zod22.z.string().min(1),
33618
- sources: import_zod22.z.array(
33619
- import_zod22.z.object({
33620
- content: import_zod22.z.string(),
33621
- name: import_zod22.z.string().optional(),
34222
+ var requestSchema = import_zod23.z.object({
34223
+ question: import_zod23.z.string().min(1),
34224
+ answer: import_zod23.z.string().min(1),
34225
+ sources: import_zod23.z.array(
34226
+ import_zod23.z.object({
34227
+ content: import_zod23.z.string(),
34228
+ name: import_zod23.z.string().optional(),
33622
34229
  // Purely informational (spec §2: no trust tiers, dropped before the
33623
34230
  // engine sees it — see assignSourceIds below), so an unrecognised
33624
34231
  // value is IGNORED, not rejected: `.catch(undefined)` keeps the enum
@@ -33630,24 +34237,24 @@ var requestSchema = import_zod22.z.object({
33630
34237
  // `.catch`) would turn that pre-existing 200 into a 400, which is a
33631
34238
  // tightening this loosening-only task must not make. Do not remove
33632
34239
  // the `.catch` to "validate properly": that is the bug this guards.
33633
- type: import_zod22.z.enum(SOURCE_TYPES).optional().catch(void 0),
33634
- id: import_zod22.z.string().min(1).optional()
34240
+ type: import_zod23.z.enum(SOURCE_TYPES).optional().catch(void 0),
34241
+ id: import_zod23.z.string().min(1).optional()
33635
34242
  })
33636
34243
  ).default([]),
33637
- agent: import_zod22.z.string().optional(),
33638
- session: import_zod22.z.string().optional(),
33639
- messageId: import_zod22.z.string().optional(),
33640
- model: import_zod22.z.string().optional(),
33641
- locale: import_zod22.z.string().refine(localeIsUsable, { message: "locale is not a usable BCP 47 language tag" }).optional(),
33642
- options: import_zod22.z.object({
33643
- fidelity: import_zod22.z.enum(["fast", "paper"]).optional(),
33644
- completions: import_zod22.z.number().int().min(1).max(3).optional(),
33645
- reRetrieve: import_zod22.z.boolean().optional(),
33646
- thresholds: import_zod22.z.object({ warn: import_zod22.z.number().min(0).max(1), alert: import_zod22.z.number().min(0).max(1) }).partial().optional(),
33647
- caps: import_zod22.z.object({
33648
- maxSentences: import_zod22.z.number().int().positive(),
33649
- maxClaims: import_zod22.z.number().int().positive(),
33650
- maxReRetrievals: import_zod22.z.number().int().min(0)
34244
+ agent: import_zod23.z.string().optional(),
34245
+ session: import_zod23.z.string().optional(),
34246
+ messageId: import_zod23.z.string().optional(),
34247
+ model: import_zod23.z.string().optional(),
34248
+ locale: import_zod23.z.string().refine(localeIsUsable, { message: "locale is not a usable BCP 47 language tag" }).optional(),
34249
+ options: import_zod23.z.object({
34250
+ fidelity: import_zod23.z.enum(["fast", "paper"]).optional(),
34251
+ completions: import_zod23.z.number().int().min(1).max(3).optional(),
34252
+ reRetrieve: import_zod23.z.boolean().optional(),
34253
+ thresholds: import_zod23.z.object({ warn: import_zod23.z.number().min(0).max(1), alert: import_zod23.z.number().min(0).max(1) }).partial().optional(),
34254
+ caps: import_zod23.z.object({
34255
+ maxSentences: import_zod23.z.number().int().positive(),
34256
+ maxClaims: import_zod23.z.number().int().positive(),
34257
+ maxReRetrievals: import_zod23.z.number().int().min(0)
33651
34258
  }).partial().optional()
33652
34259
  }).optional()
33653
34260
  });
@@ -34241,7 +34848,7 @@ function selectEvidence(claimTexts, index, topK = 4) {
34241
34848
 
34242
34849
  // ee/claim-check/stages/select-disambiguate.ts
34243
34850
  init_cjs_shims();
34244
- var import_zod24 = require("zod");
34851
+ var import_zod25 = require("zod");
34245
34852
  init_micro_call();
34246
34853
  init_types2();
34247
34854
 
@@ -34378,16 +34985,16 @@ resolvable=false and clarified=null for it.`;
34378
34985
 
34379
34986
  // ee/claim-check/stages/select.ts
34380
34987
  init_cjs_shims();
34381
- var import_zod23 = require("zod");
34988
+ var import_zod24 = require("zod");
34382
34989
  init_micro_call();
34383
34990
  init_types2();
34384
- var schema2 = import_zod23.z.object({
34385
- sentences: import_zod23.z.array(
34386
- import_zod23.z.object({
34387
- index: import_zod23.z.number().int(),
34388
- verifiable: import_zod23.z.boolean(),
34389
- rewritten: import_zod23.z.string().nullable(),
34390
- reason: import_zod23.z.string()
34991
+ var schema2 = import_zod24.z.object({
34992
+ sentences: import_zod24.z.array(
34993
+ import_zod24.z.object({
34994
+ index: import_zod24.z.number().int(),
34995
+ verifiable: import_zod24.z.boolean(),
34996
+ rewritten: import_zod24.z.string().nullable(),
34997
+ reason: import_zod24.z.string()
34391
34998
  })
34392
34999
  )
34393
35000
  });
@@ -34445,15 +35052,15 @@ async function runSelection(args) {
34445
35052
  }
34446
35053
 
34447
35054
  // ee/claim-check/stages/select-disambiguate.ts
34448
- var schema3 = import_zod24.z.object({
34449
- sentences: import_zod24.z.array(
34450
- import_zod24.z.object({
34451
- index: import_zod24.z.number().int(),
34452
- verifiable: import_zod24.z.boolean(),
34453
- rewritten: import_zod24.z.string().nullable(),
34454
- resolvable: import_zod24.z.boolean(),
34455
- clarified: import_zod24.z.string().nullable(),
34456
- reason: import_zod24.z.string()
35055
+ var schema3 = import_zod25.z.object({
35056
+ sentences: import_zod25.z.array(
35057
+ import_zod25.z.object({
35058
+ index: import_zod25.z.number().int(),
35059
+ verifiable: import_zod25.z.boolean(),
35060
+ rewritten: import_zod25.z.string().nullable(),
35061
+ resolvable: import_zod25.z.boolean(),
35062
+ clarified: import_zod25.z.string().nullable(),
35063
+ reason: import_zod25.z.string()
34457
35064
  })
34458
35065
  )
34459
35066
  });
@@ -34504,16 +35111,16 @@ async function runSelectAndDisambiguate(args) {
34504
35111
 
34505
35112
  // ee/claim-check/stages/disambiguate.ts
34506
35113
  init_cjs_shims();
34507
- var import_zod25 = require("zod");
35114
+ var import_zod26 = require("zod");
34508
35115
  init_micro_call();
34509
35116
  init_types2();
34510
- var schema4 = import_zod25.z.object({
34511
- sentences: import_zod25.z.array(
34512
- import_zod25.z.object({
34513
- index: import_zod25.z.number().int(),
34514
- resolvable: import_zod25.z.boolean(),
34515
- clarified: import_zod25.z.string().nullable(),
34516
- reason: import_zod25.z.string()
35117
+ var schema4 = import_zod26.z.object({
35118
+ sentences: import_zod26.z.array(
35119
+ import_zod26.z.object({
35120
+ index: import_zod26.z.number().int(),
35121
+ resolvable: import_zod26.z.boolean(),
35122
+ clarified: import_zod26.z.string().nullable(),
35123
+ reason: import_zod26.z.string()
34517
35124
  })
34518
35125
  )
34519
35126
  });
@@ -34560,7 +35167,7 @@ async function runDisambiguation(args) {
34560
35167
 
34561
35168
  // ee/claim-check/stages/decompose.ts
34562
35169
  init_cjs_shims();
34563
- var import_zod26 = require("zod");
35170
+ var import_zod27 = require("zod");
34564
35171
  init_micro_call();
34565
35172
  init_types2();
34566
35173
 
@@ -34611,11 +35218,11 @@ function decomposeUserPrompt(args) {
34611
35218
  }
34612
35219
 
34613
35220
  // ee/claim-check/stages/decompose.ts
34614
- var schema5 = import_zod26.z.object({
34615
- sentences: import_zod26.z.array(
34616
- import_zod26.z.object({
34617
- index: import_zod26.z.number().int(),
34618
- claims: import_zod26.z.array(import_zod26.z.object({ text: import_zod26.z.string(), inferred: import_zod26.z.boolean() }))
35221
+ var schema5 = import_zod27.z.object({
35222
+ sentences: import_zod27.z.array(
35223
+ import_zod27.z.object({
35224
+ index: import_zod27.z.number().int(),
35225
+ claims: import_zod27.z.array(import_zod27.z.object({ text: import_zod27.z.string(), inferred: import_zod27.z.boolean() }))
34619
35226
  })
34620
35227
  )
34621
35228
  });
@@ -34651,7 +35258,7 @@ async function runDecomposition(args) {
34651
35258
 
34652
35259
  // ee/claim-check/stages/verify.ts
34653
35260
  init_cjs_shims();
34654
- var import_zod27 = require("zod");
35261
+ var import_zod28 = require("zod");
34655
35262
  init_micro_call();
34656
35263
  init_types2();
34657
35264
 
@@ -34713,13 +35320,13 @@ function addUsage(a, b) {
34713
35320
  }
34714
35321
 
34715
35322
  // ee/claim-check/stages/verify.ts
34716
- var schema6 = import_zod27.z.object({
34717
- claims: import_zod27.z.array(
34718
- import_zod27.z.object({
34719
- claimId: import_zod27.z.string(),
34720
- verdict: import_zod27.z.enum(["supported", "contradicted", "unsupported"]),
34721
- evidence: import_zod27.z.array(import_zod27.z.object({ sourceId: import_zod27.z.string(), quote: import_zod27.z.string() })),
34722
- rationale: import_zod27.z.string()
35323
+ var schema6 = import_zod28.z.object({
35324
+ claims: import_zod28.z.array(
35325
+ import_zod28.z.object({
35326
+ claimId: import_zod28.z.string(),
35327
+ verdict: import_zod28.z.enum(["supported", "contradicted", "unsupported"]),
35328
+ evidence: import_zod28.z.array(import_zod28.z.object({ sourceId: import_zod28.z.string(), quote: import_zod28.z.string() })),
35329
+ rationale: import_zod28.z.string()
34723
35330
  })
34724
35331
  )
34725
35332
  });
@@ -35974,13 +36581,13 @@ var handleOauthCallback = async (req, res) => {
35974
36581
 
35975
36582
  // src/exulu/auth/submit-handler.ts
35976
36583
  init_cjs_shims();
35977
- var import_zod28 = require("zod");
36584
+ var import_zod29 = require("zod");
35978
36585
  init_registry();
35979
36586
  init_credential_store();
35980
36587
  init_credentials_request();
35981
- var bodySchema = import_zod28.z.object({
35982
- nonce: import_zod28.z.string().min(1),
35983
- values: import_zod28.z.record(import_zod28.z.string(), import_zod28.z.string())
36588
+ var bodySchema = import_zod29.z.object({
36589
+ nonce: import_zod29.z.string().min(1),
36590
+ values: import_zod29.z.record(import_zod29.z.string(), import_zod29.z.string())
35984
36591
  });
35985
36592
  async function handleCredentialSubmit(req, res) {
35986
36593
  const authResult = await requestValidators.authenticate(req);
@@ -40772,7 +41379,7 @@ init_check_record_access();
40772
41379
  init_resolve_model();
40773
41380
  init_supervisor();
40774
41381
  init_client();
40775
- var import_zod29 = require("zod");
41382
+ var import_zod30 = require("zod");
40776
41383
  init_convert_exulu_tools_to_ai_sdk_tools();
40777
41384
  init_singleton();
40778
41385
  var SESSION_ID_HEADER = "mcp-session-id";
@@ -40836,7 +41443,7 @@ var ExuluMCP = class {
40836
41443
  title: tool4.name + " agent",
40837
41444
  description: tool4.description,
40838
41445
  inputSchema: {
40839
- inputs: tool4.inputSchema || import_zod29.z.object({})
41446
+ inputs: tool4.inputSchema || import_zod30.z.object({})
40840
41447
  }
40841
41448
  },
40842
41449
  async ({ inputs }, args) => {
@@ -40887,7 +41494,7 @@ var ExuluMCP = class {
40887
41494
  title: "Get List of Prompt Templates",
40888
41495
  description: "Retrieves a list of prompt templates available for this agent. Returns the name, description, and ID of each template.",
40889
41496
  inputSchema: {
40890
- inputs: import_zod29.z.object({})
41497
+ inputs: import_zod30.z.object({})
40891
41498
  }
40892
41499
  },
40893
41500
  async ({ inputs }, args) => {
@@ -40933,8 +41540,8 @@ var ExuluMCP = class {
40933
41540
  title: "Get Prompt Template Details",
40934
41541
  description: "Retrieves the full details of a specific prompt template by ID, including the actual template content with variables.",
40935
41542
  inputSchema: {
40936
- inputs: import_zod29.z.object({
40937
- id: import_zod29.z.string().describe("The ID of the prompt template to retrieve")
41543
+ inputs: import_zod30.z.object({
41544
+ id: import_zod30.z.string().describe("The ID of the prompt template to retrieve")
40938
41545
  })
40939
41546
  }
40940
41547
  },
@@ -41175,7 +41782,7 @@ var ExuluEval = class {
41175
41782
  // src/templates/evals/index.ts
41176
41783
  init_resolve_model();
41177
41784
  init_singleton();
41178
- var import_zod30 = require("zod");
41785
+ var import_zod31 = require("zod");
41179
41786
  var import_ai17 = require("ai");
41180
41787
  var llmAsJudgeEval = () => {
41181
41788
  if (process.env.REDIS_HOST?.length && process.env.REDIS_PORT?.length) {
@@ -41226,8 +41833,8 @@ var llmAsJudgeEval = () => {
41226
41833
  prompt,
41227
41834
  maxRetries: 2,
41228
41835
  output: import_ai17.Output.object({
41229
- schema: import_zod30.z.object({
41230
- score: import_zod30.z.number().min(0).max(100).describe("The score between 0 and 100.")
41836
+ schema: import_zod31.z.object({
41837
+ score: import_zod31.z.number().min(0).max(100).describe("The score between 0 and 100.")
41231
41838
  })
41232
41839
  })
41233
41840
  });
@@ -41458,15 +42065,15 @@ Usage:
41458
42065
  - If no todos exist yet, an empty list will be returned`;
41459
42066
 
41460
42067
  // src/templates/tools/todo/todo.ts
41461
- var import_zod31 = __toESM(require("zod"), 1);
42068
+ var import_zod32 = __toESM(require("zod"), 1);
41462
42069
  init_tool();
41463
42070
  init_check_record_access();
41464
42071
  init_client();
41465
- var TodoSchema = import_zod31.default.object({
41466
- content: import_zod31.default.string().describe("Brief description of the task"),
41467
- status: import_zod31.default.string().describe("Current status of the task: pending, in_progress, completed, cancelled"),
41468
- priority: import_zod31.default.string().describe("Priority level of the task: high, medium, low"),
41469
- id: import_zod31.default.string().describe("Unique identifier for the todo item")
42072
+ var TodoSchema = import_zod32.default.object({
42073
+ content: import_zod32.default.string().describe("Brief description of the task"),
42074
+ status: import_zod32.default.string().describe("Current status of the task: pending, in_progress, completed, cancelled"),
42075
+ priority: import_zod32.default.string().describe("Priority level of the task: high, medium, low"),
42076
+ id: import_zod32.default.string().describe("Unique identifier for the todo item")
41470
42077
  });
41471
42078
  var TodoWriteTool = new ExuluTool({
41472
42079
  id: "todo_write",
@@ -41482,8 +42089,8 @@ var TodoWriteTool = new ExuluTool({
41482
42089
  default: todowrite_default
41483
42090
  }
41484
42091
  ],
41485
- inputSchema: import_zod31.default.object({
41486
- todos: import_zod31.default.array(TodoSchema).describe("The updated todo list")
42092
+ inputSchema: import_zod32.default.object({
42093
+ todos: import_zod32.default.array(TodoSchema).describe("The updated todo list")
41487
42094
  }),
41488
42095
  execute: async (inputs) => {
41489
42096
  const { sessionID, todos, user } = inputs;
@@ -41518,7 +42125,7 @@ var TodoReadTool = new ExuluTool({
41518
42125
  id: "todo_read",
41519
42126
  name: "Todo Read",
41520
42127
  description: "Use this tool to read your todo list",
41521
- inputSchema: import_zod31.default.object({}),
42128
+ inputSchema: import_zod32.default.object({}),
41522
42129
  type: "function",
41523
42130
  category: "todo",
41524
42131
  config: [
@@ -41563,7 +42170,7 @@ init_cjs_shims();
41563
42170
  var questionread_default = 'Use this tool to read questions you\'ve asked and check if they\'ve been answered by the user. This tool helps you track the status of questions and retrieve the user\'s selected answers.\n\n## When to Use This Tool\n\nUse this tool proactively in these situations:\n- After asking a question to check if the user has responded\n- To retrieve the user\'s answer before proceeding with implementation\n- To review all questions and answers in the current session\n- When you need to reference a previous answer\n\n## How It Works\n\n- This tool takes no parameters (leave the input blank or empty)\n- Returns an array of all questions in the session\n- Each question includes:\n - `id`: Unique identifier for the question\n - `question`: The question text\n - `answerOptions`: Array of answer options with their IDs and text\n - `status`: Either "pending" (not answered) or "answered"\n - `selectedAnswerId`: The ID of the chosen answer (only present if answered)\n\n## Usage Pattern\n\nTypically you\'ll:\n1. Use Question Ask to pose a question\n2. Wait for the user to respond\n3. Use Question Read to check the answer\n4. Find the selected answer by matching the `selectedAnswerId` with an option in `answerOptions`\n5. Proceed with implementation based on the user\'s choice\n\n## Example Response\n\n```json\n[\n {\n "id": "question123",\n "question": "Which authentication method would you like to implement?",\n "answerOptions": [\n { "id": "ans1", "text": "JWT tokens" },\n { "id": "ans2", "text": "OAuth 2.0" },\n { "id": "ans3", "text": "Session-based auth" },\n { "id": "ans4", "text": "None of the above..." }\n ],\n "status": "answered",\n "selectedAnswerId": "ans1"\n }\n]\n```\n\nIn this example, the user selected "JWT tokens" (id: ans1).\n\n## Important Notes\n\n- If no questions exist in the session, an empty array will be returned\n- Questions remain in the session even after being answered for reference\n- Use the `selectedAnswerId` to find which answer option the user chose by matching it against the `id` field in `answerOptions`\n';
41564
42171
 
41565
42172
  // src/templates/tools/question/question.ts
41566
- var import_zod33 = __toESM(require("zod"), 1);
42173
+ var import_zod34 = __toESM(require("zod"), 1);
41567
42174
  init_tool();
41568
42175
  init_client();
41569
42176
 
@@ -41655,21 +42262,21 @@ After asking a question, use the Question Read tool to check if the user has ans
41655
42262
  `;
41656
42263
 
41657
42264
  // src/templates/tools/question/question-ask.ts
41658
- var import_zod32 = __toESM(require("zod"), 1);
42265
+ var import_zod33 = __toESM(require("zod"), 1);
41659
42266
  init_tool();
41660
42267
  init_check_record_access();
41661
42268
  init_client();
41662
42269
  var import_node_crypto22 = require("crypto");
41663
- var AnswerOptionSchema = import_zod32.default.object({
41664
- id: import_zod32.default.string().describe("Unique identifier for the answer option"),
41665
- text: import_zod32.default.string().describe("The text of the answer option")
42270
+ var AnswerOptionSchema = import_zod33.default.object({
42271
+ id: import_zod33.default.string().describe("Unique identifier for the answer option"),
42272
+ text: import_zod33.default.string().describe("The text of the answer option")
41666
42273
  });
41667
- var _QuestionSchema = import_zod32.default.object({
41668
- id: import_zod32.default.string().describe("Unique identifier for the question"),
41669
- question: import_zod32.default.string().describe("The question to ask the user"),
41670
- answerOptions: import_zod32.default.array(AnswerOptionSchema).describe("Array of possible answer options"),
41671
- selectedAnswerId: import_zod32.default.string().optional().describe("The ID of the answer option selected by the user"),
41672
- status: import_zod32.default.enum(["pending", "answered"]).describe("Status of the question: pending or answered")
42274
+ var _QuestionSchema = import_zod33.default.object({
42275
+ id: import_zod33.default.string().describe("Unique identifier for the question"),
42276
+ question: import_zod33.default.string().describe("The question to ask the user"),
42277
+ answerOptions: import_zod33.default.array(AnswerOptionSchema).describe("Array of possible answer options"),
42278
+ selectedAnswerId: import_zod33.default.string().optional().describe("The ID of the answer option selected by the user"),
42279
+ status: import_zod33.default.enum(["pending", "answered"]).describe("Status of the question: pending or answered")
41673
42280
  });
41674
42281
  var QuestionAskTool = new ExuluTool({
41675
42282
  id: "question_ask",
@@ -41686,9 +42293,9 @@ var QuestionAskTool = new ExuluTool({
41686
42293
  default: questionask_default
41687
42294
  }
41688
42295
  ],
41689
- inputSchema: import_zod32.default.object({
41690
- question: import_zod32.default.string().describe("The question to ask the user"),
41691
- answerOptions: import_zod32.default.array(import_zod32.default.string()).describe("Array of possible answer options (strings)")
42296
+ inputSchema: import_zod33.default.object({
42297
+ question: import_zod33.default.string().describe("The question to ask the user"),
42298
+ answerOptions: import_zod33.default.array(import_zod33.default.string()).describe("Array of possible answer options (strings)")
41692
42299
  }),
41693
42300
  execute: async (inputs) => {
41694
42301
  const { sessionID, question, answerOptions, user } = inputs;
@@ -41761,7 +42368,7 @@ var QuestionReadTool = new ExuluTool({
41761
42368
  name: "Question Read",
41762
42369
  needsApproval: false,
41763
42370
  description: "Use this tool to read questions and their answers",
41764
- inputSchema: import_zod33.default.object({}),
42371
+ inputSchema: import_zod34.default.object({}),
41765
42372
  type: "function",
41766
42373
  category: "question",
41767
42374
  config: [
@@ -41794,7 +42401,7 @@ var questionTools = [QuestionAskTool, QuestionReadTool];
41794
42401
  init_cjs_shims();
41795
42402
  init_tool();
41796
42403
  var nodemailer = __toESM(require("nodemailer"), 1);
41797
- var import_zod34 = require("zod");
42404
+ var import_zod35 = require("zod");
41798
42405
  var transporter = null;
41799
42406
  function getTransporter(config) {
41800
42407
  if (!transporter) {
@@ -41818,11 +42425,11 @@ var emailTool = new ExuluTool({
41818
42425
  id: "email",
41819
42426
  name: "Email",
41820
42427
  description: "Send an email.",
41821
- inputSchema: import_zod34.z.object({
41822
- recipient: import_zod34.z.string().describe("The recipient of the email."),
41823
- subject: import_zod34.z.string().describe("The subject of the email."),
41824
- html: import_zod34.z.string().describe("The HTML body of the email."),
41825
- text: import_zod34.z.string().describe("The text body of the email.")
42428
+ inputSchema: import_zod35.z.object({
42429
+ recipient: import_zod35.z.string().describe("The recipient of the email."),
42430
+ subject: import_zod35.z.string().describe("The subject of the email."),
42431
+ html: import_zod35.z.string().describe("The HTML body of the email."),
42432
+ text: import_zod35.z.string().describe("The text body of the email.")
41826
42433
  }),
41827
42434
  type: "function",
41828
42435
  config: [{
@@ -41894,7 +42501,7 @@ init_supervisor();
41894
42501
  init_client();
41895
42502
  init_rbac_resolver();
41896
42503
  init_check_record_access();
41897
- var import_zod35 = require("zod");
42504
+ var import_zod36 = require("zod");
41898
42505
  var _cachedImageModels;
41899
42506
  var setCachedImageModels = (models2) => {
41900
42507
  _cachedImageModels = models2;
@@ -41955,8 +42562,8 @@ var createImageGenerationWidgetTool = (models2) => {
41955
42562
  needsApproval: false,
41956
42563
  type: "function",
41957
42564
  config: [],
41958
- inputSchema: import_zod35.z.object({
41959
- prompt: import_zod35.z.string().describe(
42565
+ inputSchema: import_zod36.z.object({
42566
+ prompt: import_zod36.z.string().describe(
41960
42567
  "Initial image prompt. The user can edit it before generating."
41961
42568
  )
41962
42569
  }),
@@ -45133,12 +45740,12 @@ async function fitContextProjection({
45133
45740
  const basis = randomizedPCA(vectors, dims, Math.min(budget, dims, vectors.length - 1), seed, POWER_ITERATIONS);
45134
45741
  if (basis.length === 0) return empty(`${contextId} has no variance in its embeddings`);
45135
45742
  const reduced = vectors.map((v) => projectComponents(v, mean, basis));
45136
- const spread = reduced.reduce((s, z36) => s + Math.hypot(...Array.from(z36)), 0) / reduced.length;
45743
+ const spread = reduced.reduce((s, z37) => s + Math.hypot(...Array.from(z37)), 0) / reduced.length;
45137
45744
  if (!Number.isFinite(spread) || spread < 1e-8) return empty(`${contextId} has no variance in its embeddings`);
45138
45745
  log7(`fitting ${contextId}: ${vectors.length} vectors, ${dims} dims \u2192 ${basis.length} components`);
45139
45746
  log7(`${contextId}: laying out ${reduced.length} points in 3d (the slow phase)`);
45140
45747
  const umap = (umapFactory ?? defaultUmap)(seed, reduced.length);
45141
- const raw = umap.fit(reduced.map((z36) => Array.from(z36)));
45748
+ const raw = umap.fit(reduced.map((z37) => Array.from(z37)));
45142
45749
  const oriented = rotateLayout(raw, principalRotation(raw, seed));
45143
45750
  const { points: layout, scale } = normalizeLayout(oriented);
45144
45751
  if (!Number.isFinite(scale) || scale <= 0) return empty(`${contextId} produced a degenerate layout (every point in one place)`);
@@ -45223,13 +45830,13 @@ async function backfillCoordinates({
45223
45830
  const raw = parseVector(row.embedding);
45224
45831
  if (raw.length !== projection.dims) continue;
45225
45832
  const known = layout?.get(String(row.id));
45226
- const [x, y, z36] = known ?? applyMap(
45833
+ const [x, y, z37] = known ?? applyMap(
45227
45834
  projectComponents(l2normalize(raw), mean, basis),
45228
45835
  projection.map,
45229
45836
  projection.intercept
45230
45837
  );
45231
45838
  values.push("(?::uuid, ?::real, ?::real, ?::real)");
45232
- bindings.push(row.id, x, y, z36);
45839
+ bindings.push(row.id, x, y, z37);
45233
45840
  }
45234
45841
  if (values.length) {
45235
45842
  await db2.raw(