返回 CodeWhale
index.mjs
1 export const name = 'dsh-attachments'
2 export const inject = ['tools', 'attachments']
3
4 export function apply(ctx) {
5 ctx.tools.register({
6 name: 'attachments_roundtrip',
7 description: 'Validate, read, save, thumbnail-request, and emit an image attachment.',
8 parameters: {
9 type: 'object',
10 properties: {
11 sourceRef: {
12 type: 'object',
13 properties: {
14 attachmentId: { type: 'string' },
15 mediaType: { type: 'string' },
16 bytes: { type: 'number' },
17 width: { type: 'number' },
18 height: { type: 'number' },
19 },
20 required: ['attachmentId'],
21 },
22 saveBase64: { type: 'string' },
23 mediaType: { type: 'string' },
24 imageName: { type: 'string' },
25 },
26 required: ['sourceRef', 'saveBase64', 'mediaType'],
27 additionalProperties: false,
28 },
29 output: {
30 schema: {
31 type: 'object',
32 properties: {
33 attachment: {
34 type: 'object',
35 properties: {
36 attachmentId: { type: 'string' },
37 mediaType: { type: 'string' },
38 bytes: { type: 'number' },
39 width: { type: 'number' },
40 height: { type: 'number' },
41 },
42 required: ['attachmentId', 'mediaType', 'bytes', 'width', 'height'],
43 },
44 summary: { type: 'string' },
45 },
46 required: ['attachment', 'summary'],
47 },
48 render: (_args, value) => [
49 { type: 'text', text: value.summary },
50 { type: 'image', attachment: value.attachment },
51 ],
52 },
53 async execute(input, exec) {
54 const limits = ctx.attachments.imageLimits
55 const raw = Buffer.from(input.saveBase64, 'base64')
56 if (!limits.mediaTypes.includes(input.mediaType) || raw.byteLength > limits.maxImageBytes) {
57 throw new Error('exceeds imageLimits')
58 }
59 const readBack = await ctx.attachments.readImage(input.sourceRef, exec.signal)
60 await ctx.attachments.validateImage({
61 data: raw,
62 mediaType: input.mediaType,
63 ...(input.imageName === undefined ? {} : { name: input.imageName }),
64 })
65 const saved = await ctx.attachments.saveImage({
66 data: raw,
67 mediaType: input.mediaType,
68 name: input.imageName ?? 'studio-image',
69 })
70 const thumb = await ctx.attachments.readImageRequest(
71 saved,
72 { width: 320, height: 320, maxBytes: 98304 },
73 exec.signal,
74 )
75 return {
76 attachment: saved,
77 summary: `read=${readBack.data.byteLength} saved=${saved.attachmentId} thumb=${thumb.data.byteLength}`,
78 }
79 },
80 })
81 }
82
82 lines Plain Text