@mapomodule/mcp 1.0.0-beta.2 → 1.0.0-experimental.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/README.md +26 -24
- package/dist/build.mjs +66 -4
- package/dist/cli.mjs +8 -1
- package/dist/knowledge/api.json +1 -1
- package/dist/knowledge/docs.json +1 -1
- package/dist/module.json +1 -1
- package/dist/runtime/core/ai-setup/catalog.d.ts +0 -0
- package/dist/runtime/core/ai-setup/catalog.js +411 -0
- package/dist/runtime/core/ai-setup/index.d.ts +0 -0
- package/dist/runtime/core/ai-setup/index.js +20 -0
- package/dist/runtime/core/ai-setup/plan.d.ts +0 -0
- package/dist/runtime/core/ai-setup/plan.js +640 -0
- package/dist/runtime/core/ai-setup/questions.d.ts +0 -0
- package/dist/runtime/core/ai-setup/questions.js +237 -0
- package/dist/runtime/core/indexer.js +10 -3
- package/dist/runtime/core/instructions.js +3 -2
- package/dist/runtime/core/prompts.js +25 -1
- package/dist/runtime/core/recipes.js +408 -4
- package/dist/runtime/core/search.js +2 -1
- package/dist/runtime/core/tools/ai.d.ts +0 -0
- package/dist/runtime/core/tools/ai.js +125 -0
- package/dist/runtime/core/tools/api.js +7 -1
- package/dist/runtime/mcp/handlers/mapo/prompts/ai-setup.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/tools/ai-setup.js +3 -0
- package/package.json +1 -1
- package/src/__tests__/aiSetup.test.ts +330 -0
- package/src/__tests__/cli.test.ts +1 -0
- package/src/__tests__/composables.test.ts +95 -0
- package/src/__tests__/indexer.test.ts +19 -0
- package/src/__tests__/knowledge.test.ts +48 -0
- package/src/__tests__/overview.test.ts +11 -0
- package/src/__tests__/recipes.test.ts +69 -0
- package/src/__tests__/search.test.ts +16 -0
- package/src/__tests__/tools.test.ts +27 -1
- package/src/build/extract-components.ts +33 -5
- package/src/build/extract-composables.ts +65 -2
- package/src/cli.ts +8 -1
- package/src/runtime/core/ai-setup/catalog.ts +475 -0
- package/src/runtime/core/ai-setup/index.ts +29 -0
- package/src/runtime/core/ai-setup/plan.ts +706 -0
- package/src/runtime/core/ai-setup/questions.ts +290 -0
- package/src/runtime/core/indexer.ts +16 -4
- package/src/runtime/core/instructions.ts +3 -2
- package/src/runtime/core/prompts.ts +28 -0
- package/src/runtime/core/recipes.ts +429 -4
- package/src/runtime/core/search.ts +4 -1
- package/src/runtime/core/tools/ai.ts +209 -0
- package/src/runtime/core/tools/api.ts +8 -0
- package/src/runtime/mcp/handlers/mapo/prompts/ai-setup.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/tools/ai-setup.ts +4 -0
|
@@ -0,0 +1,706 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What `mapo_ai_setup` answers: the interview, while the developer's answers
|
|
3
|
+
* are missing, and the plan, once they are given. Both are markdown, as
|
|
4
|
+
* every tool of the server returns. The plan proposes the configuration and
|
|
5
|
+
* the files; it never holds a key, and only the tool writes the files, when
|
|
6
|
+
* asked (`write: true`).
|
|
7
|
+
*/
|
|
8
|
+
import type { MapoAppManifest } from "../../../index.js";
|
|
9
|
+
import type { WriteRequest } from "../write.js";
|
|
10
|
+
import {
|
|
11
|
+
AI_AREAS,
|
|
12
|
+
AI_NEEDS,
|
|
13
|
+
AI_TOPICS,
|
|
14
|
+
AI_VERDICTS,
|
|
15
|
+
aiTopic,
|
|
16
|
+
topicLink,
|
|
17
|
+
} from "./catalog.js";
|
|
18
|
+
import type { AiNeedId } from "./catalog.js";
|
|
19
|
+
import { AI_QUESTIONS, AI_ROUNDS } from "./questions.js";
|
|
20
|
+
import type { AiQuestion } from "./questions.js";
|
|
21
|
+
|
|
22
|
+
export const AI_PROVIDER_CHOICES = [
|
|
23
|
+
"openai",
|
|
24
|
+
"anthropic",
|
|
25
|
+
"ollama",
|
|
26
|
+
"openai-compatible",
|
|
27
|
+
"own",
|
|
28
|
+
"mock",
|
|
29
|
+
] as const;
|
|
30
|
+
export const AI_KEY_CHOICES = ["project", "assigned", "personal"] as const;
|
|
31
|
+
export const AI_MAGIC_FILL_CHOICES = [
|
|
32
|
+
"every-page",
|
|
33
|
+
"some-pages",
|
|
34
|
+
"own-panel",
|
|
35
|
+
] as const;
|
|
36
|
+
export const AI_DEPLOY_CHOICES = [
|
|
37
|
+
"single-node",
|
|
38
|
+
"several-instances",
|
|
39
|
+
"serverless",
|
|
40
|
+
] as const;
|
|
41
|
+
|
|
42
|
+
export type AiProviderChoice = (typeof AI_PROVIDER_CHOICES)[number];
|
|
43
|
+
export type AiKeyChoice = (typeof AI_KEY_CHOICES)[number];
|
|
44
|
+
|
|
45
|
+
/** The developer's answers, as `mapo_ai_setup` takes them. */
|
|
46
|
+
export interface AiSetupAnswers {
|
|
47
|
+
need?: string;
|
|
48
|
+
wants?: AiNeedId[];
|
|
49
|
+
dataMayLeave?: boolean;
|
|
50
|
+
providers?: AiProviderChoice[];
|
|
51
|
+
keys?: AiKeyChoice[];
|
|
52
|
+
userGroups?: string[];
|
|
53
|
+
userPermissions?: string[];
|
|
54
|
+
allowedFlag?: string;
|
|
55
|
+
adminGroups?: string[];
|
|
56
|
+
costs?: boolean;
|
|
57
|
+
perUserPerMinute?: number;
|
|
58
|
+
magicFill?: (typeof AI_MAGIC_FILL_CHOICES)[number];
|
|
59
|
+
instructions?: string;
|
|
60
|
+
ownFormat?: string;
|
|
61
|
+
deploy?: (typeof AI_DEPLOY_CHOICES)[number];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The arguments that answer a question: `need` alone asks the questions. */
|
|
65
|
+
const ANSWER_KEYS = [
|
|
66
|
+
"wants",
|
|
67
|
+
"dataMayLeave",
|
|
68
|
+
"providers",
|
|
69
|
+
"keys",
|
|
70
|
+
"userGroups",
|
|
71
|
+
"userPermissions",
|
|
72
|
+
"allowedFlag",
|
|
73
|
+
"adminGroups",
|
|
74
|
+
"costs",
|
|
75
|
+
"perUserPerMinute",
|
|
76
|
+
"magicFill",
|
|
77
|
+
"instructions",
|
|
78
|
+
"ownFormat",
|
|
79
|
+
"deploy",
|
|
80
|
+
] as const satisfies readonly (keyof AiSetupAnswers)[];
|
|
81
|
+
|
|
82
|
+
/** Whether the developer answered anything yet, beyond their need. */
|
|
83
|
+
export function hasAiAnswers(answers: AiSetupAnswers): boolean {
|
|
84
|
+
return ANSWER_KEYS.some((key) => {
|
|
85
|
+
const value = answers[key];
|
|
86
|
+
if (Array.isArray(value)) return value.length > 0;
|
|
87
|
+
if (typeof value === "string") return value.trim() !== "";
|
|
88
|
+
return value !== undefined;
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const CLOUD: readonly AiProviderChoice[] = ["openai", "anthropic"];
|
|
93
|
+
const LOCAL: readonly AiProviderChoice[] = ["ollama", "openai-compatible"];
|
|
94
|
+
|
|
95
|
+
/** The environment variable of a provider's project key. */
|
|
96
|
+
function keyVariable(provider: string): string {
|
|
97
|
+
const id = provider.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
|
|
98
|
+
return `NUXT_MAPO_AI_PROVIDERS_${id}_API_KEY`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The id the plan gives a provider of the app's own. */
|
|
102
|
+
const OWN_PROVIDER = "my-ai";
|
|
103
|
+
|
|
104
|
+
/** A file extension a reader can take: letters and digits. */
|
|
105
|
+
const EXTENSION = /^[a-z0-9]{1,16}$/;
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The extensions and the ids of Mapo's readers (`MAPO_READERS` of
|
|
109
|
+
* `@mapomodule/ai`): a reader of the app for one of them would take the
|
|
110
|
+
* place of Mapo's, so the plan drafts none.
|
|
111
|
+
*/
|
|
112
|
+
const MAPO_EXTENSIONS = [
|
|
113
|
+
"txt",
|
|
114
|
+
"md",
|
|
115
|
+
"markdown",
|
|
116
|
+
"json",
|
|
117
|
+
"html",
|
|
118
|
+
"htm",
|
|
119
|
+
"xhtml",
|
|
120
|
+
"csv",
|
|
121
|
+
"tsv",
|
|
122
|
+
"xlsx",
|
|
123
|
+
];
|
|
124
|
+
const MAPO_READER_IDS = ["text", "markdown", "json", "html", "csv", "xlsx"];
|
|
125
|
+
|
|
126
|
+
/** The extension `ownFormat` names, lower case and without its dot. */
|
|
127
|
+
function formatOf(answers: AiSetupAnswers): string | undefined {
|
|
128
|
+
const format = answers.ownFormat?.trim().replace(/^\./, "").toLowerCase();
|
|
129
|
+
return format || undefined;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Whether the plan may draft a reader for an extension. */
|
|
133
|
+
function isDraftable(format: string): boolean {
|
|
134
|
+
return EXTENSION.test(format) && !MAPO_EXTENSIONS.includes(format);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The id of the app's reader: its extension, unless the extension does not
|
|
139
|
+
* start with a letter, as an id must, or is the id of one of Mapo's readers.
|
|
140
|
+
*/
|
|
141
|
+
function readerIdOf(format: string): string {
|
|
142
|
+
const isId = /^[a-z]/.test(format) && !MAPO_READER_IDS.includes(format);
|
|
143
|
+
return isId ? format : `format-${format}`;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** A value of the developer's, quoted in markdown: one short line, no backticks. */
|
|
147
|
+
function quoted(value: string): string {
|
|
148
|
+
const line = value.replace(/\s+/g, " ").replace(/`/g, "'").trim();
|
|
149
|
+
return line.length > 40 ? `${line.slice(0, 40)}…` : line;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* A field of the backend's user a hook can read: a name the generated code
|
|
154
|
+
* can quote, and that cannot break out of the comment that names it.
|
|
155
|
+
*/
|
|
156
|
+
const FIELD_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
|
|
157
|
+
|
|
158
|
+
// ─── The app as it is ─────────────────────────────────────────────────────
|
|
159
|
+
|
|
160
|
+
/** What the running app already has, from its manifest. */
|
|
161
|
+
function appNotes(manifest: MapoAppManifest | null): string[] {
|
|
162
|
+
if (!manifest) {
|
|
163
|
+
return [
|
|
164
|
+
"No app is connected. With the dev server running, `mapo_inspect_app` lists the Mapo modules installed, the routes and the order of the modules.",
|
|
165
|
+
];
|
|
166
|
+
}
|
|
167
|
+
const names = manifest.modules.map((entry) => entry.name);
|
|
168
|
+
const notes = [
|
|
169
|
+
names.includes("@mapomodule/ai")
|
|
170
|
+
? "`@mapomodule/ai` is installed: `mapo.ai` is set."
|
|
171
|
+
: "`@mapomodule/ai` is not installed yet: it ships with `mapomodule` on npm's `experimental` dist-tag only (`pnpm add mapomodule@experimental`), and there setting `mapo.ai` in `nuxt.config.ts` installs it, through the meta-module.",
|
|
172
|
+
names.includes("@mapomodule/uikit")
|
|
173
|
+
? "uikit is installed: Magic Fill shows on every `MapoDetail` once the module is on."
|
|
174
|
+
: "uikit is not installed: Magic Fill needs it. `useMapoAiFill()` still fills a form in the app's own components.",
|
|
175
|
+
];
|
|
176
|
+
const hasSettings = manifest.routes.some(
|
|
177
|
+
(route) => route.path === "/ai-settings",
|
|
178
|
+
);
|
|
179
|
+
if (hasSettings)
|
|
180
|
+
notes.push("The AI settings page answers at `/ai-settings`.");
|
|
181
|
+
const ui = manifest.moduleOrder.indexOf("@nuxt/ui");
|
|
182
|
+
const mapo = manifest.moduleOrder.indexOf("mapomodule");
|
|
183
|
+
const isOrdered = ui >= 0 && mapo >= 0 && ui < mapo;
|
|
184
|
+
if (!isOrdered) {
|
|
185
|
+
notes.push(
|
|
186
|
+
"Register `@nuxt/ui` before `mapomodule` in `modules`: `mapo_doctor` checks it.",
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
return notes;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// ─── The catalog ──────────────────────────────────────────────────────────
|
|
193
|
+
|
|
194
|
+
/** Every topic, by area, each with where it is documented. */
|
|
195
|
+
function catalog(): string {
|
|
196
|
+
const areas = AI_AREAS.map((area) => {
|
|
197
|
+
const lines = AI_TOPICS.filter((topic) => topic.area === area).map(
|
|
198
|
+
(topic) => `- ${topic.title}: ${topicLink(topic)}`,
|
|
199
|
+
);
|
|
200
|
+
return `### ${area}\n\n${lines.join("\n")}`;
|
|
201
|
+
});
|
|
202
|
+
return `${areas.join("\n\n")}\n\nRead any of them with \`mapo_get_doc\`.`;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** The needs the module answers, as `wants` takes them. */
|
|
206
|
+
function needsTable(): string {
|
|
207
|
+
const rows = AI_NEEDS.map(
|
|
208
|
+
(need) =>
|
|
209
|
+
`| \`${need.id}\` | ${need.need} | ${AI_VERDICTS[need.verdict]} |`,
|
|
210
|
+
);
|
|
211
|
+
return [
|
|
212
|
+
"| `wants` | The need | The module |",
|
|
213
|
+
"| --- | --- | --- |",
|
|
214
|
+
...rows,
|
|
215
|
+
].join("\n");
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// ─── The interview ────────────────────────────────────────────────────────
|
|
219
|
+
|
|
220
|
+
function question(one: AiQuestion, index: number): string {
|
|
221
|
+
const options = one.options.map((option) => {
|
|
222
|
+
const mark = option.recommended ? " (recommended)" : "";
|
|
223
|
+
const pass = option.pass ? `\`${option.pass}\`` : "nothing to pass";
|
|
224
|
+
return ` - **${option.label}**${mark}: ${option.detail} → ${pass}`;
|
|
225
|
+
});
|
|
226
|
+
const several = one.several ? "; several may apply" : "";
|
|
227
|
+
const fills = one.fills.map((name) => `\`${name}\``).join(", ");
|
|
228
|
+
return [
|
|
229
|
+
`${index}. **${one.question}** ${one.why} (fills ${fills}${several})`,
|
|
230
|
+
...options,
|
|
231
|
+
].join("\n");
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function interview(): string {
|
|
235
|
+
const rounds = ([1, 2, 3] as const).map((round) => {
|
|
236
|
+
const lines = AI_QUESTIONS.flatMap((one, index) =>
|
|
237
|
+
one.round === round ? [question(one, index + 1)] : [],
|
|
238
|
+
);
|
|
239
|
+
return `### Round ${round}: ${AI_ROUNDS[round]}\n\n${lines.join("\n")}`;
|
|
240
|
+
});
|
|
241
|
+
return rounds.join("\n\n");
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** What `mapo_ai_setup` answers before the developer answered anything. */
|
|
245
|
+
export function renderAiSetupQuestions(
|
|
246
|
+
answers: AiSetupAnswers,
|
|
247
|
+
manifest: MapoAppManifest | null,
|
|
248
|
+
): string {
|
|
249
|
+
const need = answers.need?.trim();
|
|
250
|
+
const asked = need
|
|
251
|
+
? `## The need\n\n> ${need.replace(/\n+/g, " ")}\n\nMap it to the needs below (\`wants\`) and ask the questions: the plan then says what the module can do about it.\n\n`
|
|
252
|
+
: "";
|
|
253
|
+
return (
|
|
254
|
+
"# Set up the AI and Magic Fill\n\n" +
|
|
255
|
+
"`@mapomodule/ai` is experimental and opt-in, published with `mapomodule` on npm's `experimental` dist-tag only (`pnpm add mapomodule@experimental`): there, setting `mapo.ai` in `nuxt.config.ts` installs it. It fills records from a source (a pasted text, a web page, a sheet) through a gateway on the app's server, and the operator checks every value: the AI never saves anything by itself.\n\n" +
|
|
256
|
+
`## This app\n\n${appNotes(manifest)
|
|
257
|
+
.map((note) => `- ${note}`)
|
|
258
|
+
.join("\n")}\n\n` +
|
|
259
|
+
asked +
|
|
260
|
+
"## Questions for the developer\n\n" +
|
|
261
|
+
"Ask one round at a time, at most three questions, the recommended answer first, and wait for the answers. Then call `mapo_ai_setup` again with them: it says whether the module can do what is needed, and gives the configuration, the keys, the files and the checks.\n\n" +
|
|
262
|
+
`${interview()}\n\n` +
|
|
263
|
+
`## What the module can do\n\n${needsTable()}\n\n` +
|
|
264
|
+
`## Everything it offers\n\n${catalog()}\n`
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// ─── The plan ─────────────────────────────────────────────────────────────
|
|
269
|
+
|
|
270
|
+
/** Can the module do what the developer needs? */
|
|
271
|
+
function fit(answers: AiSetupAnswers): string {
|
|
272
|
+
const wants = [...new Set(answers.wants ?? [])];
|
|
273
|
+
if (!wants.length) {
|
|
274
|
+
return "No need was mapped to `wants` yet: ask the first round, then call again with them.";
|
|
275
|
+
}
|
|
276
|
+
const needs = AI_NEEDS.filter((need) => wants.includes(need.id));
|
|
277
|
+
const rows = needs.map((need) => {
|
|
278
|
+
const docs = need.topics
|
|
279
|
+
.map((topic) => aiTopic(topic))
|
|
280
|
+
.filter((topic) => topic !== undefined)
|
|
281
|
+
.map(topicLink)
|
|
282
|
+
.join("; ");
|
|
283
|
+
return `| ${need.need} | **${AI_VERDICTS[need.verdict]}** | ${need.how} Docs: ${docs} |`;
|
|
284
|
+
});
|
|
285
|
+
return ["| Need | The module | How |", "| --- | --- | --- |", ...rows].join(
|
|
286
|
+
"\n",
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** What does not add up in the answers. */
|
|
291
|
+
function warnings(
|
|
292
|
+
answers: AiSetupAnswers,
|
|
293
|
+
manifest: MapoAppManifest | null,
|
|
294
|
+
): string[] {
|
|
295
|
+
const providers = answers.providers ?? [];
|
|
296
|
+
const keys = answers.keys ?? [];
|
|
297
|
+
const found: string[] = [];
|
|
298
|
+
const cloud = providers.filter((one) => CLOUD.includes(one));
|
|
299
|
+
if (answers.dataMayLeave === false && cloud.length) {
|
|
300
|
+
found.push(
|
|
301
|
+
`The data must stay on the company's servers, but ${cloud.map((one) => `\`${one}\``).join(" and ")} sends it to a cloud: choose \`ollama\` or \`openai-compatible\` instead.`,
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
const onlyLocal =
|
|
305
|
+
providers.length > 0 &&
|
|
306
|
+
providers.every((one) => LOCAL.includes(one) || one === "mock");
|
|
307
|
+
if (onlyLocal && keys.some((one) => one !== "project")) {
|
|
308
|
+
found.push(
|
|
309
|
+
"Models on the company's servers need no key: an assignment of the admins still narrows the models each user gets, but personal tokens have nothing to pay for.",
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
const names = manifest?.modules.map((entry) => entry.name) ?? [];
|
|
313
|
+
const wantsMagicFill = answers.magicFill !== "own-panel";
|
|
314
|
+
if (manifest && wantsMagicFill && !names.includes("@mapomodule/uikit")) {
|
|
315
|
+
found.push(
|
|
316
|
+
"Magic Fill needs `@mapomodule/uikit`, which this app does not install: build a panel of the app's own with `useMapoAiFill()` instead.",
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
const flag = answers.allowedFlag?.trim();
|
|
320
|
+
if (flag && !FIELD_NAME.test(flag)) {
|
|
321
|
+
found.push(
|
|
322
|
+
`\`${quoted(flag)}\` is not a field name (letters, digits and \`_\`): no hook was drafted.`,
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
const format = formatOf(answers);
|
|
326
|
+
if (format && !EXTENSION.test(format)) {
|
|
327
|
+
found.push(
|
|
328
|
+
`\`${quoted(answers.ownFormat ?? "")}\` is not a file extension (letters and digits): no reader was drafted.`,
|
|
329
|
+
);
|
|
330
|
+
} else if (format && MAPO_EXTENSIONS.includes(format)) {
|
|
331
|
+
found.push(
|
|
332
|
+
`Mapo reads \`.${format}\` files already: a reader of the app would take the place of Mapo's, so none was drafted. The \`mapo-ai:read\` hook touches up what Mapo's reader reads.`,
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
return found;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** The `providers` block, one line per provider. */
|
|
339
|
+
function providerLines(providers: readonly AiProviderChoice[]): string[] {
|
|
340
|
+
return providers.map((provider) => {
|
|
341
|
+
switch (provider) {
|
|
342
|
+
case "openai":
|
|
343
|
+
return " openai: {}, // its default models; `models` narrows them, the default first";
|
|
344
|
+
case "anthropic":
|
|
345
|
+
return " anthropic: {}, // its default models; `models` narrows them, the default first";
|
|
346
|
+
case "ollama":
|
|
347
|
+
return ' ollama: { models: ["gemma4:12b"] }, // the models you pulled (`ollama list`), the default first';
|
|
348
|
+
case "openai-compatible":
|
|
349
|
+
return ' "openai-compatible": { baseURL: "http://localhost:1234/v1", models: ["qwen3-32b"] }, // your server\'s address and model ids';
|
|
350
|
+
case "own":
|
|
351
|
+
return ` "${OWN_PROVIDER}": {}, // registered with registerMapoAiProvider() in a Nitro plugin`;
|
|
352
|
+
case "mock":
|
|
353
|
+
return " mock: {}, // development and tests: no key, no network, no cost";
|
|
354
|
+
}
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** A list of strings, as TypeScript writes it. */
|
|
359
|
+
function list(values: readonly string[]): string {
|
|
360
|
+
return `[${values.map((value) => JSON.stringify(value)).join(", ")}]`;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** The `mapo.ai` block of `nuxt.config.ts`. */
|
|
364
|
+
function configBlock(answers: AiSetupAnswers): string {
|
|
365
|
+
const providers = answers.providers ?? [];
|
|
366
|
+
const keys = answers.keys ?? [];
|
|
367
|
+
const lines: string[] = [];
|
|
368
|
+
if (providers.length) {
|
|
369
|
+
lines.push(" providers: {", ...providerLines(providers), " },");
|
|
370
|
+
} else {
|
|
371
|
+
lines.push(
|
|
372
|
+
" providers: {}, // none yet: `run` answers 503 until one is enabled",
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
const users = [
|
|
376
|
+
...(answers.userGroups?.length
|
|
377
|
+
? [`groups: ${list(answers.userGroups)}`]
|
|
378
|
+
: []),
|
|
379
|
+
...(answers.userPermissions?.length
|
|
380
|
+
? [`permissions: ${list(answers.userPermissions)}`]
|
|
381
|
+
: []),
|
|
382
|
+
];
|
|
383
|
+
if (users.length) lines.push(` users: { ${users.join(", ")} },`);
|
|
384
|
+
if (answers.adminGroups?.length) {
|
|
385
|
+
lines.push(` admin: { groups: ${list(answers.adminGroups)} },`);
|
|
386
|
+
}
|
|
387
|
+
const rules = answers.instructions?.trim();
|
|
388
|
+
if (rules) {
|
|
389
|
+
lines.push(` instructions: { all: ${JSON.stringify(rules)} },`);
|
|
390
|
+
}
|
|
391
|
+
if (answers.perUserPerMinute !== undefined) {
|
|
392
|
+
lines.push(
|
|
393
|
+
` limits: { perUserPerMinute: ${answers.perUserPerMinute} },`,
|
|
394
|
+
);
|
|
395
|
+
}
|
|
396
|
+
const assigns = keys.includes("assigned") || keys.includes("personal");
|
|
397
|
+
if (assigns) {
|
|
398
|
+
lines.push(
|
|
399
|
+
' settings: { usersApi: "/api/users/", groupsApi: "/api/groups/" }, // adjust: your backend\'s users and groups, which the admins search',
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
if (answers.magicFill === "own-panel") {
|
|
403
|
+
lines.push(" magicFill: false, // the app's own panel instead");
|
|
404
|
+
}
|
|
405
|
+
return [
|
|
406
|
+
"```ts",
|
|
407
|
+
"// nuxt.config.ts",
|
|
408
|
+
"export default defineNuxtConfig({",
|
|
409
|
+
' modules: ["@nuxt/ui", "mapomodule"], // @nuxt/ui first',
|
|
410
|
+
" mapo: {",
|
|
411
|
+
" ai: {",
|
|
412
|
+
...lines,
|
|
413
|
+
" },",
|
|
414
|
+
" },",
|
|
415
|
+
"});",
|
|
416
|
+
"```",
|
|
417
|
+
].join("\n");
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** The environment's variables: their names, never a value. */
|
|
421
|
+
function environmentBlock(answers: AiSetupAnswers): string {
|
|
422
|
+
const providers = answers.providers ?? [];
|
|
423
|
+
const keys = answers.keys ?? [];
|
|
424
|
+
const lines = [
|
|
425
|
+
"# .env in development, the server's environment in production; never in nuxt.config.ts",
|
|
426
|
+
"NUXT_MAPO_AI_SECRET= # openssl rand -base64 32: the same on every instance",
|
|
427
|
+
];
|
|
428
|
+
const projectKeys = keys.length === 0 || keys.includes("project");
|
|
429
|
+
for (const provider of providers) {
|
|
430
|
+
if (CLOUD.includes(provider) && projectKeys) {
|
|
431
|
+
lines.push(`${keyVariable(provider)}= # the project's key`);
|
|
432
|
+
}
|
|
433
|
+
if (provider === "own") {
|
|
434
|
+
lines.push(
|
|
435
|
+
`${keyVariable(OWN_PROVIDER)}= # its key, if it declares one`,
|
|
436
|
+
);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
if (providers.includes("ollama")) {
|
|
440
|
+
lines.push(
|
|
441
|
+
"# NUXT_MAPO_AI_PROVIDERS_OLLAMA_BASE_URL= # when Ollama is not at http://localhost:11434",
|
|
442
|
+
);
|
|
443
|
+
}
|
|
444
|
+
if (providers.includes("openai-compatible")) {
|
|
445
|
+
lines.push(
|
|
446
|
+
"# NUXT_MAPO_AI_PROVIDERS_OPENAI_COMPATIBLE_BASE_URL= # the server's address in production",
|
|
447
|
+
);
|
|
448
|
+
}
|
|
449
|
+
return ["```bash", ...lines, "```"].join("\n");
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** Where the key of each call comes from, for these answers. */
|
|
453
|
+
function keysSection(answers: AiSetupAnswers): string {
|
|
454
|
+
const providers = answers.providers ?? [];
|
|
455
|
+
const keys = answers.keys ?? [];
|
|
456
|
+
const lines = [
|
|
457
|
+
"A call uses the key nearest its user: their own token where an assignment allows it, else the key the admins assigned to them, to their group (in the order the admins set) or to everyone, else the project's key. `status` tells each user which level their key comes from and its last four characters, never the key.",
|
|
458
|
+
];
|
|
459
|
+
if (keys.length === 0 || keys.includes("project")) {
|
|
460
|
+
lines.push(
|
|
461
|
+
"- **The project's key** goes in the server's environment only. A key written in `nuxt.config.ts` is copied into the server bundle: the module warns about it.",
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
if (keys.includes("assigned")) {
|
|
465
|
+
lines.push(
|
|
466
|
+
"- **The admins' keys**: on the AI settings page (`/ai-settings`, Keys) an admin assigns a key and the models to everyone, a group or a user, and orders the groups; a user in two groups gets the higher one's. Nothing to deploy.",
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
if (keys.includes("personal")) {
|
|
470
|
+
lines.push(
|
|
471
|
+
"- **Personal tokens** are off until an assignment allows them; then each user saves theirs on the AI settings page, and pays for their own calls.",
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
if (providers.some((one) => LOCAL.includes(one))) {
|
|
475
|
+
lines.push(
|
|
476
|
+
"- **Models on the company's servers** need no key; the token of a proxy in front of them is their project key (`NUXT_MAPO_AI_PROVIDERS_OLLAMA_API_KEY`, `NUXT_MAPO_AI_PROVIDERS_OPENAI_COMPATIBLE_API_KEY`).",
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
lines.push(
|
|
480
|
+
"- **The secret** seals every key, token and setting the admins save: without `NUXT_MAPO_AI_SECRET` in production the storage stays closed and `run` answers 503. Changing it makes what was saved unreadable.",
|
|
481
|
+
);
|
|
482
|
+
const [intro, ...rest] = lines;
|
|
483
|
+
return `${intro}\n\n${rest.join("\n")}`;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** How to keep the tokens a call spends, and their cost, in check. */
|
|
487
|
+
function tokensSection(answers: AiSetupAnswers): string {
|
|
488
|
+
const providers = answers.providers ?? [];
|
|
489
|
+
const lines = [
|
|
490
|
+
"Every call is audited with its tokens. What a call spends grows with the form (the fields the AI may fill), the source and the instructions, and with the model.",
|
|
491
|
+
"- **The usage**: the AI settings page sums it by user, model and day; the admins read everyone's, each user their own.",
|
|
492
|
+
];
|
|
493
|
+
if (answers.costs !== false) {
|
|
494
|
+
const priced = providers.filter((one) => CLOUD.includes(one));
|
|
495
|
+
const example = priced.length ? priced[0] : "openai";
|
|
496
|
+
lines.push(
|
|
497
|
+
`- **The costs**: \`mapo.ai.prices\` turns tokens into money, with your contract's prices per million tokens; Mapo keeps no price list:\n\n \`\`\`ts\n prices: {\n currency: "USD",\n providers: {\n ${example}: {\n // "<model>": { input: …, output: … }, your prices per million tokens,\n // with cacheRead and cacheWrite where the prompt cache is on\n },\n },\n },\n \`\`\``,
|
|
498
|
+
);
|
|
499
|
+
}
|
|
500
|
+
lines.push(
|
|
501
|
+
`- **The limits**: \`limits.perUserPerMinute\` (${answers.perUserPerMinute ?? 20} calls), \`maxSourceChars\` (100,000) and \`maxFileBytes\` (10 MB). Each server process counts its own calls. There is no spending cap per month yet.`,
|
|
502
|
+
);
|
|
503
|
+
if (providers.some((one) => CLOUD.includes(one))) {
|
|
504
|
+
lines.push(
|
|
505
|
+
'- **Spend less**: an efficient model for everyday forms, listed first in `models`; `effort` stays `"low"`, since the reasoning is paid as written tokens; `promptCache: true` pays less for the part of the prompt that repeats; keep the forms\' fields that need no AI out with `ai: { exclude: true }`.',
|
|
506
|
+
);
|
|
507
|
+
}
|
|
508
|
+
if (providers.some((one) => LOCAL.includes(one))) {
|
|
509
|
+
lines.push(
|
|
510
|
+
"- **Models on the company's servers** cost nothing per token: the usage still counts their tokens, and the hardware decides how long a call takes.",
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
const [intro, ...rest] = lines;
|
|
514
|
+
return `${intro}\n\n${rest.join("\n")}`;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** What the forms need, for these answers. */
|
|
518
|
+
function formsSection(answers: AiSetupAnswers): string {
|
|
519
|
+
const lines: string[] = [];
|
|
520
|
+
if (answers.magicFill === "own-panel") {
|
|
521
|
+
lines.push(
|
|
522
|
+
"- **A panel of the app's own**: `mapo.ai.magicFill: false`, then `useMapoAiFill(detail)` in a detail extension sends the form and the source to `run` and marks every value for the operator; `useMapoAiRead()` reads a file.",
|
|
523
|
+
);
|
|
524
|
+
} else {
|
|
525
|
+
lines.push(
|
|
526
|
+
'- **Magic Fill** shows on every `MapoDetail`: "Fill with AI" in the sidebar card, and a banner above the form that previews every value; "Next to check" takes the operator to each one that waits.',
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
if (answers.magicFill === "some-pages") {
|
|
530
|
+
lines.push(
|
|
531
|
+
"- **Pages without it**: `definePageMeta({ magicFill: false })`; `{ magicFill: { evidence: false } }` asks the AI for no quotes, so every value waits.",
|
|
532
|
+
);
|
|
533
|
+
}
|
|
534
|
+
lines.push(
|
|
535
|
+
"- **Drafts**: on a `MapoDetail` with `draft`, the session comes back after a reload, with Restore.",
|
|
536
|
+
'- **The fields** take an `ai` option:\n\n ```ts\n { key: "excerpt", type: "textarea", label: "Excerpt", ai: { hint: "One or two sentences, in the source\'s own words." } },\n { key: "internal_notes", type: "textarea", label: "Internal notes", ai: { exclude: true } },\n { key: "contact", type: "fks", label: "Contact", attrs: { endpoint: "/api/users/", itemText: "email" }, ai: { list: false } },\n ```\n\n `hint` guides the model; `exclude` keeps the field from the AI; `list: false` never lists a relation\'s records for it, which then searches the name it reads. Fields named as secrets, read-only fields and media stay out by themselves.',
|
|
537
|
+
);
|
|
538
|
+
return lines.join("\n");
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** The files of the app the answers call for. */
|
|
542
|
+
export function aiSetupFiles(answers: AiSetupAnswers): WriteRequest[] {
|
|
543
|
+
const files: WriteRequest[] = [];
|
|
544
|
+
const flag = answers.allowedFlag?.trim();
|
|
545
|
+
if (flag && FIELD_NAME.test(flag)) {
|
|
546
|
+
files.push({
|
|
547
|
+
path: "server/plugins/mapo-ai-access.ts",
|
|
548
|
+
content: `// The AI only for the users the backend marks with \`${flag}\`: the gateway
|
|
549
|
+
// asks the backend who is signed in, and this hook refuses the others, after
|
|
550
|
+
// mapo.ai.users. A hook can only refuse: it never lets a user in.
|
|
551
|
+
export default defineNitroPlugin((nitroApp) => {
|
|
552
|
+
nitroApp.hooks.hook("mapo-ai:user", (context) => {
|
|
553
|
+
if (context.payload[${JSON.stringify(flag)}] !== true) context.allowed = false;
|
|
554
|
+
});
|
|
555
|
+
});
|
|
556
|
+
`,
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
const format = formatOf(answers);
|
|
560
|
+
if (format && isDraftable(format)) {
|
|
561
|
+
files.push({
|
|
562
|
+
path: "server/plugins/mapo-ai-readers.ts",
|
|
563
|
+
content: `// A reader of .${format} files for the AI: read() turns a file into the text
|
|
564
|
+
// the AI gets. Decoding the bytes as text is a start: write what your format
|
|
565
|
+
// needs. Return [] for a file that holds no text.
|
|
566
|
+
export default defineNitroPlugin(() => {
|
|
567
|
+
registerMapoAiReader({
|
|
568
|
+
id: ${JSON.stringify(readerIdOf(format))},
|
|
569
|
+
label: ${JSON.stringify(`${format.toUpperCase()} file`)},
|
|
570
|
+
extensions: [${JSON.stringify(format)}],
|
|
571
|
+
read(file) {
|
|
572
|
+
const text = new TextDecoder().decode(file.bytes).trim();
|
|
573
|
+
return text ? [{ kind: "text", text, name: file.name }] : [];
|
|
574
|
+
},
|
|
575
|
+
});
|
|
576
|
+
});
|
|
577
|
+
`,
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
const shared =
|
|
581
|
+
answers.deploy === "several-instances" || answers.deploy === "serverless";
|
|
582
|
+
if (shared) {
|
|
583
|
+
files.push({
|
|
584
|
+
path: "server/plugins/mapo-ai-storage.ts",
|
|
585
|
+
content: `// The AI's sealed state in Redis, shared by every instance, which need the
|
|
586
|
+
// same NUXT_MAPO_AI_SECRET too. The address comes from the environment, so
|
|
587
|
+
// the driver is mounted when the server starts, in place of the module's
|
|
588
|
+
// file-system default, which stays in development without REDIS_URL. The
|
|
589
|
+
// redis driver of unstorage needs \`ioredis\` in the app.
|
|
590
|
+
import redisDriver from "unstorage/drivers/redis";
|
|
591
|
+
|
|
592
|
+
export default defineNitroPlugin(async () => {
|
|
593
|
+
const url = process.env.REDIS_URL;
|
|
594
|
+
if (!url) {
|
|
595
|
+
if (import.meta.dev) return;
|
|
596
|
+
throw new Error("REDIS_URL is not set: the AI's state needs the shared store");
|
|
597
|
+
}
|
|
598
|
+
const storage = useStorage();
|
|
599
|
+
await storage.unmount("mapo-ai");
|
|
600
|
+
storage.mount("mapo-ai", redisDriver({ url }));
|
|
601
|
+
});
|
|
602
|
+
`,
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
return files;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** Where the state lives in production, for these answers. */
|
|
609
|
+
function productionSection(answers: AiSetupAnswers): string {
|
|
610
|
+
const lines = [
|
|
611
|
+
"- **The secret** in the server's environment, 32 characters or more, made by a generator: the storage never keeps anything in clear.",
|
|
612
|
+
];
|
|
613
|
+
switch (answers.deploy) {
|
|
614
|
+
case "several-instances":
|
|
615
|
+
lines.push(
|
|
616
|
+
"- **Several instances** share one store, here Redis: the plugin above, `REDIS_URL` in the environment and `ioredis` installed in the app. In development without `REDIS_URL` the file system stays; in production the server does not start without it. They share the secret too, and each process counts the calls per minute for itself.",
|
|
617
|
+
);
|
|
618
|
+
break;
|
|
619
|
+
case "serverless":
|
|
620
|
+
lines.push(
|
|
621
|
+
"- **Serverless**: a function's file system does not last, so the state goes to a driver. On functions that run Node (the `vercel`, `netlify` and `aws-lambda` presets) the Redis plugin above does it, with `REDIS_URL` and `ioredis` installed. An edge runtime (Cloudflare Workers and the like) has no TCP for Redis: mount a driver that works over HTTP instead, such as Upstash's or Cloudflare KV, the same way.",
|
|
622
|
+
);
|
|
623
|
+
break;
|
|
624
|
+
default:
|
|
625
|
+
lines.push(
|
|
626
|
+
"- **One Node server**: the state goes to `.data/mapo-ai` where the server starts; in a container, put it on a persistent volume, or every deploy loses the keys and the usage.",
|
|
627
|
+
);
|
|
628
|
+
}
|
|
629
|
+
lines.push(
|
|
630
|
+
"- **The audit** keeps each call's metadata for 90 days (`audit.retentionDays`), never the source, the instructions or the values.",
|
|
631
|
+
);
|
|
632
|
+
return lines.join("\n");
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/** The questions still unanswered, and what the plan assumed for each. */
|
|
636
|
+
function stillToAsk(answers: AiSetupAnswers): string[] {
|
|
637
|
+
const missing: [boolean, string, string][] = [
|
|
638
|
+
[!answers.wants?.length, "task", "no need mapped yet"],
|
|
639
|
+
[
|
|
640
|
+
answers.dataMayLeave === undefined,
|
|
641
|
+
"data",
|
|
642
|
+
"nothing about where the data may go",
|
|
643
|
+
],
|
|
644
|
+
[
|
|
645
|
+
!answers.providers?.length,
|
|
646
|
+
"providers",
|
|
647
|
+
"no provider, so `run` answers 503",
|
|
648
|
+
],
|
|
649
|
+
[!answers.keys?.length, "keys", "the project's key"],
|
|
650
|
+
[
|
|
651
|
+
answers.costs === undefined && answers.perUserPerMinute === undefined,
|
|
652
|
+
"tokens",
|
|
653
|
+
"the usage with costs, 20 calls per minute",
|
|
654
|
+
],
|
|
655
|
+
[
|
|
656
|
+
answers.magicFill === undefined,
|
|
657
|
+
"forms",
|
|
658
|
+
"Magic Fill on every detail page",
|
|
659
|
+
],
|
|
660
|
+
[
|
|
661
|
+
answers.deploy === undefined,
|
|
662
|
+
"deploy",
|
|
663
|
+
"one Node server with a lasting disk",
|
|
664
|
+
],
|
|
665
|
+
];
|
|
666
|
+
return missing.flatMap(([isMissing, id, assumed]) => {
|
|
667
|
+
const one = AI_QUESTIONS.find((asked) => asked.id === id);
|
|
668
|
+
if (!isMissing || !one) return [];
|
|
669
|
+
return [`- Round ${one.round}: "${one.question}" (assumed: ${assumed})`];
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** What `mapo_ai_setup` answers once the developer answered. */
|
|
674
|
+
export function renderAiSetupPlan(
|
|
675
|
+
answers: AiSetupAnswers,
|
|
676
|
+
manifest: MapoAppManifest | null,
|
|
677
|
+
files: string,
|
|
678
|
+
): string {
|
|
679
|
+
const need = answers.need?.trim();
|
|
680
|
+
const found = warnings(answers, manifest);
|
|
681
|
+
const missing = stillToAsk(answers);
|
|
682
|
+
return (
|
|
683
|
+
"# The AI for this backoffice: the plan\n\n" +
|
|
684
|
+
(need ? `> ${need.replace(/\n+/g, " ")}\n\n` : "") +
|
|
685
|
+
`## Can the module do it?\n\n${fit(answers)}\n\n` +
|
|
686
|
+
(found.length
|
|
687
|
+
? `## Check these first\n\n${found.map((one) => `- ${one}`).join("\n")}\n\n`
|
|
688
|
+
: "") +
|
|
689
|
+
`## This app\n\n${appNotes(manifest)
|
|
690
|
+
.map((note) => `- ${note}`)
|
|
691
|
+
.join("\n")}\n\n` +
|
|
692
|
+
`## 1. The configuration\n\nMerge it into the app's \`nuxt.config.ts\` (this tool never edits it):\n\n${configBlock(answers)}\n\n` +
|
|
693
|
+
`## 2. The environment\n\nThe names only: the values never go in a file of the repository.\n\n${environmentBlock(answers)}\n\n` +
|
|
694
|
+
`## 3. Keys and tokens\n\n### Where each call's key comes from\n\n${keysSection(answers)}\n\n### The tokens a call spends\n\n${tokensSection(answers)}\n\n` +
|
|
695
|
+
`## 4. The forms\n\n${formsSection(answers)}\n\n` +
|
|
696
|
+
`## 5. Files of the app\n\n${files}\n\n` +
|
|
697
|
+
`## 6. Production\n\n${productionSection(answers)}\n\n` +
|
|
698
|
+
"## 7. Check it\n\n" +
|
|
699
|
+
"1. Restart the dev server: a new module and new server plugins need it.\n" +
|
|
700
|
+
"2. Signed in, `GET /_mapo/ai/status`: `allowed`, the providers and models each user gets, and where their key comes from.\n" +
|
|
701
|
+
"3. Open `/ai-settings`: the preference, the connection check, and for the admins the keys, how the AI works and the usage.\n" +
|
|
702
|
+
'4. On a detail page, "Fill with AI": paste a text, Extract, check the values in the banner, Save.\n' +
|
|
703
|
+
"5. `mapo_doctor` for anything that looks misconfigured.\n" +
|
|
704
|
+
(missing.length ? `\n## Still to ask\n\n${missing.join("\n")}\n` : "")
|
|
705
|
+
);
|
|
706
|
+
}
|