tavern-harness 0.2.0 → 0.2.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/CHANGELOG.md +49 -0
- package/package.json +1 -1
- package/persistence-server.mjs +60 -1
- package/sandbox-server.mjs +11 -8
- package/src/components/ChatView.tsx +4 -2
- package/src/components/FileDisplayModal.tsx +105 -2
- package/src/components/SettingsView.tsx +112 -1
- package/src/components/WorkspaceFileManagerModal.tsx +2 -2
- package/src/components/shared.tsx +28 -9
- package/src/core/i18n.ts +39 -0
- package/src/core/imageFilename.ts +21 -0
- package/src/core/imageGeneration.ts +32 -0
- package/src/core/prompts.ts +6 -1
- package/src/core/toolDefinitions.ts +21 -0
- package/src/core/tools/generatedSkillExecutor.ts +31 -2
- package/src/core/tools/toolExecutor.ts +104 -8
- package/src/db/database.ts +36 -4
- package/src/generated/changelog.json +71 -1
- package/src/store/store.ts +19 -5
- package/src/theme/chat.css +46 -3
- package/src/theme/views.css +27 -10
- package/src/types/models.ts +14 -1
- package/vite.config.ts +1 -1
package/src/core/i18n.ts
CHANGED
|
@@ -268,6 +268,17 @@ const MESSAGES: Record<LangKey, Record<string, string>> = {
|
|
|
268
268
|
'builtinWorldbook.name': '酒馆经营手册(精华版)',
|
|
269
269
|
'settings.providerTitle': '🔌 模型服务供应商',
|
|
270
270
|
'settings.voiceProviderTitle': '🔊 语音服务供应商',
|
|
271
|
+
'settings.imageProviderTitle': '🖼️ 生图服务供应商',
|
|
272
|
+
'settings.noImageProvider': '尚未添加生图供应商',
|
|
273
|
+
'settings.addImageProvider': '添加生图供应商',
|
|
274
|
+
'settings.editImageProvider': '编辑生图供应商',
|
|
275
|
+
'settings.deleteImageProvider': '删除生图供应商',
|
|
276
|
+
'settings.imageProvider': '供应商',
|
|
277
|
+
'settings.imageProviderKind.bailianTokenPlan': '百炼 Token Plan',
|
|
278
|
+
'settings.imageServiceTag': '生图',
|
|
279
|
+
'settings.defaultImageModel': '默认生图服务与模型',
|
|
280
|
+
'settings.defaultImageModelDesc': '“生成图片”技能默认使用此配置',
|
|
281
|
+
'settings.noDefaultImageProvider': '未选择默认生图供应商',
|
|
271
282
|
'settings.noVoiceProvider': '尚未添加语音供应商',
|
|
272
283
|
'settings.voiceProvider': '供应商',
|
|
273
284
|
'settings.addVoiceProvider': '添加语音供应商',
|
|
@@ -542,6 +553,8 @@ const MESSAGES: Record<LangKey, Record<string, string>> = {
|
|
|
542
553
|
'toast.providerAdded': '已添加供应商',
|
|
543
554
|
'toast.voiceProviderAdded': '已添加语音供应商',
|
|
544
555
|
'toast.voiceProviderUpdated': '已更新语音供应商',
|
|
556
|
+
'toast.imageProviderAdded': '已添加生图供应商',
|
|
557
|
+
'toast.imageProviderUpdated': '已更新生图供应商',
|
|
545
558
|
'toast.voicePreviewPlaying': '正在播放试听',
|
|
546
559
|
'toast.voiceNotConfigured': '请先在设置中选择旁白音色',
|
|
547
560
|
'toast.voiceFailed': '语音播放失败:{msg}',
|
|
@@ -847,6 +860,17 @@ const MESSAGES: Record<LangKey, Record<string, string>> = {
|
|
|
847
860
|
'builtinWorldbook.name': '酒館經營手冊(精華版)',
|
|
848
861
|
'settings.providerTitle': '🔌 模型服務供應商',
|
|
849
862
|
'settings.voiceProviderTitle': '🔊 語音服務供應商',
|
|
863
|
+
'settings.imageProviderTitle': '🖼️ 生圖服務供應商',
|
|
864
|
+
'settings.noImageProvider': '尚未新增生圖供應商',
|
|
865
|
+
'settings.addImageProvider': '新增生圖供應商',
|
|
866
|
+
'settings.editImageProvider': '編輯生圖供應商',
|
|
867
|
+
'settings.deleteImageProvider': '刪除生圖供應商',
|
|
868
|
+
'settings.imageProvider': '供應商',
|
|
869
|
+
'settings.imageProviderKind.bailianTokenPlan': '百煉 Token Plan',
|
|
870
|
+
'settings.imageServiceTag': '生圖',
|
|
871
|
+
'settings.defaultImageModel': '預設生圖服務與模型',
|
|
872
|
+
'settings.defaultImageModelDesc': '「生成圖片」技能預設使用此設定',
|
|
873
|
+
'settings.noDefaultImageProvider': '未選擇預設生圖供應商',
|
|
850
874
|
'settings.noVoiceProvider': '尚未新增語音供應商',
|
|
851
875
|
'settings.voiceProvider': '供應商',
|
|
852
876
|
'settings.addVoiceProvider': '新增語音供應商',
|
|
@@ -1114,6 +1138,8 @@ const MESSAGES: Record<LangKey, Record<string, string>> = {
|
|
|
1114
1138
|
'toast.providerAdded': '已新增供應商',
|
|
1115
1139
|
'toast.voiceProviderAdded': '已新增語音供應商',
|
|
1116
1140
|
'toast.voiceProviderUpdated': '已更新語音供應商',
|
|
1141
|
+
'toast.imageProviderAdded': '已新增生圖供應商',
|
|
1142
|
+
'toast.imageProviderUpdated': '已更新生圖供應商',
|
|
1117
1143
|
'toast.voicePreviewPlaying': '正在播放試聽',
|
|
1118
1144
|
'toast.voiceNotConfigured': '請先在設定中選擇旁白音色',
|
|
1119
1145
|
'toast.voiceFailed': '語音播放失敗:{msg}',
|
|
@@ -1417,6 +1443,17 @@ const MESSAGES: Record<LangKey, Record<string, string>> = {
|
|
|
1417
1443
|
'builtinWorldbook.name': 'Tavern Management Handbook (Essentials)',
|
|
1418
1444
|
'settings.providerTitle': '🔌 Model Providers',
|
|
1419
1445
|
'settings.voiceProviderTitle': '🔊 Voice Service Providers',
|
|
1446
|
+
'settings.imageProviderTitle': '🖼️ Image Generation Providers',
|
|
1447
|
+
'settings.noImageProvider': 'No image provider added',
|
|
1448
|
+
'settings.addImageProvider': 'Add image provider',
|
|
1449
|
+
'settings.editImageProvider': 'Edit image provider',
|
|
1450
|
+
'settings.deleteImageProvider': 'Delete image provider',
|
|
1451
|
+
'settings.imageProvider': 'Provider',
|
|
1452
|
+
'settings.imageProviderKind.bailianTokenPlan': 'Bailian Token Plan',
|
|
1453
|
+
'settings.imageServiceTag': 'Image',
|
|
1454
|
+
'settings.defaultImageModel': 'Default image provider and model',
|
|
1455
|
+
'settings.defaultImageModelDesc': 'Used by the built-in Generate Image skill',
|
|
1456
|
+
'settings.noDefaultImageProvider': 'No default image provider',
|
|
1420
1457
|
'settings.noVoiceProvider': 'No voice provider added',
|
|
1421
1458
|
'settings.voiceProvider': 'Provider',
|
|
1422
1459
|
'settings.addVoiceProvider': 'Add voice provider',
|
|
@@ -1684,6 +1721,8 @@ const MESSAGES: Record<LangKey, Record<string, string>> = {
|
|
|
1684
1721
|
'toast.providerAdded': 'Provider added',
|
|
1685
1722
|
'toast.voiceProviderAdded': 'Voice provider added',
|
|
1686
1723
|
'toast.voiceProviderUpdated': 'Voice provider updated',
|
|
1724
|
+
'toast.imageProviderAdded': 'Image provider added',
|
|
1725
|
+
'toast.imageProviderUpdated': 'Image provider updated',
|
|
1687
1726
|
'toast.voicePreviewPlaying': 'Playing voice preview',
|
|
1688
1727
|
'toast.voiceNotConfigured': 'Select a narration voice in Settings first',
|
|
1689
1728
|
'toast.voiceFailed': 'Voice playback failed: {msg}',
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const MAX_IMAGE_FILENAME_LENGTH = 64;
|
|
2
|
+
|
|
3
|
+
function readableStem(value: string): string {
|
|
4
|
+
const withoutImageExtension = value.trim().replace(/\.(?:png|jpe?g|gif|webp|bmp)$/i, '');
|
|
5
|
+
const normalized = withoutImageExtension
|
|
6
|
+
.normalize('NFKC')
|
|
7
|
+
.replace(/[^\p{L}\p{N}_-]+/gu, '-')
|
|
8
|
+
.replace(/-+/g, '-')
|
|
9
|
+
.replace(/^[-_]+|[-_]+$/g, '');
|
|
10
|
+
return Array.from(normalized).slice(0, MAX_IMAGE_FILENAME_LENGTH).join('').replace(/[-_]+$/g, '');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function buildGeneratedImagePath(
|
|
14
|
+
requestedFilename: string,
|
|
15
|
+
prompt: string,
|
|
16
|
+
extension: string,
|
|
17
|
+
timestamp = Date.now()
|
|
18
|
+
): string {
|
|
19
|
+
const stem = readableStem(requestedFilename) || readableStem(prompt) || 'generated';
|
|
20
|
+
return `images/${stem}-${timestamp}.${extension}`;
|
|
21
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export const IMAGE_MODELS = [
|
|
2
|
+
'qwen-image-3.0-pro',
|
|
3
|
+
'qwen-image-2.0-pro',
|
|
4
|
+
'qwen-image-2.0',
|
|
5
|
+
'wan2.7-image',
|
|
6
|
+
'wan2.7-image-pro',
|
|
7
|
+
] as const;
|
|
8
|
+
|
|
9
|
+
interface GenerateImageResult {
|
|
10
|
+
dataUrl: string;
|
|
11
|
+
mimeType: string;
|
|
12
|
+
width: number | null;
|
|
13
|
+
height: number | null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function generateImage(
|
|
17
|
+
providerId: number,
|
|
18
|
+
prompt: string,
|
|
19
|
+
model: string,
|
|
20
|
+
size = '1024*1024',
|
|
21
|
+
): Promise<GenerateImageResult> {
|
|
22
|
+
const response = await fetch('/api-v3/image/generate', {
|
|
23
|
+
method: 'POST',
|
|
24
|
+
headers: { 'Content-Type': 'application/json' },
|
|
25
|
+
body: JSON.stringify({ providerId, prompt, model, size }),
|
|
26
|
+
});
|
|
27
|
+
const payload = await response.json().catch(() => null) as (GenerateImageResult & { message?: string }) | null;
|
|
28
|
+
if (!response.ok || !payload?.dataUrl) {
|
|
29
|
+
throw new Error(payload?.message || `Image generation failed (HTTP ${response.status})`);
|
|
30
|
+
}
|
|
31
|
+
return payload;
|
|
32
|
+
}
|
package/src/core/prompts.ts
CHANGED
|
@@ -103,7 +103,7 @@ export function buildNetworkMessagesForSession(p: {
|
|
|
103
103
|
if (m.toolCallId == null || !declaredToolCallIds.has(m.toolCallId) || omittedToolCallIds.has(m.toolCallId)) continue;
|
|
104
104
|
result.push({
|
|
105
105
|
role: 'tool',
|
|
106
|
-
content: m.content,
|
|
106
|
+
content: sanitizeToolResultForModel(m.content),
|
|
107
107
|
tool_call_id: m.toolCallId ?? undefined,
|
|
108
108
|
});
|
|
109
109
|
continue;
|
|
@@ -211,6 +211,11 @@ function trimMessagesForNewTopic<T extends {
|
|
|
211
211
|
return [...keepSystems, ...(keepGreeting ? [keepGreeting] : []), ...after];
|
|
212
212
|
}
|
|
213
213
|
|
|
214
|
+
function sanitizeToolResultForModel(content: string): string {
|
|
215
|
+
if (!content.startsWith('IMAGE_RESULT: ')) return content;
|
|
216
|
+
return content.replace(/^IMAGE_RESULT: [^\n]*\n?/, '') || 'OK: Image generated and displayed to the user.';
|
|
217
|
+
}
|
|
218
|
+
|
|
214
219
|
/** 附件转 data URL content parts(base64 图片/视频) */
|
|
215
220
|
function buildContentWithAttachments(content: string, attachments: string[]): string | NetworkMessage['content'] {
|
|
216
221
|
if (!attachments || attachments.length === 0) {
|
|
@@ -28,6 +28,7 @@ export const BUILTIN_TOOL_NAMES = [
|
|
|
28
28
|
'file_write',
|
|
29
29
|
'file_edit',
|
|
30
30
|
'file_display',
|
|
31
|
+
'generate_image',
|
|
31
32
|
'create_skill',
|
|
32
33
|
'update_skill',
|
|
33
34
|
'delete_skill',
|
|
@@ -169,6 +170,24 @@ export const BUILTIN_TOOLS: ChatCompletionTool[] = [
|
|
|
169
170
|
additionalProperties: false,
|
|
170
171
|
}
|
|
171
172
|
),
|
|
173
|
+
fn(
|
|
174
|
+
'generate_image',
|
|
175
|
+
'Generate an image from a text prompt with the configured image service.',
|
|
176
|
+
{
|
|
177
|
+
type: 'object',
|
|
178
|
+
properties: {
|
|
179
|
+
prompt: { type: 'string', minLength: 1, maxLength: 10000, description: 'Detailed image description.' },
|
|
180
|
+
filename: {
|
|
181
|
+
type: 'string',
|
|
182
|
+
maxLength: 64,
|
|
183
|
+
description: 'Optional readable file name without a directory. Keep it short and descriptive; the extension and a uniqueness suffix are added automatically.',
|
|
184
|
+
},
|
|
185
|
+
size: { type: 'string', pattern: '^\\d{2,5}\\*\\d{2,5}$', default: '1024*1024', description: 'Image size, for example 1024*1024.' },
|
|
186
|
+
},
|
|
187
|
+
required: ['prompt'],
|
|
188
|
+
additionalProperties: false,
|
|
189
|
+
}
|
|
190
|
+
),
|
|
172
191
|
fn(
|
|
173
192
|
'create_skill',
|
|
174
193
|
'Create a new generated skill (tool) usable by characters. The skill is defined by a declarative execution schema. New skill is NOT enabled for any character until you enable it via update_character.',
|
|
@@ -288,6 +307,7 @@ export const BUILTIN_TOOLS: ChatCompletionTool[] = [
|
|
|
288
307
|
greeting: { type: 'string', minLength: 1, maxLength: 1000, description: 'First message the character says' },
|
|
289
308
|
alternate_greetings: { type: 'array', items: { type: 'string', maxLength: 1000 }, description: 'Optional alternative greetings; one is picked at random when a chat starts' },
|
|
290
309
|
prompt: { type: 'string', minLength: 1, maxLength: 4000, description: 'Persona / system prompt' },
|
|
310
|
+
avatar_path: { type: 'string', description: 'Optional image path relative to the current workspace (PNG, JPEG, WebP, BMP, or AVIF)' },
|
|
291
311
|
},
|
|
292
312
|
required: ['name', 'greeting', 'prompt'],
|
|
293
313
|
additionalProperties: false,
|
|
@@ -304,6 +324,7 @@ export const BUILTIN_TOOLS: ChatCompletionTool[] = [
|
|
|
304
324
|
greeting: { type: 'string', maxLength: 1000 },
|
|
305
325
|
alternate_greetings: { type: 'array', items: { type: 'string', maxLength: 1000 }, description: 'Replace the full list of alternate greetings' },
|
|
306
326
|
prompt: { type: 'string', maxLength: 4000 },
|
|
327
|
+
avatar_path: { anyOf: [{ type: 'string' }, { type: 'null' }], description: 'Image path relative to the current workspace; use null to clear the avatar (PNG, JPEG, WebP, BMP, or AVIF)' },
|
|
307
328
|
enable_skills: { type: 'array', items: { type: 'string' }, description: 'Skill names to enable (must exist)' },
|
|
308
329
|
disable_skills: { type: 'array', items: { type: 'string' }, description: 'Skill names to disable' },
|
|
309
330
|
},
|
|
@@ -222,7 +222,7 @@ function createSandboxWorker(code: string): Worker {
|
|
|
222
222
|
|
|
223
223
|
const DISPLAY_REF_PREFIX = 'DISPLAY_REF: ';
|
|
224
224
|
|
|
225
|
-
type DisplayKind = 'text' | 'html' | 'unsupported';
|
|
225
|
+
type DisplayKind = 'text' | 'html' | 'image' | 'unsupported';
|
|
226
226
|
|
|
227
227
|
interface DisplayPayload {
|
|
228
228
|
path: string;
|
|
@@ -350,7 +350,7 @@ async function handleBridgeCall(
|
|
|
350
350
|
const kind: DisplayKind = /^(html?)$/.test(extension)
|
|
351
351
|
? 'html'
|
|
352
352
|
: /^(png|jpe?g|gif|webp|svg|bmp|ico)$/.test(extension)
|
|
353
|
-
? '
|
|
353
|
+
? 'image'
|
|
354
354
|
: 'text';
|
|
355
355
|
const displayPayload: DisplayPayload = { path, kind, title };
|
|
356
356
|
return { ok: true, result: `Displayed ${path} in a popup`, payload: displayPayload };
|
|
@@ -488,6 +488,22 @@ export async function readWorkspaceFileText(path: string, workspaceDir: string):
|
|
|
488
488
|
return diskFileRead(readablePath, workspaceDir);
|
|
489
489
|
}
|
|
490
490
|
|
|
491
|
+
/** 读取工作区二进制文件,供头像等受限资源使用。 */
|
|
492
|
+
export async function readWorkspaceFileBase64(path: string, workspaceDir: string): Promise<string | null> {
|
|
493
|
+
const readablePath = normalizePath(path);
|
|
494
|
+
if (!readablePath) throw new Error('Invalid path');
|
|
495
|
+
await requireFileServer(workspaceDir);
|
|
496
|
+
const resp = await fetch('/api-v2/preview_read', {
|
|
497
|
+
method: 'POST',
|
|
498
|
+
headers: { 'Content-Type': 'application/json' },
|
|
499
|
+
body: JSON.stringify({ path: readablePath, session: workspaceDir }),
|
|
500
|
+
});
|
|
501
|
+
const data = (await resp.json()) as { ok?: boolean; message?: string; content?: string };
|
|
502
|
+
if (resp.status === 404 || data.message === 'File not found') return null;
|
|
503
|
+
if (!resp.ok || !data.ok || typeof data.content !== 'string') throw new Error(data.message || `HTTP ${resp.status}`);
|
|
504
|
+
return data.content;
|
|
505
|
+
}
|
|
506
|
+
|
|
491
507
|
/**
|
|
492
508
|
* 写入本地沙箱工作区。
|
|
493
509
|
* 与 file_write 技能一致:仅允许工作区相对路径;普通会话的 public 软链只读。
|
|
@@ -505,6 +521,19 @@ export async function writeWorkspaceFileTextFor(
|
|
|
505
521
|
return diskFileWrite(normalizedPath, content, append, workspaceDir);
|
|
506
522
|
}
|
|
507
523
|
|
|
524
|
+
export async function writeWorkspaceFileBase64For(path: string, base64: string, workspaceDir: string): Promise<void> {
|
|
525
|
+
const normalizedPath = normalizePath(path);
|
|
526
|
+
if (!normalizedPath) throw new Error('Invalid path');
|
|
527
|
+
await requireFileServer(workspaceDir);
|
|
528
|
+
const resp = await fetch('/api-v2/file_write_base64', {
|
|
529
|
+
method: 'POST',
|
|
530
|
+
headers: { 'Content-Type': 'application/json' },
|
|
531
|
+
body: JSON.stringify({ path: normalizedPath, content: base64, session: workspaceDir }),
|
|
532
|
+
});
|
|
533
|
+
const data = (await resp.json()) as { ok?: boolean; message?: string };
|
|
534
|
+
if (!resp.ok || !data.ok) throw new Error(data.message || `HTTP ${resp.status}`);
|
|
535
|
+
}
|
|
536
|
+
|
|
508
537
|
/** 删除工作区中的文件或目录。 */
|
|
509
538
|
export async function deleteWorkspaceFile(path: string, workspaceDir: string): Promise<void> {
|
|
510
539
|
const normalizedPath = normalizePath(path);
|
|
@@ -12,14 +12,19 @@ import {
|
|
|
12
12
|
PERFORMANCE_GUIDANCE_TOOL_NAME,
|
|
13
13
|
} from '../toolDefinitions';
|
|
14
14
|
import { unlockAchievement } from '../achievements';
|
|
15
|
+
import { generateImage } from '../imageGeneration';
|
|
16
|
+
import { buildGeneratedImagePath } from '../imageFilename';
|
|
17
|
+
import { AVATAR_STORAGE_SIZE, shrinkAvatarDataUrl } from '../avatarThumbnail';
|
|
15
18
|
import { translate } from '../i18n';
|
|
16
19
|
import { rollDice } from './builtinTools';
|
|
17
20
|
import {
|
|
18
21
|
createSessionWorkspaceDir,
|
|
19
22
|
executeGeneratedSkill,
|
|
20
23
|
normalizeWorkspaceDir,
|
|
24
|
+
readWorkspaceFileBase64,
|
|
21
25
|
readWorkspaceFileText,
|
|
22
26
|
truncateToolOutput,
|
|
27
|
+
writeWorkspaceFileBase64For,
|
|
23
28
|
writeWorkspaceFileTextFor,
|
|
24
29
|
} from './generatedSkillExecutor';
|
|
25
30
|
|
|
@@ -149,6 +154,8 @@ async function runNativeTool(
|
|
|
149
154
|
|
|
150
155
|
case 'file_display':
|
|
151
156
|
return await handleFileDisplay(args, ctx);
|
|
157
|
+
case 'generate_image':
|
|
158
|
+
return await handleGenerateImage(args, ctx);
|
|
152
159
|
|
|
153
160
|
case 'create_skill':
|
|
154
161
|
return await handleCreateSkill(args);
|
|
@@ -159,9 +166,9 @@ async function runNativeTool(
|
|
|
159
166
|
return await handleDeleteSkill(args);
|
|
160
167
|
|
|
161
168
|
case 'create_character':
|
|
162
|
-
return await handleCreateCharacter(args);
|
|
169
|
+
return await handleCreateCharacter(args, ctx);
|
|
163
170
|
case 'update_character':
|
|
164
|
-
return await handleUpdateCharacter(args);
|
|
171
|
+
return await handleUpdateCharacter(args, ctx);
|
|
165
172
|
case 'delete_character':
|
|
166
173
|
return await handleDeleteCharacter(args);
|
|
167
174
|
|
|
@@ -295,7 +302,7 @@ const DISPLAY_REF_PREFIX = 'DISPLAY_REF: ';
|
|
|
295
302
|
|
|
296
303
|
interface DisplayPayload {
|
|
297
304
|
path: string;
|
|
298
|
-
kind: 'text' | 'html' | 'unsupported';
|
|
305
|
+
kind: 'text' | 'html' | 'image' | 'unsupported';
|
|
299
306
|
title?: string;
|
|
300
307
|
}
|
|
301
308
|
|
|
@@ -306,7 +313,7 @@ export function parseDisplayRef(result: string): DisplayPayload | null {
|
|
|
306
313
|
const firstLine = result.slice(DISPLAY_REF_PREFIX.length).split('\n')[0]!;
|
|
307
314
|
try {
|
|
308
315
|
const obj = JSON.parse(firstLine) as DisplayPayload;
|
|
309
|
-
if (!obj || typeof obj.path !== 'string' || !['text', 'html', 'unsupported'].includes(obj.kind)) return null;
|
|
316
|
+
if (!obj || typeof obj.path !== 'string' || !['text', 'html', 'image', 'unsupported'].includes(obj.kind)) return null;
|
|
310
317
|
return { path: obj.path, kind: obj.kind, title: typeof obj.title === 'string' ? obj.title : undefined };
|
|
311
318
|
} catch {
|
|
312
319
|
return null;
|
|
@@ -328,7 +335,7 @@ async function handleFileDisplay(args: Record<string, unknown>, ctx: ToolExecuti
|
|
|
328
335
|
const kind: DisplayPayload['kind'] = /^(html?)$/i.test(extLower)
|
|
329
336
|
? 'html'
|
|
330
337
|
: /^(png|jpe?g|gif|webp|svg|bmp|ico)$/i.test(extLower)
|
|
331
|
-
? '
|
|
338
|
+
? 'image'
|
|
332
339
|
: 'text';
|
|
333
340
|
|
|
334
341
|
const content = await readWorkspaceFileText(rawPath, workspaceDir);
|
|
@@ -344,6 +351,44 @@ async function handleFileDisplay(args: Record<string, unknown>, ctx: ToolExecuti
|
|
|
344
351
|
}
|
|
345
352
|
}
|
|
346
353
|
|
|
354
|
+
const IMAGE_RESULT_PREFIX = 'IMAGE_RESULT: ';
|
|
355
|
+
|
|
356
|
+
export interface ImageResultPayload {
|
|
357
|
+
path: string;
|
|
358
|
+
name: string;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
export function parseImageResult(result: string): ImageResultPayload | null {
|
|
362
|
+
if (!result.startsWith(IMAGE_RESULT_PREFIX)) return null;
|
|
363
|
+
const path = result.slice(IMAGE_RESULT_PREFIX.length).split('\n')[0]!.trim();
|
|
364
|
+
if (!path || path.startsWith('/') || path.split('/').some((part) => part === '..')) return null;
|
|
365
|
+
return { path, name: path.split('/').pop() || path };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async function handleGenerateImage(args: Record<string, unknown>, ctx: ToolExecutionContext): Promise<string> {
|
|
369
|
+
const prompt = String(args.prompt ?? '').trim();
|
|
370
|
+
const filename = String(args.filename ?? '').trim();
|
|
371
|
+
const size = String(args.size ?? '1024*1024').trim();
|
|
372
|
+
if (!prompt) return 'ERROR: Missing image prompt';
|
|
373
|
+
const settings = await db.settings.get(1);
|
|
374
|
+
const providerId = settings?.activeImageProviderId ?? null;
|
|
375
|
+
const model = settings?.defaultImageModel?.trim() || '';
|
|
376
|
+
if (providerId == null || !model) return 'ERROR: Image generation is not configured. Configure an image provider and default image model in Settings.';
|
|
377
|
+
const provider = await db.imageProviders.get(providerId);
|
|
378
|
+
if (!provider?.isEnabled || !provider.apiKey.trim()) return 'ERROR: The configured image provider is disabled or unavailable.';
|
|
379
|
+
try {
|
|
380
|
+
const generated = await generateImage(providerId, prompt, model, size);
|
|
381
|
+
const extension = generated.mimeType.split('/')[1]?.replace('jpeg', 'jpg') || 'png';
|
|
382
|
+
const workspaceDir = await applySessionWorkspace(ctx.sessionId, ctx.npcId);
|
|
383
|
+
const name = buildGeneratedImagePath(filename, prompt, extension);
|
|
384
|
+
const base64 = generated.dataUrl.slice(generated.dataUrl.indexOf(',') + 1);
|
|
385
|
+
await writeWorkspaceFileBase64For(name, base64, workspaceDir);
|
|
386
|
+
return `${IMAGE_RESULT_PREFIX}${name}\nOK: Image generated successfully. Path: ${name}`;
|
|
387
|
+
} catch (error) {
|
|
388
|
+
return `ERROR: Image generation failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
347
392
|
// ---------- file_read / file_write / run_shell_script(内置技能,复用生成式执行引擎的本地能力) ----------
|
|
348
393
|
|
|
349
394
|
async function handleFileRead(args: Record<string, unknown>, ctx: ToolExecutionContext): Promise<string> {
|
|
@@ -510,7 +555,39 @@ async function handleDeleteSkill(args: Record<string, unknown>): Promise<string>
|
|
|
510
555
|
|
|
511
556
|
// ---------- 角色 CRUD ----------
|
|
512
557
|
|
|
513
|
-
|
|
558
|
+
const AVATAR_EXTENSIONS = new Set(['avif', 'bmp', 'jpeg', 'jpg', 'png', 'webp']);
|
|
559
|
+
|
|
560
|
+
function detectAvatarMime(base64: string): string | null {
|
|
561
|
+
let bytes: Uint8Array;
|
|
562
|
+
try {
|
|
563
|
+
const binary = atob(base64.slice(0, 64));
|
|
564
|
+
bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
565
|
+
} catch {
|
|
566
|
+
return null;
|
|
567
|
+
}
|
|
568
|
+
if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return 'image/png';
|
|
569
|
+
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
|
|
570
|
+
if (bytes.length >= 2 && bytes[0] === 0x42 && bytes[1] === 0x4d) return 'image/bmp';
|
|
571
|
+
const ascii = String.fromCharCode(...bytes);
|
|
572
|
+
if (ascii.startsWith('RIFF') && ascii.slice(8, 12) === 'WEBP') return 'image/webp';
|
|
573
|
+
if (ascii.slice(4, 12) === 'ftypavif' || ascii.slice(4, 12) === 'ftypavis') return 'image/avif';
|
|
574
|
+
return null;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
async function loadWorkspaceAvatar(pathValue: unknown, ctx: ToolExecutionContext): Promise<string> {
|
|
578
|
+
const path = String(pathValue ?? '').replace(/\\/g, '/').trim();
|
|
579
|
+
if (!path) throw new Error('avatar_path must be a workspace-relative image path');
|
|
580
|
+
const extension = path.split('.').pop()?.toLowerCase() ?? '';
|
|
581
|
+
if (!AVATAR_EXTENSIONS.has(extension)) throw new Error('Avatar must be PNG, JPEG, WebP, BMP, or AVIF');
|
|
582
|
+
const workspaceDir = await applySessionWorkspace(ctx.sessionId, ctx.npcId);
|
|
583
|
+
const base64 = await readWorkspaceFileBase64(path, workspaceDir);
|
|
584
|
+
if (base64 === null) throw new Error(`Avatar file not found: ${path}`);
|
|
585
|
+
const mimeType = detectAvatarMime(base64);
|
|
586
|
+
if (!mimeType) throw new Error(`Avatar file is not a valid supported image: ${path}`);
|
|
587
|
+
return (await shrinkAvatarDataUrl(`data:${mimeType};base64,${base64}`, AVATAR_STORAGE_SIZE))!;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
async function handleCreateCharacter(args: Record<string, unknown>, ctx: ToolExecutionContext): Promise<string> {
|
|
514
591
|
const name = String(args.name ?? '').trim();
|
|
515
592
|
const greeting = String(args.greeting ?? '');
|
|
516
593
|
const prompt = String(args.prompt ?? '');
|
|
@@ -524,13 +601,21 @@ async function handleCreateCharacter(args: Record<string, unknown>): Promise<str
|
|
|
524
601
|
.slice(0, 20)
|
|
525
602
|
.map((g) => g.slice(0, 1000))
|
|
526
603
|
: [];
|
|
604
|
+
let avatarDataUrl: string | null = null;
|
|
605
|
+
if (args.avatar_path != null) {
|
|
606
|
+
try {
|
|
607
|
+
avatarDataUrl = await loadWorkspaceAvatar(args.avatar_path, ctx);
|
|
608
|
+
} catch (e) {
|
|
609
|
+
return `ERROR: ${(e as Error).message}`;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
527
612
|
await db.npcs.add({
|
|
528
613
|
name,
|
|
529
614
|
prompt,
|
|
530
615
|
greeting,
|
|
531
616
|
alternateGreetings: alternates,
|
|
532
617
|
avatarColorOrdinal: Math.floor(Math.random() * 6),
|
|
533
|
-
avatarDataUrl
|
|
618
|
+
avatarDataUrl,
|
|
534
619
|
enabledToolNames: [],
|
|
535
620
|
isBuiltIn: false,
|
|
536
621
|
createdAt: Date.now(),
|
|
@@ -539,7 +624,7 @@ async function handleCreateCharacter(args: Record<string, unknown>): Promise<str
|
|
|
539
624
|
return `OK: Created character ${name}`;
|
|
540
625
|
}
|
|
541
626
|
|
|
542
|
-
async function handleUpdateCharacter(args: Record<string, unknown
|
|
627
|
+
async function handleUpdateCharacter(args: Record<string, unknown>, ctx: ToolExecutionContext): Promise<string> {
|
|
543
628
|
const name = String(args.name ?? '');
|
|
544
629
|
const npc = await db.npcs.where('name').equals(name).first();
|
|
545
630
|
if (!npc) return `ERROR: Character ${name} does not exist`;
|
|
@@ -559,6 +644,17 @@ async function handleUpdateCharacter(args: Record<string, unknown>): Promise<str
|
|
|
559
644
|
.map((g) => g.slice(0, 1000));
|
|
560
645
|
}
|
|
561
646
|
if (args.prompt != null) updates.prompt = String(args.prompt).slice(0, 4000);
|
|
647
|
+
if (Object.prototype.hasOwnProperty.call(args, 'avatar_path')) {
|
|
648
|
+
if (args.avatar_path == null) {
|
|
649
|
+
updates.avatarDataUrl = null;
|
|
650
|
+
} else {
|
|
651
|
+
try {
|
|
652
|
+
updates.avatarDataUrl = await loadWorkspaceAvatar(args.avatar_path, ctx);
|
|
653
|
+
} catch (e) {
|
|
654
|
+
return `ERROR: ${(e as Error).message}`;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
}
|
|
562
658
|
if (Array.isArray(args.enable_skills) || Array.isArray(args.disable_skills)) {
|
|
563
659
|
const allTools = new Set((await db.tools.toArray()).map((t) => t.name));
|
|
564
660
|
const enabled = new Set(npc.enabledToolNames);
|
package/src/db/database.ts
CHANGED
|
@@ -2,6 +2,7 @@ import Dexie, { type Table } from 'dexie';
|
|
|
2
2
|
import type {
|
|
3
3
|
ApiProvider,
|
|
4
4
|
AppSettings,
|
|
5
|
+
ImageProvider,
|
|
5
6
|
VoiceProvider,
|
|
6
7
|
AchievementUnlock,
|
|
7
8
|
CareerNpcStat,
|
|
@@ -25,6 +26,8 @@ import BUILTIN_MEMORY_SKILL from '../assets/memory-skill.json';
|
|
|
25
26
|
export class TavernDB extends Dexie {
|
|
26
27
|
settings!: Table<AppSettings, number>;
|
|
27
28
|
providers!: Table<ApiProvider, number>;
|
|
29
|
+
voiceProviders!: Table<VoiceProvider, number>;
|
|
30
|
+
imageProviders!: Table<ImageProvider, number>;
|
|
28
31
|
npcs!: Table<NpcCharacter, number>;
|
|
29
32
|
sessions!: Table<ChatSession, number>;
|
|
30
33
|
participants!: Table<ChatParticipant, number>;
|
|
@@ -228,6 +231,23 @@ export class TavernDB extends Dexie {
|
|
|
228
231
|
careerNpcStats: 'npcId',
|
|
229
232
|
achievementUnlocks: '++id, achievementId, unlockedAt',
|
|
230
233
|
});
|
|
234
|
+
// v14:新增生图服务供应商。
|
|
235
|
+
this.version(14).stores({
|
|
236
|
+
settings: 'id',
|
|
237
|
+
providers: '++id, name, isEnabled',
|
|
238
|
+
voiceProviders: '++id, kind, isEnabled',
|
|
239
|
+
imageProviders: '++id, kind, isEnabled',
|
|
240
|
+
npcs: '++id, name, isBuiltIn, isTavernKeeper',
|
|
241
|
+
sessions: '++id, mode, updatedAt, associatedId, pinned, workspaceDir',
|
|
242
|
+
participants: '[sessionId+participantId], sessionId, participantId',
|
|
243
|
+
messages: '++id, [sessionId+timestamp], sessionId, timestamp',
|
|
244
|
+
contextCompressions: '++id, sessionId, endMessageId, createdAt',
|
|
245
|
+
tools: '++id, name, isBuiltIn',
|
|
246
|
+
worldBooks: '++id, name, isBuiltIn',
|
|
247
|
+
careerStats: 'id',
|
|
248
|
+
careerNpcStats: 'npcId',
|
|
249
|
+
achievementUnlocks: '++id, achievementId, unlockedAt',
|
|
250
|
+
});
|
|
231
251
|
}
|
|
232
252
|
|
|
233
253
|
/** 打开数据库后立即执行:把 pinned 字段归一化为 0/1(旧记录为 undefined) */
|
|
@@ -246,7 +266,7 @@ export class TavernDB extends Dexie {
|
|
|
246
266
|
}
|
|
247
267
|
|
|
248
268
|
const COLLECTIONS = [
|
|
249
|
-
'settings', 'providers', 'voiceProviders', 'npcs', 'sessions', 'participants', 'messages',
|
|
269
|
+
'settings', 'providers', 'voiceProviders', 'imageProviders', 'npcs', 'sessions', 'participants', 'messages',
|
|
250
270
|
'contextCompressions', 'tools', 'worldBooks', 'careerStats', 'careerNpcStats', 'achievementUnlocks',
|
|
251
271
|
] as const;
|
|
252
272
|
|
|
@@ -362,6 +382,7 @@ type StartupSnapshot = {
|
|
|
362
382
|
settings: Array<{ value: AppSettings }>;
|
|
363
383
|
providers: Array<{ value: ApiProvider }>;
|
|
364
384
|
voiceProviders: Array<{ value: VoiceProvider }>;
|
|
385
|
+
imageProviders: Array<{ value: ImageProvider }>;
|
|
365
386
|
npcs: Array<{ value: NpcCharacter }>;
|
|
366
387
|
sessions: Array<{ value: ChatSession }>;
|
|
367
388
|
worldBooks: Array<{ value: WorldBook }>;
|
|
@@ -381,10 +402,11 @@ export async function loadStartupSnapshot(): Promise<StartupSnapshot> {
|
|
|
381
402
|
if (!(error instanceof Error) || !error.message.includes('Unknown persistence endpoint: /startup/snapshot')) throw error;
|
|
382
403
|
await initDatabase();
|
|
383
404
|
const readOnly = await isWriteLocked();
|
|
384
|
-
const [settings, providers, voiceProviders, npcs, sessions, worldBooks, tools, achievementUnlocks] = await Promise.all([
|
|
405
|
+
const [settings, providers, voiceProviders, imageProviders, npcs, sessions, worldBooks, tools, achievementUnlocks] = await Promise.all([
|
|
385
406
|
db.settings.toArray(),
|
|
386
407
|
db.providers.toArray(),
|
|
387
408
|
db.voiceProviders.toArray(),
|
|
409
|
+
db.imageProviders.toArray(),
|
|
388
410
|
db.npcs.toArray(),
|
|
389
411
|
db.sessions.toArray(),
|
|
390
412
|
db.worldBooks.toArray(),
|
|
@@ -397,6 +419,7 @@ export async function loadStartupSnapshot(): Promise<StartupSnapshot> {
|
|
|
397
419
|
settings: settings.map((value) => ({ value })),
|
|
398
420
|
providers: providers.map((value) => ({ value })),
|
|
399
421
|
voiceProviders: voiceProviders.map((value) => ({ value })),
|
|
422
|
+
imageProviders: imageProviders.map((value) => ({ value })),
|
|
400
423
|
npcs: npcs.map((value) => ({ value })),
|
|
401
424
|
sessions: sessions.map((value) => ({ value })),
|
|
402
425
|
worldBooks: worldBooks.map((value) => ({ value })),
|
|
@@ -534,7 +557,7 @@ class RemoteTable<T extends object> {
|
|
|
534
557
|
async add(value: T): Promise<number> {
|
|
535
558
|
await requireWriteLock();
|
|
536
559
|
const record = { ...value } as T & { id?: number };
|
|
537
|
-
if (['providers', 'voiceProviders', 'npcs', 'sessions', 'messages', 'contextCompressions', 'tools', 'worldBooks', 'achievementUnlocks'].includes(this.collection) && record.id == null) {
|
|
560
|
+
if (['providers', 'voiceProviders', 'imageProviders', 'npcs', 'sessions', 'messages', 'contextCompressions', 'tools', 'worldBooks', 'achievementUnlocks'].includes(this.collection) && record.id == null) {
|
|
538
561
|
const result = await persistenceRequest<{ id: number }>('/records/allocate-id', { collection: this.collection });
|
|
539
562
|
record.id = result.id;
|
|
540
563
|
}
|
|
@@ -581,6 +604,7 @@ class RemoteTavernDB {
|
|
|
581
604
|
settings = new RemoteTable<AppSettings>('settings');
|
|
582
605
|
providers = new RemoteTable<ApiProvider>('providers');
|
|
583
606
|
voiceProviders = new RemoteTable<VoiceProvider>('voiceProviders');
|
|
607
|
+
imageProviders = new RemoteTable<ImageProvider>('imageProviders');
|
|
584
608
|
npcs = new RemoteTable<NpcCharacter>('npcs');
|
|
585
609
|
sessions = new RemoteTable<ChatSession>('sessions');
|
|
586
610
|
participants = new RemoteTable<ChatParticipant>('participants');
|
|
@@ -606,7 +630,7 @@ class RemoteTavernDB {
|
|
|
606
630
|
return (args.at(-1) as () => Promise<T>)();
|
|
607
631
|
}
|
|
608
632
|
async delete(): Promise<void> {
|
|
609
|
-
for (const table of [this.settings, this.providers, this.voiceProviders, this.npcs, this.sessions, this.participants, this.messages, this.contextCompressions, this.tools, this.worldBooks, this.careerStats, this.careerNpcStats, this.achievementUnlocks]) await table.clear();
|
|
633
|
+
for (const table of [this.settings, this.providers, this.voiceProviders, this.imageProviders, this.npcs, this.sessions, this.participants, this.messages, this.contextCompressions, this.tools, this.worldBooks, this.careerStats, this.careerNpcStats, this.achievementUnlocks]) await table.clear();
|
|
610
634
|
}
|
|
611
635
|
close(): void {
|
|
612
636
|
if (lockHeartbeat != null && typeof window !== 'undefined') {
|
|
@@ -702,6 +726,8 @@ export const DEFAULT_SETTINGS: AppSettings = {
|
|
|
702
726
|
autoVoiceEnabled: false,
|
|
703
727
|
activeVoiceProviderId: null,
|
|
704
728
|
activeVoiceId: null,
|
|
729
|
+
activeImageProviderId: null,
|
|
730
|
+
defaultImageModel: 'qwen-image-3.0-pro',
|
|
705
731
|
statsResetTime: null,
|
|
706
732
|
};
|
|
707
733
|
|
|
@@ -754,6 +780,12 @@ export async function initDatabase(): Promise<void> {
|
|
|
754
780
|
if (settings && settings.pureMode === undefined) {
|
|
755
781
|
await db.settings.update(1, { pureMode: false });
|
|
756
782
|
}
|
|
783
|
+
if (settings && settings.activeImageProviderId === undefined) {
|
|
784
|
+
await db.settings.update(1, { activeImageProviderId: null });
|
|
785
|
+
}
|
|
786
|
+
if (settings && settings.defaultImageModel === undefined) {
|
|
787
|
+
await db.settings.update(1, { defaultImageModel: 'qwen-image-3.0-pro' });
|
|
788
|
+
}
|
|
757
789
|
if (settings && (settings.language !== null || settings.themeMode !== 'system')) {
|
|
758
790
|
await db.settings.update(1, { language: null, themeMode: 'system' });
|
|
759
791
|
}
|