@dsh-agentic-roleplay/core 0.12.3 → 0.12.4

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 (31) hide show
  1. package/lib/{authoring-tools-hacA5fG-.js → authoring-tools-B_qYKK8c.js} +244 -27
  2. package/lib/authoring.js +175 -9
  3. package/lib/client.js +841 -482
  4. package/lib/client.js.map +1 -1
  5. package/lib/doctor.js +1 -1
  6. package/lib/{gallery-BNg0rPTp.js → gallery-Bu6eZMKk.js} +2 -2
  7. package/lib/{generator-9-5at9cZ.js → generator-CTWQWbSW.js} +2 -2
  8. package/lib/{hooks-DlrFO4aQ.js → hooks-YXQZ9G2d.js} +2 -2
  9. package/lib/images.js +4 -4
  10. package/lib/index.js +34 -25
  11. package/lib/{library-DTxakw0z.js → library-BmlHNCah.js} +2 -2
  12. package/lib/{lorebook-author-tools-dupq-kb_.js → lorebook-author-tools-C3rRpMt7.js} +6 -6
  13. package/lib/lorebook-authoring.js +5 -5
  14. package/lib/orchestration.js +8 -8
  15. package/lib/{pack-jail-Bq0fzKi4.js → pack-jail-VbcXiukr.js} +10 -9
  16. package/lib/{packs-D-7EU3yU.js → packs-CzVh2ZNe.js} +2 -2
  17. package/lib/{presenter-agent-vFOxIuWv.js → presenter-agent-CF3fneuJ.js} +4 -4
  18. package/lib/{preset-RHcOG55T.js → preset-C595KRUM.js} +3 -3
  19. package/lib/{preset-author-tools-Dwxnpv6V.js → preset-author-tools-CF_JKKTE.js} +6 -6
  20. package/lib/preset-authoring.js +5 -5
  21. package/lib/{reflection-DibpEUQK.js → reflection-ByIQSOKC.js} +6 -6
  22. package/lib/{serial-CDGoXYh-.js → serial-ULGUKWsu.js} +129 -30
  23. package/lib/{text-Dfv8S8eq.js → text-hiKTooVb.js} +3 -1
  24. package/lib/{turn-guard-DDxikrq7.js → turn-guard-DXMeAJdv.js} +2 -2
  25. package/package.json +2 -2
  26. package/prompts/en/import/opening.md +17 -0
  27. package/prompts/en/roleplay/decide-opening.md +1 -0
  28. package/prompts/en/world/procedure.md +1 -1
  29. package/prompts/zh/import/opening.md +17 -0
  30. package/prompts/zh/roleplay/decide-opening.md +1 -0
  31. package/prompts/zh/world/procedure.md +1 -1
@@ -1,10 +1,10 @@
1
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";
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-ULGUKWsu.js";
3
3
  import { f as parseSwitchboard } from "./narration--K2XVIHI.js";
4
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";
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-YXQZ9G2d.js";
6
+ import { t as trimCharacters } from "./text-hiKTooVb.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-BmlHNCah.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";
@@ -1130,6 +1130,173 @@ function originOf(card, choices, pieces, records, name, items = itemise(card, ch
1130
1130
  }];
1131
1131
  });
1132
1132
  }
1133
+ // src/host/import/opening-parts.ts
1134
+ const SCHEMA = {
1135
+ type: "object",
1136
+ properties: { parts: {
1137
+ type: "array",
1138
+ items: {
1139
+ type: "object",
1140
+ properties: {
1141
+ kind: {
1142
+ type: "string",
1143
+ enum: ["narration", "speech"]
1144
+ },
1145
+ speaker: { type: "string" },
1146
+ text: { type: "string" }
1147
+ },
1148
+ required: [
1149
+ "kind",
1150
+ "speaker",
1151
+ "text"
1152
+ ],
1153
+ additionalProperties: false
1154
+ }
1155
+ } },
1156
+ required: ["parts"],
1157
+ additionalProperties: false
1158
+ };
1159
+ const MAX_SHOWN = 6e3;
1160
+ const QUOTES = /["'“”‘’「」『』«»„‟*_]/gu;
1161
+ /** 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. */
1162
+ function lettersOf$1(text, speakers = []) {
1163
+ let rest = text;
1164
+ for (const name of speakers.flatMap((speaker) => [speaker.name, ...speaker.aliases])) rest = rest.replace(new RegExp(`(^|\\n)\\s*${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*[::]`, "gu"), "$1");
1165
+ return rest.replace(QUOTES, "").replace(/\s+/gu, "");
1166
+ }
1167
+ /** Why an answer is not the passage split into parts; nothing when it is. */
1168
+ function splitProblem(source, parts, speakers) {
1169
+ if (parts.length === 0) return "the answer has no parts";
1170
+ const wanted = lettersOf$1(source, speakers);
1171
+ const given = lettersOf$1(partsText(parts));
1172
+ if (wanted === given) return void 0;
1173
+ let same = 0;
1174
+ while (same < wanted.length && same < given.length && wanted[same] === given[same]) same += 1;
1175
+ const around = (text) => `“${text.slice(Math.max(0, same - 8), same + 24)}”`;
1176
+ 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`;
1177
+ }
1178
+ /** The speaker a name (or id) names; the player's character and unknown names are nobody, so the part is narration. */
1179
+ function speakerOf(name, speakers, player) {
1180
+ const key = norm(name);
1181
+ if (key === "") return void 0;
1182
+ return speakers.find((speaker) => speaker.id !== player && [
1183
+ speaker.id,
1184
+ speaker.name,
1185
+ ...speaker.aliases
1186
+ ].some((label) => norm(label) === key));
1187
+ }
1188
+ /** The parts an answer describes, with a speaker that is not in the cast made narration. */
1189
+ function partsOf$1(answer, speakers, player) {
1190
+ const list = Array.isArray(answer.parts) ? answer.parts : [];
1191
+ const parts = [];
1192
+ for (const entry of list) {
1193
+ if (typeof entry !== "object" || entry === null) continue;
1194
+ const body = entry;
1195
+ const text = typeof body["text"] === "string" ? tidyQuotes(body["text"]) : "";
1196
+ if (text === "") continue;
1197
+ const speaker = (body["kind"] ?? body["type"]) === "narration" ? void 0 : speakerOf(typeof body["speaker"] === "string" ? body["speaker"] : "", speakers, player);
1198
+ parts.push(speaker === void 0 ? {
1199
+ type: "narration",
1200
+ text
1201
+ } : {
1202
+ type: "utterance",
1203
+ character: speaker.id,
1204
+ text
1205
+ });
1206
+ }
1207
+ return parts;
1208
+ }
1209
+ const PAIRS = [
1210
+ ["“", "”"],
1211
+ ["‘", "’"],
1212
+ ["「", "」"],
1213
+ ["『", "』"],
1214
+ ["«", "»"],
1215
+ ["„", "“"]
1216
+ ];
1217
+ const count = (text, mark) => text.split(mark).length - 1;
1218
+ /**
1219
+ * 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
1220
+ * (an opening mark with no closing one, a closing mark with no opening one). A balanced quotation inside the words stays.
1221
+ */
1222
+ function tidyQuotes(text) {
1223
+ let result = text.trim();
1224
+ for (const [open, close] of [...PAIRS, ["\"", "\""]]) {
1225
+ const inside = result.slice(1, -1);
1226
+ if (result.length > 1 && result.startsWith(open) && result.endsWith(close) && !inside.includes(open) && !inside.includes(close)) result = inside.trim();
1227
+ }
1228
+ result = result.replace(/^[”’」』»\s]+/u, "").replace(/[“‘「『«„\s]+$/u, "");
1229
+ for (const [open, close] of PAIRS) {
1230
+ if (result.startsWith(open) && count(result, open) > count(result, close)) result = result.slice(1).trim();
1231
+ if (result.endsWith(close) && count(result, close) > count(result, open)) result = result.slice(0, -1).trim();
1232
+ }
1233
+ if (count(result, "\"") % 2 === 1) result = (result.startsWith("\"") ? result.slice(1) : result.endsWith("\"") ? result.slice(0, -1) : result).trim();
1234
+ return result;
1235
+ }
1236
+ /** 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. */
1237
+ const unquoted = (text) => text.replace(/^[\s"“”‘’「」『』«»„‟]+|[\s"“”‘’「」『』«»„‟]+$/gu, "");
1238
+ /**
1239
+ * 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.
1240
+ * Nothing is invented: a part that is not in the passage as written leaves the answer as it is, for the check to refuse.
1241
+ */
1242
+ function mendParts(source, parts, speakers) {
1243
+ const mended = [];
1244
+ let at = 0;
1245
+ for (const part of parts) {
1246
+ const found = source.indexOf(part.text, at);
1247
+ if (found < 0) return [...parts];
1248
+ const gap = unquoted(source.slice(at, found));
1249
+ if (lettersOf$1(gap, speakers) !== "") mended.push({
1250
+ type: "narration",
1251
+ text: gap
1252
+ });
1253
+ mended.push(part);
1254
+ at = found + part.text.length;
1255
+ }
1256
+ const tail = unquoted(source.slice(at));
1257
+ if (lettersOf$1(tail, speakers) !== "") mended.push({
1258
+ type: "narration",
1259
+ text: tail
1260
+ });
1261
+ return mended;
1262
+ }
1263
+ /**
1264
+ * 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
1265
+ * "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
1266
+ * 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.
1267
+ */
1268
+ async function shapeOpening(ctx, passage, speakers, player) {
1269
+ const plain = { text: passage };
1270
+ if (ctx.noModel === true || passage.trim() === "" || speakers.every((speaker) => speaker.id === player)) return plain;
1271
+ if (ctx.decide !== void 0) try {
1272
+ const speech = (await ctx.decide({ passage: passage.slice(0, MAX_SHOWN) }, [{
1273
+ key: "speech",
1274
+ instructions: ctx.text("roleplay/decide-opening")
1275
+ }])).get("speech") ?? .5;
1276
+ const confidence = ctx.confidence ?? .7;
1277
+ if (speech <= noAt(confidence)) return plain;
1278
+ } catch {}
1279
+ try {
1280
+ const tr = trOf(ctx);
1281
+ const cast = speakers.filter((speaker) => speaker.id !== player).map((speaker) => `- ${speaker.name}`).join("\n");
1282
+ const parts = mendParts(passage, partsOf$1(await ctx.run({
1283
+ persona: ctx.text("import/opening"),
1284
+ maxTokens: Math.min(8e3, Math.max(1500, Math.ceil(passage.length / 2) + 600)),
1285
+ prompt: `${tr("Cast:")}\n${cast}\n\n${tr("Passage:")}\n${passage}`,
1286
+ result: SCHEMA,
1287
+ check: (value) => splitProblem(passage, mendParts(passage, partsOf$1(value, speakers, player), speakers), speakers)
1288
+ }), speakers, player), speakers);
1289
+ return parts.some((part) => part.type === "utterance") ? {
1290
+ text: partsText(parts),
1291
+ parts
1292
+ } : plain;
1293
+ } catch (error) {
1294
+ return {
1295
+ ...plain,
1296
+ note: `the opening could not be split into parts, so it is kept as plain text: ${error instanceof Error ? error.message : String(error)}`
1297
+ };
1298
+ }
1299
+ }
1133
1300
  // src/host/import/repair.ts
1134
1301
  const ENTITY_FILE = /^(characters|locations|factions|items|lore)\/[^/]+\/(character|location|faction|item|lore)\.json$/;
1135
1302
  /** Fields a document cannot do without, and fields that tie it to others: never dropped, whatever the problem says. */
@@ -2281,21 +2448,33 @@ const STAGE = "stage";
2281
2448
  const MAX_DESCRIPTION = 500;
2282
2449
  const MAX_TAGS = 8;
2283
2450
  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. */
2451
+ /** A title for an opening taken from a card: its first words, so the start dialog shows what the story begins with. */
2452
+ function openingTitle(text) {
2453
+ const first = text.trim().split("\n")[0].replace(/\s+/g, " ");
2454
+ if (first.length <= 40) return first;
2455
+ const cut = first.slice(0, 40);
2456
+ const space = cut.lastIndexOf(" ");
2457
+ return `${(space > 15 ? cut.slice(0, space) : cut).replace(/[,;:.\s]+$/, "")}…`;
2458
+ }
2459
+ /** 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
2460
  function alternateOpenings(card, chosen, player) {
2286
2461
  if (chosen.kind === "none") return [];
2287
- return [{
2288
- title: "First message",
2462
+ const greetings = [{
2289
2463
  text: card.firstMessage,
2290
2464
  taken: chosen.kind === "first"
2291
2465
  }, ...card.alternateGreetings.map((text, index) => ({
2292
- title: `Alternate ${index + 1}`,
2293
2466
  text,
2294
2467
  taken: chosen.kind === "alternate" && chosen.index === index
2295
- }))].flatMap(({ title, text, taken }) => {
2468
+ }))];
2469
+ const used = /* @__PURE__ */ new Map();
2470
+ return greetings.flatMap(({ text, taken }) => {
2296
2471
  const cleaned = taken || text.trim() === "" ? "" : openingMessage(text, card.name, player);
2297
- return cleaned === "" || cleaned.length > 2e4 ? [] : [{
2298
- title,
2472
+ if (cleaned === "" || cleaned.length > MAX_OPENING_CHARS) return [];
2473
+ const base = openingTitle(cleaned);
2474
+ const seen = used.get(base) ?? 0;
2475
+ used.set(base, seen + 1);
2476
+ return [{
2477
+ title: seen === 0 ? base : `${base} (${seen + 1})`,
2299
2478
  text: cleaned
2300
2479
  }];
2301
2480
  }).slice(0, 30);
@@ -2582,7 +2761,23 @@ async function finishImport(ctx, input) {
2582
2761
  })}\n`);
2583
2762
  cover = true;
2584
2763
  }
2585
- const alternates = alternateOpenings(card, choices.opening, player === void 0 ? void 0 : String(player["name"]));
2764
+ const openingPlayer = player === void 0 ? void 0 : String(player["name"]);
2765
+ const speakers = extracted.characters.map((document) => ({
2766
+ id: String(document["id"]),
2767
+ name: String(document["name"]),
2768
+ aliases: Array.isArray(document["aliases"]) ? document["aliases"].filter((alias) => typeof alias === "string") : []
2769
+ }));
2770
+ const playerId = player === void 0 ? void 0 : String(player["id"]);
2771
+ const shapedMain = opening === void 0 ? void 0 : await shapeOpening(ctx, openingMessage(opening, card.name, openingPlayer), speakers, playerId);
2772
+ const shapedAlternates = await mapLimit(alternateOpenings(card, choices.opening, openingPlayer), ctx.concurrency, async (entry) => ({
2773
+ title: entry.title,
2774
+ shaped: await shapeOpening(ctx, entry.text, speakers, playerId)
2775
+ }));
2776
+ const alternates = shapedAlternates.map(({ title, shaped }) => ({
2777
+ title,
2778
+ ...shaped.parts === void 0 ? { text: shaped.text } : { parts: shaped.parts }
2779
+ }));
2780
+ for (const note of [shapedMain?.note, ...shapedAlternates.map((entry) => entry.shaped.note)]) if (note !== void 0) notes.push(note);
2586
2781
  await updateWorldFile(directory, (world) => {
2587
2782
  world["description"] = described.description;
2588
2783
  if (described.startingTime !== void 0 && world["starting_time"] === void 0) world["starting_time"] = described.startingTime;
@@ -2590,7 +2785,7 @@ async function finishImport(ctx, input) {
2590
2785
  ...typeof world["metadata"] === "object" && world["metadata"] !== null ? world["metadata"] : {},
2591
2786
  tags: described.tags
2592
2787
  };
2593
- if (opening !== void 0) world["opening_message"] = openingMessage(opening, card.name, player === void 0 ? void 0 : String(player["name"]));
2788
+ if (shapedMain !== void 0) world["opening_message"] = shapedMain.parts ?? shapedMain.text;
2594
2789
  if (alternates.length > 0) world["alternate_openings"] = alternates;
2595
2790
  if (extracted.rules.length > 0 && world["rules"] === void 0) world["rules"] = extracted.rules.slice(0, 30);
2596
2791
  if (card.creator.trim() !== "" && world["author"] === void 0) world["author"] = { name: card.creator.trim() };
@@ -3348,10 +3543,33 @@ const toolsOf = (value) => {
3348
3543
  const board = value === void 0 ? {} : parseSwitchboard(value, "tools");
3349
3544
  return typeof board === "string" ? {} : board;
3350
3545
  };
3546
+ /** The parts of an opening as the file has them; parts that cannot be read are left out. */
3547
+ function partsOf(list) {
3548
+ const parts = parseOpeningParts(list, "opening", []);
3549
+ return parts === void 0 || parts.length === 0 ? void 0 : parts;
3550
+ }
3551
+ function alternateOf(entry) {
3552
+ if (typeof entry !== "object" || entry === null) return [];
3553
+ const body = entry;
3554
+ const character = textOf(body["character"]);
3555
+ const named = character === "" ? {} : { character };
3556
+ const parts = Array.isArray(body["parts"]) ? partsOf(body["parts"]) : void 0;
3557
+ if (parts !== void 0) return [{
3558
+ title: textOf(body["title"]),
3559
+ text: partsText(parts),
3560
+ parts,
3561
+ ...named
3562
+ }];
3563
+ return typeof body["text"] === "string" ? [{
3564
+ title: textOf(body["title"]),
3565
+ text: body["text"],
3566
+ ...named
3567
+ }] : [];
3568
+ }
3351
3569
  function infoOf(document, startQuestions = []) {
3352
3570
  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") : "";
3571
+ const parts = Array.isArray(opening) ? partsOf(opening) : void 0;
3572
+ const plain = typeof opening === "string" ? opening : parts === void 0 ? "" : partsText(parts);
3355
3573
  const metadata = typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {};
3356
3574
  const author = typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {};
3357
3575
  const rules = document["rules"];
@@ -3361,7 +3579,7 @@ function infoOf(document, startQuestions = []) {
3361
3579
  tags: Array.isArray(metadata["tags"]) ? metadata["tags"].filter((tag) => typeof tag === "string") : [],
3362
3580
  rules: typeof rules === "string" ? [rules] : Array.isArray(rules) ? rules.filter((rule) => typeof rule === "string") : [],
3363
3581
  opening: plain,
3364
- openingParts: parts,
3582
+ ...parts === void 0 ? {} : { openingParts: parts },
3365
3583
  authorName: textOf(author["name"]),
3366
3584
  authorUrl: textOf(author["url"]),
3367
3585
  timeZone: textOf(document["time_zone"]),
@@ -3374,11 +3592,7 @@ function infoOf(document, startQuestions = []) {
3374
3592
  tools: toolsOf(document["tools"]),
3375
3593
  autonomy: document["autonomy"] === true,
3376
3594
  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
- }] : []) : []
3595
+ alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap(alternateOf) : []
3382
3596
  };
3383
3597
  }
3384
3598
  async function readDocument(directory) {
@@ -3416,7 +3630,6 @@ async function changeWorldInfo(directory, edit) {
3416
3630
  if (edit.startQuestions.length === 0) delete document["start_questions"];
3417
3631
  else document["start_questions"] = startQuestionsToFile(edit.startQuestions);
3418
3632
  }
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
3633
  if (edit.name !== void 0) document["name"] = edit.name;
3421
3634
  if (edit.description !== void 0) document["description"] = edit.description;
3422
3635
  if (edit.tags !== void 0) document["metadata"] = {
@@ -3427,7 +3640,11 @@ async function changeWorldInfo(directory, edit) {
3427
3640
  if (edit.rules.length === 0) delete document["rules"];
3428
3641
  else document["rules"] = edit.rules;
3429
3642
  }
3430
- if (edit.opening !== void 0 && !before.openingParts) setOrRemove(document, "opening_message", edit.opening);
3643
+ if (edit.opening !== void 0) setOrRemove(document, "opening_message", edit.opening);
3644
+ if (edit.openingParts !== void 0) {
3645
+ if (edit.openingParts.length === 0) delete document["opening_message"];
3646
+ else document["opening_message"] = edit.openingParts;
3647
+ }
3431
3648
  if (edit.authorName !== void 0 || edit.authorUrl !== void 0) {
3432
3649
  const name = edit.authorName ?? before.authorName;
3433
3650
  const url = edit.authorUrl ?? before.authorUrl;
@@ -3453,7 +3670,7 @@ async function changeWorldInfo(directory, edit) {
3453
3670
  if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
3454
3671
  else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
3455
3672
  title: entry.title === "" ? entry.text.slice(0, 40) : entry.title,
3456
- text: entry.text,
3673
+ ...entry.parts === void 0 ? { text: entry.text } : { parts: entry.parts },
3457
3674
  ...entry.character === void 0 || entry.character === "" ? {} : { character: entry.character }
3458
3675
  }));
3459
3676
  }
@@ -5212,7 +5429,7 @@ const about = {
5212
5429
  where: "world.json",
5213
5430
  message: "the world has no tags"
5214
5431
  });
5215
- if (text(info.opening) === "" && !info.openingParts) found.push({
5432
+ if (text(info.opening) === "" && info.openingParts === void 0) found.push({
5216
5433
  severity: "info",
5217
5434
  code: "no-opening",
5218
5435
  where: "world.json",
@@ -6276,6 +6493,6 @@ function limitAuthoringAgents(ctx, kindOf) {
6276
6493
  return await next();
6277
6494
  });
6278
6495
  }
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 };
6496
+ 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
6497
 
6281
- //# sourceMappingURL=authoring-tools-hacA5fG-.js.map
6498
+ //# sourceMappingURL=authoring-tools-B_qYKK8c.js.map
package/lib/authoring.js CHANGED
@@ -1,11 +1,11 @@
1
- import { $ as checkWorld, A as loadWorldParts, At as UPDATE_FOLDER, C as cardChanges, D as worldFieldChanges, E as pictureChange, F as editsSince, Ft as readSource, It as COMMANDS_FILE_NAME, M as CHECK_COMMANDS, N as CHECK_COMMAND_DESCRIPTIONS, Nt as cardTools, O as editWorldInfo, Pt as entitiesByPiece, S as addressChanges, St as DICE_FILE_NAME, T as matchPieces, Tt as CALENDAR_FILE_NAME, Xt as authoredWorldOf, b as CHECKS, j as loadCardEvidence, k as readWorldInfo, l as importTools, n as limitAuthoringAgents, o as contextOf, p as isReviewing, s as importHooks, v as checkImported, w as diffText, x as runChecks, y as presentReport } from "./authoring-tools-hacA5fG-.js";
2
- import { t as guardAuthoringTurns } from "./turn-guard-DDxikrq7.js";
1
+ import { $ as checkWorld, A as loadWorldParts, At as lettersOf, C as cardChanges, D as worldFieldChanges, E as pictureChange, F as editsSince, Ft as cardTools, It as entitiesByPiece, Lt as readSource, M as CHECK_COMMANDS, Mt as UPDATE_FOLDER, N as CHECK_COMMAND_DESCRIPTIONS, O as editWorldInfo, Qt as authoredWorldOf, Rt as COMMANDS_FILE_NAME, S as addressChanges, St as DICE_FILE_NAME, T as matchPieces, Tt as CALENDAR_FILE_NAME, b as CHECKS, j as loadCardEvidence, jt as shapeOpening, k as readWorldInfo, kt as loadCharacters, l as importTools, n as limitAuthoringAgents, o as contextOf, p as isReviewing, s as importHooks, u as worldOf, v as checkImported, w as diffText, x as runChecks, y as presentReport } from "./authoring-tools-B_qYKK8c.js";
2
+ import { t as guardAuthoringTurns } from "./turn-guard-DXMeAJdv.js";
3
3
  import { n as silenceRuntimeContext, t as silenceHarnessDevContext } from "./dev-context-Cgv_wZbG.js";
4
- import { B as deleteTriggerDocument, D as editWorldPlots, G as parseVariablesEdit, H as writeTriggerDocument, K as parseDiceEdit, M as readWorldEditor, O as editWorldRelation, Q as translateTools, U as parseCalendarEdit, V as readTriggerDocuments, X as presetTools, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, f as editCalendar, g as editVariables, i as checkWorldPack, l as deleteAuthoredEntity, m as editDice, nt as finishUpdate, o as listWorldPacks, p as editCommands, q as parseCommandsEdit, r as registerPackJail, rt as pendingUpdate, s as AUTHORED_ENTITY_KINDS, u as readAuthoredEntityDocument } from "./pack-jail-Bq0fzKi4.js";
5
- import { i as translator, r as languageOf } from "./text-Dfv8S8eq.js";
6
- import { $ as deleteWorldPrompt, Ct as IMPORT_FOLDER, Et as PICTURE_FILE, F as parseWorldInfoEdit, It as parseRelationEdit, Q as PROSE_PROMPTS, Wt as VARIABLES_FILE_NAME, et as listWorldPrompts, jt as InvalidEditProblems, nt as writeWorldPrompt, tt as readWorldPrompt } from "./serial-CDGoXYh-.js";
7
- import { B as parsePlotsFile, at as shippedPromptsDirectory, ht as registerCommands, q as formatIssue } from "./hooks-DlrFO4aQ.js";
8
- import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-D-7EU3yU.js";
4
+ import { B as deleteTriggerDocument, D as editWorldPlots, G as parseVariablesEdit, H as writeTriggerDocument, K as parseDiceEdit, M as readWorldEditor, O as editWorldRelation, Q as translateTools, U as parseCalendarEdit, V as readTriggerDocuments, X as presetTools, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, f as editCalendar, g as editVariables, i as checkWorldPack, l as deleteAuthoredEntity, m as editDice, nt as finishUpdate, o as listWorldPacks, p as editCommands, q as parseCommandsEdit, r as registerPackJail, rt as pendingUpdate, s as AUTHORED_ENTITY_KINDS, u as readAuthoredEntityDocument } from "./pack-jail-VbcXiukr.js";
5
+ import { i as translator, r as languageOf } from "./text-hiKTooVb.js";
6
+ import { Et as IMPORT_FOLDER, F as parseWorldInfoEdit, I as hasSpeech, Pt as InvalidEditProblems, R as partsText, at as writeWorldPrompt, it as readWorldPrompt, kt as PICTURE_FILE, nt as deleteWorldPrompt, qt as VARIABLES_FILE_NAME, rt as listWorldPrompts, tt as PROSE_PROMPTS, zt as parseRelationEdit } from "./serial-ULGUKWsu.js";
7
+ import { B as parsePlotsFile, at as shippedPromptsDirectory, ht as registerCommands, q as formatIssue } from "./hooks-YXQZ9G2d.js";
8
+ import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-CzVh2ZNe.js";
9
9
  import "./access-Csp80TFX.js";
10
10
  import { join, relative } from "node:path";
11
11
  import { createHash } from "node:crypto";
@@ -321,6 +321,26 @@ function authoredWorldReadTools(reader) {
321
321
  })
322
322
  ];
323
323
  }
324
+ // src/host/authoring/opening-speakers.ts
325
+ /**
326
+ * Refuses an opening whose lines are spoken by someone the world does not have, and lists the ids it does have: a model asked to change who speaks writes a name's initials or an
327
+ * invented id unless it is told the real ones (found live: "hale" and "oldge" for a character whose id was "miller").
328
+ * @throws {InvalidEditProblems}
329
+ */
330
+ async function checkOpeningSpeakers(directory, edit) {
331
+ const spoken = [...(edit.openingParts ?? []).map((part) => ({
332
+ where: "openingParts",
333
+ part
334
+ })), ...(edit.alternateOpenings ?? []).flatMap((entry, index) => (entry.parts ?? []).map((part) => ({
335
+ where: `alternateOpenings[${index}].parts`,
336
+ part
337
+ })))].filter((entry) => entry.part.type === "utterance");
338
+ if (spoken.length === 0) return;
339
+ const { characters } = await loadCharacters(directory);
340
+ const ids = new Set(characters.map((character) => character.id));
341
+ const problems = spoken.flatMap(({ where, part }) => part.type === "utterance" && !ids.has(part.character) ? [`${where}: "${part.character}" is not a character of this world; the characters are ${characters.map((character) => `${character.id} (${character.name})`).join(", ")}`] : []);
342
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
343
+ }
324
344
  // src/host/authoring/pack-tools.ts
325
345
  const PACK_MUTATION_TOOLS = ["delete_world_pack_file"];
326
346
  const output$4 = (value) => [{
@@ -616,6 +636,7 @@ const WORLD_INFO_FIELDS = [
616
636
  "tags",
617
637
  "rules",
618
638
  "opening",
639
+ "openingParts",
619
640
  "alternateOpenings",
620
641
  "startQuestions",
621
642
  "startingTime",
@@ -626,6 +647,7 @@ const WORLD_INFO_FIELDS = [
626
647
  ];
627
648
  const AUTHORING_MUTATION_TOOLS = /* @__PURE__ */ new Set([
628
649
  "import_preset",
650
+ "reshape_opening",
629
651
  "edit_world_info",
630
652
  "create_world_element",
631
653
  "replace_world_element",
@@ -667,6 +689,11 @@ function plotDocument(value) {
667
689
  /** Checks a write the way its tool will, and writes nothing: a change the tool would refuse is not put to the person. @throws {InvalidEditProblems} */
668
690
  async function validateMutation(reader, exec) {
669
691
  const args = exec.arguments;
692
+ if (exec.name === "edit_world_info") {
693
+ const { record } = await reader.read(exec);
694
+ await checkOpeningSpeakers(record.directory, parseWorldInfoEdit(args["changes"]));
695
+ return;
696
+ }
670
697
  if (exec.name !== "create_world_element" && exec.name !== "replace_world_element" && exec.name !== "write_world_trigger" && exec.name !== "write_world_file") return;
671
698
  const { record } = await reader.read(exec);
672
699
  if (exec.name === "write_world_file") {
@@ -690,6 +717,16 @@ async function validateMutation(reader, exec) {
690
717
  dryRun: true
691
718
  });
692
719
  }
720
+ /** Which openings (the world's own, or an alternate by position) hold other words than before, ignoring quotation marks and spacing: a change of form alone must not change them. */
721
+ function openingWordsChanged(before, after) {
722
+ const changed = [];
723
+ if (lettersOf(before.opening) !== lettersOf(after.opening)) changed.push("opening");
724
+ after.alternateOpenings.forEach((entry, index) => {
725
+ const was = before.alternateOpenings[index];
726
+ if (was !== void 0 && lettersOf(was.text) !== lettersOf(entry.text)) changed.push(`alternate:${index}`);
727
+ });
728
+ return changed;
729
+ }
693
730
  /** The most problems a write reports back; `check_world` lists the rest. */
694
731
  const REPORTED_PROBLEMS = 8;
695
732
  /**
@@ -793,7 +830,7 @@ function authoredWorldWriteTools(reader) {
793
830
  }),
794
831
  defineTool({
795
832
  name: "edit_world_info",
796
- description: `Change what the world says about itself in world.json: ${WORLD_INFO_FIELDS.join(", ")}. Give only the fields to change, as {"description": "...", "tags": ["..."], "opening": "...", "alternateOpenings": [{"title": "...", "text": "..."}]}: a list replaces the whole list, so read get_world_info first. The description is a short summary (a few sentences). An opening with lines spoken by characters cannot be edited as text. startQuestions is a list of {"id", "text", "options": [{"id", "label", "effect": {...}}]} with two to eight options each; an effect may hold rules (a list of text), opening (the position of an alternate opening), startingTime, clockMode (simulated or real), tools and plots, and {} changes nothing. The name, preset, lorebooks, sampling and tool switches are the person's and cannot be changed here. Requires user approval.`,
833
+ description: `Change what the world says about itself in world.json: ${WORLD_INFO_FIELDS.join(", ")}. Give only the fields to change, as {"description": "...", "tags": ["..."], "opening": "...", "alternateOpenings": [{"title": "...", "text": "..."}]}: a list replaces the whole list, so read get_world_info first. The description is a short summary (a few sentences). An opening is either plain text, which is narration only (opening, and text in an alternate opening), or an ordered list of parts, [{"type": "narration", "text": "..."}, {"type": "utterance", "character": "<character id>", "text": "..."}] (openingParts, and parts in an alternate opening); give one form, not both. Use parts whenever a character speaks, with the speaker's id from list_characters, and plain text only for pure narration; the words must stay exactly as they are when you only change the form, and a speaker you are not sure of stays narration. To only change the form of an opening, or to split it, use reshape_opening: it keeps every word, while retyping the opening here can lose some. Giving opening replaces parts with plain text; giving openingParts replaces plain text with parts. startQuestions is a list of {"id", "text", "options": [{"id", "label", "effect": {...}}]} with two to eight options each; an effect may hold rules (a list of text), opening (the position of an alternate opening), startingTime, clockMode (simulated or real), tools and plots, and {} changes nothing. The name, preset, lorebooks, sampling and tool switches are the person's and cannot be changed here. Requires user approval.`,
797
834
  parameters: { changes: {
798
835
  type: "json",
799
836
  required: true,
@@ -805,13 +842,20 @@ function authoredWorldWriteTools(reader) {
805
842
  const edit = parseWorldInfoEdit(args.changes);
806
843
  const refused = Object.keys(edit).filter((key) => !WORLD_INFO_FIELDS.includes(key));
807
844
  if (refused.length > 0) throw new InvalidEditProblems([`${refused.join(", ")} cannot be changed here: ${WORLD_INFO_FIELDS.join(", ")} can`]);
845
+ await checkOpeningSpeakers(record.directory, edit);
846
+ const before = await readWorldInfo(record.directory);
808
847
  const info = await editWorldInfo(record.directory, edit);
809
848
  await reader.refresh();
849
+ const reworded = openingWordsChanged(before, info);
810
850
  return {
811
851
  action: "edited",
812
852
  kind: "world info",
813
853
  changed: Object.keys(edit),
814
- info
854
+ info,
855
+ ...reworded.length === 0 ? {} : {
856
+ opening_words_changed: reworded,
857
+ note: "The words of these openings are not what they were. If you only meant to change their form (plain text or parts), put the original words back or use reshape_opening, which keeps every word."
858
+ }
815
859
  };
816
860
  }
817
861
  }),
@@ -984,6 +1028,17 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
984
1028
  }, remove ? void 0 : sizeOf(args["text"]))
985
1029
  };
986
1030
  }
1031
+ if (exec.name === "reshape_opening") {
1032
+ const target = String(args["target"]);
1033
+ return {
1034
+ kind: "ask",
1035
+ reason: `change the form of the authored world's ${target}`,
1036
+ displayReason: {
1037
+ en: `Change the opening “${target}” to ${String(args["form"]) === "parts" ? "parts (narration and spoken lines)" : "plain text"}? Its words stay the same.`,
1038
+ zh: `把开场“${target}”改为${String(args["form"]) === "parts" ? "分段形式(叙述与台词)" : "纯文本"}?文字内容不变。`
1039
+ }
1040
+ };
1041
+ }
987
1042
  if (exec.name === "edit_world_info") return {
988
1043
  kind: "ask",
989
1044
  reason: "edit the authored world's description, tags, opening or other world.json fields",
@@ -1250,6 +1305,116 @@ function updateHooks(ctx, worlds, languageOf$1) {
1250
1305
  }));
1251
1306
  });
1252
1307
  }
1308
+ // src/host/import/opening-tools.ts
1309
+ const OPENING_TOOL = "reshape_opening";
1310
+ /**
1311
+ * The tool that turns an opening of the world into parts (narration and lines of characters) or back into plain text, for a world imported before openings could have parts
1312
+ * or whose split was wrong. It keeps every word: a split that changes the text is refused. Every call asks the person first.
1313
+ */
1314
+ function openingTools(worlds, settings, prompting) {
1315
+ return [defineTool({
1316
+ name: OPENING_TOOL,
1317
+ description: "Change the form of an opening without changing its words. form \"parts\" splits plain text into narration and the lines that characters of this world speak (a speaker you are not sure of stays narration; an opening with no spoken line stays plain text); form \"plain\" joins parts that are only narration back into plain text and is refused when a character speaks. target is \"opening\" (the world's opening message) or \"alternate:<position>\" (an alternate opening, counting from 0). To correct who speaks a line, or to change words, use edit_world_info with openingParts instead. When the person asks to change the form of an opening, call this at once: the person approves the call itself, so do not ask first, and never retype the opening with edit_world_info to do it. Requires user approval.",
1318
+ parameters: {
1319
+ target: {
1320
+ type: "string",
1321
+ required: true,
1322
+ description: "\"opening\" or \"alternate:<position>\"."
1323
+ },
1324
+ form: {
1325
+ type: "string",
1326
+ required: true,
1327
+ enum: ["parts", "plain"],
1328
+ description: "The form to give it."
1329
+ }
1330
+ },
1331
+ output: {
1332
+ schema: { type: "json" },
1333
+ render: (_args, value) => [{
1334
+ type: "text",
1335
+ text: JSON.stringify(value, null, 1)
1336
+ }]
1337
+ },
1338
+ isConcurrencySafe: () => false,
1339
+ async execute(args, exec) {
1340
+ const world = await worldOf(worlds, exec);
1341
+ const info = await readWorldInfo(world.directory);
1342
+ const match = /^alternate:(\d+)$/.exec(args.target.trim());
1343
+ const position = match === null ? void 0 : Number(match[1]);
1344
+ if (args.target.trim() !== "opening" && position === void 0) throw new Error("target is \"opening\" or \"alternate:<position>\"");
1345
+ const alternate = position === void 0 ? void 0 : info.alternateOpenings[position];
1346
+ if (position !== void 0 && alternate === void 0) throw new Error(`the world has no alternate opening ${position}`);
1347
+ const current = alternate === void 0 ? {
1348
+ text: info.opening,
1349
+ parts: info.openingParts
1350
+ } : {
1351
+ text: alternate.text,
1352
+ parts: alternate.parts
1353
+ };
1354
+ if (current.text.trim() === "") throw new Error("that opening is empty");
1355
+ const write = async (form) => {
1356
+ if (alternate === void 0 || position === void 0) {
1357
+ await editWorldInfo(world.directory, form);
1358
+ return;
1359
+ }
1360
+ const { text: _text, parts: _parts, ...rest } = alternate;
1361
+ const entry = "opening" in form ? {
1362
+ ...rest,
1363
+ text: form.opening
1364
+ } : {
1365
+ ...rest,
1366
+ text: partsText(form.openingParts),
1367
+ parts: form.openingParts
1368
+ };
1369
+ await editWorldInfo(world.directory, { alternateOpenings: info.alternateOpenings.map((item, index) => index === position ? entry : item) });
1370
+ };
1371
+ if (args.form === "plain") {
1372
+ if (current.parts === void 0) return {
1373
+ target: args.target,
1374
+ form: "plain",
1375
+ changed: false,
1376
+ note: "it is already plain text"
1377
+ };
1378
+ if (hasSpeech(current.parts)) throw new Error("characters speak in this opening, so it cannot be plain text; remove their lines first");
1379
+ await write({ opening: partsText(current.parts) });
1380
+ await worlds.list({ refresh: true });
1381
+ return {
1382
+ target: args.target,
1383
+ form: "plain",
1384
+ changed: true
1385
+ };
1386
+ }
1387
+ if (current.parts !== void 0) return {
1388
+ target: args.target,
1389
+ form: "parts",
1390
+ changed: false,
1391
+ note: "it is already in parts"
1392
+ };
1393
+ const language = prompting.languages().get(world.id);
1394
+ const ctx = contextOf(exec, settings(), (id, variables) => prompting.prompts().text(id, language, variables), language);
1395
+ const cast = (await loadCharacters(world.directory)).characters.map((character) => ({
1396
+ id: character.id,
1397
+ name: character.name,
1398
+ aliases: character.aliases ?? []
1399
+ }));
1400
+ const shaped = await shapeOpening(ctx, current.text, cast);
1401
+ if (shaped.parts === void 0) return {
1402
+ target: args.target,
1403
+ form: "parts",
1404
+ changed: false,
1405
+ note: shaped.note ?? "no character speaks in it, so it stays plain text"
1406
+ };
1407
+ await write({ openingParts: shaped.parts });
1408
+ await worlds.list({ refresh: true });
1409
+ return {
1410
+ target: args.target,
1411
+ form: "parts",
1412
+ changed: true,
1413
+ parts: shaped.parts
1414
+ };
1415
+ }
1416
+ })];
1417
+ }
1253
1418
  // src/host/checks/tools.ts
1254
1419
  const output = {
1255
1420
  schema: { type: "json" },
@@ -1399,6 +1564,7 @@ function apply(ctx) {
1399
1564
  for (const tool of cardTools(ctx.roleplayWorlds)) ctx.tools.register(tool);
1400
1565
  for (const tool of updateTools(ctx.roleplayWorlds)) ctx.tools.register(tool);
1401
1566
  for (const tool of presetTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1567
+ for (const tool of openingTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1402
1568
  for (const tool of translateTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1403
1569
  for (const tool of checkTools(reader, {
1404
1570
  settings: () => ctx.roleplayImport.settings,