@dsh-agentic-roleplay/core 0.12.0 → 0.12.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/lib/{access-DAw54-NI.js → access-DifaiHrI.js} +2 -2
- package/lib/{authoring-tools-4NgDhIJV.js → authoring-tools-VOaXzr_R.js} +23 -771
- package/lib/authoring.js +135 -12
- package/lib/{child-D3QUNb3m.js → child-DzZ-aI6k.js} +10 -1
- package/lib/client.js +16162 -1902
- package/lib/client.js.map +1 -1
- package/lib/compaction.js +3 -3
- package/lib/dev-context-Bdm-eVer.js +40 -0
- package/lib/doctor.js +5 -3
- package/lib/{gallery-Ct6nm4UQ.js → gallery-Ctz-UoFk.js} +3 -3
- package/lib/{generator-CI8fOnXy.js → generator-Cv6WWmZT.js} +2 -2
- package/lib/helper.js +4 -2
- package/lib/{hooks-BNeoGMHZ.js → hooks-BdR3mBeM.js} +33 -14
- package/lib/images.js +4 -4
- package/lib/index.js +128 -463
- package/lib/{jail-BIF79PJO.js → jail-Cp4zEfip.js} +2 -2
- package/lib/{library-BF9ZMSFz.js → library-BU2A_Dx8.js} +2 -2
- package/lib/{lorebook-author-tools-DBk-V0hp.js → lorebook-author-tools-DUKcQu8P.js} +19 -6
- package/lib/lorebook-authoring.js +12 -5
- package/lib/{narration-xvErE2yp.js → narration-CDsJ5wxH.js} +2 -2
- package/lib/orchestration.js +33 -12
- package/lib/{pack-jail-C8EyX9Ix.js → pack-jail-CzHQu0n3.js} +558 -23
- package/lib/{packs-S0SzrVv-.js → packs-BZ-45J4-.js} +2 -2
- package/lib/{presenter-agent-Bc478nTA.js → presenter-agent-C2ZkoxZu.js} +9 -9
- package/lib/{preset-SJZyw0kt.js → preset-BPnRPW-1.js} +4 -4
- package/lib/{preset-author-tools-CzogjK42.js → preset-author-tools-DBqPwn-o.js} +8 -7
- package/lib/preset-authoring.js +11 -6
- package/lib/{reflection-buQiSdvq.js → reflection-Cuy0YLv0.js} +14 -15
- package/lib/{presets-DQ5rioMh.js → serial-BZNeK57v.js} +1180 -389
- package/lib/{turn-guard-BSAba8sp.js → turn-guard-xaFxYc1T.js} +3 -3
- package/locale/de.json +6 -0
- package/locale/en.json +6 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +33 -33
- package/prompts/en/import/style.md +2 -1
- package/prompts/en/world/procedure.md +1 -1
- package/prompts/zh/import/style.md +2 -1
- package/prompts/zh/world/procedure.md +1 -1
package/lib/index.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import { A as chatSessionId, _ as RECOVERY_SHRINK, g as RECOVERY_FLOOR, h as sharedSamplingOf, i as childSamplingOf, j as roleplaySessionOf, m as parseSampling, s as isUnfinishedCall, w as totalTokens } from "./child-
|
|
2
|
-
import {
|
|
3
|
-
import { a as lorebookImportMessage, c as readLorebook, d as lorebookOfChat, l as selectEntries, s as previewLorebook, t as LOREBOOK_UPLOAD, u as lorebookChatSessionId } from "./lorebook-author-tools-
|
|
4
|
-
import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-
|
|
5
|
-
import { A as plotProgressOf, B as parsePlotsFile, C as readNotes, G as readDocument, H as COMMANDS_KEY, J as errorMessage, L as readUsage, Q as copyWorldPrompts, S as notesOfSession, T as defaultBoundaries, V as plotReferenceProblems, X as PROMPTS_FOLDER, Y as LANGUAGE_FOLDER, Z as PromptLibrary, _ as readTraces, b as readWithdrawn, ct as InvalidWorldError, dt as SessionNotFoundError, et as languageOf, ft as WorldNotFoundError, g as readRunDetail, h as readActivity, ht as zoneOf, j as populatePlots, k as PLOTS_METADATA_KEY, lt as ReflectionRefusedError, m as readDecisionStats, nt as promptProblem, o as externalTools, ot as AgentUnavailableError, q as formatIssue, rt as shippedLanguages, st as InvalidStartError, tt as listFiles, ut as SessionArchivedError, w as observeAsPlayer, x as addToNote } from "./hooks-
|
|
6
|
-
import { a as liveSettings, c as writeSettings, d as parseSettings, i as InvalidSettingsError, l as DEFAULT_SETTINGS, o as readSettings, p as WORLD_RULES_KEY, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-
|
|
7
|
-
import { $ as
|
|
8
|
-
import { $ as
|
|
9
|
-
import {
|
|
1
|
+
import { A as chatSessionId, _ as RECOVERY_SHRINK, g as RECOVERY_FLOOR, h as sharedSamplingOf, i as childSamplingOf, j as roleplaySessionOf, m as parseSampling, s as isUnfinishedCall, w as totalTokens } from "./child-DzZ-aI6k.js";
|
|
2
|
+
import { Bt as isPng, E as loadWorldParts, F as localChanges, Ft as CHARACTERS_DIR, G as vetUrl, Ht as readCard, I as readOrigin, It as loadCharacters, Kt as authoredWorldOf, L as writeOrigin, Lt as knownOutputCeiling, M as describeChanges, N as hashWorld, P as isUnchanged, R as CatalogueError, Rt as ImportCardError, T as readWorldInfo, U as guardedLookup, Vt as pictureOf, _ as runChecks, at as populateCharacters, bt as loadLocations, c as importPhase, ct as populateFactions, d as markReady, dt as populateLocations, et as checkWorld, f as settleDraft, ft as populateLore, ht as populateVariables, it as populateCalendar, lt as populateItems, mt as populateTriggers, ot as populateClock, p as structureImport, pt as populateRoutines, qt as authoringChatSessionId, rt as knowsCharacter, st as populateDice, t as AuthoringTools, tt as loadValidatedWorld, u as keepDraft, ut as populateKnowledge, w as editWorldInfo, zt as cardFormat } from "./authoring-tools-VOaXzr_R.js";
|
|
3
|
+
import { a as lorebookImportMessage, c as readLorebook, d as lorebookOfChat, l as selectEntries, s as previewLorebook, t as LOREBOOK_UPLOAD, u as lorebookChatSessionId } from "./lorebook-author-tools-DUKcQu8P.js";
|
|
4
|
+
import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-DBqPwn-o.js";
|
|
5
|
+
import { A as plotProgressOf, B as parsePlotsFile, C as readNotes, G as readDocument, H as COMMANDS_KEY, J as errorMessage, L as readUsage, Q as copyWorldPrompts, S as notesOfSession, T as defaultBoundaries, V as plotReferenceProblems, X as PROMPTS_FOLDER, Y as LANGUAGE_FOLDER, Z as PromptLibrary, _ as readTraces, b as readWithdrawn, ct as InvalidWorldError, dt as SessionNotFoundError, et as languageOf, ft as WorldNotFoundError, g as readRunDetail, h as readActivity, ht as zoneOf, j as populatePlots, k as PLOTS_METADATA_KEY, lt as ReflectionRefusedError, m as readDecisionStats, nt as promptProblem, o as externalTools, ot as AgentUnavailableError, q as formatIssue, rt as shippedLanguages, st as InvalidStartError, tt as listFiles, ut as SessionArchivedError, w as observeAsPlayer, x as addToNote } from "./hooks-BdR3mBeM.js";
|
|
6
|
+
import { a as liveSettings, c as writeSettings, d as parseSettings, i as InvalidSettingsError, l as DEFAULT_SETTINGS, o as readSettings, p as WORLD_RULES_KEY, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-CDsJ5wxH.js";
|
|
7
|
+
import { $ as deleteWorldPrompt, $t as subfolders, Et as readImportFolder, F as parseWorldInfoEdit, G as loadPreset, H as deletePreset, I as combineAnswers, J as reservePreset, K as presetDirectory, L as questionView, M as WORLD_FILE_NAME, N as parseWorldFile, Ot as IMPORT_COMMAND, Pt as sourceSummary, Qt as parseCharacterFile, St as ImportStore, Tt as parseChoices, U as isPresetName, V as createPresetFromShipped, W as listPresets, Y as savePresetFromWorld, Z as updatePresetInfo, an as parseRelationEdit, at as deleteLorebook, bt as IMPORT_FOLDER, cn as LORE_KINDS, ct as isLorebookName, dt as lorebookDirectory, en as InvalidEditProblems, et as listWorldPrompts, ht as writeLorebookEntry, in as parsePlaceEdit, it as createLorebook, ln as LORE_SCOPES, lt as listLorebooks, mt as updateLorebookInfo, nn as parseFactionEdit, nt as writeWorldPrompt, on as parseThingEdit, ot as deleteLorebookEntry, pt as reserveLorebook, rn as parseLoreEdit, rt as addLorebookEntries, sn as guarded, st as entriesOf, tn as parseCharacterEdit, tt as readWorldPrompt, ut as loadLorebook, vt as partsOf, xt as ImportNotFoundError, yt as withPlayer, z as PRESET_FILE } from "./serial-BZNeK57v.js";
|
|
8
|
+
import { $ as languageOfDocuments, A as generateWorldCharacterPortrait, C as editWorldFaction$1, D as editWorldPlots$1, E as editWorldPlace$1, F as uploadWorldCharacterPortrait, G as parseVariablesEdit, I as uploadWorldEntityImage, J as PRESET_FILE$1, K as parseDiceEdit, L as worldCharacterPortraitFile, M as readWorldEditor, N as readWorldTrigger, O as editWorldRelation$1, P as removeWorldTrigger, R as worldEntityImageFile, S as editWorldCharacter$1, T as editWorldNarrationVoice, U as parseCalendarEdit, W as parseRoutineEdit, Y as presetMessage, Z as translateMessage, _ as readCalendarDocument, a as deleteWorldPackFile, at as startUpdate, b as readRoutines, c as createAuthoredEntity, ct as authoringTitle, dt as agentServicesOf, et as readWorldDocuments, f as editCalendar, ft as DOCTOR_OPENING_SOURCE, g as editVariables, h as editRoutine, it as revertUpdate, j as generateWorldEntityImage, k as editWorldThing$1, l as deleteAuthoredEntity, lt as ensureAuthoringChat, m as editDice, mt as appendNarratedTurn, n as packFileProblem, ot as updateStatus, p as editCommands, pt as appendEmptyTurn, q as parseCommandsEdit, st as AuthoringSessions, t as MAX_PACK_TEXT, tt as findTargets, u as readAuthoredEntityDocument, ut as AgentSessions, v as readCommandsDocument, w as editWorldLore$1, x as readVariables, y as readDiceDocument, z as writeWorldTrigger } from "./pack-jail-CzHQu0n3.js";
|
|
9
|
+
import { i as atomicWriteSync, n as atomicWrite, r as atomicWriteJson } from "./access-DifaiHrI.js";
|
|
10
10
|
import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-Dfv8S8eq.js";
|
|
11
|
-
import { _ as snapshotOf, c as copyPreset, d as switchPreset, f as readTimeline, g as pathTo, h as childrenOf, i as reflectionStatus, l as presetStatus, m as START_SNAPSHOT, o as TimelineError, p as writeTimeline, u as recordPreset } from "./reflection-
|
|
12
|
-
import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-
|
|
13
|
-
import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-
|
|
11
|
+
import { _ as snapshotOf, c as copyPreset, d as switchPreset, f as readTimeline, g as pathTo, h as childrenOf, i as reflectionStatus, l as presetStatus, m as START_SNAPSHOT, o as TimelineError, p as writeTimeline, u as recordPreset } from "./reflection-Cuy0YLv0.js";
|
|
12
|
+
import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-BPnRPW-1.js";
|
|
13
|
+
import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-BU2A_Dx8.js";
|
|
14
14
|
import { o as FOLDER_ACCESS, r as InvalidFoldersError, t as StoryFoldersService } from "./service-mRKwpWjX.js";
|
|
15
15
|
import { t as doctorChatSessionId } from "./doctor-chat-hL1a61hp.js";
|
|
16
|
-
import { _ as API_PREFIX, a as packIds, c as describePack, d as packPath, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-
|
|
17
|
-
import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-
|
|
18
|
-
import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-
|
|
16
|
+
import { _ as API_PREFIX, a as packIds, c as describePack, d as packPath, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-BZ-45J4-.js";
|
|
17
|
+
import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-Cv6WWmZT.js";
|
|
18
|
+
import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-Ctz-UoFk.js";
|
|
19
19
|
import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
|
|
20
20
|
import { SESSION_DATABASE_FILE, addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, openSessionStore, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
|
|
21
21
|
import { copyFileSync, cpSync, createReadStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
@@ -338,6 +338,15 @@ var RoleplayImport = class extends Service {
|
|
|
338
338
|
super(ctx, "roleplayImport");
|
|
339
339
|
this.read = read;
|
|
340
340
|
}
|
|
341
|
+
turns = /* @__PURE__ */ new Map();
|
|
342
|
+
/** Notes that a turn of a chat ended; the authoring chats are the ones that report here. */
|
|
343
|
+
turnEnded(chat) {
|
|
344
|
+
this.turns.set(chat, (this.turns.get(chat) ?? 0) + 1);
|
|
345
|
+
}
|
|
346
|
+
/** How many turns of the chat have ended since the plugin started. */
|
|
347
|
+
turnsOf(chat) {
|
|
348
|
+
return this.turns.get(chat) ?? 0;
|
|
349
|
+
}
|
|
341
350
|
/** The settings as they stand now: they are edited while the plugin runs. */
|
|
342
351
|
get settings() {
|
|
343
352
|
return this.read();
|
|
@@ -545,7 +554,7 @@ async function actOnDraft(deps, worldId, action, language) {
|
|
|
545
554
|
await deps.worlds.list({ refresh: true });
|
|
546
555
|
return {
|
|
547
556
|
action,
|
|
548
|
-
keptIn: relative(deps.root(), destination)
|
|
557
|
+
keptIn: relative(deps.root(), destination).split(sep).join("/")
|
|
549
558
|
};
|
|
550
559
|
}
|
|
551
560
|
// src/host/sessions/statistics.ts
|
|
@@ -3263,7 +3272,7 @@ function languageField(value) {
|
|
|
3263
3272
|
}
|
|
3264
3273
|
// src/host/http/routes/worlds.ts
|
|
3265
3274
|
/** The routes of the API for worlds. */
|
|
3266
|
-
function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, avatars, playtest }) {
|
|
3275
|
+
function worldsRoutes({ worlds, createWorld, starter, authorWorld, sayToAuthor, authoringStatus, chatStatus, forgetAuthoring, translation, worldCharacters, avatars, playtest }) {
|
|
3267
3276
|
return {
|
|
3268
3277
|
"/worlds": {
|
|
3269
3278
|
GET: async (_req, res) => {
|
|
@@ -3319,6 +3328,37 @@ function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation,
|
|
|
3319
3328
|
throw error;
|
|
3320
3329
|
}
|
|
3321
3330
|
} },
|
|
3331
|
+
"/authoring/status": { GET: async (_req, res, url) => {
|
|
3332
|
+
sendJson(res, 200, chatStatus(url.searchParams.get("chat") ?? ""));
|
|
3333
|
+
} },
|
|
3334
|
+
"/worlds/authoring/chat": { DELETE: async (_req, res, url) => {
|
|
3335
|
+
try {
|
|
3336
|
+
await forgetAuthoring(url.searchParams.get("id") ?? "");
|
|
3337
|
+
sendJson(res, 200, { ok: true });
|
|
3338
|
+
} catch (error) {
|
|
3339
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
3340
|
+
throw error;
|
|
3341
|
+
}
|
|
3342
|
+
} },
|
|
3343
|
+
"/worlds/authoring/message": { POST: async (req, res, url) => {
|
|
3344
|
+
const body = await readJsonBody(req);
|
|
3345
|
+
if (typeof body.text !== "string" || body.text.trim() === "") return sendError(res, 400, "the request needs the text to say");
|
|
3346
|
+
try {
|
|
3347
|
+
sendJson(res, 202, await sayToAuthor(url.searchParams.get("id") ?? "", body.text, languageField(body.language)));
|
|
3348
|
+
} catch (error) {
|
|
3349
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
3350
|
+
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
3351
|
+
throw error;
|
|
3352
|
+
}
|
|
3353
|
+
} },
|
|
3354
|
+
"/worlds/authoring/status": { GET: async (_req, res, url) => {
|
|
3355
|
+
try {
|
|
3356
|
+
sendJson(res, 200, await authoringStatus(url.searchParams.get("id") ?? ""));
|
|
3357
|
+
} catch (error) {
|
|
3358
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
3359
|
+
throw error;
|
|
3360
|
+
}
|
|
3361
|
+
} },
|
|
3322
3362
|
"/worlds/language": { GET: async (_req, res, url) => {
|
|
3323
3363
|
try {
|
|
3324
3364
|
sendJson(res, 200, { language: await translation.language(url.searchParams.get("id") ?? "") ?? null });
|
|
@@ -3796,298 +3836,6 @@ function importsRoutes({ importer }) {
|
|
|
3796
3836
|
} }
|
|
3797
3837
|
};
|
|
3798
3838
|
}
|
|
3799
|
-
// src/shared/world-dice.ts
|
|
3800
|
-
const isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3801
|
-
const CHECK_FIELDS = [
|
|
3802
|
-
"key",
|
|
3803
|
-
"name",
|
|
3804
|
-
"use",
|
|
3805
|
-
"dice",
|
|
3806
|
-
"reading",
|
|
3807
|
-
"hit",
|
|
3808
|
-
"compare",
|
|
3809
|
-
"modifier",
|
|
3810
|
-
"bands"
|
|
3811
|
-
];
|
|
3812
|
-
const BAND_FIELDS = [
|
|
3813
|
-
"min",
|
|
3814
|
-
"max",
|
|
3815
|
-
"label",
|
|
3816
|
-
"result",
|
|
3817
|
-
"critical"
|
|
3818
|
-
];
|
|
3819
|
-
/** Reads a body that came from the browser: the shape of every field is checked here, and what the checks mean when the world is validated. */
|
|
3820
|
-
function parseDiceEdit(value) {
|
|
3821
|
-
const problems = [];
|
|
3822
|
-
if (!isObject$1(value) || !Array.isArray(value["checks"])) throw new InvalidEditProblems(["the dice must be { checks: [...] }"]);
|
|
3823
|
-
const checks = value["checks"].map((entry, index) => {
|
|
3824
|
-
const at = `checks[${index}]`;
|
|
3825
|
-
const empty = {
|
|
3826
|
-
key: "",
|
|
3827
|
-
name: "",
|
|
3828
|
-
use: "",
|
|
3829
|
-
dice: "",
|
|
3830
|
-
bands: []
|
|
3831
|
-
};
|
|
3832
|
-
if (!isObject$1(entry)) {
|
|
3833
|
-
problems.push(`${at} must be an object`);
|
|
3834
|
-
return empty;
|
|
3835
|
-
}
|
|
3836
|
-
for (const key of Object.keys(entry)) if (!CHECK_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a check`);
|
|
3837
|
-
for (const key of [
|
|
3838
|
-
"key",
|
|
3839
|
-
"name",
|
|
3840
|
-
"use",
|
|
3841
|
-
"dice"
|
|
3842
|
-
]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
3843
|
-
if (entry["reading"] !== void 0 && !DICE_READINGS.includes(entry["reading"])) problems.push(`${at}.reading must be one of: ${DICE_READINGS.join(", ")}`);
|
|
3844
|
-
if (entry["compare"] !== void 0 && !DICE_COMPARISONS.includes(entry["compare"])) problems.push(`${at}.compare must be one of: ${DICE_COMPARISONS.join(", ")}`);
|
|
3845
|
-
if (entry["hit"] !== void 0 && (typeof entry["hit"] !== "number" || !Number.isInteger(entry["hit"]))) problems.push(`${at}.hit must be a whole number`);
|
|
3846
|
-
if (entry["modifier"] !== void 0 && typeof entry["modifier"] !== "string") problems.push(`${at}.modifier must be text`);
|
|
3847
|
-
const bands = Array.isArray(entry["bands"]) ? entry["bands"] : void 0;
|
|
3848
|
-
if (bands === void 0) problems.push(`${at}.bands must be a list`);
|
|
3849
|
-
const text = (field) => typeof field === "string" ? field.trim() : "";
|
|
3850
|
-
const hit = entry["hit"];
|
|
3851
|
-
return {
|
|
3852
|
-
key: text(entry["key"]),
|
|
3853
|
-
name: text(entry["name"]),
|
|
3854
|
-
use: text(entry["use"]),
|
|
3855
|
-
dice: text(entry["dice"]),
|
|
3856
|
-
...entry["reading"] === void 0 ? {} : { reading: entry["reading"] },
|
|
3857
|
-
...typeof hit === "number" ? { hit } : {},
|
|
3858
|
-
...entry["compare"] === void 0 ? {} : { compare: entry["compare"] },
|
|
3859
|
-
...text(entry["modifier"]) === "" ? {} : { modifier: text(entry["modifier"]) },
|
|
3860
|
-
bands: (bands ?? []).map((band, bandIndex) => {
|
|
3861
|
-
const where = `${at}.bands[${bandIndex}]`;
|
|
3862
|
-
if (!isObject$1(band)) {
|
|
3863
|
-
problems.push(`${where} must be an object`);
|
|
3864
|
-
return {
|
|
3865
|
-
label: "",
|
|
3866
|
-
result: "failed"
|
|
3867
|
-
};
|
|
3868
|
-
}
|
|
3869
|
-
for (const key of Object.keys(band)) if (!BAND_FIELDS.includes(key)) problems.push(`${where}.${key} is not a field of a band`);
|
|
3870
|
-
for (const key of ["min", "max"]) if (band[key] !== void 0 && (typeof band[key] !== "number" || !Number.isFinite(band[key]))) problems.push(`${where}.${key} must be a number`);
|
|
3871
|
-
if (typeof band["label"] !== "string") problems.push(`${where}.label must be text`);
|
|
3872
|
-
if (!DICE_RESULTS.includes(band["result"])) problems.push(`${where}.result must be one of: ${DICE_RESULTS.join(", ")}`);
|
|
3873
|
-
const min = band["min"];
|
|
3874
|
-
const max = band["max"];
|
|
3875
|
-
return {
|
|
3876
|
-
label: text(band["label"]),
|
|
3877
|
-
result: band["result"],
|
|
3878
|
-
...typeof min === "number" ? { min } : {},
|
|
3879
|
-
...typeof max === "number" ? { max } : {},
|
|
3880
|
-
...band["critical"] === true ? { critical: true } : {}
|
|
3881
|
-
};
|
|
3882
|
-
})
|
|
3883
|
-
};
|
|
3884
|
-
});
|
|
3885
|
-
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
3886
|
-
return { checks };
|
|
3887
|
-
}
|
|
3888
|
-
// src/shared/world-daily.ts
|
|
3889
|
-
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3890
|
-
const ROUTINE_FIELDS = [
|
|
3891
|
-
"days",
|
|
3892
|
-
"on",
|
|
3893
|
-
"from",
|
|
3894
|
-
"to",
|
|
3895
|
-
"activity",
|
|
3896
|
-
"location",
|
|
3897
|
-
"feature",
|
|
3898
|
-
"position",
|
|
3899
|
-
"interruptible",
|
|
3900
|
-
"sleep"
|
|
3901
|
-
];
|
|
3902
|
-
/**
|
|
3903
|
-
* The windows of a day as the browser sends them.
|
|
3904
|
-
* @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the times and places are acceptable is checked when the file is read back.
|
|
3905
|
-
*/
|
|
3906
|
-
function parseRoutineEdit(value) {
|
|
3907
|
-
const problems = [];
|
|
3908
|
-
const list = isObject(value) && Array.isArray(value["windows"]) ? value["windows"] : void 0;
|
|
3909
|
-
if (list === void 0) throw new InvalidEditProblems(["the day must be { windows: [...] }"]);
|
|
3910
|
-
const windows = list.map((entry, index) => {
|
|
3911
|
-
const at = `windows[${index}]`;
|
|
3912
|
-
if (!isObject(entry)) {
|
|
3913
|
-
problems.push(`${at} must be an object`);
|
|
3914
|
-
return {
|
|
3915
|
-
days: [],
|
|
3916
|
-
from: "",
|
|
3917
|
-
to: "",
|
|
3918
|
-
activity: "",
|
|
3919
|
-
interruptible: true
|
|
3920
|
-
};
|
|
3921
|
-
}
|
|
3922
|
-
for (const key of Object.keys(entry)) if (!ROUTINE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a window`);
|
|
3923
|
-
for (const key of [
|
|
3924
|
-
"from",
|
|
3925
|
-
"to",
|
|
3926
|
-
"activity"
|
|
3927
|
-
]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
3928
|
-
for (const key of [
|
|
3929
|
-
"location",
|
|
3930
|
-
"feature",
|
|
3931
|
-
"position"
|
|
3932
|
-
]) if (entry[key] !== void 0 && typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
3933
|
-
if (entry["days"] !== void 0 && !(Array.isArray(entry["days"]) && entry["days"].every((day) => typeof day === "string"))) problems.push(`${at}.days must be a list of days`);
|
|
3934
|
-
if (entry["interruptible"] !== void 0 && typeof entry["interruptible"] !== "boolean") problems.push(`${at}.interruptible must be true or false`);
|
|
3935
|
-
if (entry["sleep"] !== void 0 && typeof entry["sleep"] !== "boolean") problems.push(`${at}.sleep must be true or false`);
|
|
3936
|
-
const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
|
|
3937
|
-
return {
|
|
3938
|
-
days: Array.isArray(entry["days"]) ? entry["days"].map((day) => day.trim().toLowerCase()).filter((day) => day !== "") : [],
|
|
3939
|
-
...Array.isArray(entry["on"]) && entry["on"].length > 0 ? { on: entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") } : {},
|
|
3940
|
-
from: text("from"),
|
|
3941
|
-
to: text("to"),
|
|
3942
|
-
activity: text("activity"),
|
|
3943
|
-
...text("location") === "" ? {} : { location: text("location") },
|
|
3944
|
-
...text("feature") === "" ? {} : { feature: text("feature") },
|
|
3945
|
-
...text("position") === "" ? {} : { position: text("position") },
|
|
3946
|
-
interruptible: entry["interruptible"] !== false,
|
|
3947
|
-
...entry["sleep"] === true ? { sleep: true } : {}
|
|
3948
|
-
};
|
|
3949
|
-
});
|
|
3950
|
-
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
3951
|
-
return windows;
|
|
3952
|
-
}
|
|
3953
|
-
const VARIABLE_FIELDS = [
|
|
3954
|
-
"key",
|
|
3955
|
-
"name",
|
|
3956
|
-
"kind",
|
|
3957
|
-
"subject",
|
|
3958
|
-
"visibility",
|
|
3959
|
-
"description",
|
|
3960
|
-
"update",
|
|
3961
|
-
"min",
|
|
3962
|
-
"max",
|
|
3963
|
-
"integer",
|
|
3964
|
-
"baseline",
|
|
3965
|
-
"always",
|
|
3966
|
-
"default",
|
|
3967
|
-
"only",
|
|
3968
|
-
"options",
|
|
3969
|
-
"bands"
|
|
3970
|
-
];
|
|
3971
|
-
/**
|
|
3972
|
-
* The declarations as the browser sends them, with empty fields left out. Whether they are acceptable together is checked against the world's files.
|
|
3973
|
-
* @throws {InvalidEditProblems} naming every field that has the wrong shape.
|
|
3974
|
-
*/
|
|
3975
|
-
function parseVariablesEdit(value) {
|
|
3976
|
-
const problems = [];
|
|
3977
|
-
const list = isObject(value) && Array.isArray(value["variables"]) ? value["variables"] : void 0;
|
|
3978
|
-
if (list === void 0) throw new InvalidEditProblems(["the variables must be { variables: [...] }"]);
|
|
3979
|
-
const declarations = list.flatMap((entry, index) => {
|
|
3980
|
-
const at = `variables[${index}]`;
|
|
3981
|
-
if (!isObject(entry)) {
|
|
3982
|
-
problems.push(`${at} must be an object`);
|
|
3983
|
-
return [];
|
|
3984
|
-
}
|
|
3985
|
-
for (const key of Object.keys(entry)) if (!VARIABLE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a variable`);
|
|
3986
|
-
const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
|
|
3987
|
-
const number = (key) => {
|
|
3988
|
-
if (entry[key] === void 0 || entry[key] === null || entry[key] === "") return void 0;
|
|
3989
|
-
if (typeof entry[key] !== "number" || !Number.isFinite(entry[key])) {
|
|
3990
|
-
problems.push(`${at}.${key} must be a number`);
|
|
3991
|
-
return;
|
|
3992
|
-
}
|
|
3993
|
-
return entry[key];
|
|
3994
|
-
};
|
|
3995
|
-
const flag = (key) => {
|
|
3996
|
-
if (entry[key] === void 0) return void 0;
|
|
3997
|
-
if (typeof entry[key] !== "boolean") {
|
|
3998
|
-
problems.push(`${at}.${key} must be true or false`);
|
|
3999
|
-
return;
|
|
4000
|
-
}
|
|
4001
|
-
return entry[key];
|
|
4002
|
-
};
|
|
4003
|
-
const strings = (key) => {
|
|
4004
|
-
if (entry[key] === void 0) return [];
|
|
4005
|
-
if (!(Array.isArray(entry[key]) && entry[key].every((item) => typeof item === "string"))) {
|
|
4006
|
-
problems.push(`${at}.${key} must be a list of text`);
|
|
4007
|
-
return [];
|
|
4008
|
-
}
|
|
4009
|
-
return entry[key].map((item) => item.trim()).filter((item) => item !== "");
|
|
4010
|
-
};
|
|
4011
|
-
const bands = Array.isArray(entry["bands"]) ? entry["bands"].flatMap((band) => isObject(band) && typeof band["up_to"] === "number" && typeof band["label"] === "string" && band["label"].trim() !== "" ? [{
|
|
4012
|
-
up_to: band["up_to"],
|
|
4013
|
-
label: band["label"].trim()
|
|
4014
|
-
}] : (problems.push(`${at}.bands needs { up_to, label } entries`), [])) : [];
|
|
4015
|
-
const rawDefault = entry["default"];
|
|
4016
|
-
if (rawDefault !== void 0 && rawDefault !== null && rawDefault !== "" && typeof rawDefault !== "number" && typeof rawDefault !== "boolean" && typeof rawDefault !== "string") problems.push(`${at}.default must be a number, true or false, or text`);
|
|
4017
|
-
for (const [key, allowed] of [
|
|
4018
|
-
["kind", VARIABLE_KINDS],
|
|
4019
|
-
["subject", VARIABLE_SUBJECTS],
|
|
4020
|
-
["visibility", VARIABLE_VISIBILITIES]
|
|
4021
|
-
]) if (!allowed.includes(text(key))) problems.push(`${at}.${key} must be one of: ${allowed.join(", ")}`);
|
|
4022
|
-
const [min, max] = [number("min"), number("max")];
|
|
4023
|
-
const [integer, baseline, always] = [
|
|
4024
|
-
flag("integer"),
|
|
4025
|
-
flag("baseline"),
|
|
4026
|
-
flag("always")
|
|
4027
|
-
];
|
|
4028
|
-
const only = strings("only");
|
|
4029
|
-
const options = strings("options");
|
|
4030
|
-
return [{
|
|
4031
|
-
key: text("key"),
|
|
4032
|
-
name: text("name"),
|
|
4033
|
-
kind: text("kind"),
|
|
4034
|
-
subject: text("subject"),
|
|
4035
|
-
visibility: text("visibility"),
|
|
4036
|
-
...text("description") === "" ? {} : { description: text("description") },
|
|
4037
|
-
...text("update") === "" ? {} : { update: text("update") },
|
|
4038
|
-
...min === void 0 ? {} : { min },
|
|
4039
|
-
...max === void 0 ? {} : { max },
|
|
4040
|
-
...integer === true ? { integer } : {},
|
|
4041
|
-
...baseline === true ? { baseline } : {},
|
|
4042
|
-
...always === true ? { always } : {},
|
|
4043
|
-
...rawDefault === void 0 || rawDefault === null || rawDefault === "" ? {} : { default: rawDefault },
|
|
4044
|
-
...only.length === 0 ? {} : { only },
|
|
4045
|
-
...options.length === 0 ? {} : { options },
|
|
4046
|
-
...bands.length === 0 ? {} : { bands }
|
|
4047
|
-
}];
|
|
4048
|
-
});
|
|
4049
|
-
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
4050
|
-
return declarations;
|
|
4051
|
-
}
|
|
4052
|
-
/**
|
|
4053
|
-
* The calendar as the browser sends it.
|
|
4054
|
-
* @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the days and ids are acceptable is checked as the file is read.
|
|
4055
|
-
*/
|
|
4056
|
-
function parseCalendarEdit(value) {
|
|
4057
|
-
const problems = [];
|
|
4058
|
-
if (!isObject(value)) throw new InvalidEditProblems(["the calendar must be { hemisphere, holidays: [...] }"]);
|
|
4059
|
-
if (value["hemisphere"] !== "north" && value["hemisphere"] !== "south") problems.push("hemisphere must be \"north\" or \"south\"");
|
|
4060
|
-
const list = Array.isArray(value["holidays"]) ? value["holidays"] : void 0;
|
|
4061
|
-
if (list === void 0) problems.push("holidays must be a list");
|
|
4062
|
-
const holidays = (list ?? []).map((entry, index) => {
|
|
4063
|
-
const at = `holidays[${index}]`;
|
|
4064
|
-
if (!isObject(entry)) {
|
|
4065
|
-
problems.push(`${at} must be an object`);
|
|
4066
|
-
return {
|
|
4067
|
-
id: "",
|
|
4068
|
-
name: "",
|
|
4069
|
-
on: []
|
|
4070
|
-
};
|
|
4071
|
-
}
|
|
4072
|
-
for (const key of Object.keys(entry)) if (![
|
|
4073
|
-
"id",
|
|
4074
|
-
"name",
|
|
4075
|
-
"on"
|
|
4076
|
-
].includes(key)) problems.push(`${at}.${key} is not a field of a holiday`);
|
|
4077
|
-
for (const key of ["id", "name"]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
4078
|
-
if (!(Array.isArray(entry["on"]) && entry["on"].every((day) => typeof day === "string"))) problems.push(`${at}.on must be a list of days`);
|
|
4079
|
-
return {
|
|
4080
|
-
id: typeof entry["id"] === "string" ? entry["id"].trim() : "",
|
|
4081
|
-
name: typeof entry["name"] === "string" ? entry["name"].trim() : "",
|
|
4082
|
-
on: Array.isArray(entry["on"]) ? entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") : []
|
|
4083
|
-
};
|
|
4084
|
-
});
|
|
4085
|
-
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
4086
|
-
return {
|
|
4087
|
-
hemisphere: value["hemisphere"],
|
|
4088
|
-
holidays
|
|
4089
|
-
};
|
|
4090
|
-
}
|
|
4091
3839
|
// src/host/http/routes/worldFiles.ts
|
|
4092
3840
|
/** The routes of the API for worldFiles. */
|
|
4093
3841
|
function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
|
|
@@ -4343,6 +4091,28 @@ function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
|
|
|
4343
4091
|
}
|
|
4344
4092
|
}
|
|
4345
4093
|
},
|
|
4094
|
+
"/worlds/commands": {
|
|
4095
|
+
GET: async (_req, res, url) => {
|
|
4096
|
+
try {
|
|
4097
|
+
sendJson(res, 200, await worldFiles.commands(url.searchParams.get("id") ?? ""));
|
|
4098
|
+
} catch (error) {
|
|
4099
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
4100
|
+
throw error;
|
|
4101
|
+
}
|
|
4102
|
+
},
|
|
4103
|
+
PUT: async (req, res, url) => {
|
|
4104
|
+
try {
|
|
4105
|
+
sendJson(res, 200, await worldFiles.editCommands(url.searchParams.get("id") ?? "", parseCommandsEdit(await readJsonBody(req))));
|
|
4106
|
+
} catch (error) {
|
|
4107
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
4108
|
+
if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
|
|
4109
|
+
message: error.message,
|
|
4110
|
+
problems: error.problems
|
|
4111
|
+
});
|
|
4112
|
+
throw error;
|
|
4113
|
+
}
|
|
4114
|
+
}
|
|
4115
|
+
},
|
|
4346
4116
|
"/worlds/calendar": {
|
|
4347
4117
|
GET: async (_req, res, url) => {
|
|
4348
4118
|
try {
|
|
@@ -6067,7 +5837,21 @@ const SINGLE = [
|
|
|
6067
5837
|
"dsh-agentic-roleplay-core",
|
|
6068
5838
|
"dsh-roleplay-state"
|
|
6069
5839
|
];
|
|
6070
|
-
/**
|
|
5840
|
+
/**
|
|
5841
|
+
* The profile directory DSH launched this plugin in: `DSH_PROFILE_DIR`, which a profile-launched Host carries, or
|
|
5842
|
+
* `DSH_HOME/profiles/<DSH_PROFILE>` when only those are set (a `dsh` CLI launch). Both are environment facts; a
|
|
5843
|
+
* Harness booted without a profile has none.
|
|
5844
|
+
*/
|
|
5845
|
+
function profileDirectory() {
|
|
5846
|
+
if (process.env.DSH_PROFILE_DIR !== void 0) return process.env.DSH_PROFILE_DIR;
|
|
5847
|
+
const home = process.env.DSH_HOME;
|
|
5848
|
+
const profile = process.env.DSH_PROFILE;
|
|
5849
|
+
return home === void 0 || profile === void 0 ? void 0 : join(home, "profiles", profile);
|
|
5850
|
+
}
|
|
5851
|
+
/**
|
|
5852
|
+
* The bundle layers the profile has selected, in order; none when there is no profile to read. DSH exposes no
|
|
5853
|
+
* service for a profile's selected bundles, so this reads the profile's own manifest — never writes it.
|
|
5854
|
+
*/
|
|
6071
5855
|
function selectedBundles(profileDir) {
|
|
6072
5856
|
if (profileDir === void 0) return [];
|
|
6073
5857
|
try {
|
|
@@ -6087,157 +5871,6 @@ function redundantLayers(bundles) {
|
|
|
6087
5871
|
function redundantLayersMessage(layers) {
|
|
6088
5872
|
return `the profile selects ${layers.map((name) => `"${name}"`).join(", ")} next to the all bundle, which already inserts the same plugin rows, so DSH refuses to save the Role Play settings: deselect them (keep the packages installed) and restart`;
|
|
6089
5873
|
}
|
|
6090
|
-
// src/host/worlds/daily-life.ts
|
|
6091
|
-
/** The day each character lives, and the places its windows may name. */
|
|
6092
|
-
async function readRoutines(world) {
|
|
6093
|
-
const [{ characters }, { locations }] = await Promise.all([loadCharacters(world.directory), loadLocations(world.directory)]);
|
|
6094
|
-
return {
|
|
6095
|
-
characters: characters.map((character) => ({
|
|
6096
|
-
key: character.id,
|
|
6097
|
-
name: character.name,
|
|
6098
|
-
routine: character.routine ?? []
|
|
6099
|
-
})),
|
|
6100
|
-
places: locations.map((place) => ({
|
|
6101
|
-
key: place.id,
|
|
6102
|
-
name: place.name,
|
|
6103
|
-
features: place.features.map((feature) => ({
|
|
6104
|
-
key: feature.key,
|
|
6105
|
-
name: feature.name
|
|
6106
|
-
}))
|
|
6107
|
-
}))
|
|
6108
|
-
};
|
|
6109
|
-
}
|
|
6110
|
-
/**
|
|
6111
|
-
* Replaces the day of one character in its file, keeping everything else in it. The times, days and places are checked as the world is read at a start.
|
|
6112
|
-
* @throws {InvalidEditProblems} when the character does not exist or a window is not acceptable; nothing is written.
|
|
6113
|
-
*/
|
|
6114
|
-
async function editRoutine(world, key, windows) {
|
|
6115
|
-
const folder = await entityFolder(world.directory, CHARACTERS_DIR, CHARACTER_FILE_NAME, key, parseCharacterFile);
|
|
6116
|
-
if (folder === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
|
|
6117
|
-
const file = join(world.directory, CHARACTERS_DIR, folder, CHARACTER_FILE_NAME);
|
|
6118
|
-
const text = (await readFile(file, "utf8")).replace(/^/, "");
|
|
6119
|
-
const document = JSON.parse(text);
|
|
6120
|
-
if (windows.length === 0) delete document["routine"];
|
|
6121
|
-
else document["routine"] = windows;
|
|
6122
|
-
const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
|
|
6123
|
-
const parsed = parseCharacterFile(next, folder);
|
|
6124
|
-
if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
|
|
6125
|
-
const { locations } = await loadLocations(world.directory);
|
|
6126
|
-
const { calendar } = await loadCalendar(world.directory);
|
|
6127
|
-
const places = routineProblems([parsed.value], locations, calendar);
|
|
6128
|
-
if (places.length > 0) throw new InvalidEditProblems(places);
|
|
6129
|
-
await replaceFile(file, next);
|
|
6130
|
-
return await readRoutines(world);
|
|
6131
|
-
}
|
|
6132
|
-
/** The variables the world declares, as the file writes them. */
|
|
6133
|
-
async function readVariables(world) {
|
|
6134
|
-
try {
|
|
6135
|
-
const parsed = JSON.parse((await readFile(join(world.directory, VARIABLES_FILE_NAME), "utf8")).replace(/^/, ""));
|
|
6136
|
-
return Array.isArray(parsed) ? parsed : [];
|
|
6137
|
-
} catch (error) {
|
|
6138
|
-
if (error.code === "ENOENT") return [];
|
|
6139
|
-
throw error;
|
|
6140
|
-
}
|
|
6141
|
-
}
|
|
6142
|
-
/**
|
|
6143
|
-
* Replaces the world's declarations. They are read as the world is at a start and checked against everything that has a value for one: a variable a
|
|
6144
|
-
* character, item, place or the world still gives a value to cannot be removed, and a value must still fit its declaration.
|
|
6145
|
-
* @throws {InvalidEditProblems} naming each problem; nothing is written.
|
|
6146
|
-
*/
|
|
6147
|
-
async function editVariables(world, declarations) {
|
|
6148
|
-
const text = `${JSON.stringify(declarations, null, 2)}\n`;
|
|
6149
|
-
const parsed = parseVariablesFile(text);
|
|
6150
|
-
if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
|
|
6151
|
-
const [{ characters }, { locations }] = await Promise.all([loadCharacters(world.directory), loadLocations(world.directory)]);
|
|
6152
|
-
const { items } = await loadItems(world.directory, {
|
|
6153
|
-
characters: characters.map((character) => character.id),
|
|
6154
|
-
locations
|
|
6155
|
-
});
|
|
6156
|
-
const worldFile = parseWorldFile(await readFile(join(world.directory, WORLD_FILE_NAME), "utf8"));
|
|
6157
|
-
const problems = variableProblems({
|
|
6158
|
-
defs: parsed.value,
|
|
6159
|
-
characters,
|
|
6160
|
-
items,
|
|
6161
|
-
locations,
|
|
6162
|
-
values: worldFile.ok ? worldFile.value.variables : void 0
|
|
6163
|
-
});
|
|
6164
|
-
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
6165
|
-
if (declarations.length === 0) await rm(join(world.directory, VARIABLES_FILE_NAME), { force: true });
|
|
6166
|
-
else await replaceFileOrCreate(join(world.directory, VARIABLES_FILE_NAME), text);
|
|
6167
|
-
return await readVariables(world);
|
|
6168
|
-
}
|
|
6169
|
-
async function replaceFileOrCreate(file, text) {
|
|
6170
|
-
try {
|
|
6171
|
-
await replaceFile(file, text);
|
|
6172
|
-
} catch (error) {
|
|
6173
|
-
if (error.code !== "ENOENT") throw error;
|
|
6174
|
-
await writeFile(file, text, { flag: "wx" });
|
|
6175
|
-
}
|
|
6176
|
-
}
|
|
6177
|
-
/** The calendar of the world as `calendar.json` writes it; a world without one has the northern seasons and no holidays. */
|
|
6178
|
-
async function readCalendarDocument(world) {
|
|
6179
|
-
const { calendar } = await loadCalendar(world.directory);
|
|
6180
|
-
return {
|
|
6181
|
-
hemisphere: calendar.hemisphere,
|
|
6182
|
-
holidays: calendar.holidays.map((holiday) => ({
|
|
6183
|
-
id: holiday.id,
|
|
6184
|
-
name: holiday.name,
|
|
6185
|
-
on: [...holiday.on]
|
|
6186
|
-
}))
|
|
6187
|
-
};
|
|
6188
|
-
}
|
|
6189
|
-
/**
|
|
6190
|
-
* Replaces the calendar. The days are read as the file is at a start, and a holiday that a routine of a character or a trigger still names cannot be removed or renamed.
|
|
6191
|
-
* A calendar with no holidays and the northern seasons is no file at all.
|
|
6192
|
-
* @throws {InvalidEditProblems} naming each problem; nothing is written.
|
|
6193
|
-
*/
|
|
6194
|
-
async function editCalendar(world, calendar) {
|
|
6195
|
-
const text = `${JSON.stringify(calendar, null, 2)}\n`;
|
|
6196
|
-
const parsed = parseCalendarFile(text);
|
|
6197
|
-
if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
|
|
6198
|
-
const [{ characters }, { locations }] = await Promise.all([loadCharacters(world.directory), loadLocations(world.directory)]);
|
|
6199
|
-
const problems = routineProblems(characters, locations, parsed.value);
|
|
6200
|
-
const triggers = await readFile(join(world.directory, TRIGGERS_FILE_NAME), "utf8").catch((error) => {
|
|
6201
|
-
if (error.code === "ENOENT") return "";
|
|
6202
|
-
throw error;
|
|
6203
|
-
});
|
|
6204
|
-
const named = new Set(calendar.holidays.map((holiday) => holiday.id));
|
|
6205
|
-
for (const id of new Set([...triggers.matchAll(/holiday:([\p{L}\p{N}_-]+)/gu)].map((match) => match[1]))) if (!named.has(id)) problems.push(`a trigger names the holiday "${id}", which the calendar does not have`);
|
|
6206
|
-
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
6207
|
-
if (calendar.holidays.length === 0 && calendar.hemisphere === "north") await rm(join(world.directory, CALENDAR_FILE_NAME), { force: true });
|
|
6208
|
-
else await replaceFileOrCreate(join(world.directory, CALENDAR_FILE_NAME), text);
|
|
6209
|
-
return await readCalendarDocument(world);
|
|
6210
|
-
}
|
|
6211
|
-
/** The checks of a world as its `dice.json` has them; none without the file. */
|
|
6212
|
-
async function readDiceDocument(world) {
|
|
6213
|
-
const { checks } = await loadDice(world.directory);
|
|
6214
|
-
return { checks };
|
|
6215
|
-
}
|
|
6216
|
-
/**
|
|
6217
|
-
* Replaces the world's checks. They are read as a story start reads them, and a quality of the character that a check adds must be a number the world
|
|
6218
|
-
* declares for characters. No checks is no file at all.
|
|
6219
|
-
* @throws {InvalidEditProblems} naming each problem; nothing is written.
|
|
6220
|
-
*/
|
|
6221
|
-
async function editDice(world, dice) {
|
|
6222
|
-
const written = dice.checks.map(({ reading, compare, ...check }) => ({
|
|
6223
|
-
...check,
|
|
6224
|
-
...reading === void 0 || reading === "total" ? {} : { reading },
|
|
6225
|
-
...compare === void 0 || compare === "absolute" ? {} : { compare }
|
|
6226
|
-
}));
|
|
6227
|
-
const text = `${JSON.stringify({ checks: written }, null, 2)}\n`;
|
|
6228
|
-
const parsed = parseDiceFile(text);
|
|
6229
|
-
if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
|
|
6230
|
-
const declared = await loadVariables(world.directory);
|
|
6231
|
-
const problems = parsed.value.flatMap((check) => {
|
|
6232
|
-
if (check.modifier === void 0) return [];
|
|
6233
|
-
const variable = declared.defs.find((def) => def.key === check.modifier);
|
|
6234
|
-
return variable === void 0 || variable.kind !== "number" || variable.subject !== "character" ? [`the check "${check.key}" adds "${check.modifier}", which the world does not declare as a number about characters (Tracked values)`] : [];
|
|
6235
|
-
});
|
|
6236
|
-
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
6237
|
-
if (dice.checks.length === 0) await rm(join(world.directory, DICE_FILE_NAME), { force: true });
|
|
6238
|
-
else await replaceFileOrCreate(join(world.directory, DICE_FILE_NAME), text);
|
|
6239
|
-
return await readDiceDocument(world);
|
|
6240
|
-
}
|
|
6241
5874
|
// src/host/worlds/lore-entries.ts
|
|
6242
5875
|
const MAX_TITLE = 200;
|
|
6243
5876
|
/**
|
|
@@ -8249,7 +7882,11 @@ async function installWorld(catalog, archive, maxBytes, options) {
|
|
|
8249
7882
|
await mkdir(catalog.directory, { recursive: true });
|
|
8250
7883
|
if (replacing !== void 0) {
|
|
8251
7884
|
placed = basename(replacing.directory);
|
|
8252
|
-
backup =
|
|
7885
|
+
backup = [
|
|
7886
|
+
".trash",
|
|
7887
|
+
"worlds",
|
|
7888
|
+
`${placed}-${stamp()}`
|
|
7889
|
+
].join("/");
|
|
8253
7890
|
await mkdir(join(root, dirname(backup)), { recursive: true });
|
|
8254
7891
|
await rename(replacing.directory, join(root, backup));
|
|
8255
7892
|
} else placed = freeFolder(catalog.directory, folder);
|
|
@@ -10107,7 +9744,7 @@ const name = "@dsh-agentic-roleplay/core";
|
|
|
10107
9744
|
/** Sessions are kept by the state plugin, which the bundle installs with this one. */
|
|
10108
9745
|
const inject = ["roleplayState"];
|
|
10109
9746
|
function apply(ctx, config) {
|
|
10110
|
-
const layers = () => redundantLayers(selectedBundles(
|
|
9747
|
+
const layers = () => redundantLayers(selectedBundles(profileDirectory()));
|
|
10111
9748
|
const repeated = layers();
|
|
10112
9749
|
if (repeated.length > 0) ctx.logger.error(redundantLayersMessage(repeated));
|
|
10113
9750
|
ctx.inject(["aiProviders"], (scope) => {
|
|
@@ -10219,6 +9856,14 @@ function apply(ctx, config) {
|
|
|
10219
9856
|
};
|
|
10220
9857
|
const staging = new ImportStaging();
|
|
10221
9858
|
const purgeChat = purgeOf(ctx, config.sessionStorePath);
|
|
9859
|
+
const chatStatus = (chatSessionId) => {
|
|
9860
|
+
const live = ctx.get("agents")?.get(SessionId(chatSessionId));
|
|
9861
|
+
return {
|
|
9862
|
+
chatSessionId,
|
|
9863
|
+
turns: roleplayImport.turnsOf(chatSessionId),
|
|
9864
|
+
running: live !== void 0 && live.status !== "idle"
|
|
9865
|
+
};
|
|
9866
|
+
};
|
|
10222
9867
|
const deps = {
|
|
10223
9868
|
worlds,
|
|
10224
9869
|
state: ctx.roleplayState,
|
|
@@ -10394,6 +10039,24 @@ function apply(ctx, config) {
|
|
|
10394
10039
|
if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
|
|
10395
10040
|
return { chatSessionId: await authoring.ensure(world.summary.id, world.summary.name, title, language) };
|
|
10396
10041
|
},
|
|
10042
|
+
sayToAuthor: async (worldId, text, language) => {
|
|
10043
|
+
const world = await worlds.find(worldId);
|
|
10044
|
+
if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
|
|
10045
|
+
const chatSessionId = await authoring.ensure(world.summary.id, world.summary.name, void 0, language);
|
|
10046
|
+
await authoring.send(chatSessionId, text);
|
|
10047
|
+
return { chatSessionId };
|
|
10048
|
+
},
|
|
10049
|
+
authoringStatus: async (worldId) => {
|
|
10050
|
+
const world = await worlds.find(worldId);
|
|
10051
|
+
if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
|
|
10052
|
+
return chatStatus(authoringChatSessionId(world.summary.id));
|
|
10053
|
+
},
|
|
10054
|
+
chatStatus,
|
|
10055
|
+
forgetAuthoring: async (worldId) => {
|
|
10056
|
+
const world = await worlds.find(worldId);
|
|
10057
|
+
if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
|
|
10058
|
+
await purgeChat(authoringChatSessionId(world.summary.id));
|
|
10059
|
+
},
|
|
10397
10060
|
translation: {
|
|
10398
10061
|
language: (id) => worldLanguage(worlds, id),
|
|
10399
10062
|
start: (id, to, title, language) => startTranslation({
|
|
@@ -10499,6 +10162,8 @@ function apply(ctx, config) {
|
|
|
10499
10162
|
editRoutine: async (worldId, key, windows) => await editRoutine(await editableWorld(worlds, worldId, root.path), key, windows),
|
|
10500
10163
|
dice: async (worldId) => await readDiceDocument(await editableWorld(worlds, worldId, root.path)),
|
|
10501
10164
|
editDice: async (worldId, dice) => await editDice(await editableWorld(worlds, worldId, root.path), dice),
|
|
10165
|
+
commands: async (worldId) => await readCommandsDocument(await editableWorld(worlds, worldId, root.path)),
|
|
10166
|
+
editCommands: async (worldId, commands) => await editCommands(await editableWorld(worlds, worldId, root.path), commands),
|
|
10502
10167
|
calendar: async (worldId) => await readCalendarDocument(await editableWorld(worlds, worldId, root.path)),
|
|
10503
10168
|
editCalendar: async (worldId, calendar) => await editCalendar(await editableWorld(worlds, worldId, root.path), calendar),
|
|
10504
10169
|
variables: async (worldId) => await readVariables(await editableWorld(worlds, worldId, root.path)),
|