@dsh-agentic-roleplay/core 0.8.1 → 0.8.2

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 (35) hide show
  1. package/lib/{access-DtOxFKBK.js → access-CfQWbNZP.js} +4 -7
  2. package/lib/{authoring-tools-DNnx0Nts.js → authoring-tools-BgmC2oqU.js} +223 -106
  3. package/lib/authoring.js +15 -22
  4. package/lib/{child-D6mpkkCE.js → child-lYYeOwl2.js} +28 -51
  5. package/lib/client.js +615 -778
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +8 -13
  8. package/lib/{doctor-chat-ByDfCMeo.js → doctor-chat-hL1a61hp.js} +2 -3
  9. package/lib/doctor.js +6 -8
  10. package/lib/{gallery-D9nG3C78.js → gallery-D1V4h8vh.js} +3 -4
  11. package/lib/{generator-r1Czm7oi.js → generator-CLPosooC.js} +3 -4
  12. package/lib/helper.js +2 -3
  13. package/lib/{hooks-BQCzgggH.js → hooks-rQTTeOC4.js} +69 -97
  14. package/lib/images.js +4 -4
  15. package/lib/index.js +194 -264
  16. package/lib/{library-zI-2tG7h.js → library-Dfu0dgRj.js} +9 -15
  17. package/lib/{lorebook-author-tools-ywaYicwd.js → lorebook-author-tools-BAaAqZZm.js} +10 -13
  18. package/lib/lorebook-authoring.js +5 -6
  19. package/lib/{narration-CnBlVure.js → narration-CjB_KwwY.js} +9 -15
  20. package/lib/orchestration.js +53 -64
  21. package/lib/{pack-jail-5EJ-WYyW.js → pack-jail-CN-314ln.js} +76 -81
  22. package/lib/{packs-Cv8hanXJ.js → packs-DIj5BEfq.js} +6 -10
  23. package/lib/{presenter-agent-BSaMSd3G.js → presenter-agent-DR0KvLE0.js} +12 -18
  24. package/lib/{preset-CWI3-0r1.js → preset-CscHj1-Y.js} +5 -6
  25. package/lib/{preset-author-tools-BrJYa2cr.js → preset-author-tools-CxluF8qc.js} +12 -14
  26. package/lib/preset-authoring.js +6 -7
  27. package/lib/{presets-MwOSMMyu.js → presets-HB8kJTaE.js} +51 -56
  28. package/lib/{reflection-zSaMsjKj.js → reflection-Dg1xtOTW.js} +19 -30
  29. package/lib/{text-BzudpQLS.js → text-DyRN4nDP.js} +6 -8
  30. package/lib/{turn-guard-Cv8pfHEA.js → turn-guard-g_hDn0jR.js} +6 -11
  31. package/package.json +29 -29
  32. package/prompts/en/import/casting.md +1 -1
  33. package/prompts/en/import/character.md +1 -0
  34. package/prompts/zh/import/casting.md +1 -1
  35. package/prompts/zh/import/character.md +1 -0
@@ -1,4 +1,4 @@
1
- //#region src/shared/chat.ts
1
+ // src/shared/chat.ts
2
2
  const CHAT_PREFIX = "session-";
3
3
  const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
4
4
  /** The DSH chat of a roleplay session is named after the session's id. */
@@ -11,8 +11,7 @@ function roleplaySessionOf(chat) {
11
11
  const id = chat.slice(8);
12
12
  return UUID_V4.test(id) ? id : void 0;
13
13
  }
14
- //#endregion
15
- //#region ../dsh-roleplay-model/src/variable.ts
14
+ // ../dsh-roleplay-model/src/variable.ts
16
15
  /** What a variable holds: a number within bounds, a yes or no, or one of a list of words. */
17
16
  const VARIABLE_KINDS = [
18
17
  "number",
@@ -136,15 +135,13 @@ const VARIABLE_VISIBILITIES = [
136
135
  always: false,
137
136
  builtin: true
138
137
  }));
139
- //#endregion
140
- //#region src/host/prompts/access.ts
138
+ // src/host/prompts/access.ts
141
139
  /** The prompt `id` in `language`, from the library of the agent's own context. */
142
140
  function promptFor(agent, id, language, variables) {
143
141
  const library = agent.ctx.get("roleplayPrompts");
144
142
  if (library === void 0) throw new Error("the prompt library is not running");
145
143
  return library.text(id, language, variables, roleplaySessionOf(agent.session.id));
146
144
  }
147
- //#endregion
148
145
  export { chatSessionId as a, VARIABLE_VISIBILITIES as i, VARIABLE_KINDS as n, roleplaySessionOf as o, VARIABLE_SUBJECTS as r, promptFor as t };
149
146
 
150
- //# sourceMappingURL=access-DtOxFKBK.js.map
147
+ //# sourceMappingURL=access-CfQWbNZP.js.map
@@ -1,10 +1,10 @@
1
- import "./access-DtOxFKBK.js";
2
- import { A as isLeftOut, At as DEFAULT_SLOTS, C as pruneMembers, D as classifyItems, Dt as LORE_KINDS, E as buildRoster, G as withPlayer, H as cleanText, K as IMPORT_FOLDER, M as askYesNo, Ot as LORE_SCOPES, Q as readImportFolder, S as pruneLoreSubjects, U as itemise, X as openingText, Y as PICTURE_FILE, _ as extractStyle, _t as parseCharacterFile, a as isPresetName, at as variableProblems, b as pruneKnowledge, bt as InvalidEditProblems, ct as LOCATION_FILE_NAME, dt as SLOTS_FILE_NAME, ft as parseItemFile, g as extractEntities, gt as CHARACTER_FILE_NAME, h as emptyExtracted, ht as parseFactionFile, k as ROLES, kt as WEEKDAY_NAMES, lt as parseLocationFile, mt as FACTION_FILE_NAME, nt as VARIABLES_FILE_NAME, ot as LORE_FILE_NAME, pt as parseSlotsFile, rt as loadVariables, st as parseLoreFile, tt as parseImportCommand, ut as ITEM_FILE_NAME, vt as readVariableValues, w as pruneRelationships, x as pruneLinks, y as extractVariables, yt as readIdentifier } from "./presets-MwOSMMyu.js";
3
- import { l as atomicWrite, m as parseSwitchboard, u as atomicWriteJson } from "./narration-CnBlVure.js";
4
- import { G as commandFlagKey, K as readDocument, U as plotReferenceProblems, V as loadPlots, Y as errorMessage, Z as PROMPTS_FOLDER, a as externalWithheld, it as shippedLanguages, lt as InvalidWorldError, q as Reader, r as externalGiven, rt as promptProblem, t as externalToolLimit } from "./hooks-BQCzgggH.js";
5
- import { t as trimCharacters } from "./text-BzudpQLS.js";
6
- import { c as runChild, h as currentTurn, s as namedModel, t as ChildTimeoutError, u as parseSampling } from "./child-D6mpkkCE.js";
7
- import { C as trOf, _ as writeImageFileMetadata, b as mapLimit, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as uniqueKey, x as norm } from "./library-zI-2tG7h.js";
1
+ import "./access-CfQWbNZP.js";
2
+ import { C as inert, Ct as parseCharacterFile, D as pruneLoreSubjects, E as pruneLinks, Et as InvalidEditProblems, F as isLeftOut, Ft as WEEKDAY_NAMES, It as DEFAULT_SLOTS, J as cleanText, L as askYesNo, M as classifyItems, Nt as LORE_KINDS, O as pruneMembers, P as ROLES, Pt as LORE_SCOPES, Q as IMPORT_FOLDER, S as extractVariables, St as CHARACTER_FILE_NAME, T as pruneKnowledge, Tt as readIdentifier, Y as itemise, Z as withPlayer, _ as characterDocument, _t as SLOTS_FILE_NAME, a as isPresetName, b as extractStyle, bt as FACTION_FILE_NAME, ct as VARIABLES_FILE_NAME, dt as variableProblems, ft as LORE_FILE_NAME, g as asWritten, gt as ITEM_FILE_NAME, h as addLore, ht as parseLocationFile, it as readImportFolder, j as buildRoster, k as pruneRelationships, lt as loadVariables, mt as LOCATION_FILE_NAME, nt as openingText, pt as parseLoreFile, st as parseImportCommand, tt as PICTURE_FILE, v as emptyExtracted, vt as parseItemFile, w as loreDocuments, wt as readVariableValues, xt as parseFactionFile, y as extractEntities, yt as parseSlotsFile } from "./presets-HB8kJTaE.js";
3
+ import { l as atomicWrite, m as parseSwitchboard, u as atomicWriteJson } from "./narration-CjB_KwwY.js";
4
+ import { B as loadPlots, H as plotReferenceProblems, K as readDocument, W as commandFlagKey, Y as errorMessage, Z as PROMPTS_FOLDER, a as externalWithheld, ht as COMPARISONS, it as shippedLanguages, lt as InvalidWorldError, ot as shippedText, q as Reader, r as externalGiven, rt as promptProblem, t as externalToolLimit } from "./hooks-rQTTeOC4.js";
5
+ import { t as trimCharacters } from "./text-DyRN4nDP.js";
6
+ import { c as runChild, h as currentTurn, s as namedModel, t as ChildTimeoutError, u as parseSampling } from "./child-lYYeOwl2.js";
7
+ import { C as trOf, S as slug, _ as writeImageFileMetadata, b as mapLimit, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as uniqueKey, x as norm } from "./library-Dfu0dgRj.js";
8
8
  import { dirname, join, relative } from "node:path";
9
9
  import { existsSync, readFileSync } from "node:fs";
10
10
  import { createHash } from "node:crypto";
@@ -18,7 +18,7 @@ import { lookup } from "node:dns";
18
18
  import { request } from "node:http";
19
19
  import { request as request$1 } from "node:https";
20
20
  import { BlockList, isIP } from "node:net";
21
- //#region src/shared/authoring-chat.ts
21
+ // src/shared/authoring-chat.ts
22
22
  const PREFIX = "world-author-";
23
23
  /** Stable DSH chat identity for the authoring conversation of one world. */
24
24
  function authoringChatSessionId(worldId) {
@@ -35,18 +35,7 @@ function authoredWorldOf(chatSessionId) {
35
35
  return;
36
36
  }
37
37
  }
38
- //#endregion
39
- //#region ../dsh-roleplay-model/src/trigger.ts
40
- const COMPARISONS = [
41
- "eq",
42
- "ne",
43
- "lt",
44
- "le",
45
- "gt",
46
- "ge"
47
- ];
48
- //#endregion
49
- //#region ../dsh-roleplay-model/src/dice.ts
38
+ // ../dsh-roleplay-model/src/dice.ts
50
39
  /** What a band of a check makes of an attempt; the same three results a round's outcome has. */
51
40
  const DICE_RESULTS = [
52
41
  "succeeded",
@@ -64,8 +53,7 @@ const DICE_COMPARISONS = [
64
53
  "over",
65
54
  "under"
66
55
  ];
67
- //#endregion
68
- //#region src/host/import/card.ts
56
+ // src/host/import/card.ts
69
57
  /** The file is not a character card this importer reads. The message says why, for the person who uploaded it. */
70
58
  var ImportCardError = class extends Error {};
71
59
  const PNG_SIGNATURE = Buffer.from([
@@ -237,8 +225,7 @@ function readCard(file, name) {
237
225
  }
238
226
  /** Whether a file looks like a PNG, so that its picture can be kept. */
239
227
  const isPng = (file) => file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE);
240
- //#endregion
241
- //#region src/host/import/output-ceiling.ts
228
+ // src/host/import/output-ceiling.ts
242
229
  /** A share of the model's context window, and the least and the fallback when the window is not known: the default of what one helper request may write. */
243
230
  const AUTO_OUTPUT_SHARE = .1;
244
231
  const AUTO_OUTPUT_MIN = 16e3;
@@ -274,8 +261,7 @@ async function outputCeiling(configured, agent, named, signal) {
274
261
  }
275
262
  return autoOutputCeiling(window);
276
263
  }
277
- //#endregion
278
- //#region src/host/folders.ts
264
+ // src/host/folders.ts
279
265
  /**
280
266
  * Names of the subfolders of `dir`, sorted. Symbolic links are not followed
281
267
  * and a missing directory has none; any other failure is thrown.
@@ -288,8 +274,7 @@ async function subfolders(dir) {
288
274
  throw error;
289
275
  }
290
276
  }
291
- //#endregion
292
- //#region src/host/characters/load.ts
277
+ // src/host/characters/load.ts
293
278
  const CHARACTERS_DIR = "characters";
294
279
  /**
295
280
  * Read the cast of one world: every subfolder of `<world>/characters/` that
@@ -337,8 +322,7 @@ async function loadCharacters(worldDir) {
337
322
  }
338
323
  return result;
339
324
  }
340
- //#endregion
341
- //#region src/host/calendar/load.ts
325
+ // src/host/calendar/load.ts
342
326
  const CALENDAR_FILE_NAME = "calendar.json";
343
327
  const HOLIDAY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,59}$/u;
344
328
  /**
@@ -401,8 +385,7 @@ async function loadCalendar(worldDir) {
401
385
  }
402
386
  return result;
403
387
  }
404
- //#endregion
405
- //#region src/host/commands/load.ts
388
+ // src/host/commands/load.ts
406
389
  const COMMANDS_FILE_NAME = "commands.json";
407
390
  /** The words the game itself uses after a slash. */
408
391
  const RESERVED = /* @__PURE__ */ new Set(["ooc", "roll"]);
@@ -475,8 +458,7 @@ async function loadCommands(worldDir) {
475
458
  }
476
459
  return result;
477
460
  }
478
- //#endregion
479
- //#region src/host/dice/load.ts
461
+ // src/host/dice/load.ts
480
462
  const DICE_FILE_NAME = "dice.json";
481
463
  function readBand(band) {
482
464
  const label = band.string("label", { required: true });
@@ -564,8 +546,7 @@ async function loadDice(worldDir) {
564
546
  }
565
547
  return result;
566
548
  }
567
- //#endregion
568
- //#region src/host/factions/load.ts
549
+ // src/host/factions/load.ts
569
550
  const FACTIONS_DIR = "factions";
570
551
  async function loadFactions(worldDir) {
571
552
  const dir = join(worldDir, FACTIONS_DIR);
@@ -612,8 +593,7 @@ async function loadFactions(worldDir) {
612
593
  });
613
594
  return result;
614
595
  }
615
- //#endregion
616
- //#region src/host/items/load.ts
596
+ // src/host/items/load.ts
617
597
  const ITEMS_DIR = "items";
618
598
  /** At most this many items in one world. */
619
599
  const MAX_ITEMS = 2e3;
@@ -739,8 +719,7 @@ function containersFirst(items) {
739
719
  for (const item of items) place(item);
740
720
  return ordered;
741
721
  }
742
- //#endregion
743
- //#region src/host/locations/load.ts
722
+ // src/host/locations/load.ts
744
723
  const LOCATIONS_DIR = "locations";
745
724
  /**
746
725
  * Read the places of one world: every subfolder of `<world>/locations/` that holds a
@@ -841,8 +820,7 @@ function parentsFirst(locations) {
841
820
  for (const location of locations) place(location);
842
821
  return ordered;
843
822
  }
844
- //#endregion
845
- //#region src/host/lore/load.ts
823
+ // src/host/lore/load.ts
846
824
  const LORE_DIR = "lore";
847
825
  async function loadLore(worldDir) {
848
826
  const dir = join(worldDir, LORE_DIR);
@@ -889,8 +867,7 @@ async function loadLore(worldDir) {
889
867
  });
890
868
  return result;
891
869
  }
892
- //#endregion
893
- //#region src/host/triggers/load.ts
870
+ // src/host/triggers/load.ts
894
871
  const TRIGGERS_FILE_NAME = "triggers.json";
895
872
  /** Read `triggers.json`: a list of what the world does by itself when something comes true (docs/world-format.md). */
896
873
  function parseTriggersFile(text) {
@@ -958,8 +935,7 @@ async function loadTriggers(worldDir) {
958
935
  }
959
936
  return result;
960
937
  }
961
- //#endregion
962
- //#region src/host/sessions/populate.ts
938
+ // src/host/sessions/populate.ts
963
939
  /** What is wrong with how the characters stand towards each other, found before anything is created. */
964
940
  function relationshipProblems(characters) {
965
941
  const ids = new Set(characters.map((character) => character.id));
@@ -1336,8 +1312,7 @@ function populateTriggers(session, definitions) {
1336
1312
  })));
1337
1313
  for (const definition of definitions) session.triggers.add(definition, "world", 0);
1338
1314
  }
1339
- //#endregion
1340
- //#region src/host/worlds/validated-world.ts
1315
+ // src/host/worlds/validated-world.ts
1341
1316
  /**
1342
1317
  * Reads everything a world's files hold and checks it all as a session start does: every file reads, and what refers to something refers to something that is there.
1343
1318
  * @throws {InvalidWorldError} naming every problem of the first part of the world that has any.
@@ -1447,8 +1422,7 @@ async function loadValidatedWorld(world) {
1447
1422
  commands: commandFile.commands
1448
1423
  };
1449
1424
  }
1450
- //#endregion
1451
- //#region src/host/worlds/world-check.ts
1425
+ // src/host/worlds/world-check.ts
1452
1426
  /** The most problems listed at once: the rest are named by their number. */
1453
1427
  const LISTED = 40;
1454
1428
  /**
@@ -1478,8 +1452,7 @@ async function checkWorld(world) {
1478
1452
  };
1479
1453
  }
1480
1454
  }
1481
- //#endregion
1482
- //#region src/host/import/casting.ts
1455
+ // src/host/import/casting.ts
1483
1456
  const CASTING_SCHEMA = {
1484
1457
  type: "object",
1485
1458
  properties: {
@@ -1503,7 +1476,10 @@ const CASTING_SCHEMA = {
1503
1476
  name: { type: "string" },
1504
1477
  command: { type: "string" },
1505
1478
  happens: { type: "string" },
1506
- need: { type: "string" },
1479
+ need: {
1480
+ type: "string",
1481
+ enum: ["arrival", "introduction"]
1482
+ },
1507
1483
  text: { type: "string" },
1508
1484
  options: {
1509
1485
  type: "array",
@@ -1566,10 +1542,10 @@ function castingDocuments(answer, passages = []) {
1566
1542
  const name = str(mechanism["name"]);
1567
1543
  const command = usable.find((entry) => entry.word === str(mechanism["command"]).toLowerCase());
1568
1544
  const happens = str(mechanism["happens"]) || (command === void 0 && str(mechanism["command"]) !== "" ? str(mechanism["name"]) : "");
1569
- const need = str(mechanism["need"]);
1545
+ const need = mechanism["need"] === "introduction" ? "introduction" : "arrival";
1570
1546
  const options = Array.isArray(mechanism["options"]) ? mechanism["options"].map(str).filter((option) => option !== "") : [];
1571
- let words = str(mechanism["text"]) || need;
1572
- if (name === "" || need === "" || command === void 0 && happens === "") {
1547
+ let words = str(mechanism["text"]) || name;
1548
+ if (name === "" || command === void 0 && happens === "") {
1573
1549
  notes.push(`casting not carried: "${name || "unnamed"}" has no reason to start it`);
1574
1550
  continue;
1575
1551
  }
@@ -1643,8 +1619,90 @@ async function extractCasting(ctx, card, passages) {
1643
1619
  };
1644
1620
  }
1645
1621
  }
1646
- //#endregion
1647
- //#region src/host/lorebooks/lorebooks.ts
1622
+ // src/host/import/structure.ts
1623
+ /** The most example lines the character keeps. */
1624
+ const MAX_EXAMPLES = 8;
1625
+ /** The summary is the start of the description: a sentence or two. */
1626
+ const SUMMARY_CHARS = 280;
1627
+ /** The lines of the example messages that the character speaks, as written; the markers of the tool that wrote them are taken out. */
1628
+ function exampleLines(text, name) {
1629
+ const lines = cleanText(text, name).split("\n").map((line) => line.trim()).filter((line) => line !== "");
1630
+ const speaker = /^([^:\n]{1,100}):\s*(.*)$/;
1631
+ if (!lines.some((line) => speaker.test(line))) return lines.slice(0, MAX_EXAMPLES);
1632
+ const names = new Set([name, name.split(/\s+/)[0] ?? ""].map((part) => part.toLocaleLowerCase()));
1633
+ return lines.flatMap((line) => {
1634
+ const match = speaker.exec(line);
1635
+ if (match?.[1] === void 0 || !names.has(match[1].trim().toLocaleLowerCase())) return [];
1636
+ const utterance = match[2]?.trim();
1637
+ return utterance === void 0 || utterance === "" ? [] : [utterance];
1638
+ }).slice(0, MAX_EXAMPLES);
1639
+ }
1640
+ /**
1641
+ * What a card holds, laid out without a model: the card's own character from its description, personality and examples, its lorebook entries as lore in its own words (for the game master only,
1642
+ * as nothing has read what they say), and its instructions as the narration style, word for word. No place, faction, thing or other person is found: those take a reader.
1643
+ */
1644
+ function structureOnly(card, items, _choices) {
1645
+ const taken = /* @__PURE__ */ new Set();
1646
+ const roster = [{
1647
+ kind: "character",
1648
+ key: uniqueKey(slug(card.name, "character"), taken),
1649
+ name: card.name,
1650
+ aliases: [],
1651
+ player: false
1652
+ }];
1653
+ const target = [{
1654
+ name: card.name,
1655
+ kind: "character"
1656
+ }];
1657
+ const classified = {};
1658
+ for (const item of items) if (item.id.startsWith("field:description") || item.id.startsWith("field:personality")) classified[item.id] = {
1659
+ roles: ["character"],
1660
+ targets: target
1661
+ };
1662
+ else if (item.id.startsWith("field:example")) classified[item.id] = {
1663
+ roles: ["speech"],
1664
+ targets: target
1665
+ };
1666
+ else if (item.id.startsWith("field:")) classified[item.id] = {
1667
+ roles: ["scenario"],
1668
+ targets: []
1669
+ };
1670
+ else classified[item.id] = {
1671
+ roles: ["world"],
1672
+ targets: []
1673
+ };
1674
+ const extracted = emptyExtracted();
1675
+ const description = cleanText(card.description, card.name);
1676
+ const built = characterDocument(roster[0], {
1677
+ tier: "principal",
1678
+ kind: "person",
1679
+ summary: description.slice(0, SUMMARY_CHARS).trim(),
1680
+ personality: cleanText(card.personality, card.name),
1681
+ background: description,
1682
+ speech: {
1683
+ style: "",
1684
+ examples: exampleLines(card.messageExample, card.name)
1685
+ }
1686
+ }, roster);
1687
+ extracted.characters.push(built.document);
1688
+ extracted.notes.push(...built.notes);
1689
+ for (const item of items.filter((entry) => entry.id.startsWith("entry:"))) for (const entry of loreDocuments(asWritten(item), roster, taken)) addLore(extracted.lore, {
1690
+ ...entry.document,
1691
+ scope: "listed"
1692
+ });
1693
+ const instructions = [card.systemPrompt, card.postHistoryInstructions].map((text) => cleanText(text, card.name)).filter((text) => text !== "");
1694
+ if (instructions.length > 0) extracted.prompts.push({
1695
+ id: "roleplay/style",
1696
+ text: inert(instructions.join("\n\n"))
1697
+ });
1698
+ extracted.notes.push("imported without a model: only the card's own character, its lorebook and its instructions were carried over");
1699
+ return {
1700
+ classified,
1701
+ roster,
1702
+ extracted
1703
+ };
1704
+ }
1705
+ // src/host/lorebooks/lorebooks.ts
1648
1706
  const LOREBOOKS_FOLDER = "lorebooks";
1649
1707
  const LOREBOOK_FILE = "lorebook.json";
1650
1708
  const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
@@ -1926,8 +1984,7 @@ function parseWorldInfoEdit(value) {
1926
1984
  if (problems.length > 0) throw new InvalidEditProblems(problems);
1927
1985
  return edit;
1928
1986
  }
1929
- //#endregion
1930
- //#region src/host/worlds/world-file.ts
1987
+ // src/host/worlds/world-file.ts
1931
1988
  const WORLD_FILE_NAME = "world.json";
1932
1989
  /** `alternate_openings` is a list of `{ title, text, character? }`: other first messages the player may start with, each for any character or for one playable character. */
1933
1990
  function readAlternateOpenings(reader) {
@@ -2098,8 +2155,7 @@ function parseWorldFile(text) {
2098
2155
  }
2099
2156
  };
2100
2157
  }
2101
- //#endregion
2102
- //#region src/host/worlds/world-file-io.ts
2158
+ // src/host/worlds/world-file-io.ts
2103
2159
  const queues = /* @__PURE__ */ new Map();
2104
2160
  /**
2105
2161
  * Runs `work` after everything asked for the same folder before it has finished. The import, the editor and the assistant each read `world.json`, change a field and write it
@@ -2125,8 +2181,7 @@ function updateWorldFile(directory, update) {
2125
2181
  return document;
2126
2182
  });
2127
2183
  }
2128
- //#endregion
2129
- //#region src/host/import/finish.ts
2184
+ // src/host/import/finish.ts
2130
2185
  const STAGE = "stage";
2131
2186
  const MAX_DESCRIPTION = 500;
2132
2187
  const MAX_TAGS = 8;
@@ -2325,6 +2380,10 @@ function worldJob(text, tr, card, roster, scenario, opening) {
2325
2380
  /** The description and tags of the world: asked of one call, and from the card's own fields when that fails. */
2326
2381
  async function describeWorld(ctx, card, roster, items, opening) {
2327
2382
  const scenario = items.filter((item) => item.id.startsWith("field:scenario")).map((item) => item.text).join("\n\n");
2383
+ if (ctx.noModel === true) return {
2384
+ description: (scenario || cleanText(card.description, card.name)).slice(0, MAX_DESCRIPTION).trim(),
2385
+ tags: card.tags.filter((tag) => tag.trim() !== "" && tag.length <= MAX_TAG).slice(0, MAX_TAGS)
2386
+ };
2328
2387
  try {
2329
2388
  const answer = await ctx.run(worldJob(ctx.text, trOf(ctx), card, roster, scenario, opening));
2330
2389
  return {
@@ -2496,8 +2555,7 @@ async function finishImport(ctx, input) {
2496
2555
  ...check.ok ? {} : { draft: check }
2497
2556
  };
2498
2557
  }
2499
- //#endregion
2500
- //#region src/host/import/pictures.ts
2558
+ // src/host/import/pictures.ts
2501
2559
  /** The address is not one a picture may be fetched from: it names this machine or a private network. */
2502
2560
  var BlockedAddressError = class extends Error {};
2503
2561
  const MAX_BYTES = 20971520;
@@ -2869,8 +2927,7 @@ function mergeReports(earlier, later, found) {
2869
2927
  skipped: [...(earlier?.skipped ?? []).filter((entry) => !asked.has(addressKey(entry.url))), ...later.skipped]
2870
2928
  };
2871
2929
  }
2872
- //#endregion
2873
- //#region src/host/catalogue/errors.ts
2930
+ // src/host/catalogue/errors.ts
2874
2931
  var CatalogueError = class extends Error {
2875
2932
  failure;
2876
2933
  detail;
@@ -2880,8 +2937,7 @@ var CatalogueError = class extends Error {
2880
2937
  this.detail = detail;
2881
2938
  }
2882
2939
  };
2883
- //#endregion
2884
- //#region src/host/catalogue/origin.ts
2940
+ // src/host/catalogue/origin.ts
2885
2941
  const ORIGIN_FILE = ".catalogue.json";
2886
2942
  const MAX_LISTED_CHANGES = 12;
2887
2943
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -2962,8 +3018,7 @@ async function localChanges(directory) {
2962
3018
  if (origin?.kind !== "release") return "unverified";
2963
3019
  return compare(origin.files, await hashWorld(directory));
2964
3020
  }
2965
- //#endregion
2966
- //#region src/host/import/snapshot.ts
3021
+ // src/host/import/snapshot.ts
2967
3022
  const SNAPSHOT = "files.json";
2968
3023
  /** The pictures of a world are fetched and generated in the background and are not what a card says. */
2969
3024
  const notTheCards = (path) => path.startsWith("images/");
@@ -2987,8 +3042,7 @@ async function editsSince(directory) {
2987
3042
  changes: describeChanges(changes)
2988
3043
  };
2989
3044
  }
2990
- //#endregion
2991
- //#region src/host/import/provenance.ts
3045
+ // src/host/import/provenance.ts
2992
3046
  const FILE = "provenance.json";
2993
3047
  const PROVENANCE_SCHEMA = "dsh-roleplay-import/v1";
2994
3048
  /** The import record of a world, or nothing for a world imported before records were kept. */
@@ -3020,8 +3074,7 @@ async function recordProvenance(directory, entry, cardJson) {
3020
3074
  history: [...earlier?.history ?? [], line]
3021
3075
  });
3022
3076
  }
3023
- //#endregion
3024
- //#region src/host/import/run-import.ts
3077
+ // src/host/import/run-import.ts
3025
3078
  /** The import in a world is not in the state the step needs, or there is none. The message says what to do. */
3026
3079
  var ImportStateError = class extends Error {};
3027
3080
  const PHASES = [
@@ -3261,8 +3314,53 @@ async function finish(ctx, world) {
3261
3314
  }
3262
3315
  return result;
3263
3316
  }
3264
- //#endregion
3265
- //#region src/host/import/tools.ts
3317
+ /**
3318
+ * Imports the card waiting in a world without a model: what {@link structureOnly} lays out is written as the world, with no review after it. A world that would not start yet is left a draft, which the person
3319
+ * can keep, discard or have an assistant repair.
3320
+ */
3321
+ async function structureImport(world, language) {
3322
+ await need(world, ["ready"], "the import without a model");
3323
+ const { card, choices, items, picture } = await load(world);
3324
+ const { classified, roster, extracted } = structureOnly(card, items, choices);
3325
+ const pictures = await ensurePictures(world, card.urls ?? []);
3326
+ const result = await finishImport({
3327
+ noModel: true,
3328
+ run: () => Promise.reject(/* @__PURE__ */ new Error("this import has no model")),
3329
+ concurrency: 1,
3330
+ text: (id, variables) => shippedText(id, language ?? "en", variables),
3331
+ say: () => void 0,
3332
+ ...language === void 0 ? {} : { language }
3333
+ }, {
3334
+ directory: world,
3335
+ card,
3336
+ choices,
3337
+ roster,
3338
+ items,
3339
+ classified,
3340
+ extracted,
3341
+ ...picture ? { picture: await readFile(join(folder(world), PICTURE_FILE)) } : {},
3342
+ notes: [],
3343
+ pictures: {
3344
+ found: pictures.found,
3345
+ added: pictures.added.length
3346
+ }
3347
+ });
3348
+ if (!result.ok) throw new ImportStateError(`the card could not be written as a world: ${result.problems.join("; ")}`);
3349
+ if (result.draft === void 0) await finishedImport(world);
3350
+ else await writeJson(join(folder(world), STATE), { phase: "repair" });
3351
+ await recordProvenance(world, {
3352
+ kind: "import",
3353
+ card: { name: card.name },
3354
+ language: language ?? "",
3355
+ counts: result.report.counts,
3356
+ notes: result.report.notes.length
3357
+ }, await readFile(join(folder(world), "card.json"), "utf8"));
3358
+ return {
3359
+ report: result.report,
3360
+ ...result.draft === void 0 ? {} : { draft: result.draft }
3361
+ };
3362
+ }
3363
+ // src/host/import/tools.ts
3266
3364
  const SURVEY_TOOL = "import_survey";
3267
3365
  const BUILD_TOOL = "import_build";
3268
3366
  const FINISH_TOOL = "import_finish";
@@ -3294,33 +3392,55 @@ const output = (render) => ({
3294
3392
  }]
3295
3393
  });
3296
3394
  const json = (value) => JSON.parse(JSON.stringify(value));
3395
+ /** What an endpoint says when it will not take `response_format` with a JSON schema. */
3396
+ const SCHEMA_REFUSED = /response_format|json_schema|Extra inputs are not permitted|unknown (?:field|parameter)/i;
3397
+ /** The models (`provider/model`) found not to take a JSON schema: they are asked for their result by a tool call. */
3398
+ const refusesSchema = /* @__PURE__ */ new Set();
3399
+ /** The model a helper runs on, as `provider/model`: the one named in the settings, else the chat's own. */
3400
+ function modelKeyOf(agent, named) {
3401
+ const config = agent?.session.requestHeader()?.config;
3402
+ const model = named ?? (config?.provider === void 0 || config.model === void 0 ? void 0 : {
3403
+ provider: config.provider,
3404
+ model: config.model
3405
+ });
3406
+ return model === void 0 ? "" : `${model.provider}/${model.model}`;
3407
+ }
3297
3408
  /** The runner of an import: every job is a narrow agent below the chat's own, on the chat's model. */
3298
3409
  function contextOf(exec, settings, text, language) {
3299
3410
  const agent = exec.agent;
3300
3411
  if (agent === void 0) throw new Error("the import tools can only be called by an agent");
3301
3412
  const run = async (job) => {
3302
- for (let attempt = 1;; attempt += 1) try {
3413
+ for (let attempt = 1;; attempt += 1) {
3303
3414
  const named = namedModel(settings.model);
3304
- const ceiling = await outputCeiling(settings.maxTokens, agent, named.model, exec.signal);
3305
- return await runChild({
3306
- parent: agent,
3307
- signal: exec.signal,
3308
- persona: job.persona,
3309
- prompt: job.prompt,
3310
- result: job.result,
3311
- ...job.check === void 0 ? {} : { beforeSubmit: (value) => job.check?.(value) },
3312
- maxTokens: Math.min((job.maxTokens ?? ceiling) + ANALYSIS_TOKENS, ceiling),
3313
- timeoutMinutes: settings.timeoutMinutes,
3314
- ...named,
3315
- ...settings.structured === "schema" ? { structured: true } : {},
3316
- sampling: {
3317
- temperature: settings.temperature,
3318
- toolChoice: "required"
3319
- },
3320
- ...settings.reasoning === "" ? {} : { reasoningEffort: settings.reasoning }
3321
- });
3322
- } catch (error) {
3323
- if (exec.signal.aborted || attempt >= ATTEMPTS || error instanceof ChildTimeoutError) throw error;
3415
+ const model = modelKeyOf(agent, named.model);
3416
+ const structured = settings.structured === "schema" && !refusesSchema.has(model);
3417
+ try {
3418
+ const ceiling = await outputCeiling(settings.maxTokens, agent, named.model, exec.signal);
3419
+ return await runChild({
3420
+ parent: agent,
3421
+ signal: exec.signal,
3422
+ persona: job.persona,
3423
+ prompt: job.prompt,
3424
+ result: job.result,
3425
+ ...job.check === void 0 ? {} : { beforeSubmit: (value) => job.check?.(value) },
3426
+ maxTokens: Math.min((job.maxTokens ?? ceiling) + ANALYSIS_TOKENS, ceiling),
3427
+ timeoutMinutes: settings.timeoutMinutes,
3428
+ ...named,
3429
+ ...structured ? { structured: true } : {},
3430
+ sampling: {
3431
+ temperature: settings.temperature,
3432
+ toolChoice: "required"
3433
+ },
3434
+ ...settings.reasoning === "" ? {} : { reasoningEffort: settings.reasoning }
3435
+ });
3436
+ } catch (error) {
3437
+ if (structured && !exec.signal.aborted && SCHEMA_REFUSED.test(error instanceof Error ? error.message : "")) {
3438
+ refusesSchema.add(model);
3439
+ attempt -= 1;
3440
+ continue;
3441
+ }
3442
+ if (exec.signal.aborted || attempt >= ATTEMPTS || error instanceof ChildTimeoutError) throw error;
3443
+ }
3324
3444
  }
3325
3445
  };
3326
3446
  const decide = settings.decisions === "decision" ? (state, asks) => {
@@ -3525,11 +3645,9 @@ function importHooks(ctx, worlds, prompting) {
3525
3645
  }));
3526
3646
  });
3527
3647
  }
3528
- //#endregion
3529
- //#region src/shared/import-selection.ts
3648
+ // src/shared/import-selection.ts
3530
3649
  const MAX_PREVIEW_TEXT = 4e3;
3531
- //#endregion
3532
- //#region src/host/tools/authoring-tools.ts
3650
+ // src/host/tools/authoring-tools.ts
3533
3651
  /** Which of the tools other plugins registered for everyone each assistant of the authoring chats was given in the settings; read afresh, so a change applies at its next step. */
3534
3652
  var AuthoringTools = class extends Service {
3535
3653
  board;
@@ -3568,7 +3686,6 @@ function limitAuthoringAgents(ctx, kindOf) {
3568
3686
  return await next();
3569
3687
  });
3570
3688
  }
3571
- //#endregion
3572
- export { knowsCharacter as $, alternateOpenings as A, loadCharacters as At, deleteLorebook as B, authoredWorldOf as Bt, addressKey as C, DICE_FILE_NAME as Ct, guardedLookup as D, loadCalendar as Dt, fetchPictures as E, CALENDAR_FILE_NAME as Et, WORLD_FILE_NAME as F, pictureOf as Ft, loadLorebook as G, entriesOf as H, parseWorldFile as I, readCard as It, reserveLorebook as J, lorebookDirectory as K, parseWorldInfoEdit as L, DICE_COMPARISONS as Lt, openingMessage as M, knownOutputCeiling as Mt, writePortrait as N, ImportCardError as Nt, mergeReports as O, parseCalendarFile as Ot, serialized as P, isPng as Pt, loadValidatedWorld as Q, addLorebookEntries as R, DICE_READINGS as Rt, CatalogueError as S, loadFactions as St, candidateUrls as T, parseDiceFile as Tt, isLorebookName as U, deleteLorebookEntry as V, authoringChatSessionId as Vt, listLorebooks as W, writeLorebookEntry as X, updateLorebookInfo as Y, checkWorld as Z, hashWorld as _, LOCATIONS_DIR as _t, importHooks as a, populateItems as at, readOrigin as b, loadItems as bt, importPhase as c, populateLore as ct, markReady as d, populateVariables as dt, populateCalendar as et, settleDraft as f, routineProblems as ft, describeChanges as g, loadLore as gt, writeSnapshot as h, LORE_DIR as ht, contextOf as i, populateFactions as it, cardCharacter as j, subfolders as jt, vetUrl as k, CHARACTERS_DIR as kt, isReviewing as l, populateRoutines as lt, editsSince as m, loadTriggers as mt, limitAuthoringAgents as n, populateClock as nt, importTools as o, populateKnowledge as ot, recordProvenance as p, TRIGGERS_FILE_NAME as pt, readLorebook as q, MAX_PREVIEW_TEXT as r, populateDice as rt, worldOf as s, populateLocations as st, AuthoringTools as t, populateCharacters as tt, keepDraft as u, populateTriggers as ut, isUnchanged as v, loadLocations as vt, addressesToFetch as w, loadDice as wt, writeOrigin as x, FACTIONS_DIR as xt, localChanges as y, ITEMS_DIR as yt, createLorebook as z, DICE_RESULTS as zt };
3689
+ export { loadValidatedWorld as $, vetUrl as A, CHARACTERS_DIR as At, createLorebook as B, DICE_RESULTS as Bt, CatalogueError as C, loadFactions as Ct, fetchPictures as D, CALENDAR_FILE_NAME as Dt, candidateUrls as E, parseDiceFile as Et, serialized as F, isPng as Ft, listLorebooks as G, deleteLorebookEntry as H, authoringChatSessionId as Ht, WORLD_FILE_NAME as I, pictureOf as It, readLorebook as J, loadLorebook as K, parseWorldFile as L, readCard as Lt, cardCharacter as M, subfolders as Mt, openingMessage as N, knownOutputCeiling as Nt, guardedLookup as O, loadCalendar as Ot, writePortrait as P, ImportCardError as Pt, checkWorld as Q, parseWorldInfoEdit as R, DICE_COMPARISONS as Rt, writeOrigin as S, FACTIONS_DIR as St, addressesToFetch as T, loadDice as Tt, entriesOf as U, deleteLorebook as V, authoredWorldOf as Vt, isLorebookName as W, updateLorebookInfo as X, reserveLorebook as Y, writeLorebookEntry as Z, describeChanges as _, loadLore as _t, importHooks as a, populateFactions as at, localChanges as b, ITEMS_DIR as bt, importPhase as c, populateLocations as ct, markReady as d, populateTriggers as dt, knowsCharacter as et, settleDraft as f, populateVariables as ft, writeSnapshot as g, LORE_DIR as gt, editsSince as h, loadTriggers as ht, contextOf as i, populateDice as it, alternateOpenings as j, loadCharacters as jt, mergeReports as k, parseCalendarFile as kt, isReviewing as l, populateLore as lt, recordProvenance as m, TRIGGERS_FILE_NAME as mt, limitAuthoringAgents as n, populateCharacters as nt, importTools as o, populateItems as ot, structureImport as p, routineProblems as pt, lorebookDirectory as q, MAX_PREVIEW_TEXT as r, populateClock as rt, worldOf as s, populateKnowledge as st, AuthoringTools as t, populateCalendar as tt, keepDraft as u, populateRoutines as ut, hashWorld as v, LOCATIONS_DIR as vt, addressKey as w, DICE_FILE_NAME as wt, readOrigin as x, loadItems as xt, isUnchanged as y, loadLocations as yt, addLorebookEntries as z, DICE_READINGS as zt };
3573
3690
 
3574
- //# sourceMappingURL=authoring-tools-DNnx0Nts.js.map
3691
+ //# sourceMappingURL=authoring-tools-BgmC2oqU.js.map