All files / app/mods/ai neo-banana.ts

100% Statements 4/4
100% Branches 0/0
100% Functions 0/0
100% Lines 4/4

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215124x       124x                                                                                                                                                                                                                                                                                                                                                                                       124x                                     124x      
import { DateTime } from 'luxon';
import { Plugin } from '../../model/plugin';
import { Mod } from '../../model/tag';
 
export const neoQueryPlugin: Plugin = {
  tag: 'plugin/delta/neo',
  name: $localize`🍌️💭️ Ask Neo Banana`,
  config: {
    mod: $localize`🍌️ Neo Banana`,
    version: 2,
    type: 'tool',
    default: false,
    add: true,
    signature: '+plugin/delta/neo',
    reply: ['plugin/delta/neo'],
    generated: $localize`Generated by jasper-ui ${DateTime.now().toISO()}`,
    description: $localize`Generate an image with Neo Banana.`,
    aiInstructions: `# plugin/delta/neo
    The Neo Banana image generator responds to Refs tagged plugin/delta/neo and signs generated images with +plugin/delta/neo.
    When asked to create or edit an image, forward the request by creating a separate Ref tagged plugin/delta/neo. Put the complete image prompt in that Ref's comment and use a temporary URL such as add:1. Do not claim to have generated the image yourself.
    In the first response Ref, embed the generated response using:
    ![](/tag/+plugin/delta/neo?view=plugin/image&filter=responses/add:1&filter=query/plugin/image&pageSize=1&cols=1)
    The temporary URL and matching query reference will be rewritten together. Preserve requested public and topical tags on the prompt Ref. Neo Banana returns one or more plugin/image response Refs sourced to the prompt.
`,
    icons: [{ thumbnail: $localize`🍌️`, order: -1 }],
    advancedActions: [
      { tag: 'plugin/delta/neo', labelOff: $localize`ask neo banana`, global: true },
    ],
    timeoutMs: 300_000,
    language: 'javascript',
    subDiff: ['script'],
    adminForm: [{
      key: 'script',
      type: 'code',
      props: {
        label: $localize`Script:`,
        language: 'javascript',
      },
    }],
    // language=JavaScript
    script: `
      const axios = require('axios');
      const { Buffer } = require('node:buffer');
      const { GoogleGenAI, Modality } = require('@google/genai');
      const ref = JSON.parse(require('fs').readFileSync(0, 'utf-8'));
      const origin = ref.origin || '';
      const config = ref.plugins?.['plugin/delta/neo'] || {};
      const uniq = (value, index, array) => array.indexOf(value) === index;
      const apiKey = (await axios.get(process.env.JASPER_API + '/api/v1/ref/page', {
        headers: {
          'Local-Origin': origin || 'default',
          'User-Role': 'ROLE_ADMIN',
        },
        params: {
          query: (config.apiKeyTag || '+plugin/secret/gemini') + (origin || '@'),
          size: 1,
        },
      }).catch(e => {
        console.error(e.response?.data || e.message);
        throw e;
      })).data.content[0]?.comment;
      if (!apiKey) throw new Error('Gemini API key not found.');
      const prompt = [ref.title, ref.comment]
        .filter(Boolean)
        .join(ref.title && ref.comment ? ': ' : '');
      if (!prompt) throw new Error('Neo Banana prompt is empty.');
      const ai = new GoogleGenAI({ apiKey });
      const result = await ai.models.generateContent({
        model: config.model || 'gemini-3.1-flash-image',
        contents: prompt,
        config: {
          responseModalities: [Modality.TEXT, Modality.IMAGE],
          imageConfig: {
            aspectRatio: config.aspectRatio || '1:1',
            imageSize: config.imageSize || '1K',
          },
        },
      });
      const parts = result.candidates?.[0]?.content?.parts || [];
      const description = parts
        .filter(part => part.text)
        .map(part => part.text)
        .join('\\n')
        .trim();
      const images = parts.filter(part => part.inlineData?.data);
      if (!images.length) {
        throw new Error(description || 'Neo Banana returned no images.');
      }
      let tags = ['+plugin/delta/neo', '_plugin/cache', 'plugin/image', 'plugin/thumbnail', 'plugin/alt'];
      if (ref.tags?.includes('public')) tags.push('public');
      if (ref.tags?.includes('internal')) tags.push('internal');
      if (ref.tags?.includes('dm')) tags.push('dm', 'internal', 'plugin/thread');
      if (ref.tags?.includes('plugin/comment')) tags.push('plugin/comment', 'internal');
      if (ref.tags?.includes('plugin/thread')) tags.push('plugin/thread', 'internal');
      const authors = ref.tags?.filter(tag => tag === '+user' || tag === '_user' || tag.startsWith('+user/') || tag.startsWith('_user/')) || [];
      const aiTags = ref.tags?.filter(tag => tag.startsWith('+plugin/delta/ai/')) || [];
      const mailboxes = ref.tags?.filter(tag => tag.startsWith('plugin/inbox') || tag.startsWith('plugin/outbox')) || [];
      tags.push(...mailboxes, ...authors.map(tag => 'plugin/inbox/' + tag.substring(1)), ...aiTags.map(tag => tag.substring(1)));
      tags = tags.filter(uniq);
      const sources = [ref.url];
      if (ref.sources && (ref.tags?.includes('plugin/thread') || ref.tags?.includes('plugin/comment'))) {
        sources.push(ref.sources[1] || ref.sources[0] || ref.url);
      } else {
        sources.push(ref.url);
      }
      const refs = [];
      for (const part of images) {
        const mime = part.inlineData.mimeType || 'image/png';
        const cache = (await axios.post(
          process.env.JASPER_API + '/pub/api/v1/repl/cache',
          Buffer.from(part.inlineData.data, 'base64'),
          {
            headers: {
              'Local-Origin': origin || 'default',
              'User-Role': 'ROLE_ADMIN',
              'User-Tag': '+plugin/delta/neo',
              'Content-Type': mime,
            },
            params: { origin, mime },
          }
        ).catch(e => {
          console.error(e.response?.data || e.message);
          throw e;
        })).data;
        delete cache.metadata;
        refs.push({
          ...cache,
          title: ref.title,
          comment: description || prompt,
          sources,
          tags,
          plugins: {
            ...cache.plugins,
          },
        });
      }
      console.log(JSON.stringify({ ref: refs }));
    `,
    advancedForm: [{
      key: 'apiKeyTag',
      type: 'tag',
      props: {
        label: $localize`🔑️ API Key Tag:`,
      },
    }, {
      key: 'model',
      type: 'string',
      props: {
        label: $localize`Model:`,
      },
    }, {
      key: 'aspectRatio',
      type: 'select',
      props: {
        label: $localize`Aspect Ratio:`,
        options: [
          { value: '1:1', label: $localize`Square` },
          { value: '16:9', label: $localize`Landscape` },
          { value: '9:16', label: $localize`Portrait` },
          { value: '4:3', label: $localize`Landscape 4:3` },
          { value: '3:4', label: $localize`Portrait 3:4` },
        ],
      },
    }, {
      key: 'imageSize',
      type: 'select',
      props: {
        label: $localize`Image Size:`,
        options: [
          { value: '1K', label: $localize`1K` },
          { value: '2K', label: $localize`2K` },
          { value: '4K', label: $localize`4K` },
        ],
      },
    }],
  },
  defaults: {
    apiKeyTag: '+plugin/secret/gemini',
    model: 'gemini-3.1-flash-image',
    aspectRatio: '1:1',
    imageSize: '1K',
  },
  schema: {
    optionalProperties: {
      apiKeyTag: { type: 'string' },
      model: { type: 'string' },
      aspectRatio: { type: 'string' },
      imageSize: { type: 'string' },
    },
  },
};
 
export const neoPlugin: Plugin = {
  tag: '+plugin/delta/neo',
  name: $localize`🍌️ Neo Banana`,
  config: {
    mod: $localize`🍌️ Neo Banana`,
    version: 1,
    type: 'tool',
    default: false,
    genId: true,
    submit: $localize`🍌️💭️`,
    submitDm: true,
    signature: '+plugin/delta/neo',
    reply: ['plugin/delta/neo'],
    generated: $localize`Generated by jasper-ui ${DateTime.now().toISO()}`,
    icons: [{ thumbnail: $localize`🍌️`, order: 1 }],
    description: $localize`Neo Banana image-generation signature tag.`,
  },
};
 
export const neoMod: Mod = {
  plugin: [neoQueryPlugin, neoPlugin],
};