1
0
Fork 0

Compare commits

..

No commits in common. "c0167ac44b28d7e1b2ba608a79f7b78552e2eb52" and "d82e8057ba25fb3e61f34a15c45f0645e153565c" have entirely different histories.

6 changed files with 48 additions and 329 deletions

View file

@ -1,17 +1,5 @@
# Changelog
# v0.12.10
### Improvements
- **Ordnance Disposal.** Matches are now synced live between everyone in the same game, so you see the other technicians moving as it happens instead of waiting on periodic refreshes.
### Fixes
- Various bug fixes and improvements.
---
# v0.12.9
### Improvements

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.12.10",
"version": "0.12.9",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",

View file

@ -1,124 +0,0 @@
/**
* The single output contract shared by every AI Compose generation.
*
* The plugin builds a richText system prompt that asks the model for lexical
* JSON and injects a blog layout of `[paragraph]` / `[heading]` markers, while
* the same field's instruction asks for plain prose with "no markdown, no
* lists, no headings". Both reach the model in one request, and it answers by
* arguing about the conflict (which the handler then saves as the first
* paragraph of the field).
*
* Every field now follows one rule instead: the model is asked for plain prose
* and nothing else, and the application assembles the JSON the Compose client
* parses. `AI_OUTPUT_RULES` is appended to every generation; the helpers below
* decide what prose is wrapped into for a given field schema.
*/
export const AI_OUTPUT_RULES = `OUTPUT RULES:
Respond with plain prose only. Do not output JSON, code fences, schema definitions, or layout markers.
Ordinary sentences and paragraphs are the entire expected output; the application converts them into the editor's format.
CRITICAL:
Never use em-dashes (\u2014) in your writing. Avoid obvious AI tells.`;
/**
* The plugin's block-placeholder paragraph. Preserved embed blocks are replaced
* with `[[[BLOCK_<n>]]]` tokens before generation and swapped back afterwards, so
* the model has to echo the tokens verbatim for the blocks to survive. It is the
* only instruction from the plugin's richText system worth keeping.
*/
const BLOCK_PLACEHOLDER_INSTRUCTION =
/- The text may contain one or more standalone placeholder tokens[\s\S]*?surrounding text\./;
export const extractBlockPlaceholderInstruction = (pluginSystem?: string): string => {
if (!pluginSystem) return "";
const match = pluginSystem.match(BLOCK_PLACEHOLDER_INSTRUCTION);
return match ? match[0].trim() : "";
};
export const buildComposeSystem = ({
pluginSystem,
fieldType,
}: {
pluginSystem?: string;
fieldType?: string;
}): string => {
const parts: string[] = [];
if (fieldType === "richText") {
const blockInstruction = extractBlockPlaceholderInstruction(pluginSystem);
if (blockInstruction) parts.push(blockInstruction);
}
parts.push(AI_OUTPUT_RULES);
return parts.join("\n\n");
};
type JsonSchemaLike = {
definitions?: unknown;
properties?: Record<string, { type?: string } | undefined>;
};
export type ProseShape = { kind: "lexical" } | { kind: "field"; key: string };
/**
* Whether a generation schema is one this module knows how to fill with prose:
* the lexical editor schema for richText (identified by its `definitions`), or
* a single string property for text/textarea. Anything else (e.g. a hasMany
* array) is left to the handler's structured fallback.
*/
export const resolveProseShape = (schema: unknown): ProseShape | null => {
if (!schema || typeof schema !== "object") return null;
const candidate = schema as JsonSchemaLike;
if (candidate.definitions) return { kind: "lexical" };
const keys = Object.keys(candidate.properties ?? {});
if (keys.length !== 1) return null;
const property = candidate.properties?.[keys[0]];
if (property?.type !== "string") return null;
return { kind: "field", key: keys[0] };
};
export const wrapProse = (shape: ProseShape, text: string): Record<string, unknown> =>
shape.kind === "lexical" ? plainTextToLexicalJson(text) : { [shape.key]: text };
export function plainTextToLexicalJson(text: string): Record<string, unknown> {
const paragraphs = text.split(/\n\n+/).filter((p) => p.trim());
const children = paragraphs.map((para) => ({
type: "paragraph",
children: [
{
type: "text",
text: para.trim(),
format: 0,
style: "",
mode: "normal",
detail: 0,
direction: "ltr",
indent: 0,
version: 1,
},
],
direction: "ltr",
format: "start",
indent: 0,
textFormat: 0,
textStyle: "",
version: 1,
}));
return {
root: {
type: "root",
children,
direction: "ltr",
format: "",
indent: 0,
version: 1,
},
};
}

View file

@ -6597,9 +6597,6 @@ export interface PluginAiInstruction {
system?: string | null;
layout?: string | null;
'ornith-9b-settings'?: {
/**
* Leave blank to use the UNSLOTH_MODEL environment variable.
*/
model?: string | null;
};
updatedAt: string;

View file

@ -109,7 +109,6 @@ import type { SeedPromptFunction } from "@ai-stack/payloadcms/types";
import { mcpPlugin } from "@payloadcms/plugin-mcp";
import { formBuilderPlugin } from "@payloadcms/plugin-form-builder";
import { surveyFormBuilderConfig } from "@/lib/surveys/formBuilderConfig";
import { buildComposeSystem, resolveProseShape, wrapProse } from "@/lib/ai/composeSystem";
import { createOpenAI } from "@ai-sdk/openai";
import { createTextStreamResponse, jsonSchema, streamObject } from "ai";
@ -211,7 +210,7 @@ const staticAiPrompt = (
: `Suggest a single fitting title for the ${noun} {{ title }}. Reply with the title only, no explanation.`;
default:
if (fieldType === "richText") {
return `Write long-form content for the "${fieldLabel}" section of the ${noun} {{ title }}. Several paragraphs of plain prose with an opening, supporting detail, and a closing sentence.`;
return `Write long-form content for the "${fieldLabel}" section of the ${noun} {{ title }}. Structured prose with an introduction, clear sections, and a conclusion.`;
}
return `Write suitable content for the "${fieldLabel}" of the ${noun} {{ title }}. Plain prose, concise and relevant.`;
}
@ -238,6 +237,44 @@ const aiFieldSeedPrompts: SeedPromptFunction = ({ path, fieldType, fieldLabel })
return false;
};
function plainTextToLexicalJson(text: string): Record<string, unknown> {
const paragraphs = text.split(/\n\n+/).filter((p) => p.trim());
const children = paragraphs.map((para) => ({
type: "paragraph",
children: [
{
type: "text",
text: para.trim(),
format: 0,
style: "",
mode: "normal",
detail: 0,
direction: "ltr",
indent: 0,
version: 1,
},
],
direction: "ltr",
format: "start",
indent: 0,
textFormat: 0,
textStyle: "",
version: 1,
}));
return {
root: {
type: "root",
children,
direction: "ltr",
format: "",
indent: 0,
version: 1,
},
};
}
// Gemma tends to answer schema-y prompts with fenced JSON blobs. The plain-text
// fallback is meant to produce prose that plainTextToLexicalJson wraps into
// paragraphs, so strip any markdown code fences before using the output.
@ -247,19 +284,7 @@ const stripCodeFences = (text: string): string =>
.replace(/\n?```\s*$/, "")
.trim();
type PlainTextResult = { text: string; truncated: boolean };
// Every Compose field now runs through this one call: the model is asked for
// prose and the handler wraps the result into the JSON the client parses. The
// token cap and temperature mirror what the old structured path used, and
// `finish_reason === "length"` is reported so the truncation marker reaches the
// client (the prose path previously swallowed it).
async function generatePlainText(
prompt: string,
system: string,
model: string,
options: { maxTokens?: number; temperature?: number } = {},
): Promise<PlainTextResult> {
async function generatePlainText(prompt: string, system: string, model: string): Promise<string> {
const baseUrl = process.env.UNSLOTH_URL || "http://192.168.1.7:8888/v1";
const response = await fetch(`${baseUrl}/chat/completions`, {
method: "POST",
@ -274,8 +299,6 @@ async function generatePlainText(
{ role: "user", content: prompt },
],
stream: false,
max_tokens: options.maxTokens ?? 5000,
temperature: options.temperature ?? 0.7,
...REASONING_DISABLED,
}),
});
@ -285,11 +308,7 @@ async function generatePlainText(
}
const result = await response.json();
const choice = result.choices?.[0];
return {
text: stripCodeFences(choice?.message?.content ?? ""),
truncated: choice?.finish_reason === "length",
};
return stripCodeFences(result.choices[0].message.content ?? "");
}
const filename = fileURLToPath(import.meta.url);
@ -781,35 +800,23 @@ export default buildConfig({
},
) => {
const model = options.model || DEFAULT_MODEL;
const shape = resolveProseShape(options.schema);
// One contract for every supported field: the model writes prose and
// the JSON the Compose client parses is assembled here. The plugin's
// richText system asks for lexical JSON and a blog layout, which is
// exactly what contradicted the prose instruction, so only its
// block-placeholder paragraph survives (see composeSystem.ts).
if (shape) {
const { text, truncated } = await generatePlainText(
if (options.schema?.definitions) {
const text = await generatePlainText(
prompt,
buildComposeSystem({
pluginSystem: options.system,
fieldType: shape.kind === "lexical" ? "richText" : "text",
}),
`${options.system}\n\nOUTPUT RULES:\nRespond with plain prose paragraphs only. Do not output JSON, code fences, or schema definitions. Plain sentences and paragraphs are the entire expected output.`,
model,
{ maxTokens: options.maxTokens, temperature: options.temperature },
);
const json = wrapProse(shape, text);
const lexicalJson = plainTextToLexicalJson(text);
const ts = new ReadableStream({
start(controller) {
controller.enqueue(JSON.stringify(json) + (truncated ? "\u0000" : ""));
controller.enqueue(JSON.stringify(lexicalJson));
controller.close();
},
});
return createTextStreamResponse({ textStream: ts });
}
// Shapes we do not convert (e.g. a hasMany array) keep the
// structured path rather than guessing at a wrapper.
const streamResult = streamObject({
maxOutputTokens: options.maxTokens || 5000,
model: unslothProvider(model),
@ -848,8 +855,7 @@ export default buildConfig({
return createTextStreamResponse({ textStream });
},
generateText: async (prompt: string, system: string) => {
const { text } = await generatePlainText(prompt, system, DEFAULT_MODEL);
return text;
return generatePlainText(prompt, system, DEFAULT_MODEL);
},
output: "text",
settings: {

View file

@ -1,148 +0,0 @@
import { describe, expect, it } from "vitest";
import {
AI_OUTPUT_RULES,
buildComposeSystem,
extractBlockPlaceholderInstruction,
plainTextToLexicalJson,
resolveProseShape,
wrapProse,
} from "@/lib/ai/composeSystem";
// The exact system `@ai-stack/payloadcms@3.2.30` builds for a richText field
// (dist/endpoints/index.js -> buildRichTextSystem). Captured verbatim so that a
// plugin upgrade which changes the wording fails this spec loudly instead of
// silently letting the JSON/layout instructions back into the model's prompt.
const PLUGIN_RICH_TEXT_SYSTEM = `INSTRUCTIONS:
You are a highly skilled and professional blog writer,
renowned for crafting engaging and well-organized articles.
RULES:
- Generate original and unique content based on the given topic.
- Ensure the output follows the provided rich text JSON schema exactly.
- Produce valid JSON with no undefined or null values.
- The text may contain one or more standalone placeholder tokens of the exact form
"[[[BLOCK_<number>]]]" (e.g. "[[[BLOCK_0]]]").
These represent embedded content you cannot see. Reproduce every such token EXACTLY as given,
completely unchanged (do not translate, reword, remove, or merge it with other text), as its
own paragraph, in the same relative position within the surrounding text.
---
LAYOUT INSTRUCTIONS:
[paragraph] - Write a concise introduction (2-3 sentences) that outlines the main topic.
[horizontalrule] - Insert a horizontal rule to separate the introduction from the main content.
[list] - Create a list with 3-5 items. Each list item should contain:
a. [heading] - A brief, descriptive heading (up to 5 words)
b. [paragraph] - A short explanation or elaboration (1-2 sentences)
---
ADDITIONAL GUIDELINES:
- Ensure coherence and logical flow between all sections.
`;
describe("buildComposeSystem", () => {
it("strips the plugin's JSON rules and layout markers from the model's system prompt", () => {
const system = buildComposeSystem({
pluginSystem: PLUGIN_RICH_TEXT_SYSTEM,
fieldType: "richText",
});
expect(system).not.toContain("rich text JSON schema");
expect(system).not.toContain("Produce valid JSON");
expect(system).not.toMatch(/LAYOUT INSTRUCTIONS/);
expect(system).not.toMatch(/\[paragraph\]|\[horizontalrule\]|\[list\]|\[heading\]|\[quote\]/);
});
it("keeps the block-placeholder paragraph and nothing else from the plugin system", () => {
const system = buildComposeSystem({
pluginSystem: PLUGIN_RICH_TEXT_SYSTEM,
fieldType: "richText",
});
expect(system).toContain("- The text may contain one or more standalone placeholder tokens");
expect(system).toContain("[[[BLOCK_<number>]]]");
expect(system).not.toContain("professional blog writer");
});
it("asks for prose plus the em-dash rule exactly once for every field type", () => {
for (const fieldType of ["richText", "text", "textarea"]) {
const system = buildComposeSystem({
pluginSystem: PLUGIN_RICH_TEXT_SYSTEM,
fieldType,
});
expect(system.match(/Never use em-dashes/g)).toHaveLength(1);
expect(system).toContain("Respond with plain prose only.");
expect(system).not.toContain("rich text JSON schema");
expect(system).not.toContain("Produce valid JSON");
}
});
it("sends short fields only the shared rules, with no plugin material", () => {
const system = buildComposeSystem({
pluginSystem: PLUGIN_RICH_TEXT_SYSTEM,
fieldType: "text",
});
expect(system).toBe(AI_OUTPUT_RULES);
});
it("sends the real em-dash character to the model", () => {
expect(AI_OUTPUT_RULES).toContain("em-dashes (\u2014)");
});
});
describe("extractBlockPlaceholderInstruction", () => {
it("returns the placeholder paragraph without the surrounding rules", () => {
const block = extractBlockPlaceholderInstruction(PLUGIN_RICH_TEXT_SYSTEM);
expect(block.startsWith("- The text may contain")).toBe(true);
expect(block.endsWith("surrounding text.")).toBe(true);
expect(block).not.toMatch(/JSON/);
});
it("returns an empty string when there is nothing to keep", () => {
expect(extractBlockPlaceholderInstruction(undefined)).toBe("");
expect(extractBlockPlaceholderInstruction("just some prose")).toBe("");
});
});
describe("resolveProseShape / wrapProse", () => {
const lexicalSchema = { definitions: { root: {} }, type: "object" };
const textSchema = {
type: "object",
properties: { name: { type: "string" } },
required: ["name"],
};
it("wraps prose into lexical JSON for a richText schema", () => {
const shape = resolveProseShape(lexicalSchema);
expect(shape).toEqual({ kind: "lexical" });
const json = wrapProse(shape!, "First paragraph.\n\nSecond paragraph.");
expect(json).toEqual(plainTextToLexicalJson("First paragraph.\n\nSecond paragraph."));
const root = (json as { root: { children: Array<{ children: Array<{ text: string }> }> } }).root;
expect(root.children).toHaveLength(2);
expect(root.children[0].children[0].text).toBe("First paragraph.");
});
it("wraps prose into the field's own key for a single string property", () => {
const shape = resolveProseShape(textSchema);
expect(shape).toEqual({ kind: "field", key: "name" });
expect(wrapProse(shape!, "Barracks")).toEqual({ name: "Barracks" });
});
it("declines shapes it cannot wrap", () => {
expect(
resolveProseShape({ type: "object", properties: { tags: { type: "array" } } }),
).toBeNull();
expect(
resolveProseShape({
type: "object",
properties: { a: { type: "string" }, b: { type: "string" } },
}),
).toBeNull();
expect(resolveProseShape(undefined)).toBeNull();
});
});