- permissions: mission-ratings group + ALL_PERMISSION_VALUES, granted in seedRoles
- collection: src/collections/intelligence/MissionRatings.ts (field-gated, Intelligence group)
- Missions: missionRating.customFactors group (array of {label})
- payload.config: register MissionRatings + requireAdminPageAccess
- regenerate payload-types
916 lines
34 KiB
TypeScript
916 lines
34 KiB
TypeScript
import { migrations } from "./migrations";
|
|
import { postgresAdapter } from "@payloadcms/db-postgres";
|
|
import { FixedToolbarFeature, lexicalEditor } from "@payloadcms/richtext-lexical";
|
|
import { nodemailerAdapter } from "@payloadcms/email-nodemailer";
|
|
import path from "path";
|
|
import { buildConfig, formatLabels } from "payload";
|
|
import { fileURLToPath } from "url";
|
|
import sharp from "sharp";
|
|
import nodemailer from "nodemailer";
|
|
|
|
import { Users } from "@/collections/users/Users";
|
|
import { Roles } from "@/collections/users/Roles";
|
|
import { Awards } from "@/collections/users/Awards";
|
|
import { AwardRules } from "@/collections/users/AwardRules";
|
|
import { Media } from "@/collections/Media";
|
|
import { Ranks } from "@/collections/users/Ranks";
|
|
import { Profiles } from "@/collections/users/Profiles";
|
|
import { Missions } from "@/collections/intelligence/Missions";
|
|
import { MissionAttendances } from "@/collections/intelligence/MissionAttendances";
|
|
import { MissionRoleSignups } from "@/collections/intelligence/MissionRoleSignups";
|
|
import { MissionMapMarkers } from "@/collections/intelligence/MissionMapMarkers";
|
|
import { MissionRatings } from "@/collections/intelligence/MissionRatings";
|
|
import { Maps } from "@/collections/world/Maps";
|
|
import { MapRoads } from "@/collections/world/MapRoads";
|
|
import { MapZones } from "@/collections/world/MapZones";
|
|
import { MapObjectives } from "@/collections/world/MapObjectives";
|
|
import { ResourceNodes } from "@/collections/world/ResourceNodes";
|
|
import { Campaigns } from "@/collections/intelligence/Campaigns";
|
|
import { Qualifications } from "@/collections/users/Qualifications";
|
|
import { MissionFiles } from "@/collections/server/MissionFiles";
|
|
import { ModLists } from "@/collections/server/ModLists";
|
|
import { GameServers } from "@/collections/server/GameServers";
|
|
import { ArmaSyncEvents } from "@/collections/server/ArmaSyncEvents";
|
|
import { ArmaCommands } from "@/collections/server/ArmaCommands";
|
|
import { RespawnTickets } from "@/collections/server/RespawnTickets";
|
|
import { SupplyBoxes } from "@/collections/server/SupplyBoxes";
|
|
import { OperationEvents } from "@/collections/operations/OperationEvents";
|
|
import { OperationEffects } from "@/collections/operations/OperationEffects";
|
|
import { OperationReservations } from "@/collections/operations/OperationReservations";
|
|
import { OperationReadiness } from "@/collections/operations/OperationReadiness";
|
|
import { ZonePressure } from "@/collections/operations/ZonePressure";
|
|
import { Factions } from "@/collections/intelligence/Factions";
|
|
import { Assets } from "@/collections/logistics/Assets";
|
|
import { NarrativeEvents } from "@/collections/world/NarrativeEvents";
|
|
import { Resources } from "@/collections/logistics/Resources";
|
|
import { Vehicles } from "@/collections/logistics/Vehicles";
|
|
import { Structures } from "@/collections/logistics/Structures";
|
|
import { Shipments } from "@/collections/logistics/Shipments";
|
|
import { Assignments } from "@/collections/users/Assignments";
|
|
import { AssignmentTransfers } from "@/collections/users/AssignmentTransfers";
|
|
import { Technologies } from "@/collections/intelligence/Technologies";
|
|
import { TechCategories } from "@/collections/intelligence/TechCategories";
|
|
import { TechResearches } from "@/collections/intelligence/TechResearches";
|
|
import { TechBallots } from "@/collections/intelligence/TechBallots";
|
|
import { TechBallotVotes } from "@/collections/intelligence/TechBallotVotes";
|
|
import { GameRules } from "@/collections/game/GameRules";
|
|
import { DiscordPresence } from "@/collections/discord/DiscordPresence";
|
|
import { GameStructures } from "@/collections/game/GameStructures";
|
|
import { GameHardResources } from "@/collections/game/GameHardResources";
|
|
import { GameEventLogs } from "@/collections/game/GameEventLogs";
|
|
import { StructureRooms } from "@/collections/interior/StructureRooms";
|
|
import { InteriorJobs } from "@/collections/interior/InteriorJobs";
|
|
import { GameVehicles } from "@/collections/game/GameVehicles";
|
|
import { GameNpcs } from "@/collections/game/GameNpcs";
|
|
import { NpcStaffing } from "@/collections/game/NpcStaffing";
|
|
import { NpcDialogues } from "@/collections/game/NpcDialogues";
|
|
import { NpcDialogueStates } from "@/collections/game/NpcDialogueStates";
|
|
import { PlayerFlags } from "@/collections/game/PlayerFlags";
|
|
import { ReinforcementPools } from "@/collections/game/ReinforcementPools";
|
|
import { LaborClassifications } from "@/collections/game/LaborClassifications";
|
|
import { Experience } from "@/collections/users/Experience";
|
|
import { ContributionEntries } from "@/collections/users/ContributionEntries";
|
|
import { BankAccounts } from "@/collections/banking/BankAccounts";
|
|
import { BankTransactions } from "@/collections/banking/BankTransactions";
|
|
import { LedgerEntries } from "@/collections/banking/LedgerEntries";
|
|
import { LockerStorages } from "@/collections/locker/LockerStorages";
|
|
import { Loadouts } from "@/collections/locker/Loadouts";
|
|
import { MarketListings } from "@/collections/market/MarketListings";
|
|
import { MarketNegotiations } from "@/collections/market/MarketNegotiations";
|
|
import { MarketState } from "@/collections/market/MarketState";
|
|
import { VoiceScripts } from "@/collections/voiceover/VoiceScripts";
|
|
import { VoiceSubmissions } from "@/collections/voiceover/VoiceSubmissions";
|
|
import { UserNotifications } from "@/collections/users/UserNotifications";
|
|
import { Evaluations } from "@/collections/users/Evaluations";
|
|
import { Tickets } from "@/collections/tickets/Tickets";
|
|
import { TicketVotes } from "@/collections/tickets/TicketVotes";
|
|
import { WikiPages } from "@/collections/wiki/WikiPages";
|
|
import { WikiRevisions } from "@/collections/wiki/WikiRevisions";
|
|
import { WikiTemplates } from "@/collections/wiki/WikiTemplates";
|
|
import { Projects } from "@/collections/projects/Projects";
|
|
import { Sprints } from "@/collections/projects/Sprints";
|
|
import { Releases } from "@/collections/projects/Releases";
|
|
import { Labels } from "@/collections/projects/Labels";
|
|
import { StoryBeats } from "@/collections/story/StoryBeats";
|
|
import { Journals } from "@/collections/story/Journals";
|
|
import { StoryBeatStates } from "@/collections/story/StoryBeatStates";
|
|
import { Voiceovers } from "@/collections/story/Voiceovers";
|
|
import { Shims } from "@/collections/Shims";
|
|
import { Announcements } from "@/collections/Announcements";
|
|
import { CustomMinefields } from "@/collections/minigames/CustomMinefields";
|
|
import { CustomMinefieldScores } from "@/collections/minigames/CustomMinefieldScores";
|
|
import { CustomRadioTests } from "@/collections/minigames/CustomRadioTests";
|
|
import { CustomRadioTestScores } from "@/collections/minigames/CustomRadioTestScores";
|
|
import { Minigames } from "@/collections/minigames/Minigames";
|
|
import { MinigameEntries } from "@/collections/minigames/MinigameEntries";
|
|
import { MinigamePeriods } from "@/collections/minigames/MinigamePeriods";
|
|
import { Achievements } from "@/collections/minigames/Achievements";
|
|
import { MinigameRules } from "@/collections/game/MinigameRules";
|
|
import { RibbonSubmissions } from "@/collections/users/RibbonSubmissions";
|
|
import { PromotionNominations } from "@/collections/users/PromotionNominations";
|
|
import { LeadershipTransfers } from "@/collections/users/LeadershipTransfers";
|
|
import { requirePermission } from "@/utils/access-control/hasPermission";
|
|
import { scopedAdminPageAccess } from "@/utils/access-control/divisionAccess";
|
|
import { payloadAiPlugin, PayloadAiPluginLexicalEditorFeature } from "@ai-stack/payloadcms";
|
|
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";
|
|
|
|
// Ornith-9B is served by the "Apex" Unsloth connection (a separate machine,
|
|
// apex-lnx / 192.168.1.7), reached through Unsloth Studio's OpenAI-compatible
|
|
// API. Point UNSLOTH_URL at that instance; the default is the LAN address of
|
|
// the Apex box.
|
|
const unslothProvider = createOpenAI({
|
|
apiKey: process.env.UNSLOTH_API_KEY,
|
|
baseURL: process.env.UNSLOTH_URL || "http://192.168.1.7:8888/v1",
|
|
});
|
|
|
|
// The model-id select and its Postgres enum use a stable internal key. Changing
|
|
// that key requires a migration, so the served model is configured separately:
|
|
// point UNSLOTH_MODEL at the GGUF loaded in Unsloth Studio.
|
|
const MODEL_ID = "unsloth/Ornith-1.0-9B-GGUF";
|
|
const DEFAULT_MODEL = process.env.UNSLOTH_MODEL || MODEL_ID;
|
|
|
|
// Dropdown label for the model. UNSLOTH_MODEL_NAME wins; otherwise derive a
|
|
// readable name from UNSLOTH_MODEL, falling back to the bundled Ornith label.
|
|
const prettifyModel = (id: string) =>
|
|
(id.split("/").pop() || id).replace(/[-_]+/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
|
|
const MODEL_LABEL =
|
|
process.env.UNSLOTH_MODEL_NAME ||
|
|
(process.env.UNSLOTH_MODEL ? prettifyModel(process.env.UNSLOTH_MODEL) : "Ornith 1.0 9B");
|
|
|
|
// Ornith is a reasoning model: it emits a long `reasoning_content` block before
|
|
// the actual answer, and with a small token budget the reasoning consumes the
|
|
// whole allowance, leaving `content` empty. Unsloth Studio (llama.cpp) accepts
|
|
// `reasoning_effort: "none"` to turn thinking off for the request, so the model
|
|
// behaves like a plain instruct model and small budgets still produce output.
|
|
// Sent on every request; harmless on models that do not support it.
|
|
const REASONING_DISABLED = { reasoning_effort: "none" } as const;
|
|
|
|
// AI Compose allowlist: the plugin's default init makes an LLM call per field
|
|
// to seed prompts. Returning false here skips a field (no instruction row, no
|
|
// AI UI), and returning { data: { prompt } } (without a top-level `prompt` key)
|
|
// seeds the row statically, so no LLM call ever happens at boot and a wiped
|
|
// instructions table (e.g. after scripts/sync-prod.sh) rebuilds in
|
|
// milliseconds on the next startup.
|
|
const AI_TEXT_FIELD_ALLOWLIST = new Set([
|
|
"description",
|
|
"gamedescription",
|
|
"summary",
|
|
"bio",
|
|
"occupation",
|
|
"name",
|
|
"title",
|
|
]);
|
|
|
|
// Textarea/richText fields that are system-managed or technical, never AI-able.
|
|
const AI_FIELD_DENYLIST = new Set(["contentsnapshot", "html", "script"]);
|
|
|
|
// Entity noun for a collection, used to tell the model what kind of document it
|
|
// is writing for ("the technology Barracks"). Prefers an explicit collection
|
|
// label (e.g. Experience → "XP Level"); otherwise Payload's slug-derived label.
|
|
const collectionNoun = (slug: string): string => {
|
|
const collection = collections.find((candidate) => candidate.slug === slug);
|
|
const custom = collection?.labels?.singular;
|
|
const label = typeof custom === "string" ? custom : formatLabels(slug).singular;
|
|
return label.toLowerCase();
|
|
};
|
|
|
|
// True when the field being generated *is* the collection's own title field, so
|
|
// `{{ title }}` would be empty (new document) or the value being replaced
|
|
// (existing document). Those prompts read "this <noun>" instead of the token.
|
|
const isIdentityField = (slug: string, path: string): boolean => {
|
|
const collection = collections.find((candidate) => candidate.slug === slug);
|
|
return path === `${slug}.${collection?.admin?.useAsTitle ?? "title"}`;
|
|
};
|
|
|
|
const staticAiPrompt = (
|
|
fieldName: string,
|
|
fieldLabel: string,
|
|
fieldType: string,
|
|
collectionSlug: string,
|
|
path: string,
|
|
): string => {
|
|
const noun = collectionNoun(collectionSlug);
|
|
const identity = isIdentityField(collectionSlug, path);
|
|
|
|
switch (fieldName) {
|
|
case "description":
|
|
case "gamedescription":
|
|
return `Write an immersive, in-universe description for the "${fieldLabel}" of the ${noun} {{ title }}. 2-4 sentences of plain prose. No markdown, no lists, no headings.`;
|
|
case "summary":
|
|
return `Write a concise summary for the "${fieldLabel}" of the ${noun} {{ title }}. 1-3 sentences of plain prose.`;
|
|
case "bio":
|
|
return `Write a short in-universe biography for the ${noun} {{ title }}. A few sentences of plain prose covering background and personality.`;
|
|
case "occupation":
|
|
return `Suggest a short occupation label for the ${noun} {{ title }}. Reply with 1-3 words only, no explanation.`;
|
|
case "name":
|
|
return identity
|
|
? `Suggest a single fitting name for this ${noun}. Reply with the name only, no explanation.`
|
|
: `Suggest a single fitting name for the ${noun} {{ title }}. Reply with the name only, no explanation.`;
|
|
case "title":
|
|
return identity
|
|
? `Suggest a single fitting title for this ${noun}. Reply with the title only, no explanation.`
|
|
: `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 suitable content for the "${fieldLabel}" of the ${noun} {{ title }}. Plain prose, concise and relevant.`;
|
|
}
|
|
};
|
|
|
|
const aiFieldSeedPrompts: SeedPromptFunction = ({ path, fieldType, fieldLabel }) => {
|
|
const fieldName = (path.split(".").pop() ?? "").toLowerCase();
|
|
const collectionSlug = path.split(".")[0] ?? "";
|
|
|
|
if (AI_FIELD_DENYLIST.has(fieldName)) return false;
|
|
|
|
if (fieldType === "textarea" || fieldType === "richText") {
|
|
return {
|
|
data: { prompt: staticAiPrompt(fieldName, fieldLabel, fieldType, collectionSlug, path) },
|
|
};
|
|
}
|
|
|
|
if (fieldType === "text" && AI_TEXT_FIELD_ALLOWLIST.has(fieldName)) {
|
|
return {
|
|
data: { prompt: staticAiPrompt(fieldName, fieldLabel, fieldType, collectionSlug, path) },
|
|
};
|
|
}
|
|
|
|
return false;
|
|
};
|
|
|
|
// 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.
|
|
const stripCodeFences = (text: string): string =>
|
|
text
|
|
.replace(/^```[a-zA-Z]*\s*\n?/, "")
|
|
.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> {
|
|
const baseUrl = process.env.UNSLOTH_URL || "http://192.168.1.7:8888/v1";
|
|
const response = await fetch(`${baseUrl}/chat/completions`, {
|
|
method: "POST",
|
|
headers: {
|
|
Authorization: "Bearer " + process.env.UNSLOTH_API_KEY,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
model,
|
|
messages: [
|
|
{ role: "system", content: system || "You are a helpful assistant." },
|
|
{ role: "user", content: prompt },
|
|
],
|
|
stream: false,
|
|
max_tokens: options.maxTokens ?? 5000,
|
|
temperature: options.temperature ?? 0.7,
|
|
...REASONING_DISABLED,
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`Unsloth API error: ${response.statusText}`);
|
|
}
|
|
|
|
const result = await response.json();
|
|
const choice = result.choices?.[0];
|
|
return {
|
|
text: stripCodeFences(choice?.message?.content ?? ""),
|
|
truncated: choice?.finish_reason === "length",
|
|
};
|
|
}
|
|
|
|
const filename = fileURLToPath(import.meta.url);
|
|
const dirname = path.dirname(filename);
|
|
const META_TITLE = "Polaris Task Force";
|
|
const META_DESCRIPTION = "A gamified platform for Polaris Task Force, an Arma 3 unit.";
|
|
|
|
const collections = [
|
|
Media,
|
|
|
|
// Announcements
|
|
Announcements,
|
|
|
|
// Game
|
|
GameHardResources,
|
|
GameStructures,
|
|
GameVehicles,
|
|
GameNpcs,
|
|
NpcStaffing,
|
|
NpcDialogues,
|
|
NpcDialogueStates,
|
|
PlayerFlags,
|
|
ReinforcementPools,
|
|
LaborClassifications,
|
|
GameEventLogs,
|
|
StructureRooms,
|
|
InteriorJobs,
|
|
|
|
// Users
|
|
Users,
|
|
Roles,
|
|
Ranks,
|
|
Profiles,
|
|
Awards,
|
|
AwardRules,
|
|
Qualifications,
|
|
Assignments,
|
|
AssignmentTransfers,
|
|
Experience,
|
|
ContributionEntries,
|
|
UserNotifications,
|
|
Evaluations,
|
|
RibbonSubmissions,
|
|
PromotionNominations,
|
|
LeadershipTransfers,
|
|
|
|
// Intel
|
|
Missions,
|
|
MissionAttendances,
|
|
MissionRoleSignups,
|
|
MissionMapMarkers,
|
|
MissionRatings,
|
|
Campaigns,
|
|
Factions,
|
|
Technologies,
|
|
TechCategories,
|
|
TechResearches,
|
|
TechBallots,
|
|
TechBallotVotes,
|
|
|
|
// Logistics
|
|
Assets,
|
|
Resources,
|
|
Vehicles,
|
|
Structures,
|
|
Shipments,
|
|
|
|
// Banking
|
|
BankAccounts,
|
|
BankTransactions,
|
|
LedgerEntries,
|
|
|
|
// Locker
|
|
LockerStorages,
|
|
Loadouts,
|
|
|
|
// Market
|
|
MarketListings,
|
|
MarketNegotiations,
|
|
MarketState,
|
|
|
|
// Voiceover
|
|
VoiceScripts,
|
|
VoiceSubmissions,
|
|
|
|
// Helpdesk
|
|
Tickets,
|
|
TicketVotes,
|
|
|
|
// Wiki
|
|
WikiPages,
|
|
WikiRevisions,
|
|
WikiTemplates,
|
|
|
|
// Projects
|
|
Projects,
|
|
Sprints,
|
|
Releases,
|
|
Labels,
|
|
|
|
// World
|
|
Maps,
|
|
MapRoads,
|
|
MapZones,
|
|
MapObjectives,
|
|
ResourceNodes,
|
|
NarrativeEvents,
|
|
|
|
// Story
|
|
StoryBeats,
|
|
StoryBeatStates,
|
|
Voiceovers,
|
|
Journals,
|
|
|
|
// Server
|
|
MissionFiles,
|
|
ModLists,
|
|
GameServers,
|
|
ArmaSyncEvents,
|
|
ArmaCommands,
|
|
RespawnTickets,
|
|
SupplyBoxes,
|
|
|
|
// Operations
|
|
OperationEvents,
|
|
OperationEffects,
|
|
OperationReservations,
|
|
OperationReadiness,
|
|
ZonePressure,
|
|
|
|
// Minigames
|
|
CustomMinefields,
|
|
CustomMinefieldScores,
|
|
CustomRadioTests,
|
|
CustomRadioTestScores,
|
|
Minigames,
|
|
MinigameEntries,
|
|
MinigamePeriods,
|
|
Achievements,
|
|
];
|
|
|
|
// Scoped admin pages: a user needs BOTH `<slug>:read` AND `admin:<slug>:manage`
|
|
// to see/interact with a collection in the Payload admin panel, except the four
|
|
// division-scoped collections (technologies → intelligence; assets/resources/
|
|
// vehicles → logistics), where a division member passes instead. Non-admin
|
|
// (REST/API) reads keep the collection's original access behavior.
|
|
const scopedCollections = collections.map((collection) => ({
|
|
...collection,
|
|
access: {
|
|
...collection.access,
|
|
read: scopedAdminPageAccess(collection.slug, collection.access?.read),
|
|
},
|
|
}));
|
|
|
|
// AI Compose prompt templates use `{{ title }}` for the document being edited.
|
|
// Payload's `useAsTitle` is per-collection (usually `name`, not `title`), and the
|
|
// plugin's Handlebars context only exposes raw document fields, so `{{ title }}`
|
|
// resolved to an empty string on every collection without a literal `title` field.
|
|
// Expose `title` as a computed prompt field backed by the collection's real
|
|
// `useAsTitle` field, with fallbacks for partial/unsaved documents.
|
|
const useAsTitleByCollection = new Map(
|
|
scopedCollections.map((collection) => [collection.slug, collection.admin?.useAsTitle ?? "title"]),
|
|
);
|
|
|
|
const TITLE_FALLBACK_FIELDS = [
|
|
"title",
|
|
"name",
|
|
"label",
|
|
"subject",
|
|
"summary",
|
|
"detail",
|
|
"username",
|
|
"email",
|
|
"id",
|
|
] as const;
|
|
|
|
const titleValueToString = (value: unknown): string => {
|
|
if (value == null) return "";
|
|
if (typeof value === "string" || typeof value === "number") return String(value);
|
|
if (Array.isArray(value)) {
|
|
return value.map(titleValueToString).filter(Boolean).join(", ");
|
|
}
|
|
if (typeof value === "object") {
|
|
const record = value as Record<string, unknown>;
|
|
return titleValueToString(record.title ?? record.name ?? record.label ?? record.id);
|
|
}
|
|
return "";
|
|
};
|
|
|
|
const readDocumentPath = (data: Record<string, unknown>, path: string): unknown =>
|
|
path
|
|
.split(".")
|
|
.reduce<unknown>(
|
|
(value, key) =>
|
|
value && typeof value === "object" ? (value as Record<string, unknown>)[key] : undefined,
|
|
data,
|
|
);
|
|
|
|
const resolvePromptTitle = (data: Record<string, unknown>, collection: string): string => {
|
|
const configured = titleValueToString(
|
|
readDocumentPath(data, useAsTitleByCollection.get(collection) ?? "title"),
|
|
);
|
|
if (configured) return configured;
|
|
|
|
for (const field of TITLE_FALLBACK_FIELDS) {
|
|
const value = titleValueToString(readDocumentPath(data, field));
|
|
if (value) return value;
|
|
}
|
|
|
|
return "";
|
|
};
|
|
|
|
// MCP: eligible per collection, not granted: `enabled: true` makes all CRUD
|
|
// capabilities available, but each MCP API key still picks its own capability
|
|
// checkboxes and each collection's access control still applies.
|
|
const mcpCollections = Object.fromEntries(
|
|
scopedCollections.map((collection) => [collection.slug, { enabled: true } as const]),
|
|
);
|
|
|
|
export default buildConfig({
|
|
// serverURL: "http://localhost:3000/",
|
|
admin: {
|
|
user: Users.slug,
|
|
importMap: {
|
|
baseDir: path.resolve(dirname),
|
|
},
|
|
meta: {
|
|
titleSuffix: "- Polaris Task Force",
|
|
applicationName: META_TITLE,
|
|
abstract: META_DESCRIPTION,
|
|
keywords: "Polaris Task Force, Polaris, Task Force, Polaris Task Force official website",
|
|
description: META_DESCRIPTION,
|
|
openGraph: {
|
|
title: META_TITLE,
|
|
description: META_DESCRIPTION,
|
|
url: "https://polaris-task-force.com",
|
|
siteName: META_TITLE,
|
|
images: [
|
|
{
|
|
url: "/images/icon-favicon.png",
|
|
width: 512,
|
|
height: 512,
|
|
alt: "Polaris Task Force Logo",
|
|
},
|
|
],
|
|
},
|
|
icons: [
|
|
{
|
|
rel: "icon",
|
|
type: "image/png",
|
|
url: "/images/icon-favicon.png",
|
|
},
|
|
],
|
|
},
|
|
|
|
// Overrides the built-in collection-cards grid on the admin dashboard
|
|
// (Payload appends its default `collections` widget after user widgets and
|
|
// resolves by first match). Same grid + permissions, plus lucide icons.
|
|
dashboard: {
|
|
widgets: [
|
|
{
|
|
slug: "collections",
|
|
Component: "@/components/admin/dashboard/CollectionCards",
|
|
minWidth: "full",
|
|
},
|
|
],
|
|
},
|
|
components: {
|
|
beforeDashboard: ["@/components/static/BeforeDashboardText"],
|
|
header: ["@/components/static/VersionOverlay"],
|
|
beforeNav: ["@/components/static/GoToFrontendLink"],
|
|
graphics: {
|
|
Logo: "@/components/graphics/AppLogo",
|
|
Icon: "@/components/graphics/AppIcon",
|
|
},
|
|
Nav: "@/components/admin/tech-tree/TechTreeNav",
|
|
views: {
|
|
techTree: {
|
|
path: "/tech-tree",
|
|
Component: "@/components/admin/tech-tree/TechTreeView",
|
|
},
|
|
analytics: {
|
|
path: "/analytics",
|
|
Component: "@/components/admin/analytics/AnalyticsView",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
globals: [GameRules, Shims, MinigameRules, DiscordPresence],
|
|
collections: scopedCollections,
|
|
editor: lexicalEditor({
|
|
features: ({ defaultFeatures }) => {
|
|
return [...defaultFeatures, FixedToolbarFeature(), PayloadAiPluginLexicalEditorFeature()];
|
|
},
|
|
}),
|
|
secret: process.env.PAYLOAD_SECRET || "",
|
|
typescript: {
|
|
outputFile: path.resolve(dirname, "payload-types.ts"),
|
|
},
|
|
db: postgresAdapter({
|
|
pool: {
|
|
connectionString: process.env.DATABASE_URI || "",
|
|
// Test workers cap the pg pool per boot (tests/vitest-worker-setup.ts
|
|
// sets TEST_PG_POOL_MAX); unset in dev/prod, zero behavior change there.
|
|
...(process.env.TEST_PG_POOL_MAX ? { max: Number(process.env.TEST_PG_POOL_MAX) } : {}),
|
|
},
|
|
// push: process.env.NODE_ENV === "development",
|
|
// Env-gated drizzle push: only the test-database bootstrap (DB_PUSH=1) uses
|
|
// it, because the migration chain assumes a schema that push created.
|
|
push: process.env.DB_PUSH === "1",
|
|
prodMigrations: migrations,
|
|
}),
|
|
sharp,
|
|
bin: [
|
|
{
|
|
scriptPath: path.resolve(dirname, "scripts/gameTick.ts"),
|
|
key: "game-tick",
|
|
},
|
|
{
|
|
scriptPath: path.resolve(dirname, "scripts/marketTick.ts"),
|
|
key: "market-tick",
|
|
},
|
|
{
|
|
scriptPath: path.resolve(dirname, "scripts/missionTick.ts"),
|
|
key: "mission-tick",
|
|
},
|
|
{
|
|
scriptPath: path.resolve(dirname, "scripts/serverTick.ts"),
|
|
key: "server-tick",
|
|
},
|
|
{
|
|
scriptPath: path.resolve(dirname, "scripts/baseTick.ts"),
|
|
key: "base-tick",
|
|
},
|
|
{
|
|
scriptPath: path.resolve(dirname, "scripts/economyTick.ts"),
|
|
key: "economy-tick",
|
|
},
|
|
{
|
|
scriptPath: path.resolve(dirname, "scripts/techTick.ts"),
|
|
key: "tech-tick",
|
|
},
|
|
{
|
|
scriptPath: path.resolve(dirname, "scripts/periodTick.ts"),
|
|
key: "period-tick",
|
|
},
|
|
{
|
|
scriptPath: path.resolve(dirname, "scripts/awardTick.ts"),
|
|
key: "award-tick",
|
|
},
|
|
{
|
|
scriptPath: path.resolve(dirname, "scripts/interiorTick.ts"),
|
|
key: "interior-tick",
|
|
},
|
|
{
|
|
scriptPath: path.resolve(dirname, "scripts/generateNextMission.ts"),
|
|
key: "generate-mission",
|
|
},
|
|
{
|
|
scriptPath: path.resolve(dirname, "scripts/analyticsRollup.ts"),
|
|
key: "analytics-rollup",
|
|
},
|
|
{
|
|
scriptPath: path.resolve(dirname, "scripts/analyticsPurge.ts"),
|
|
key: "analytics-purge",
|
|
},
|
|
],
|
|
plugins: [
|
|
formBuilderPlugin(surveyFormBuilderConfig()),
|
|
// payloadCloudPlugin(),
|
|
// storage-adapter-placeholder
|
|
mcpPlugin({
|
|
collections: mcpCollections,
|
|
// Server-side guidance shown to MCP clients: this endpoint is read-only
|
|
// (keys carry only the `find` capability), so it is a reference surface
|
|
// for current production state, never a write path.
|
|
mcp: {
|
|
serverOptions: {
|
|
serverInfo: { name: "Polaris Task Force (production)", version: "1.0.0" },
|
|
instructions: [
|
|
"Polaris Task Force production data, read-only.",
|
|
"Every collection is exposed as a find<Collection> tool (and find<Global> for globals).",
|
|
"These tools only read: the API key has the find capability only, so mutations are impossible.",
|
|
"Use them to look up current production state for reference (tickets, users, structures, market listings, and so on) rather than deriving it from source.",
|
|
"Pass Payload `where` clauses as JSON strings; limit is capped at 100.",
|
|
"Writes and schema changes go through the normal channels (server actions, Payload migrations), never this server.",
|
|
].join("\n"),
|
|
},
|
|
},
|
|
// MCP API keys let a client act as their user, so issuing them is a
|
|
// superuser-tier operation: `system:admin-access` passes for dynamic
|
|
// superusers (hasPermission bypass) and for roles explicitly holding it.
|
|
// The legacy `hasRoles` enum check this replaced read only the old
|
|
// `roles` column, which every current admin user lacks, so nobody could
|
|
// create or see keys and no MCP client could authenticate. Admin-panel
|
|
// visibility follows the read gate (the repo's requireAdminPageAccess
|
|
// pattern); `admin.hidden` is sync-only and cannot run permission lookups.
|
|
overrideApiKeyCollection: (collection) => ({
|
|
...collection,
|
|
access: {
|
|
...collection.access,
|
|
read: requirePermission("system:admin-access"),
|
|
update: requirePermission("system:admin-access"),
|
|
create: requirePermission("system:admin-access"),
|
|
delete: requirePermission("system:admin-access"),
|
|
},
|
|
}),
|
|
}),
|
|
payloadAiPlugin({
|
|
seedPrompts: aiFieldSeedPrompts,
|
|
// Resolve `{{ title }}` from the collection's actual `useAsTitle` field
|
|
// (e.g. `name` on Technologies) instead of requiring a literal `title`.
|
|
promptFields: [
|
|
{
|
|
name: "title",
|
|
getter: (data, ctx) =>
|
|
resolvePromptTitle((data ?? {}) as Record<string, unknown>, ctx.collection),
|
|
},
|
|
],
|
|
collections: {
|
|
[GameHardResources.slug]: true,
|
|
[GameStructures.slug]: true,
|
|
[GameVehicles.slug]: true,
|
|
[GameNpcs.slug]: true,
|
|
[NpcStaffing.slug]: true,
|
|
[LaborClassifications.slug]: true,
|
|
[GameEventLogs.slug]: true,
|
|
|
|
// Users
|
|
[Users.slug]: true,
|
|
[Roles.slug]: true,
|
|
[Ranks.slug]: true,
|
|
[Profiles.slug]: true,
|
|
[Awards.slug]: true,
|
|
[Qualifications.slug]: true,
|
|
[Assignments.slug]: true,
|
|
[Experience.slug]: true,
|
|
[UserNotifications.slug]: true,
|
|
[Evaluations.slug]: true,
|
|
|
|
// Intel
|
|
[Missions.slug]: true,
|
|
[MissionAttendances.slug]: true,
|
|
[MissionRoleSignups.slug]: true,
|
|
[MissionRatings.slug]: true,
|
|
[Campaigns.slug]: true,
|
|
[Factions.slug]: true,
|
|
[Technologies.slug]: true,
|
|
|
|
// Logistics
|
|
[Assets.slug]: true,
|
|
[Resources.slug]: true,
|
|
[Vehicles.slug]: true,
|
|
[Structures.slug]: true,
|
|
[Shipments.slug]: true,
|
|
|
|
// Banking
|
|
[BankAccounts.slug]: true,
|
|
[BankTransactions.slug]: true,
|
|
[LedgerEntries.slug]: true,
|
|
|
|
// Locker
|
|
[LockerStorages.slug]: true,
|
|
[Loadouts.slug]: true,
|
|
|
|
// Market
|
|
[MarketListings.slug]: true,
|
|
[MarketNegotiations.slug]: true,
|
|
|
|
// Helpdesk
|
|
[Tickets.slug]: true,
|
|
|
|
// Wiki
|
|
[WikiPages.slug]: true,
|
|
[WikiRevisions.slug]: true,
|
|
[WikiTemplates.slug]: true,
|
|
|
|
// Projects
|
|
[Projects.slug]: true,
|
|
[Sprints.slug]: true,
|
|
[Releases.slug]: true,
|
|
[Labels.slug]: true,
|
|
},
|
|
debugging: true,
|
|
// Same superuser-tier gate as the MCP API keys above; the AI plugin's
|
|
// instructions collection is admin-only tooling.
|
|
overrideInstructions: {
|
|
access: {
|
|
read: requirePermission("system:admin-access"),
|
|
update: requirePermission("system:admin-access"),
|
|
create: requirePermission("system:admin-access"),
|
|
delete: requirePermission("system:admin-access"),
|
|
},
|
|
},
|
|
generationModels: [
|
|
{
|
|
id: MODEL_ID,
|
|
name: MODEL_LABEL,
|
|
fields: ["text", "textarea", "richText"],
|
|
handler: async (
|
|
prompt: string,
|
|
options: {
|
|
locale: string;
|
|
model: string;
|
|
system: string;
|
|
schema: Record<string, unknown>;
|
|
maxTokens?: number;
|
|
temperature?: number;
|
|
},
|
|
) => {
|
|
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 system
|
|
// prompt keeps the task the plugin sent (the field's own prompt, or a
|
|
// named action's instruction such as Expand or Simplify) and drops
|
|
// only the JSON/layout demands that contradicted it, so the action
|
|
// instructions still reach the model (see composeSystem.ts).
|
|
if (shape) {
|
|
const { text, truncated } = await generatePlainText(
|
|
prompt,
|
|
buildComposeSystem({ pluginSystem: options.system }),
|
|
model,
|
|
{ maxTokens: options.maxTokens, temperature: options.temperature },
|
|
);
|
|
const json = wrapProse(shape, text);
|
|
const ts = new ReadableStream({
|
|
start(controller) {
|
|
controller.enqueue(JSON.stringify(json) + (truncated ? "\u0000" : ""));
|
|
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),
|
|
onError: (error) => {
|
|
console.error("Unsloth generateObject: ", error);
|
|
},
|
|
prompt,
|
|
schema: jsonSchema(options.schema),
|
|
system: options.system,
|
|
temperature: options.temperature ?? 0.7,
|
|
providerOptions: {
|
|
openai: {
|
|
strictJsonSchema: true,
|
|
structuredOutputs: true,
|
|
...REASONING_DISABLED,
|
|
},
|
|
},
|
|
});
|
|
|
|
const textStream = new ReadableStream({
|
|
async start(controller) {
|
|
try {
|
|
for await (const chunk of streamResult.textStream) {
|
|
controller.enqueue(chunk);
|
|
}
|
|
if ((await streamResult.finishReason) === "length") {
|
|
controller.enqueue("\u0000");
|
|
}
|
|
controller.close();
|
|
} catch (error) {
|
|
controller.error(error);
|
|
}
|
|
},
|
|
});
|
|
|
|
return createTextStreamResponse({ textStream });
|
|
},
|
|
generateText: async (prompt: string, system: string) => {
|
|
const { text } = await generatePlainText(prompt, system, DEFAULT_MODEL);
|
|
return text;
|
|
},
|
|
output: "text",
|
|
settings: {
|
|
name: "ornith-9b-settings",
|
|
type: "group",
|
|
admin: {
|
|
condition(data) {
|
|
return data["model-id"] === MODEL_ID;
|
|
},
|
|
},
|
|
fields: [
|
|
{
|
|
name: "model",
|
|
type: "text",
|
|
admin: {
|
|
description: "Leave blank to use the UNSLOTH_MODEL environment variable.",
|
|
},
|
|
label: "Model",
|
|
},
|
|
],
|
|
label: `${MODEL_LABEL} Settings`,
|
|
},
|
|
},
|
|
],
|
|
}),
|
|
],
|
|
email: nodemailerAdapter({
|
|
defaultFromAddress: process.env.EMAIL_FROM_ADDRESS || "",
|
|
defaultFromName: process.env.EMAIL_FROM_NAME || "",
|
|
transport: nodemailer.createTransport({
|
|
host: process.env.EMAIL_HOST || "",
|
|
port: Number(process.env.EMAIL_PORT) || 587,
|
|
auth: {
|
|
user: process.env.EMAIL_USERNAME || "",
|
|
pass: process.env.EMAIL_PASSWORD || "",
|
|
},
|
|
}),
|
|
}),
|
|
});
|