@usabledev/usable-chat 1.235.0 → 1.236.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.
Files changed (2) hide show
  1. package/cli.js +422 -411
  2. package/package.json +1 -1
package/cli.js CHANGED
@@ -53353,7 +53353,7 @@ var init_model_registry = __esm({
53353
53353
  var version2;
53354
53354
  var init_package = __esm({
53355
53355
  "package.json"() {
53356
- version2 = "1.235.0";
53356
+ version2 = "1.236.1";
53357
53357
  }
53358
53358
  });
53359
53359
 
@@ -255166,6 +255166,414 @@ var init_embed_key = __esm({
255166
255166
  }
255167
255167
  });
255168
255168
 
255169
+ // src/lib/rich-fragment-prompt.ts
255170
+ var RICH_FRAGMENT_RENDERING_PROMPT;
255171
+ var init_rich_fragment_prompt = __esm({
255172
+ "src/lib/rich-fragment-prompt.ts"() {
255173
+ "use strict";
255174
+ RICH_FRAGMENT_RENDERING_PROMPT = `## Fragment Rich Content Rendering
255175
+
255176
+ When creating or updating Usable fragment markdown:
255177
+ - Do NOT write raw inline HTML or SVG directly into markdown. Raw HTML/SVG is blocked by the canvas renderer.
255178
+ - To render SVG, use an explicit fenced block:
255179
+
255180
+ \`\`\`svg render
255181
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 250">
255182
+ <!-- SVG content -->
255183
+ </svg>
255184
+ \`\`\`
255185
+
255186
+ - To render HTML, use an explicit fenced block:
255187
+
255188
+ \`\`\`html render
255189
+ <div>HTML content</div>
255190
+ \`\`\`
255191
+
255192
+ - Plain \`svg\`, \`html\`, or other code fences stay code blocks. Only \`svg render\` and \`html render\` are rendered in the canvas sandbox.
255193
+ - Images in fragments should use \`usable://files/<full-file-id>\` for attached files or \`https://\` for external images. Other image URL schemes are blocked.
255194
+ - Chat file ids are not Usable file ids, and Chat's \`https://usable.dev/files/<id>\` image links only work inside the chat: never put either into fragment content.`;
255195
+ }
255196
+ });
255197
+
255198
+ // src/core/types/system-prompt-source.ts
255199
+ function getPromptUnavailableBehavior(source) {
255200
+ return source?.type === "fragment" ? source.unavailableBehavior ?? "error" : "fallback";
255201
+ }
255202
+ var systemPromptSourceSchema;
255203
+ var init_system_prompt_source = __esm({
255204
+ "src/core/types/system-prompt-source.ts"() {
255205
+ "use strict";
255206
+ init_zod();
255207
+ systemPromptSourceSchema = external_exports.discriminatedUnion("type", [
255208
+ external_exports.object({
255209
+ type: external_exports.literal("inline")
255210
+ }),
255211
+ external_exports.object({
255212
+ type: external_exports.literal("fragment"),
255213
+ fragmentId: external_exports.string().uuid(),
255214
+ workspaceId: external_exports.string().uuid().optional(),
255215
+ unavailableBehavior: external_exports.enum(["error", "fallback"]).optional()
255216
+ })
255217
+ ]);
255218
+ }
255219
+ });
255220
+
255221
+ // src/core/types/custom-expert.ts
255222
+ var custom_expert_exports = {};
255223
+ __export2(custom_expert_exports, {
255224
+ BUILT_IN_TOOLS: () => BUILT_IN_TOOLS,
255225
+ FEATURE_GATED_TOOLS: () => FEATURE_GATED_TOOLS,
255226
+ MAX_PARENT_TOOLS: () => MAX_PARENT_TOOLS,
255227
+ convertCustomExpertToSubAgent: () => convertCustomExpertToSubAgent,
255228
+ createCustomExpertSchema: () => createCustomExpertSchema,
255229
+ expertConfigSchema: () => expertConfigSchema,
255230
+ expertRoutingSchema: () => expertRoutingSchema,
255231
+ getAvailableToolsForExpert: () => getAvailableToolsForExpert,
255232
+ getParentToolName: () => getParentToolName,
255233
+ isParentToolComplete: () => isParentToolComplete,
255234
+ mergeParentToolSchemas: () => mergeParentToolSchemas,
255235
+ normalizeParentToolConfig: () => normalizeParentToolConfig,
255236
+ parentToolDefinitionSchema: () => parentToolDefinitionSchema,
255237
+ parentToolFullDefinitionSchema: () => parentToolFullDefinitionSchema,
255238
+ parentToolNameSchema: () => parentToolNameSchema,
255239
+ parentToolSchemaSchema: () => parentToolSchemaSchema,
255240
+ updateCustomExpertSchema: () => updateCustomExpertSchema
255241
+ });
255242
+ function convertCustomExpertToSubAgent(expert, options2 = {}) {
255243
+ const { enabledFeatures = {} } = options2;
255244
+ const filteredTools = filterToolsByFeatures(expert.enabledTools, enabledFeatures);
255245
+ const ui2 = buildUIMetadata(expert);
255246
+ const canHandle = buildCanHandleFunction(expert.routing, expert.excludeKeywords);
255247
+ const parentToolConfigs = expert.parentTools;
255248
+ const normalizedParentTools = parentToolConfigs?.map(normalizeParentToolConfig);
255249
+ return {
255250
+ id: expert.id,
255251
+ displayName: expert.name,
255252
+ description: expert.description,
255253
+ systemPrompt: withRichFragmentRenderingPrompt(expert.systemPrompt),
255254
+ tools: filteredTools,
255255
+ ui: ui2,
255256
+ modelPreference: expert.modelPreference,
255257
+ directModelId: expert.directModelId,
255258
+ temperature: expert.temperature,
255259
+ maxTokens: expert.maxTokens,
255260
+ priority: expert.priority,
255261
+ maxTurns: expert.maxTurns,
255262
+ canHandle,
255263
+ // Include normalized parent tools if defined
255264
+ parentTools: normalizedParentTools
255265
+ };
255266
+ }
255267
+ function withRichFragmentRenderingPrompt(systemPrompt) {
255268
+ if (systemPrompt.includes("## Fragment Rich Content Rendering")) {
255269
+ return systemPrompt;
255270
+ }
255271
+ return `${systemPrompt.trim()}
255272
+
255273
+ ${RICH_FRAGMENT_RENDERING_PROMPT}`;
255274
+ }
255275
+ function filterToolsByFeatures(requestedTools, enabledFeatures = {}) {
255276
+ const availableTools = new Set(BUILT_IN_TOOLS);
255277
+ if (enabledFeatures.webSearch) {
255278
+ FEATURE_GATED_TOOLS.webSearch.forEach((tool2) => availableTools.add(tool2));
255279
+ }
255280
+ if (enabledFeatures.imageGeneration) {
255281
+ FEATURE_GATED_TOOLS.imageGeneration.forEach((tool2) => availableTools.add(tool2));
255282
+ }
255283
+ if (enabledFeatures.documentation) {
255284
+ FEATURE_GATED_TOOLS.documentation.forEach((tool2) => availableTools.add(tool2));
255285
+ }
255286
+ if (enabledFeatures.codeExecution) {
255287
+ for (const tool2 of ["execute_code", "clone_repo", "file_to_sandbox"]) availableTools.add(tool2);
255288
+ }
255289
+ return requestedTools.filter((tool2) => availableTools.has(tool2));
255290
+ }
255291
+ function buildUIMetadata(expert) {
255292
+ const color = expert.uiColor || "purple-500";
255293
+ return {
255294
+ color,
255295
+ bgColor: `bg-${color}/10`,
255296
+ textColor: `text-${color}`,
255297
+ borderColor: `border-${color}`,
255298
+ avatar: expert.avatarUrl || "/experts/custom-expert-placeholder.svg",
255299
+ emoji: expert.uiEmoji || "\u{1F916}",
255300
+ shortName: expert.uiShortName || expert.name.slice(0, 10)
255301
+ };
255302
+ }
255303
+ function buildCanHandleFunction(routing, excludeKeywords) {
255304
+ return (query) => {
255305
+ const lowerQuery = query.toLowerCase();
255306
+ if (excludeKeywords && excludeKeywords.length > 0) {
255307
+ for (const excluded of excludeKeywords) {
255308
+ if (lowerQuery.includes(excluded.toLowerCase())) {
255309
+ return false;
255310
+ }
255311
+ }
255312
+ }
255313
+ for (const keyword of routing.keywords) {
255314
+ if (lowerQuery.includes(keyword.toLowerCase())) {
255315
+ return true;
255316
+ }
255317
+ }
255318
+ if (routing.patterns && routing.patterns.length > 0) {
255319
+ for (const pattern of routing.patterns) {
255320
+ try {
255321
+ if (new RegExp(pattern, "i").test(query)) {
255322
+ return true;
255323
+ }
255324
+ } catch {
255325
+ console.warn(`Invalid regex pattern in expert routing: ${pattern}`);
255326
+ }
255327
+ }
255328
+ }
255329
+ return false;
255330
+ };
255331
+ }
255332
+ function getAvailableToolsForExpert(enabledFeatures) {
255333
+ return [
255334
+ {
255335
+ category: "Usable (Built-in)",
255336
+ tools: [...BUILT_IN_TOOLS],
255337
+ available: true
255338
+ },
255339
+ {
255340
+ category: "Web Search",
255341
+ tools: [...FEATURE_GATED_TOOLS.webSearch],
255342
+ available: enabledFeatures.webSearch ?? false
255343
+ },
255344
+ {
255345
+ category: "Image Generation",
255346
+ tools: [...FEATURE_GATED_TOOLS.imageGeneration],
255347
+ available: enabledFeatures.imageGeneration ?? false
255348
+ },
255349
+ {
255350
+ category: "Documentation",
255351
+ tools: [...FEATURE_GATED_TOOLS.documentation],
255352
+ available: enabledFeatures.documentation ?? false
255353
+ }
255354
+ ];
255355
+ }
255356
+ function normalizeParentToolConfig(config3) {
255357
+ if (typeof config3 === "string") {
255358
+ return { name: config3 };
255359
+ }
255360
+ return config3;
255361
+ }
255362
+ function getParentToolName(config3) {
255363
+ if (typeof config3 === "string") {
255364
+ return config3;
255365
+ }
255366
+ return config3.name;
255367
+ }
255368
+ function mergeParentToolSchemas(parentTools, registeredSchemas) {
255369
+ return parentTools.map((config3) => {
255370
+ const normalized = normalizeParentToolConfig(config3);
255371
+ const toolName = normalized.name;
255372
+ if (normalized.description) {
255373
+ return normalized;
255374
+ }
255375
+ const schema = registeredSchemas?.get(toolName);
255376
+ if (schema) {
255377
+ return {
255378
+ name: toolName,
255379
+ description: schema.description,
255380
+ parameters: schema.parameters || normalized.parameters
255381
+ };
255382
+ }
255383
+ return normalized;
255384
+ });
255385
+ }
255386
+ function isParentToolComplete(tool2) {
255387
+ return !!(tool2.name && tool2.description);
255388
+ }
255389
+ var BUILT_IN_TOOLS, FEATURE_GATED_TOOLS, expertRoutingSchema, parentToolNameSchema, parentToolFullDefinitionSchema, parentToolDefinitionSchema, parentToolSchemaSchema, MAX_PARENT_TOOLS, expertConfigSchema, createCustomExpertSchema, updateCustomExpertSchema;
255390
+ var init_custom_expert = __esm({
255391
+ "src/core/types/custom-expert.ts"() {
255392
+ "use strict";
255393
+ init_zod();
255394
+ init_rich_fragment_prompt();
255395
+ init_system_prompt_source();
255396
+ BUILT_IN_TOOLS = [
255397
+ "agentic-search-fragments",
255398
+ "search-memory-fragments",
255399
+ "list-memory-fragments",
255400
+ "get-memory-fragment-content",
255401
+ "create-memory-fragment",
255402
+ "update-memory-fragment",
255403
+ "list-workspaces",
255404
+ "get-fragment-types"
255405
+ ];
255406
+ FEATURE_GATED_TOOLS = {
255407
+ webSearch: [
255408
+ "exa-search",
255409
+ "exa-find-similar",
255410
+ "exa-get-contents",
255411
+ "WebFetch",
255412
+ "WebSearch"
255413
+ ],
255414
+ imageGeneration: ["generate-image", "view-image"],
255415
+ documentation: ["resolve-library-id", "query-docs"]
255416
+ };
255417
+ expertRoutingSchema = external_exports.object({
255418
+ keywords: external_exports.array(external_exports.string().min(1).max(100)).min(1, "At least one keyword is required for routing"),
255419
+ patterns: external_exports.array(external_exports.string().max(500)).optional()
255420
+ });
255421
+ parentToolNameSchema = external_exports.string().min(1).max(100).regex(/^[a-z][a-z0-9_-]*$/i, "Tool name must start with a letter and contain only alphanumeric, underscores, or hyphens");
255422
+ parentToolFullDefinitionSchema = external_exports.object({
255423
+ name: external_exports.string().min(1).max(100).regex(/^[a-z][a-z0-9_-]*$/i, "Tool name must start with a letter and contain only alphanumeric, underscores, or hyphens"),
255424
+ description: external_exports.string().min(1).max(1e3).optional(),
255425
+ parameters: external_exports.record(external_exports.unknown()).optional()
255426
+ });
255427
+ parentToolDefinitionSchema = external_exports.union([
255428
+ parentToolNameSchema,
255429
+ parentToolFullDefinitionSchema
255430
+ ]);
255431
+ parentToolSchemaSchema = external_exports.object({
255432
+ name: external_exports.string().min(1).max(100).regex(/^[a-z][a-z0-9_-]*$/i, "Tool name must start with a letter and contain only alphanumeric, underscores, or hyphens"),
255433
+ description: external_exports.string().min(1).max(1e3),
255434
+ parameters: external_exports.object({
255435
+ type: external_exports.literal("object"),
255436
+ properties: external_exports.record(external_exports.unknown()),
255437
+ required: external_exports.array(external_exports.string()).optional()
255438
+ }).optional(),
255439
+ skill: external_exports.object({
255440
+ id: external_exports.string().min(1).max(100).optional(),
255441
+ title: external_exports.string().min(1).max(200).optional(),
255442
+ summary: external_exports.string().max(1e3).optional(),
255443
+ tags: external_exports.array(external_exports.string().min(1).max(100)).max(20).optional(),
255444
+ scope: external_exports.enum(["global", "page"]).optional()
255445
+ }).optional()
255446
+ });
255447
+ MAX_PARENT_TOOLS = 32;
255448
+ expertConfigSchema = external_exports.object({
255449
+ systemPrompt: external_exports.string().min(1).max(5e4),
255450
+ systemPromptSource: systemPromptSourceSchema.nullable().optional(),
255451
+ enabledTools: external_exports.array(external_exports.string()),
255452
+ routing: expertRoutingSchema,
255453
+ modelPreference: external_exports.enum(["inherit", "quick-thinking", "deep-thinking", "multi-lingual"]),
255454
+ directModelId: external_exports.string().regex(
255455
+ /^[a-z0-9-]+\/[a-z0-9.-]+$/,
255456
+ "Must be a valid model ID (e.g., anthropic/claude-sonnet-4.5)"
255457
+ ).optional().nullable(),
255458
+ temperature: external_exports.number().min(0).max(1).optional(),
255459
+ maxTokens: external_exports.number().min(100).max(32e3).optional(),
255460
+ uiColor: external_exports.string().max(50).optional(),
255461
+ uiEmoji: external_exports.string().max(10).optional(),
255462
+ avatarUrl: external_exports.string().refine(
255463
+ (val) => val.startsWith("data:") || val.startsWith("http://") || val.startsWith("https://") || val.startsWith("/"),
255464
+ "Must be a valid URL, data URL, or path"
255465
+ ).optional(),
255466
+ parentTools: external_exports.array(parentToolDefinitionSchema).max(MAX_PARENT_TOOLS).optional(),
255467
+ excludeKeywords: external_exports.array(external_exports.string().min(1).max(50)).max(20).optional(),
255468
+ priority: external_exports.number().int().min(0).max(100).optional(),
255469
+ maxTurns: external_exports.number().int().min(1).max(50).optional(),
255470
+ uiShortName: external_exports.string().max(30).optional()
255471
+ });
255472
+ createCustomExpertSchema = external_exports.object({
255473
+ key: external_exports.string().min(1).max(100).regex(/^[a-z0-9-]+$/, "Key must be lowercase alphanumeric with hyphens").optional(),
255474
+ workspaceId: external_exports.string().uuid().optional(),
255475
+ name: external_exports.string().min(1).max(255),
255476
+ description: external_exports.string().min(1).max(1e3),
255477
+ expertConfig: expertConfigSchema
255478
+ });
255479
+ updateCustomExpertSchema = external_exports.object({
255480
+ name: external_exports.string().min(1).max(255).optional(),
255481
+ description: external_exports.string().min(1).max(1e3).optional(),
255482
+ expertConfig: expertConfigSchema.partial().optional(),
255483
+ status: external_exports.enum(["active", "archived", "draft"]).optional()
255484
+ });
255485
+ }
255486
+ });
255487
+
255488
+ // src/lib/services/expert-permission.service.ts
255489
+ async function checkExpertPermission(expertId, userId) {
255490
+ const [collaborator] = await db.select({ role: expertCollaborators.role }).from(expertCollaborators).where(
255491
+ and(
255492
+ eq(expertCollaborators.expertId, expertId),
255493
+ eq(expertCollaborators.userId, userId),
255494
+ isNull(expertCollaborators.deletedAt)
255495
+ )
255496
+ ).limit(1);
255497
+ if (collaborator) {
255498
+ const role = collaborator.role;
255499
+ return {
255500
+ hasAccess: true,
255501
+ role,
255502
+ isOwner: role === "owner",
255503
+ isViewer: role === "viewer" || role === "subscriber"
255504
+ };
255505
+ }
255506
+ const [expert] = await db.select({ createdBy: customExperts.createdBy }).from(customExperts).where(eq(customExperts.id, expertId)).limit(1);
255507
+ if (expert && expert.createdBy === userId) {
255508
+ return {
255509
+ hasAccess: true,
255510
+ role: "owner",
255511
+ isOwner: true,
255512
+ isViewer: false
255513
+ };
255514
+ }
255515
+ return {
255516
+ hasAccess: false,
255517
+ role: "none",
255518
+ isOwner: false,
255519
+ isViewer: false
255520
+ };
255521
+ }
255522
+ async function canViewExpert(expertId, userId) {
255523
+ const permission = await checkExpertPermission(expertId, userId);
255524
+ return permission.hasAccess;
255525
+ }
255526
+ async function checkConfigPermission(configId, userId) {
255527
+ const [collaborator] = await db.select({ role: configCollaborators.role }).from(configCollaborators).where(
255528
+ and(
255529
+ eq(configCollaborators.configId, configId),
255530
+ eq(configCollaborators.userId, userId),
255531
+ isNull(configCollaborators.deletedAt)
255532
+ )
255533
+ ).limit(1);
255534
+ if (collaborator) {
255535
+ const role = collaborator.role;
255536
+ return {
255537
+ hasAccess: true,
255538
+ role,
255539
+ isOwner: role === "owner",
255540
+ isViewer: role === "viewer"
255541
+ };
255542
+ }
255543
+ const [config3] = await db.select({ createdBy: chatConfigs.createdBy }).from(chatConfigs).where(eq(chatConfigs.id, configId)).limit(1);
255544
+ if (config3 && config3.createdBy === userId) {
255545
+ return {
255546
+ hasAccess: true,
255547
+ role: "owner",
255548
+ isOwner: true,
255549
+ isViewer: false
255550
+ };
255551
+ }
255552
+ return {
255553
+ hasAccess: false,
255554
+ role: "none",
255555
+ isOwner: false,
255556
+ isViewer: false
255557
+ };
255558
+ }
255559
+ async function canEditConfig(configId, userId) {
255560
+ const permission = await checkConfigPermission(configId, userId);
255561
+ return permission.isOwner;
255562
+ }
255563
+ async function canManageConfigCollaborators(configId, userId) {
255564
+ const permission = await checkConfigPermission(configId, userId);
255565
+ return permission.isOwner;
255566
+ }
255567
+ var init_expert_permission_service = __esm({
255568
+ "src/lib/services/expert-permission.service.ts"() {
255569
+ "use strict";
255570
+ init_client7();
255571
+ init_schema4();
255572
+ init_drizzle_orm();
255573
+ init_custom_expert();
255574
+ }
255575
+ });
255576
+
255169
255577
  // src/lib/services/embed-key.service.ts
255170
255578
  var embed_key_service_exports = {};
255171
255579
  __export2(embed_key_service_exports, {
@@ -255280,6 +255688,9 @@ async function createEmbedKey(sessionPathway, input, userId, options2) {
255280
255688
  if (options2?.serviceAccount && options2.usablePatEncrypted !== void 0) {
255281
255689
  throw new Error("An embed key holds either an API key or a service account, not both");
255282
255690
  }
255691
+ if (options2?.serviceAccount && !await canManageConfigCollaborators(input.configId, userId)) {
255692
+ throw new Error("Only embed owners can change service account credentials");
255693
+ }
255283
255694
  const keyId = randomUUID7();
255284
255695
  const token = generateEmbedToken();
255285
255696
  const timestamp2 = (/* @__PURE__ */ new Date()).toISOString();
@@ -255454,10 +255865,9 @@ function nextEmbedKeyMutationTimestamp(observedUpdatedAt) {
255454
255865
  async function updateEmbedKey(sessionPathway, keyId, configId, input, userId) {
255455
255866
  const [key3] = await db.select().from(embedKeys).where(and(eq(embedKeys.id, keyId), eq(embedKeys.configId, configId))).limit(1);
255456
255867
  if (!key3) return false;
255457
- if ((key3.serviceAccountSecretEncrypted || key3.serviceAccountBinding) && ("usablePatEncrypted" in input || "usablePatMetadata" in input || input.serviceAccount !== void 0)) {
255458
- const [configuration] = await db.select({ createdBy: chatConfigs.createdBy }).from(chatConfigs).where(eq(chatConfigs.id, configId)).limit(1);
255459
- if (!configuration || configuration.createdBy !== userId) {
255460
- throw new Error("Only the config creator can bind or disconnect a service account");
255868
+ if (input.serviceAccount !== void 0 || (key3.serviceAccountSecretEncrypted || key3.serviceAccountBinding) && ("usablePatEncrypted" in input || "usablePatMetadata" in input)) {
255869
+ if (!await canManageConfigCollaborators(configId, userId)) {
255870
+ throw new Error("Only embed owners can change service account credentials");
255461
255871
  }
255462
255872
  }
255463
255873
  const accessPolicy = embedKeyAccessPolicySchema.parse({
@@ -255517,6 +255927,7 @@ var init_embed_key_service = __esm({
255517
255927
  init_drizzle_orm();
255518
255928
  init_origin_matcher();
255519
255929
  init_redis();
255930
+ init_expert_permission_service();
255520
255931
  init_logger3();
255521
255932
  EMBED_KEY_CACHE_TTL_MS = 6e4;
255522
255933
  EMBED_KEY_CACHE_MAX_ENTRIES = 1e3;
@@ -255742,7 +256153,7 @@ var init_embed_service_account = __esm({
255742
256153
  * before it are refused, so a rebind never continues another account's runs.
255743
256154
  */
255744
256155
  accountBoundAt: external_exports.string().datetime().optional(),
255745
- /** Authenticated config creator who authorized this binding, set only by the server. */
256156
+ /** Authenticated embed owner who authorized this binding, set only by the server. */
255746
256157
  boundByUserId: external_exports.string().min(1).max(255).optional(),
255747
256158
  /** Display-only snapshot at verifiedAt. Runtime never authorizes from it. */
255748
256159
  grantsSnapshot: external_exports.array(serviceAccountGrantSnapshotSchema).max(500)
@@ -256337,7 +256748,10 @@ async function resolveEmbedAuth(request, options2 = {}) {
256337
256748
  }
256338
256749
  const { key: key3, config: config3 } = result.data;
256339
256750
  if (key3.serviceAccountSecretEncrypted) {
256340
- if (!config3.createdBy || (key3.serviceAccountBinding?.boundByUserId ?? key3.createdBy) !== config3.createdBy) return null;
256751
+ if (!await canManageConfigCollaborators(
256752
+ config3.id,
256753
+ key3.serviceAccountBinding?.boundByUserId ?? key3.createdBy
256754
+ )) return null;
256341
256755
  return resolveServiceAccountEmbedAuth(request, key3, config3.id, config3.configData);
256342
256756
  }
256343
256757
  if (!key3.usablePatEncrypted) {
@@ -256503,6 +256917,7 @@ var init_embed_auth = __esm({
256503
256917
  init_config();
256504
256918
  init_logger();
256505
256919
  init_env2();
256920
+ init_expert_permission_service();
256506
256921
  init_visitor_proof();
256507
256922
  init_embed_service_account_service();
256508
256923
  }
@@ -256872,410 +257287,6 @@ var init_config_error = __esm({
256872
257287
  }
256873
257288
  });
256874
257289
 
256875
- // src/lib/rich-fragment-prompt.ts
256876
- var RICH_FRAGMENT_RENDERING_PROMPT;
256877
- var init_rich_fragment_prompt = __esm({
256878
- "src/lib/rich-fragment-prompt.ts"() {
256879
- "use strict";
256880
- RICH_FRAGMENT_RENDERING_PROMPT = `## Fragment Rich Content Rendering
256881
-
256882
- When creating or updating Usable fragment markdown:
256883
- - Do NOT write raw inline HTML or SVG directly into markdown. Raw HTML/SVG is blocked by the canvas renderer.
256884
- - To render SVG, use an explicit fenced block:
256885
-
256886
- \`\`\`svg render
256887
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 250">
256888
- <!-- SVG content -->
256889
- </svg>
256890
- \`\`\`
256891
-
256892
- - To render HTML, use an explicit fenced block:
256893
-
256894
- \`\`\`html render
256895
- <div>HTML content</div>
256896
- \`\`\`
256897
-
256898
- - Plain \`svg\`, \`html\`, or other code fences stay code blocks. Only \`svg render\` and \`html render\` are rendered in the canvas sandbox.
256899
- - Images in fragments should use \`usable://files/<full-file-id>\` for attached files or \`https://\` for external images. Other image URL schemes are blocked.
256900
- - Chat file ids are not Usable file ids, and Chat's \`https://usable.dev/files/<id>\` image links only work inside the chat: never put either into fragment content.`;
256901
- }
256902
- });
256903
-
256904
- // src/core/types/system-prompt-source.ts
256905
- function getPromptUnavailableBehavior(source) {
256906
- return source?.type === "fragment" ? source.unavailableBehavior ?? "error" : "fallback";
256907
- }
256908
- var systemPromptSourceSchema;
256909
- var init_system_prompt_source = __esm({
256910
- "src/core/types/system-prompt-source.ts"() {
256911
- "use strict";
256912
- init_zod();
256913
- systemPromptSourceSchema = external_exports.discriminatedUnion("type", [
256914
- external_exports.object({
256915
- type: external_exports.literal("inline")
256916
- }),
256917
- external_exports.object({
256918
- type: external_exports.literal("fragment"),
256919
- fragmentId: external_exports.string().uuid(),
256920
- workspaceId: external_exports.string().uuid().optional(),
256921
- unavailableBehavior: external_exports.enum(["error", "fallback"]).optional()
256922
- })
256923
- ]);
256924
- }
256925
- });
256926
-
256927
- // src/core/types/custom-expert.ts
256928
- var custom_expert_exports = {};
256929
- __export2(custom_expert_exports, {
256930
- BUILT_IN_TOOLS: () => BUILT_IN_TOOLS,
256931
- FEATURE_GATED_TOOLS: () => FEATURE_GATED_TOOLS,
256932
- MAX_PARENT_TOOLS: () => MAX_PARENT_TOOLS,
256933
- convertCustomExpertToSubAgent: () => convertCustomExpertToSubAgent,
256934
- createCustomExpertSchema: () => createCustomExpertSchema,
256935
- expertConfigSchema: () => expertConfigSchema,
256936
- expertRoutingSchema: () => expertRoutingSchema,
256937
- getAvailableToolsForExpert: () => getAvailableToolsForExpert,
256938
- getParentToolName: () => getParentToolName,
256939
- isParentToolComplete: () => isParentToolComplete,
256940
- mergeParentToolSchemas: () => mergeParentToolSchemas,
256941
- normalizeParentToolConfig: () => normalizeParentToolConfig,
256942
- parentToolDefinitionSchema: () => parentToolDefinitionSchema,
256943
- parentToolFullDefinitionSchema: () => parentToolFullDefinitionSchema,
256944
- parentToolNameSchema: () => parentToolNameSchema,
256945
- parentToolSchemaSchema: () => parentToolSchemaSchema,
256946
- updateCustomExpertSchema: () => updateCustomExpertSchema
256947
- });
256948
- function convertCustomExpertToSubAgent(expert, options2 = {}) {
256949
- const { enabledFeatures = {} } = options2;
256950
- const filteredTools = filterToolsByFeatures(expert.enabledTools, enabledFeatures);
256951
- const ui2 = buildUIMetadata(expert);
256952
- const canHandle = buildCanHandleFunction(expert.routing, expert.excludeKeywords);
256953
- const parentToolConfigs = expert.parentTools;
256954
- const normalizedParentTools = parentToolConfigs?.map(normalizeParentToolConfig);
256955
- return {
256956
- id: expert.id,
256957
- displayName: expert.name,
256958
- description: expert.description,
256959
- systemPrompt: withRichFragmentRenderingPrompt(expert.systemPrompt),
256960
- tools: filteredTools,
256961
- ui: ui2,
256962
- modelPreference: expert.modelPreference,
256963
- directModelId: expert.directModelId,
256964
- temperature: expert.temperature,
256965
- maxTokens: expert.maxTokens,
256966
- priority: expert.priority,
256967
- maxTurns: expert.maxTurns,
256968
- canHandle,
256969
- // Include normalized parent tools if defined
256970
- parentTools: normalizedParentTools
256971
- };
256972
- }
256973
- function withRichFragmentRenderingPrompt(systemPrompt) {
256974
- if (systemPrompt.includes("## Fragment Rich Content Rendering")) {
256975
- return systemPrompt;
256976
- }
256977
- return `${systemPrompt.trim()}
256978
-
256979
- ${RICH_FRAGMENT_RENDERING_PROMPT}`;
256980
- }
256981
- function filterToolsByFeatures(requestedTools, enabledFeatures = {}) {
256982
- const availableTools = new Set(BUILT_IN_TOOLS);
256983
- if (enabledFeatures.webSearch) {
256984
- FEATURE_GATED_TOOLS.webSearch.forEach((tool2) => availableTools.add(tool2));
256985
- }
256986
- if (enabledFeatures.imageGeneration) {
256987
- FEATURE_GATED_TOOLS.imageGeneration.forEach((tool2) => availableTools.add(tool2));
256988
- }
256989
- if (enabledFeatures.documentation) {
256990
- FEATURE_GATED_TOOLS.documentation.forEach((tool2) => availableTools.add(tool2));
256991
- }
256992
- if (enabledFeatures.codeExecution) {
256993
- for (const tool2 of ["execute_code", "clone_repo", "file_to_sandbox"]) availableTools.add(tool2);
256994
- }
256995
- return requestedTools.filter((tool2) => availableTools.has(tool2));
256996
- }
256997
- function buildUIMetadata(expert) {
256998
- const color = expert.uiColor || "purple-500";
256999
- return {
257000
- color,
257001
- bgColor: `bg-${color}/10`,
257002
- textColor: `text-${color}`,
257003
- borderColor: `border-${color}`,
257004
- avatar: expert.avatarUrl || "/experts/custom-expert-placeholder.svg",
257005
- emoji: expert.uiEmoji || "\u{1F916}",
257006
- shortName: expert.uiShortName || expert.name.slice(0, 10)
257007
- };
257008
- }
257009
- function buildCanHandleFunction(routing, excludeKeywords) {
257010
- return (query) => {
257011
- const lowerQuery = query.toLowerCase();
257012
- if (excludeKeywords && excludeKeywords.length > 0) {
257013
- for (const excluded of excludeKeywords) {
257014
- if (lowerQuery.includes(excluded.toLowerCase())) {
257015
- return false;
257016
- }
257017
- }
257018
- }
257019
- for (const keyword of routing.keywords) {
257020
- if (lowerQuery.includes(keyword.toLowerCase())) {
257021
- return true;
257022
- }
257023
- }
257024
- if (routing.patterns && routing.patterns.length > 0) {
257025
- for (const pattern of routing.patterns) {
257026
- try {
257027
- if (new RegExp(pattern, "i").test(query)) {
257028
- return true;
257029
- }
257030
- } catch {
257031
- console.warn(`Invalid regex pattern in expert routing: ${pattern}`);
257032
- }
257033
- }
257034
- }
257035
- return false;
257036
- };
257037
- }
257038
- function getAvailableToolsForExpert(enabledFeatures) {
257039
- return [
257040
- {
257041
- category: "Usable (Built-in)",
257042
- tools: [...BUILT_IN_TOOLS],
257043
- available: true
257044
- },
257045
- {
257046
- category: "Web Search",
257047
- tools: [...FEATURE_GATED_TOOLS.webSearch],
257048
- available: enabledFeatures.webSearch ?? false
257049
- },
257050
- {
257051
- category: "Image Generation",
257052
- tools: [...FEATURE_GATED_TOOLS.imageGeneration],
257053
- available: enabledFeatures.imageGeneration ?? false
257054
- },
257055
- {
257056
- category: "Documentation",
257057
- tools: [...FEATURE_GATED_TOOLS.documentation],
257058
- available: enabledFeatures.documentation ?? false
257059
- }
257060
- ];
257061
- }
257062
- function normalizeParentToolConfig(config3) {
257063
- if (typeof config3 === "string") {
257064
- return { name: config3 };
257065
- }
257066
- return config3;
257067
- }
257068
- function getParentToolName(config3) {
257069
- if (typeof config3 === "string") {
257070
- return config3;
257071
- }
257072
- return config3.name;
257073
- }
257074
- function mergeParentToolSchemas(parentTools, registeredSchemas) {
257075
- return parentTools.map((config3) => {
257076
- const normalized = normalizeParentToolConfig(config3);
257077
- const toolName = normalized.name;
257078
- if (normalized.description) {
257079
- return normalized;
257080
- }
257081
- const schema = registeredSchemas?.get(toolName);
257082
- if (schema) {
257083
- return {
257084
- name: toolName,
257085
- description: schema.description,
257086
- parameters: schema.parameters || normalized.parameters
257087
- };
257088
- }
257089
- return normalized;
257090
- });
257091
- }
257092
- function isParentToolComplete(tool2) {
257093
- return !!(tool2.name && tool2.description);
257094
- }
257095
- var BUILT_IN_TOOLS, FEATURE_GATED_TOOLS, expertRoutingSchema, parentToolNameSchema, parentToolFullDefinitionSchema, parentToolDefinitionSchema, parentToolSchemaSchema, MAX_PARENT_TOOLS, expertConfigSchema, createCustomExpertSchema, updateCustomExpertSchema;
257096
- var init_custom_expert = __esm({
257097
- "src/core/types/custom-expert.ts"() {
257098
- "use strict";
257099
- init_zod();
257100
- init_rich_fragment_prompt();
257101
- init_system_prompt_source();
257102
- BUILT_IN_TOOLS = [
257103
- "agentic-search-fragments",
257104
- "search-memory-fragments",
257105
- "list-memory-fragments",
257106
- "get-memory-fragment-content",
257107
- "create-memory-fragment",
257108
- "update-memory-fragment",
257109
- "list-workspaces",
257110
- "get-fragment-types"
257111
- ];
257112
- FEATURE_GATED_TOOLS = {
257113
- webSearch: [
257114
- "exa-search",
257115
- "exa-find-similar",
257116
- "exa-get-contents",
257117
- "WebFetch",
257118
- "WebSearch"
257119
- ],
257120
- imageGeneration: ["generate-image", "view-image"],
257121
- documentation: ["resolve-library-id", "query-docs"]
257122
- };
257123
- expertRoutingSchema = external_exports.object({
257124
- keywords: external_exports.array(external_exports.string().min(1).max(100)).min(1, "At least one keyword is required for routing"),
257125
- patterns: external_exports.array(external_exports.string().max(500)).optional()
257126
- });
257127
- parentToolNameSchema = external_exports.string().min(1).max(100).regex(/^[a-z][a-z0-9_-]*$/i, "Tool name must start with a letter and contain only alphanumeric, underscores, or hyphens");
257128
- parentToolFullDefinitionSchema = external_exports.object({
257129
- name: external_exports.string().min(1).max(100).regex(/^[a-z][a-z0-9_-]*$/i, "Tool name must start with a letter and contain only alphanumeric, underscores, or hyphens"),
257130
- description: external_exports.string().min(1).max(1e3).optional(),
257131
- parameters: external_exports.record(external_exports.unknown()).optional()
257132
- });
257133
- parentToolDefinitionSchema = external_exports.union([
257134
- parentToolNameSchema,
257135
- parentToolFullDefinitionSchema
257136
- ]);
257137
- parentToolSchemaSchema = external_exports.object({
257138
- name: external_exports.string().min(1).max(100).regex(/^[a-z][a-z0-9_-]*$/i, "Tool name must start with a letter and contain only alphanumeric, underscores, or hyphens"),
257139
- description: external_exports.string().min(1).max(1e3),
257140
- parameters: external_exports.object({
257141
- type: external_exports.literal("object"),
257142
- properties: external_exports.record(external_exports.unknown()),
257143
- required: external_exports.array(external_exports.string()).optional()
257144
- }).optional(),
257145
- skill: external_exports.object({
257146
- id: external_exports.string().min(1).max(100).optional(),
257147
- title: external_exports.string().min(1).max(200).optional(),
257148
- summary: external_exports.string().max(1e3).optional(),
257149
- tags: external_exports.array(external_exports.string().min(1).max(100)).max(20).optional(),
257150
- scope: external_exports.enum(["global", "page"]).optional()
257151
- }).optional()
257152
- });
257153
- MAX_PARENT_TOOLS = 32;
257154
- expertConfigSchema = external_exports.object({
257155
- systemPrompt: external_exports.string().min(1).max(5e4),
257156
- systemPromptSource: systemPromptSourceSchema.nullable().optional(),
257157
- enabledTools: external_exports.array(external_exports.string()),
257158
- routing: expertRoutingSchema,
257159
- modelPreference: external_exports.enum(["inherit", "quick-thinking", "deep-thinking", "multi-lingual"]),
257160
- directModelId: external_exports.string().regex(
257161
- /^[a-z0-9-]+\/[a-z0-9.-]+$/,
257162
- "Must be a valid model ID (e.g., anthropic/claude-sonnet-4.5)"
257163
- ).optional().nullable(),
257164
- temperature: external_exports.number().min(0).max(1).optional(),
257165
- maxTokens: external_exports.number().min(100).max(32e3).optional(),
257166
- uiColor: external_exports.string().max(50).optional(),
257167
- uiEmoji: external_exports.string().max(10).optional(),
257168
- avatarUrl: external_exports.string().refine(
257169
- (val) => val.startsWith("data:") || val.startsWith("http://") || val.startsWith("https://") || val.startsWith("/"),
257170
- "Must be a valid URL, data URL, or path"
257171
- ).optional(),
257172
- parentTools: external_exports.array(parentToolDefinitionSchema).max(MAX_PARENT_TOOLS).optional(),
257173
- excludeKeywords: external_exports.array(external_exports.string().min(1).max(50)).max(20).optional(),
257174
- priority: external_exports.number().int().min(0).max(100).optional(),
257175
- maxTurns: external_exports.number().int().min(1).max(50).optional(),
257176
- uiShortName: external_exports.string().max(30).optional()
257177
- });
257178
- createCustomExpertSchema = external_exports.object({
257179
- key: external_exports.string().min(1).max(100).regex(/^[a-z0-9-]+$/, "Key must be lowercase alphanumeric with hyphens").optional(),
257180
- workspaceId: external_exports.string().uuid().optional(),
257181
- name: external_exports.string().min(1).max(255),
257182
- description: external_exports.string().min(1).max(1e3),
257183
- expertConfig: expertConfigSchema
257184
- });
257185
- updateCustomExpertSchema = external_exports.object({
257186
- name: external_exports.string().min(1).max(255).optional(),
257187
- description: external_exports.string().min(1).max(1e3).optional(),
257188
- expertConfig: expertConfigSchema.partial().optional(),
257189
- status: external_exports.enum(["active", "archived", "draft"]).optional()
257190
- });
257191
- }
257192
- });
257193
-
257194
- // src/lib/services/expert-permission.service.ts
257195
- async function checkExpertPermission(expertId, userId) {
257196
- const [collaborator] = await db.select({ role: expertCollaborators.role }).from(expertCollaborators).where(
257197
- and(
257198
- eq(expertCollaborators.expertId, expertId),
257199
- eq(expertCollaborators.userId, userId),
257200
- isNull(expertCollaborators.deletedAt)
257201
- )
257202
- ).limit(1);
257203
- if (collaborator) {
257204
- const role = collaborator.role;
257205
- return {
257206
- hasAccess: true,
257207
- role,
257208
- isOwner: role === "owner",
257209
- isViewer: role === "viewer" || role === "subscriber"
257210
- };
257211
- }
257212
- const [expert] = await db.select({ createdBy: customExperts.createdBy }).from(customExperts).where(eq(customExperts.id, expertId)).limit(1);
257213
- if (expert && expert.createdBy === userId) {
257214
- return {
257215
- hasAccess: true,
257216
- role: "owner",
257217
- isOwner: true,
257218
- isViewer: false
257219
- };
257220
- }
257221
- return {
257222
- hasAccess: false,
257223
- role: "none",
257224
- isOwner: false,
257225
- isViewer: false
257226
- };
257227
- }
257228
- async function canViewExpert(expertId, userId) {
257229
- const permission = await checkExpertPermission(expertId, userId);
257230
- return permission.hasAccess;
257231
- }
257232
- async function checkConfigPermission(configId, userId) {
257233
- const [collaborator] = await db.select({ role: configCollaborators.role }).from(configCollaborators).where(
257234
- and(
257235
- eq(configCollaborators.configId, configId),
257236
- eq(configCollaborators.userId, userId),
257237
- isNull(configCollaborators.deletedAt)
257238
- )
257239
- ).limit(1);
257240
- if (collaborator) {
257241
- const role = collaborator.role;
257242
- return {
257243
- hasAccess: true,
257244
- role,
257245
- isOwner: role === "owner",
257246
- isViewer: role === "viewer"
257247
- };
257248
- }
257249
- const [config3] = await db.select({ createdBy: chatConfigs.createdBy }).from(chatConfigs).where(eq(chatConfigs.id, configId)).limit(1);
257250
- if (config3 && config3.createdBy === userId) {
257251
- return {
257252
- hasAccess: true,
257253
- role: "owner",
257254
- isOwner: true,
257255
- isViewer: false
257256
- };
257257
- }
257258
- return {
257259
- hasAccess: false,
257260
- role: "none",
257261
- isOwner: false,
257262
- isViewer: false
257263
- };
257264
- }
257265
- async function canEditConfig(configId, userId) {
257266
- const permission = await checkConfigPermission(configId, userId);
257267
- return permission.isOwner;
257268
- }
257269
- var init_expert_permission_service = __esm({
257270
- "src/lib/services/expert-permission.service.ts"() {
257271
- "use strict";
257272
- init_client7();
257273
- init_schema4();
257274
- init_drizzle_orm();
257275
- init_custom_expert();
257276
- }
257277
- });
257278
-
257279
257290
  // node_modules/.pnpm/parse5@8.0.1/node_modules/parse5/dist/common/unicode.js
257280
257291
  function isSurrogate(cp) {
257281
257292
  return cp >= 55296 && cp <= 57343;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usabledev/usable-chat",
3
- "version": "1.235.0",
3
+ "version": "1.236.1",
4
4
  "description": "usable-chat — terminal harness for usable-chat (headless + TUI)",
5
5
  "type": "module",
6
6
  "bin": {