@dsh-agentic-roleplay/core 0.12.3 → 0.12.5

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.
Files changed (37) hide show
  1. package/lib/{access-Csp80TFX.js → access-DjA0kvPM.js} +2 -2
  2. package/lib/{authoring-tools-hacA5fG-.js → authoring-tools-DqAttdUN.js} +260 -36
  3. package/lib/authoring.js +176 -10
  4. package/lib/{child-DTdY14S9.js → child-SMvjNsb8.js} +63 -9
  5. package/lib/client.js +2043 -1236
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -3
  8. package/lib/doctor.js +3 -3
  9. package/lib/{gallery-BNg0rPTp.js → gallery-Dahi5TkO.js} +3 -3
  10. package/lib/{generator-9-5at9cZ.js → generator-BvSZGpzy.js} +2 -2
  11. package/lib/helper.js +2 -2
  12. package/lib/{hooks-DlrFO4aQ.js → hooks-OLl-1AOS.js} +67 -28
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +45 -30
  15. package/lib/{jail-DVbPSC0R.js → jail-CDW5iymd.js} +2 -2
  16. package/lib/{library-DTxakw0z.js → library-D6AcyxGZ.js} +3 -3
  17. package/lib/{lorebook-author-tools-dupq-kb_.js → lorebook-author-tools-CXV1KD4Q.js} +7 -7
  18. package/lib/lorebook-authoring.js +5 -5
  19. package/lib/{narration--K2XVIHI.js → narration-Bnrvl0UQ.js} +2 -2
  20. package/lib/orchestration.js +37 -38
  21. package/lib/{pack-jail-Bq0fzKi4.js → pack-jail-CZAmlgE1.js} +16 -15
  22. package/lib/{packs-D-7EU3yU.js → packs-DUVCSHqi.js} +2 -2
  23. package/lib/{presenter-agent-vFOxIuWv.js → presenter-agent-CGCJrg7V.js} +7 -6
  24. package/lib/{preset-RHcOG55T.js → preset-BYfXYvp0.js} +4 -4
  25. package/lib/{preset-author-tools-Dwxnpv6V.js → preset-author-tools-DYxTLm9U.js} +7 -7
  26. package/lib/preset-authoring.js +5 -5
  27. package/lib/{reflection-DibpEUQK.js → reflection-C3zdufN9.js} +8 -8
  28. package/lib/{serial-CDGoXYh-.js → serial-Bh6gqb3f.js} +239 -51
  29. package/lib/{text-Dfv8S8eq.js → text-B-HsLdb-.js} +4 -1
  30. package/lib/{turn-guard-DDxikrq7.js → turn-guard-CNFvmz_F.js} +3 -3
  31. package/package.json +2 -2
  32. package/prompts/en/import/opening.md +17 -0
  33. package/prompts/en/roleplay/decide-opening.md +1 -0
  34. package/prompts/en/world/procedure.md +1 -1
  35. package/prompts/zh/import/opening.md +17 -0
  36. package/prompts/zh/roleplay/decide-opening.md +1 -0
  37. package/prompts/zh/world/procedure.md +1 -1
@@ -1,4 +1,4 @@
1
- import { j as roleplaySessionOf } from "./child-DTdY14S9.js";
1
+ import { j as roleplaySessionOf } from "./child-SMvjNsb8.js";
2
2
  import { basename, dirname, join } from "node:path";
3
3
  import { chmodSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
4
  import { randomUUID } from "node:crypto";
@@ -183,4 +183,4 @@ function promptFor(agent, id, language, variables) {
183
183
  }
184
184
  export { VARIABLE_KINDS as a, atomicWriteSync as i, atomicWrite as n, VARIABLE_SUBJECTS as o, atomicWriteJson as r, VARIABLE_VISIBILITIES as s, promptFor as t };
185
185
 
186
- //# sourceMappingURL=access-Csp80TFX.js.map
186
+ //# sourceMappingURL=access-DjA0kvPM.js.map
@@ -1,10 +1,10 @@
1
- import { T as currentTurn, c as namedModel, l as runChild, m as parseSampling, t as ChildTimeoutError } from "./child-DTdY14S9.js";
2
- import { $t as SLOTS_FILE_NAME, Bt as findPanel, C as ROLE_TABLE, Ct as IMPORT_FOLDER, Dt as openingText, E as askYesNo, Et as PICTURE_FILE, Gt as loadVariables, Ht as dialectOf, Jt as LORE_FILE_NAME, M as WORLD_FILE_NAME, N as parseWorldFile, Qt as ITEM_FILE_NAME, R as startQuestionsToFile, Rt as IMPORT_COMMAND, S as ROLES, St as withPlayer, Vt as splitPanels, Wt as VARIABLES_FILE_NAME, Xt as LOCATION_FILE_NAME, Yt as parseLoreFile, Zt as parseLocationFile, _ as pruneRelationships, _t as loadLore, a as characterDocument, an as parseCharacterFile, b as classifyItems, bt as itemise, c as extractStyle, d as inert, en as parseItemFile, f as loreDocuments, g as pruneMembers, gt as LORE_DIR, h as pruneLoreSubjects, i as asWritten, in as CHARACTER_FILE_NAME, j as yesAt, jt as InvalidEditProblems, k as noAt, kt as readImportFolder, ln as WEEKDAY_NAMES, m as pruneLinks, nn as FACTION_FILE_NAME, o as emptyExtracted, on as guarded, p as pruneKnowledge, qt as variableProblems, r as addLore, rn as parseFactionFile, s as extractEntities, t as SerialQueue, tn as parseSlotsFile, u as extractVariables, un as DEFAULT_SLOTS, v as sourcesFor, vt as subfolders, w as isLeftOut, x as findEntity, y as buildRoster, yt as cleanText, zt as importRequestOf } from "./serial-CDGoXYh-.js";
3
- import { f as parseSwitchboard } from "./narration--K2XVIHI.js";
4
- import { n as atomicWrite, r as atomicWriteJson } from "./access-Csp80TFX.js";
5
- import { $ as copyWorldPrompts, G as readDocument$1, J as errorMessage, K as Reader, U as commandFlagKey, V as plotReferenceProblems, Z as PROMPTS_FOLDER, c as externalWithheld, ht as registerCommands, it as shippedLanguages, lt as InvalidWorldError, nt as listFiles, o as externalGiven, ot as shippedText, q as formatIssue, rt as promptProblem, t as externalToolLimit, xt as COMPARISONS, z as loadPlots } from "./hooks-DlrFO4aQ.js";
6
- import { t as trimCharacters } from "./text-Dfv8S8eq.js";
7
- import { C as slug, S as norm, T as uniqueKey, _ as writeImageFileMetadata, b as NoEmbeddingService, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as trOf, x as mapLimit } from "./library-DTxakw0z.js";
1
+ import { T as currentTurn, c as namedModel, l as runChild, m as parseSampling, t as ChildTimeoutError } from "./child-SMvjNsb8.js";
2
+ import { $t as LOCATION_FILE_NAME, At as openingText, C as ROLE_TABLE, Ct as itemise, E as askYesNo, Et as IMPORT_FOLDER, Gt as dialectOf, Ht as importRequestOf, Jt as loadVariables, L as parseOpeningParts, M as WORLD_FILE_NAME, Mt as readImportFolder, N as parseWorldFile, P as MAX_OPENING_CHARS, Pt as InvalidEditProblems, Qt as parseLoreFile, R as partsText, S as ROLES, St as cleanText, Tt as withPlayer, Ut as findPanel, V as startQuestionsToFile, Vt as IMPORT_COMMAND, Wt as splitPanels, Xt as variableProblems, Zt as LORE_FILE_NAME, _ as pruneRelationships, a as characterDocument, an as FACTION_FILE_NAME, b as classifyItems, bt as loadLore, c as extractStyle, cn as parseCharacterFile, d as inert, en as parseLocationFile, f as loreDocuments, fn as WEEKDAY_NAMES, g as pruneMembers, h as pruneLoreSubjects, i as asWritten, in as parseSlotsFile, j as yesAt, k as noAt, kt as PICTURE_FILE, ln as guarded, m as pruneLinks, nn as SLOTS_FILE_NAME, o as emptyExtracted, on as parseFactionFile, p as pruneKnowledge, pn as DEFAULT_SLOTS, qt as VARIABLES_FILE_NAME, r as addLore, rn as parseItemFile, s as extractEntities, sn as CHARACTER_FILE_NAME, t as SerialQueue, tn as ITEM_FILE_NAME, u as extractVariables, v as sourcesFor, w as isLeftOut, x as findEntity, xt as subfolders, y as buildRoster, yt as LORE_DIR } from "./serial-Bh6gqb3f.js";
3
+ import { f as parseSwitchboard } from "./narration-Bnrvl0UQ.js";
4
+ import { n as atomicWrite, r as atomicWriteJson } from "./access-DjA0kvPM.js";
5
+ import { $ as copyWorldPrompts, G as readDocument$1, J as errorMessage, K as Reader, U as commandFlagKey, V as plotReferenceProblems, Z as PROMPTS_FOLDER, c as externalWithheld, ht as registerCommands, it as shippedLanguages, lt as InvalidWorldError, nt as listFiles, o as externalGiven, ot as shippedText, q as formatIssue, rt as promptProblem, t as externalToolLimit, xt as COMPARISONS, z as loadPlots } from "./hooks-OLl-1AOS.js";
6
+ import { t as trimCharacters } from "./text-B-HsLdb-.js";
7
+ import { C as slug, S as norm, T as uniqueKey, _ as writeImageFileMetadata, b as NoEmbeddingService, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as trOf, x as mapLimit } from "./library-D6AcyxGZ.js";
8
8
  import { join, relative, sep } from "node:path";
9
9
  import { MINUTE, MONTH_NAMES, SEASONS, checkProblems, createSessionStore, dayTokenProblems, lintWorld, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, writeCalendar } from "@dsh-agentic-roleplay/state";
10
10
  import { createHash } from "node:crypto";
@@ -581,17 +581,24 @@ async function extractCasting(ctx, card, passages) {
581
581
  const MAX_EXAMPLES = 8;
582
582
  /** The summary is the start of the description: a sentence or two. */
583
583
  const SUMMARY_CHARS = 280;
584
+ /** A line an example speaks through: a short name, a colon, and what the character says. */
585
+ function spoken(line) {
586
+ const colon = line.indexOf(":");
587
+ if (colon < 1 || colon > 100) return void 0;
588
+ return {
589
+ name: line.slice(0, colon),
590
+ utterance: line.slice(colon + 1).trimStart()
591
+ };
592
+ }
584
593
  /** The lines of the example messages that the character speaks, as written; the markers of the tool that wrote them are taken out. */
585
594
  function exampleLines(text, name) {
586
595
  const lines = cleanText(text, name).split("\n").map((line) => line.trim()).filter((line) => line !== "");
587
- const speaker = /^([^:\n]{1,100}):\s*(.*)$/;
588
- if (!lines.some((line) => speaker.test(line))) return lines.slice(0, MAX_EXAMPLES);
596
+ if (!lines.some((line) => spoken(line) !== void 0)) return lines.slice(0, MAX_EXAMPLES);
589
597
  const names = new Set([name, name.split(/\s+/)[0] ?? ""].map((part) => part.toLocaleLowerCase()));
590
598
  return lines.flatMap((line) => {
591
- const match = speaker.exec(line);
592
- if (match?.[1] === void 0 || !names.has(match[1].trim().toLocaleLowerCase())) return [];
593
- const utterance = match[2]?.trim();
594
- return utterance === void 0 || utterance === "" ? [] : [utterance];
599
+ const match = spoken(line);
600
+ if (match === void 0 || !names.has(match.name.trim().toLocaleLowerCase())) return [];
601
+ return match.utterance === "" ? [] : [match.utterance];
595
602
  }).slice(0, MAX_EXAMPLES);
596
603
  }
597
604
  /**
@@ -1130,6 +1137,173 @@ function originOf(card, choices, pieces, records, name, items = itemise(card, ch
1130
1137
  }];
1131
1138
  });
1132
1139
  }
1140
+ // src/host/import/opening-parts.ts
1141
+ const SCHEMA = {
1142
+ type: "object",
1143
+ properties: { parts: {
1144
+ type: "array",
1145
+ items: {
1146
+ type: "object",
1147
+ properties: {
1148
+ kind: {
1149
+ type: "string",
1150
+ enum: ["narration", "speech"]
1151
+ },
1152
+ speaker: { type: "string" },
1153
+ text: { type: "string" }
1154
+ },
1155
+ required: [
1156
+ "kind",
1157
+ "speaker",
1158
+ "text"
1159
+ ],
1160
+ additionalProperties: false
1161
+ }
1162
+ } },
1163
+ required: ["parts"],
1164
+ additionalProperties: false
1165
+ };
1166
+ const MAX_SHOWN = 6e3;
1167
+ const QUOTES = /["'“”‘’「」『』«»„‟*_]/gu;
1168
+ /** The letters of a passage with quotation marks, emphasis marks, labels that name a speaker and all spacing taken out: what must be the same before and after splitting. */
1169
+ function lettersOf$1(text, speakers = []) {
1170
+ let rest = text;
1171
+ for (const name of speakers.flatMap((speaker) => [speaker.name, ...speaker.aliases])) rest = rest.replace(new RegExp(`(^|\\n)\\s*${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*[::]`, "gu"), "$1");
1172
+ return rest.replace(QUOTES, "").replace(/\s+/gu, "");
1173
+ }
1174
+ /** Why an answer is not the passage split into parts; nothing when it is. */
1175
+ function splitProblem(source, parts, speakers) {
1176
+ if (parts.length === 0) return "the answer has no parts";
1177
+ const wanted = lettersOf$1(source, speakers);
1178
+ const given = lettersOf$1(partsText(parts));
1179
+ if (wanted === given) return void 0;
1180
+ let same = 0;
1181
+ while (same < wanted.length && same < given.length && wanted[same] === given[same]) same += 1;
1182
+ const around = (text) => `“${text.slice(Math.max(0, same - 8), same + 24)}”`;
1183
+ return `the parts do not hold exactly the words of the passage, in order: they agree up to ${around(wanted)} and then the passage goes on with “${wanted.slice(same, same + 24)}” where your parts have “${given.slice(same, same + 24)}”. Keep every sentence, narration between spoken lines included; change none, add none`;
1184
+ }
1185
+ /** The speaker a name (or id) names; the player's character and unknown names are nobody, so the part is narration. */
1186
+ function speakerOf(name, speakers, player) {
1187
+ const key = norm(name);
1188
+ if (key === "") return void 0;
1189
+ return speakers.find((speaker) => speaker.id !== player && [
1190
+ speaker.id,
1191
+ speaker.name,
1192
+ ...speaker.aliases
1193
+ ].some((label) => norm(label) === key));
1194
+ }
1195
+ /** The parts an answer describes, with a speaker that is not in the cast made narration. */
1196
+ function partsOf$1(answer, speakers, player) {
1197
+ const list = Array.isArray(answer.parts) ? answer.parts : [];
1198
+ const parts = [];
1199
+ for (const entry of list) {
1200
+ if (typeof entry !== "object" || entry === null) continue;
1201
+ const body = entry;
1202
+ const text = typeof body["text"] === "string" ? tidyQuotes(body["text"]) : "";
1203
+ if (text === "") continue;
1204
+ const speaker = (body["kind"] ?? body["type"]) === "narration" ? void 0 : speakerOf(typeof body["speaker"] === "string" ? body["speaker"] : "", speakers, player);
1205
+ parts.push(speaker === void 0 ? {
1206
+ type: "narration",
1207
+ text
1208
+ } : {
1209
+ type: "utterance",
1210
+ character: speaker.id,
1211
+ text
1212
+ });
1213
+ }
1214
+ return parts;
1215
+ }
1216
+ const PAIRS = [
1217
+ ["“", "”"],
1218
+ ["‘", "’"],
1219
+ ["「", "」"],
1220
+ ["『", "』"],
1221
+ ["«", "»"],
1222
+ ["„", "“"]
1223
+ ];
1224
+ const count = (text, mark) => text.split(mark).length - 1;
1225
+ /**
1226
+ * A part's words without the quotation marks that belong to its surroundings: the marks around a whole quoted line, and a mark left at an edge by a cut that fell inside a quotation
1227
+ * (an opening mark with no closing one, a closing mark with no opening one). A balanced quotation inside the words stays.
1228
+ */
1229
+ function tidyQuotes(text) {
1230
+ let result = text.trim();
1231
+ for (const [open, close] of [...PAIRS, ["\"", "\""]]) {
1232
+ const inside = result.slice(1, -1);
1233
+ if (result.length > 1 && result.startsWith(open) && result.endsWith(close) && !inside.includes(open) && !inside.includes(close)) result = inside.trim();
1234
+ }
1235
+ result = result.replace(/^[”’」』»\s]+/u, "").replace(/[“‘「『«„\s]+$/u, "");
1236
+ for (const [open, close] of PAIRS) {
1237
+ if (result.startsWith(open) && count(result, open) > count(result, close)) result = result.slice(1).trim();
1238
+ if (result.endsWith(close) && count(result, close) > count(result, open)) result = result.slice(0, -1).trim();
1239
+ }
1240
+ if (count(result, "\"") % 2 === 1) result = (result.startsWith("\"") ? result.slice(1) : result.endsWith("\"") ? result.slice(0, -1) : result).trim();
1241
+ return result;
1242
+ }
1243
+ /** A stretch of the passage without the spacing and the quotation marks at its ends: an opening quote belongs to the line after it, a closing one to the line before. */
1244
+ const unquoted = (text) => text.replace(/^[\s"“”‘’「」『』«»„‟]+|[\s"“”‘’「」『』«»„‟]+$/gu, "");
1245
+ /**
1246
+ * Puts back, as narration, the words of the passage that no part holds (a sentence between two spoken lines that the model skipped), when every part can be found in the passage in order.
1247
+ * Nothing is invented: a part that is not in the passage as written leaves the answer as it is, for the check to refuse.
1248
+ */
1249
+ function mendParts(source, parts, speakers) {
1250
+ const mended = [];
1251
+ let at = 0;
1252
+ for (const part of parts) {
1253
+ const found = source.indexOf(part.text, at);
1254
+ if (found < 0) return [...parts];
1255
+ const gap = unquoted(source.slice(at, found));
1256
+ if (lettersOf$1(gap, speakers) !== "") mended.push({
1257
+ type: "narration",
1258
+ text: gap
1259
+ });
1260
+ mended.push(part);
1261
+ at = found + part.text.length;
1262
+ }
1263
+ const tail = unquoted(source.slice(at));
1264
+ if (lettersOf$1(tail, speakers) !== "") mended.push({
1265
+ type: "narration",
1266
+ text: tail
1267
+ });
1268
+ return mended;
1269
+ }
1270
+ /**
1271
+ * Decides whether an opening is pure narration (kept as plain text) or has characters speaking (split into parts), and splits it. With a decision model the closed question
1272
+ * "does anyone speak" is asked first and a sure answer settles it; otherwise, or when it is unsure, the language model answers both in one reply. With no model the
1273
+ * opening stays as it is. A split that does not hold exactly the passage's words is refused, and the opening then stays plain with a note: no text is lost or invented.
1274
+ */
1275
+ async function shapeOpening(ctx, passage, speakers, player) {
1276
+ const plain = { text: passage };
1277
+ if (ctx.noModel === true || passage.trim() === "" || speakers.every((speaker) => speaker.id === player)) return plain;
1278
+ if (ctx.decide !== void 0) try {
1279
+ const speech = (await ctx.decide({ passage: passage.slice(0, MAX_SHOWN) }, [{
1280
+ key: "speech",
1281
+ instructions: ctx.text("roleplay/decide-opening")
1282
+ }])).get("speech") ?? .5;
1283
+ const confidence = ctx.confidence ?? .7;
1284
+ if (speech <= noAt(confidence)) return plain;
1285
+ } catch {}
1286
+ try {
1287
+ const tr = trOf(ctx);
1288
+ const cast = speakers.filter((speaker) => speaker.id !== player).map((speaker) => `- ${speaker.name}`).join("\n");
1289
+ const parts = mendParts(passage, partsOf$1(await ctx.run({
1290
+ persona: ctx.text("import/opening"),
1291
+ maxTokens: Math.min(8e3, Math.max(1500, Math.ceil(passage.length / 2) + 600)),
1292
+ prompt: `${tr("Cast:")}\n${cast}\n\n${tr("Passage:")}\n${passage}`,
1293
+ result: SCHEMA,
1294
+ check: (value) => splitProblem(passage, mendParts(passage, partsOf$1(value, speakers, player), speakers), speakers)
1295
+ }), speakers, player), speakers);
1296
+ return parts.some((part) => part.type === "utterance") ? {
1297
+ text: partsText(parts),
1298
+ parts
1299
+ } : plain;
1300
+ } catch (error) {
1301
+ return {
1302
+ ...plain,
1303
+ note: `the opening could not be split into parts, so it is kept as plain text: ${error instanceof Error ? error.message : String(error)}`
1304
+ };
1305
+ }
1306
+ }
1133
1307
  // src/host/import/repair.ts
1134
1308
  const ENTITY_FILE = /^(characters|locations|factions|items|lore)\/[^/]+\/(character|location|faction|item|lore)\.json$/;
1135
1309
  /** Fields a document cannot do without, and fields that tie it to others: never dropped, whatever the problem says. */
@@ -2281,21 +2455,33 @@ const STAGE = "stage";
2281
2455
  const MAX_DESCRIPTION = 500;
2282
2456
  const MAX_TAGS = 8;
2283
2457
  const MAX_TAG = 30;
2284
- /** The card's other greetings, as the other openings a player may start with: the first message and the alternates that were not chosen. */
2458
+ /** A title for an opening taken from a card: its first words, so the start dialog shows what the story begins with. */
2459
+ function openingTitle(text) {
2460
+ const first = text.trim().split("\n")[0].replace(/\s+/g, " ");
2461
+ if (first.length <= 40) return first;
2462
+ const cut = first.slice(0, 40);
2463
+ const space = cut.lastIndexOf(" ");
2464
+ return `${(space > 15 ? cut.slice(0, space) : cut).replace(/[,;:.\s]+$/, "")}…`;
2465
+ }
2466
+ /** The card's other greetings, as the other openings a player may start with: the first message and the alternates that were not chosen, each titled by its first words. */
2285
2467
  function alternateOpenings(card, chosen, player) {
2286
2468
  if (chosen.kind === "none") return [];
2287
- return [{
2288
- title: "First message",
2469
+ const greetings = [{
2289
2470
  text: card.firstMessage,
2290
2471
  taken: chosen.kind === "first"
2291
2472
  }, ...card.alternateGreetings.map((text, index) => ({
2292
- title: `Alternate ${index + 1}`,
2293
2473
  text,
2294
2474
  taken: chosen.kind === "alternate" && chosen.index === index
2295
- }))].flatMap(({ title, text, taken }) => {
2475
+ }))];
2476
+ const used = /* @__PURE__ */ new Map();
2477
+ return greetings.flatMap(({ text, taken }) => {
2296
2478
  const cleaned = taken || text.trim() === "" ? "" : openingMessage(text, card.name, player);
2297
- return cleaned === "" || cleaned.length > 2e4 ? [] : [{
2298
- title,
2479
+ if (cleaned === "" || cleaned.length > MAX_OPENING_CHARS) return [];
2480
+ const base = openingTitle(cleaned);
2481
+ const seen = used.get(base) ?? 0;
2482
+ used.set(base, seen + 1);
2483
+ return [{
2484
+ title: seen === 0 ? base : `${base} (${seen + 1})`,
2299
2485
  text: cleaned
2300
2486
  }];
2301
2487
  }).slice(0, 30);
@@ -2582,7 +2768,23 @@ async function finishImport(ctx, input) {
2582
2768
  })}\n`);
2583
2769
  cover = true;
2584
2770
  }
2585
- const alternates = alternateOpenings(card, choices.opening, player === void 0 ? void 0 : String(player["name"]));
2771
+ const openingPlayer = player === void 0 ? void 0 : String(player["name"]);
2772
+ const speakers = extracted.characters.map((document) => ({
2773
+ id: String(document["id"]),
2774
+ name: String(document["name"]),
2775
+ aliases: Array.isArray(document["aliases"]) ? document["aliases"].filter((alias) => typeof alias === "string") : []
2776
+ }));
2777
+ const playerId = player === void 0 ? void 0 : String(player["id"]);
2778
+ const shapedMain = opening === void 0 ? void 0 : await shapeOpening(ctx, openingMessage(opening, card.name, openingPlayer), speakers, playerId);
2779
+ const shapedAlternates = await mapLimit(alternateOpenings(card, choices.opening, openingPlayer), ctx.concurrency, async (entry) => ({
2780
+ title: entry.title,
2781
+ shaped: await shapeOpening(ctx, entry.text, speakers, playerId)
2782
+ }));
2783
+ const alternates = shapedAlternates.map(({ title, shaped }) => ({
2784
+ title,
2785
+ ...shaped.parts === void 0 ? { text: shaped.text } : { parts: shaped.parts }
2786
+ }));
2787
+ for (const note of [shapedMain?.note, ...shapedAlternates.map((entry) => entry.shaped.note)]) if (note !== void 0) notes.push(note);
2586
2788
  await updateWorldFile(directory, (world) => {
2587
2789
  world["description"] = described.description;
2588
2790
  if (described.startingTime !== void 0 && world["starting_time"] === void 0) world["starting_time"] = described.startingTime;
@@ -2590,7 +2792,7 @@ async function finishImport(ctx, input) {
2590
2792
  ...typeof world["metadata"] === "object" && world["metadata"] !== null ? world["metadata"] : {},
2591
2793
  tags: described.tags
2592
2794
  };
2593
- if (opening !== void 0) world["opening_message"] = openingMessage(opening, card.name, player === void 0 ? void 0 : String(player["name"]));
2795
+ if (shapedMain !== void 0) world["opening_message"] = shapedMain.parts ?? shapedMain.text;
2594
2796
  if (alternates.length > 0) world["alternate_openings"] = alternates;
2595
2797
  if (extracted.rules.length > 0 && world["rules"] === void 0) world["rules"] = extracted.rules.slice(0, 30);
2596
2798
  if (card.creator.trim() !== "" && world["author"] === void 0) world["author"] = { name: card.creator.trim() };
@@ -3348,10 +3550,33 @@ const toolsOf = (value) => {
3348
3550
  const board = value === void 0 ? {} : parseSwitchboard(value, "tools");
3349
3551
  return typeof board === "string" ? {} : board;
3350
3552
  };
3553
+ /** The parts of an opening as the file has them; parts that cannot be read are left out. */
3554
+ function partsOf(list) {
3555
+ const parts = parseOpeningParts(list, "opening", []);
3556
+ return parts === void 0 || parts.length === 0 ? void 0 : parts;
3557
+ }
3558
+ function alternateOf(entry) {
3559
+ if (typeof entry !== "object" || entry === null) return [];
3560
+ const body = entry;
3561
+ const character = textOf(body["character"]);
3562
+ const named = character === "" ? {} : { character };
3563
+ const parts = Array.isArray(body["parts"]) ? partsOf(body["parts"]) : void 0;
3564
+ if (parts !== void 0) return [{
3565
+ title: textOf(body["title"]),
3566
+ text: partsText(parts),
3567
+ parts,
3568
+ ...named
3569
+ }];
3570
+ return typeof body["text"] === "string" ? [{
3571
+ title: textOf(body["title"]),
3572
+ text: body["text"],
3573
+ ...named
3574
+ }] : [];
3575
+ }
3351
3576
  function infoOf(document, startQuestions = []) {
3352
3577
  const opening = document["opening_message"];
3353
- const parts = Array.isArray(opening) && opening.some((part) => typeof part === "object" && part !== null && part["type"] === "utterance");
3354
- const plain = typeof opening === "string" ? opening : Array.isArray(opening) ? opening.map((part) => textOf(part?.["text"])).filter((text) => text !== "").join("\n\n") : "";
3578
+ const parts = Array.isArray(opening) ? partsOf(opening) : void 0;
3579
+ const plain = typeof opening === "string" ? opening : parts === void 0 ? "" : partsText(parts);
3355
3580
  const metadata = typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {};
3356
3581
  const author = typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {};
3357
3582
  const rules = document["rules"];
@@ -3361,7 +3586,7 @@ function infoOf(document, startQuestions = []) {
3361
3586
  tags: Array.isArray(metadata["tags"]) ? metadata["tags"].filter((tag) => typeof tag === "string") : [],
3362
3587
  rules: typeof rules === "string" ? [rules] : Array.isArray(rules) ? rules.filter((rule) => typeof rule === "string") : [],
3363
3588
  opening: plain,
3364
- openingParts: parts,
3589
+ ...parts === void 0 ? {} : { openingParts: parts },
3365
3590
  authorName: textOf(author["name"]),
3366
3591
  authorUrl: textOf(author["url"]),
3367
3592
  timeZone: textOf(document["time_zone"]),
@@ -3374,11 +3599,7 @@ function infoOf(document, startQuestions = []) {
3374
3599
  tools: toolsOf(document["tools"]),
3375
3600
  autonomy: document["autonomy"] === true,
3376
3601
  startQuestions,
3377
- alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
3378
- title: textOf(entry["title"]),
3379
- text: entry["text"],
3380
- ...textOf(entry["character"]) === "" ? {} : { character: textOf(entry["character"]) }
3381
- }] : []) : []
3602
+ alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap(alternateOf) : []
3382
3603
  };
3383
3604
  }
3384
3605
  async function readDocument(directory) {
@@ -3416,7 +3637,6 @@ async function changeWorldInfo(directory, edit) {
3416
3637
  if (edit.startQuestions.length === 0) delete document["start_questions"];
3417
3638
  else document["start_questions"] = startQuestionsToFile(edit.startQuestions);
3418
3639
  }
3419
- if (edit.opening !== void 0 && before.openingParts && edit.opening !== before.opening) throw new InvalidEditProblems(["the opening has lines spoken by characters: change it in the file, or ask the authoring assistant"]);
3420
3640
  if (edit.name !== void 0) document["name"] = edit.name;
3421
3641
  if (edit.description !== void 0) document["description"] = edit.description;
3422
3642
  if (edit.tags !== void 0) document["metadata"] = {
@@ -3427,7 +3647,11 @@ async function changeWorldInfo(directory, edit) {
3427
3647
  if (edit.rules.length === 0) delete document["rules"];
3428
3648
  else document["rules"] = edit.rules;
3429
3649
  }
3430
- if (edit.opening !== void 0 && !before.openingParts) setOrRemove(document, "opening_message", edit.opening);
3650
+ if (edit.opening !== void 0) setOrRemove(document, "opening_message", edit.opening);
3651
+ if (edit.openingParts !== void 0) {
3652
+ if (edit.openingParts.length === 0) delete document["opening_message"];
3653
+ else document["opening_message"] = edit.openingParts;
3654
+ }
3431
3655
  if (edit.authorName !== void 0 || edit.authorUrl !== void 0) {
3432
3656
  const name = edit.authorName ?? before.authorName;
3433
3657
  const url = edit.authorUrl ?? before.authorUrl;
@@ -3453,7 +3677,7 @@ async function changeWorldInfo(directory, edit) {
3453
3677
  if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
3454
3678
  else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
3455
3679
  title: entry.title === "" ? entry.text.slice(0, 40) : entry.title,
3456
- text: entry.text,
3680
+ ...entry.parts === void 0 ? { text: entry.text } : { parts: entry.parts },
3457
3681
  ...entry.character === void 0 || entry.character === "" ? {} : { character: entry.character }
3458
3682
  }));
3459
3683
  }
@@ -5212,7 +5436,7 @@ const about = {
5212
5436
  where: "world.json",
5213
5437
  message: "the world has no tags"
5214
5438
  });
5215
- if (text(info.opening) === "" && !info.openingParts) found.push({
5439
+ if (text(info.opening) === "" && info.openingParts === void 0) found.push({
5216
5440
  severity: "info",
5217
5441
  code: "no-opening",
5218
5442
  where: "world.json",
@@ -6276,6 +6500,6 @@ function limitAuthoringAgents(ctx, kindOf) {
6276
6500
  return await next();
6277
6501
  });
6278
6502
  }
6279
- export { checkWorld as $, loadWorldParts as A, UPDATE_FOLDER as At, localChanges as B, TRIGGERS_FILE_NAME as Bt, cardChanges as C, loadDice as Ct, worldFieldChanges as D, parseCalendarFile as Dt, pictureChange as E, loadCalendar as Et, editsSince as F, readSource as Ft, addressesToFetch as G, pictureOf as Gt, writeOrigin as H, ImportCardError as Ht, writeSnapshot as I, COMMANDS_FILE_NAME as It, guardedLookup as J, DICE_READINGS as Jt, candidateUrls as K, readCard as Kt, describeChanges as L, commandVariable as Lt, CHECK_COMMANDS as M, cardPieces as Mt, CHECK_COMMAND_DESCRIPTIONS as N, cardTools as Nt, editWorldInfo as O, CHARACTERS_DIR as Ot, recordProvenance as P, entitiesByPiece as Pt, writePortrait as Q, hashWorld as R, loadCommands as Rt, addressChanges as S, DICE_FILE_NAME as St, matchPieces as T, CALENDAR_FILE_NAME as Tt, CatalogueError as U, cardFormat as Ut, readOrigin as V, loadTriggers as Vt, addressKey as W, isPng as Wt, vetUrl as X, authoredWorldOf as Xt, mergeReports as Y, DICE_RESULTS as Yt, cardCharacter as Z, authoringChatSessionId as Zt, structureImport as _, loadLocations as _t, beginImport as a, populateClock as at, CHECKS as b, FACTIONS_DIR as bt, importTextFor as c, populateItems as ct, knownOutputCeiling as d, populateLore as dt, loadValidatedWorld as et, importPhase as f, populateRoutines as ft, settleDraft as g, LOCATIONS_DIR as gt, markReady as h, routineProblems as ht, ImportState as i, populateCharacters as it, loadCardEvidence as j, baseId as jt, readWorldInfo as k, loadCharacters as kt, importTools as l, populateKnowledge as lt, keepDraft as m, populateVariables as mt, limitAuthoringAgents as n, knowsCharacter as nt, contextOf as o, populateDice as ot, isReviewing as p, populateTriggers as pt, fetchPictures as q, DICE_COMPARISONS as qt, MAX_PREVIEW_TEXT as r, populateCalendar as rt, importHooks as s, populateFactions as st, AuthoringTools as t, withScratchStory as tt, worldOf as u, populateLocations as ut, checkImported as v, ITEMS_DIR as vt, diffText as w, parseDiceFile as wt, runChecks as x, loadFactions as xt, presentReport as y, loadItems as yt, isUnchanged as z, parseCommandsFile as zt };
6503
+ export { checkWorld as $, authoringChatSessionId as $t, loadWorldParts as A, lettersOf$1 as At, localChanges as B, loadCommands as Bt, cardChanges as C, loadDice as Ct, worldFieldChanges as D, parseCalendarFile as Dt, pictureChange as E, loadCalendar as Et, editsSince as F, cardTools as Ft, addressesToFetch as G, cardFormat as Gt, writeOrigin as H, TRIGGERS_FILE_NAME as Ht, writeSnapshot as I, entitiesByPiece as It, guardedLookup as J, readCard as Jt, candidateUrls as K, isPng as Kt, describeChanges as L, readSource as Lt, CHECK_COMMANDS as M, UPDATE_FOLDER as Mt, CHECK_COMMAND_DESCRIPTIONS as N, baseId as Nt, editWorldInfo as O, CHARACTERS_DIR as Ot, recordProvenance as P, cardPieces as Pt, writePortrait as Q, authoredWorldOf as Qt, hashWorld as R, COMMANDS_FILE_NAME as Rt, addressChanges as S, DICE_FILE_NAME as St, matchPieces as T, CALENDAR_FILE_NAME as Tt, CatalogueError as U, loadTriggers as Ut, readOrigin as V, parseCommandsFile as Vt, addressKey as W, ImportCardError as Wt, vetUrl as X, DICE_READINGS as Xt, mergeReports as Y, DICE_COMPARISONS as Yt, cardCharacter as Z, DICE_RESULTS as Zt, structureImport as _, loadLocations as _t, beginImport as a, populateClock as at, CHECKS as b, FACTIONS_DIR as bt, importTextFor as c, populateItems as ct, knownOutputCeiling as d, populateLore as dt, loadValidatedWorld as et, importPhase as f, populateRoutines as ft, settleDraft as g, LOCATIONS_DIR as gt, markReady as h, routineProblems as ht, ImportState as i, populateCharacters as it, loadCardEvidence as j, shapeOpening as jt, readWorldInfo as k, loadCharacters as kt, importTools as l, populateKnowledge as lt, keepDraft as m, populateVariables as mt, limitAuthoringAgents as n, knowsCharacter as nt, contextOf as o, populateDice as ot, isReviewing as p, populateTriggers as pt, fetchPictures as q, pictureOf as qt, MAX_PREVIEW_TEXT as r, populateCalendar as rt, importHooks as s, populateFactions as st, AuthoringTools as t, withScratchStory as tt, worldOf as u, populateLocations as ut, checkImported as v, ITEMS_DIR as vt, diffText as w, parseDiceFile as wt, runChecks as x, loadFactions as xt, presentReport as y, loadItems as yt, isUnchanged as z, commandVariable as zt };
6280
6504
 
6281
- //# sourceMappingURL=authoring-tools-hacA5fG-.js.map
6505
+ //# sourceMappingURL=authoring-tools-DqAttdUN.js.map