@dsh-agentic-roleplay/core 0.8.1 → 0.9.0

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 (51) hide show
  1. package/lib/{access-DtOxFKBK.js → access-CfQWbNZP.js} +4 -7
  2. package/lib/{authoring-tools-DNnx0Nts.js → authoring-tools-CdHlvx32.js} +2125 -152
  3. package/lib/authoring.js +143 -47
  4. package/lib/{child-D6mpkkCE.js → child-lYYeOwl2.js} +28 -51
  5. package/lib/client.js +611 -774
  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-BKh7eu80.js} +3 -4
  11. package/lib/{generator-r1Czm7oi.js → generator-DdZ1-sgv.js} +3 -4
  12. package/lib/helper.js +2 -3
  13. package/lib/{hooks-BQCzgggH.js → hooks-CcQj_dJo.js} +69 -97
  14. package/lib/images.js +4 -4
  15. package/lib/index.js +195 -265
  16. package/lib/{library-zI-2tG7h.js → library-QFL6Z_Nr.js} +9 -15
  17. package/lib/{lorebook-author-tools-ywaYicwd.js → lorebook-author-tools-DWBnYo1E.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-BMy6NcCY.js} +81 -788
  22. package/lib/{packs-Cv8hanXJ.js → packs-BREPSfHy.js} +6 -10
  23. package/lib/{presenter-agent-BSaMSd3G.js → presenter-agent-B49-_iUm.js} +12 -18
  24. package/lib/{preset-CWI3-0r1.js → preset-BqgY1Tz4.js} +5 -6
  25. package/lib/{preset-author-tools-BrJYa2cr.js → preset-author-tools-BB_Dcv2o.js} +12 -14
  26. package/lib/preset-authoring.js +6 -7
  27. package/lib/{presets-MwOSMMyu.js → presets-Bwnrx7p0.js} +69 -63
  28. package/lib/{reflection-zSaMsjKj.js → reflection-CUWG-6Qg.js} +19 -30
  29. package/lib/{text-BzudpQLS.js → text-CbGQhK1-.js} +9 -10
  30. package/lib/{turn-guard-Cv8pfHEA.js → turn-guard-Bb8Ew-1z.js} +6 -11
  31. package/package.json +29 -29
  32. package/prompts/en/checks/decide-sheet.md +1 -0
  33. package/prompts/en/checks/fidelity.md +7 -0
  34. package/prompts/en/checks/gaps.md +4 -0
  35. package/prompts/en/checks/notice.md +3 -0
  36. package/prompts/en/import/casting.md +1 -1
  37. package/prompts/en/import/character.md +1 -0
  38. package/prompts/en/import/finish-draft.md +1 -1
  39. package/prompts/en/import/finish-ok.md +3 -1
  40. package/prompts/en/import/notice-repair.md +2 -2
  41. package/prompts/en/import/repair-again.md +2 -2
  42. package/prompts/zh/checks/decide-sheet.md +1 -0
  43. package/prompts/zh/checks/fidelity.md +7 -0
  44. package/prompts/zh/checks/gaps.md +4 -0
  45. package/prompts/zh/checks/notice.md +3 -0
  46. package/prompts/zh/import/casting.md +1 -1
  47. package/prompts/zh/import/character.md +1 -0
  48. package/prompts/zh/import/finish-draft.md +1 -1
  49. package/prompts/zh/import/finish-ok.md +3 -1
  50. package/prompts/zh/import/notice-repair.md +2 -2
  51. package/prompts/zh/import/repair-again.md +2 -2
@@ -1,14 +1,13 @@
1
- import { a as chatSessionId } from "./access-DtOxFKBK.js";
2
- import { $ as knowsCharacter, A as alternateOpenings, At as loadCharacters, Bt as authoredWorldOf, C as addressKey, Dt as loadCalendar, E as fetchPictures, F as WORLD_FILE_NAME, I as parseWorldFile, M as openingMessage, N as writePortrait, O as mergeReports, P as serialized, Q as loadValidatedWorld, St as loadFactions, T as candidateUrls, Vt as authoringChatSessionId, _t as LOCATIONS_DIR, at as populateItems, bt as loadItems, c as importPhase, dt as populateVariables, gt as loadLore, h as writeSnapshot, ht as LORE_DIR, i as contextOf, j as cardCharacter, jt as subfolders, kt as CHARACTERS_DIR, m as editsSince, mt as loadTriggers, p as recordProvenance, pt as TRIGGERS_FILE_NAME, s as worldOf, st as populateLocations, tt as populateCharacters, vt as loadLocations, w as addressesToFetch, xt as FACTIONS_DIR, yt as ITEMS_DIR } from "./authoring-tools-DNnx0Nts.js";
3
- import { $ as writeChoices, G as withPlayer, K as IMPORT_FOLDER, O as findEntity, Q as readImportFolder, T as sourcesFor, U as itemise, V as writeWorldPrompt, X as openingText, Y as PICTURE_FILE, _t as parseCharacterFile, bt as InvalidEditProblems, ct as LOCATION_FILE_NAME, ft as parseItemFile, gt as CHARACTER_FILE_NAME, ht as parseFactionFile, lt as parseLocationFile, mt as FACTION_FILE_NAME, ot as LORE_FILE_NAME, rt as loadVariables, st as parseLoreFile, ut as ITEM_FILE_NAME, v as extractStyleFrom } from "./presets-MwOSMMyu.js";
4
- import { l as atomicWrite, m as parseSwitchboard, n as encodeOutput, u as atomicWriteJson } from "./narration-CnBlVure.js";
5
- import { B as PLOTS_FILE_NAME, F as LANGUAGE_NAMES, H as parsePlotsFile, I as STORY_LANGUAGES, J as formatIssue, L as isStoryLanguage, R as textLanguage, U as plotReferenceProblems, V as loadPlots, Z as PROMPTS_FOLDER, it as shippedLanguages, lt as InvalidWorldError, pt as WorldNotFoundError, st as AgentUnavailableError } from "./hooks-BQCzgggH.js";
6
- import { i as translator, r as languageOf } from "./text-BzudpQLS.js";
7
- import { u as parseSampling } from "./child-D6mpkkCE.js";
8
- import { b as mapLimit, h as readImageFileMetadata, u as referenceImagePath, x as norm } from "./library-zI-2tG7h.js";
9
- import { n as readPreset } from "./preset-CWI3-0r1.js";
10
- import { _ as API_PREFIX, a as packIds, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId } from "./packs-Cv8hanXJ.js";
11
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-r1Czm7oi.js";
1
+ import { a as chatSessionId } from "./access-CfQWbNZP.js";
2
+ import { Bt as loadFactions, C as worldFieldChanges, D as UPDATE_FOLDER, F as editsSince, Ft as LOCATIONS_DIR, G as addressesToFetch, Gt as loadCalendar, I as writeSnapshot, It as loadLocations, Jt as loadCharacters, K as candidateUrls, Lt as ITEMS_DIR, Mt as loadTriggers, Nt as LORE_DIR, O as baseId, P as recordProvenance, Pt as loadLore, Q as writePortrait, Rt as loadItems, S as matchPieces, T as loadWorldParts, W as addressKey, Y as mergeReports, Yt as subfolders, Z as cardCharacter, _t as knowsCharacter, an as authoringChatSessionId, c as importPhase, gt as loadValidatedWorld, i as contextOf, in as authoredWorldOf, jt as TRIGGERS_FILE_NAME, k as cardPieces, q as fetchPictures, qt as CHARACTERS_DIR, s as worldOf, v as editWorldInfo, w as withScratchStory, zt as FACTIONS_DIR } from "./authoring-tools-CdHlvx32.js";
3
+ import { Ct as CHARACTER_FILE_NAME, Dt as InvalidEditProblems, Q as IMPORT_FOLDER, St as parseFactionFile, Z as withPlayer, _t as ITEM_FILE_NAME, at as writeChoices, gt as parseLocationFile, ht as LOCATION_FILE_NAME, it as readImportFolder, mt as parseLoreFile, pt as LORE_FILE_NAME, q as writeWorldPrompt, tt as PICTURE_FILE, ut as loadVariables, wt as parseCharacterFile, x as extractStyleFrom, xt as FACTION_FILE_NAME, yt as parseItemFile } from "./presets-Bwnrx7p0.js";
4
+ import { l as atomicWrite, n as encodeOutput, u as atomicWriteJson } from "./narration-CjB_KwwY.js";
5
+ import { B as loadPlots, F as STORY_LANGUAGES, H as plotReferenceProblems, I as isStoryLanguage, J as formatIssue, L as textLanguage, P as LANGUAGE_NAMES, V as parsePlotsFile, Z as PROMPTS_FOLDER, it as shippedLanguages, lt as InvalidWorldError, pt as WorldNotFoundError, st as AgentUnavailableError, z as PLOTS_FILE_NAME } from "./hooks-CcQj_dJo.js";
6
+ import { i as translator, r as languageOf } from "./text-CbGQhK1-.js";
7
+ import { b as mapLimit, h as readImageFileMetadata, u as referenceImagePath } from "./library-QFL6Z_Nr.js";
8
+ import { n as readPreset } from "./preset-BqgY1Tz4.js";
9
+ import { _ as API_PREFIX, a as packIds, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId } from "./packs-BREPSfHy.js";
10
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-DdZ1-sgv.js";
12
11
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
13
12
  import { existsSync, lstatSync, statSync } from "node:fs";
14
13
  import { randomUUID } from "node:crypto";
@@ -17,8 +16,8 @@ import { Session, SessionId } from "@deepseek-ai/dsh-session";
17
16
  import { ToolCallId, createMessage, createSystemMessage, createToolResultMessage } from "@deepseek-ai/dsh-llm";
18
17
  import { setApprovalPolicy } from "@deepseek-ai/dsh-user-approval";
19
18
  import { defineTool } from "@deepseek-ai/dsh-tools";
20
- import { createSessionStore, readTriggerDefinition, triggerReferenceProblems, writeCalendar } from "@dsh-agentic-roleplay/state";
21
- //#region src/host/agent/opening.ts
19
+ import { readTriggerDefinition, triggerReferenceProblems } from "@dsh-agentic-roleplay/state";
20
+ // src/host/agent/opening.ts
22
21
  /** What the opening is reported to come from, where a chat shows the source of a message. */
23
22
  const OPENING_SOURCE = {
24
23
  provider: "roleplay",
@@ -195,11 +194,8 @@ function authoringOpeningEvents(welcome, source = AUTHORING_OPENING_SOURCE) {
195
194
  async function storeOpening(persistence, chat, segments, events = openingEvents(segments)) {
196
195
  await storeInitialEvents(persistence, chat, events);
197
196
  }
198
- async function storeAuthoringOpening(persistence, chat, welcome) {
199
- await storeInitialEvents(persistence, chat, authoringOpeningEvents(welcome));
200
- }
201
- async function storeDoctorOpening(persistence, chat, welcome) {
202
- await storeInitialEvents(persistence, chat, authoringOpeningEvents(welcome, DOCTOR_OPENING_SOURCE));
197
+ async function storeAuthoringOpening(persistence, chat, welcome, source) {
198
+ await storeInitialEvents(persistence, chat, authoringOpeningEvents(welcome, source));
203
199
  }
204
200
  async function storeInitialEvents(persistence, chat, events) {
205
201
  const header = {
@@ -218,8 +214,7 @@ async function storeInitialEvents(persistence, chat, events) {
218
214
  await handle.close();
219
215
  }
220
216
  }
221
- //#endregion
222
- //#region src/host/agent/agent-sessions.ts
217
+ // src/host/agent/agent-sessions.ts
223
218
  /** Title of the DSH project that groups every roleplay chat. */
224
219
  const PROJECT_TITLE = "Roleplay";
225
220
  /** The agent preset roleplay chats run under; it is declared by the bundle. */
@@ -394,10 +389,42 @@ var AgentSessions = class {
394
389
  }
395
390
  }
396
391
  };
397
- //#endregion
398
- //#region src/host/agent/authoring-sessions.ts
399
- const AUTHORING_PROJECT_TITLE = "World Authoring";
400
- const AUTHORING_AGENT_PRESET = "world-authoring";
392
+ // src/host/agent/ensure-authoring-chat.ts
393
+ /**
394
+ * Creates or reopens the authoring chat of a subject in the project of its kind: its language is kept, its opening is stored before the chat is made (a stored chat not yet in the project is adopted,
395
+ * not made again), and the chat is made or adopted.
396
+ * @throws {AgentUnavailableError} when the profile cannot store an opening.
397
+ */
398
+ async function ensureAuthoringChat(services, roleplayRoot, prompts, languages, kind, subject) {
399
+ if (subject.languageKey !== void 0) languages?.set(subject.languageKey, subject.language);
400
+ const language = subject.languageKey === void 0 ? subject.language : languages?.get(subject.languageKey);
401
+ const projectPath = join(roleplayRoot, kind.folder);
402
+ const project = await services.registry.create(projectPath, kind.projectTitle);
403
+ const existed = project.sessionIds.includes(subject.chatId);
404
+ const stored = !existed && await isStored(services.persistence, subject.chatId);
405
+ if (!existed && !stored) {
406
+ if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of an authoring chat");
407
+ await storeAuthoringOpening(services.persistence, {
408
+ id: subject.chatId,
409
+ cwd: project.path,
410
+ agentPreset: kind.agentPreset
411
+ }, prompts.text(kind.welcome, language, subject.welcome), kind.openingSource);
412
+ }
413
+ return await ensureAgentChat(services, {
414
+ projectPath,
415
+ projectTitle: kind.projectTitle,
416
+ sessionId: subject.chatId,
417
+ agentPreset: kind.agentPreset,
418
+ title: subject.title,
419
+ renameExisting: subject.renameExisting
420
+ }, project);
421
+ }
422
+ const KIND = {
423
+ folder: "worlds",
424
+ projectTitle: "World Authoring",
425
+ agentPreset: "world-authoring",
426
+ welcome: "world/welcome"
427
+ };
401
428
  /** The title of a world's authoring chat, in the language of the person who opened it. */
402
429
  function authoringTitle(worldName, language) {
403
430
  return translator(languageOf(language))("Authoring {name}", { name: worldName });
@@ -415,30 +442,14 @@ var AuthoringSessions = class {
415
442
  this.languages = languages;
416
443
  }
417
444
  async ensure(worldId, worldName, title, language) {
418
- const chatTitle = title ?? authoringTitle(worldName, language);
419
- this.languages.set(worldId, language);
420
- const services = this.services();
421
- const projectPath = join(this.roleplayRoot(), "worlds");
422
- const project = await services.registry.create(projectPath, AUTHORING_PROJECT_TITLE);
423
- const sessionId = authoringChatSessionId(worldId);
424
- const existed = project.sessionIds.includes(sessionId);
425
- const stored = !existed && await isStored(services.persistence, sessionId);
426
- if (!existed && !stored) {
427
- if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of an authoring chat");
428
- await storeAuthoringOpening(services.persistence, {
429
- id: sessionId,
430
- cwd: project.path,
431
- agentPreset: AUTHORING_AGENT_PRESET
432
- }, this.prompts.text("world/welcome", this.languages.get(worldId), { world: worldName }));
433
- }
434
- return await ensureAgentChat(services, {
435
- projectPath,
436
- projectTitle: AUTHORING_PROJECT_TITLE,
437
- sessionId,
438
- agentPreset: AUTHORING_AGENT_PRESET,
439
- title: chatTitle,
445
+ return await ensureAuthoringChat(this.services(), this.roleplayRoot(), this.prompts, this.languages, KIND, {
446
+ chatId: authoringChatSessionId(worldId),
447
+ languageKey: worldId,
448
+ title: title ?? authoringTitle(worldName, language),
449
+ language,
450
+ welcome: { world: worldName },
440
451
  renameExisting: true
441
- }, project);
452
+ });
442
453
  }
443
454
  /** Sends a message into a chat as if the person had written it. */
444
455
  async send(sessionId, text) {
@@ -453,551 +464,7 @@ var AuthoringSessions = class {
453
464
  }, new AbortController().signal);
454
465
  }
455
466
  };
456
- //#endregion
457
- //#region src/host/import/card-tools.ts
458
- /** The most of a piece one `card_read` returns; a long lorebook entry is read in turns. */
459
- const READ_CHARS = 6e3;
460
- const SNIPPET_CHARS = 240;
461
- const DEFAULT_HITS = 8;
462
- const MAX_HITS = 20;
463
- const baseId = (id) => id.replace(/#\d+$/, "");
464
- /** The folder inside `.import` where a newer version of the card waits to be applied to the world. */
465
- const UPDATE_FOLDER = "update";
466
- /** Everything the card holds, in the order the card has it. */
467
- function cardPieces(card, choices) {
468
- const read = new Set(itemise(card, choices).map((item) => baseId(item.id)));
469
- const field = (id, label, text) => text.trim() === "" ? [] : [{
470
- id,
471
- label,
472
- title: "",
473
- keys: [],
474
- text,
475
- used: read.has(id)
476
- }];
477
- return [
478
- ...field("field:description", "description", card.description),
479
- ...field("field:personality", "personality", card.personality),
480
- ...field("field:scenario", "scenario", card.scenario),
481
- ...field("field:example", "example messages", card.messageExample),
482
- ...field("field:first-message", "first message", card.firstMessage),
483
- ...card.alternateGreetings.flatMap((text, index) => field(`field:greeting-${index + 1}`, `alternate greeting ${index + 1}`, text)),
484
- ...field("field:creator-notes", "creator's notes", card.creatorNotes),
485
- ...field("field:system-prompt", "system prompt", card.systemPrompt),
486
- ...field("field:post-history", "post-history instructions", card.postHistoryInstructions),
487
- ...(card.book?.entries ?? []).filter((entry) => entry.content.trim() !== "").map((entry) => ({
488
- id: entry.id,
489
- label: entry.title === "" ? entry.id : `entry “${entry.title}”`,
490
- title: entry.title,
491
- keys: entry.keys,
492
- text: entry.content,
493
- used: read.has(entry.id),
494
- enabled: entry.enabled
495
- }))
496
- ];
497
- }
498
- async function optional(file) {
499
- try {
500
- return JSON.parse(await readFile(file, "utf8"));
501
- } catch (error) {
502
- if (error.code === "ENOENT") return void 0;
503
- throw error;
504
- }
505
- }
506
- /** The card kept in a world's import folder, and what the import made of it. The tools exist as long as the card does. */
507
- async function readSource(directory, withRecords, version = "current") {
508
- const folder = join(directory, IMPORT_FOLDER);
509
- let read;
510
- try {
511
- read = await readImportFolder(version === "new" ? join(folder, UPDATE_FOLDER) : folder);
512
- } catch (error) {
513
- if (error.code === "ENOENT") throw new Error(version === "new" ? "no newer version of the card is waiting to update this world" : "this world has no source card: it was not imported from one, or its .import folder was removed");
514
- throw error;
515
- }
516
- const records = withRecords && version === "current" ? {
517
- classified: await optional(join(folder, "classification.json")),
518
- roster: await optional(join(folder, "roster.json")),
519
- report: await optional(join(folder, "report.json"))
520
- } : {};
521
- return {
522
- card: read.card,
523
- choices: read.choices,
524
- pieces: cardPieces(read.card, read.choices),
525
- records
526
- };
527
- }
528
- const rolesOf = (classified, id) => {
529
- if (classified === void 0) return [];
530
- return [...new Set(Object.entries(classified).filter(([key]) => baseId(key) === id).flatMap(([, entry]) => entry.roles))];
531
- };
532
- function snippet(text, at, length) {
533
- const start = Math.max(0, at - Math.floor((SNIPPET_CHARS - length) / 2));
534
- const end = Math.min(text.length, start + SNIPPET_CHARS);
535
- return `${start > 0 ? "…" : ""}${text.slice(start, end).replace(/\s+/g, " ")}${end < text.length ? "…" : ""}`;
536
- }
537
- function searchPieces(pieces, query, limit) {
538
- const phrase = query.trim().toLowerCase();
539
- if (phrase === "") return [];
540
- const words = [...new Set(phrase.split(/[\s,;,、]+/).filter((word) => word.length >= (/^[\x00-\x7f]+$/.test(word) ? 3 : 2)))];
541
- const count = (text, needle) => {
542
- let n = 0;
543
- let first = -1;
544
- for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + needle.length)) {
545
- n += 1;
546
- if (first < 0) first = at;
547
- }
548
- return {
549
- n,
550
- first
551
- };
552
- };
553
- const look = (text) => {
554
- const lowered = text.toLowerCase();
555
- const whole = count(lowered, phrase);
556
- if (whole.n > 0) return {
557
- matches: whole.n,
558
- score: whole.n * 4 + 100,
559
- at: whole.first,
560
- length: phrase.length
561
- };
562
- const found = words.map((word) => ({
563
- word,
564
- ...count(lowered, word)
565
- })).filter((entry) => entry.n > 0);
566
- if (found.length === 0) return void 0;
567
- const best = found.reduce((a, b) => a.first <= b.first ? a : b, found[0]);
568
- return {
569
- matches: found.reduce((sum, entry) => sum + entry.n, 0),
570
- score: found.length * 10 + found.reduce((sum, entry) => sum + entry.n, 0),
571
- at: best.first,
572
- length: best.word.length
573
- };
574
- };
575
- return pieces.flatMap((piece) => {
576
- const inText = look(piece.text);
577
- if (inText !== void 0) return [{
578
- piece,
579
- in: "text",
580
- matches: inText.matches,
581
- score: inText.score,
582
- snippet: snippet(piece.text, inText.at, inText.length)
583
- }];
584
- const head = [piece.title, ...piece.keys].filter((part) => part !== "").join(" · ");
585
- const inHead = look(head);
586
- return inHead === void 0 ? [] : [{
587
- piece,
588
- in: "title or keys",
589
- matches: inHead.matches,
590
- score: inHead.score - 50,
591
- snippet: `${piece.title === "" ? "" : `title: ${piece.title}`}${piece.keys.length === 0 ? "" : `${piece.title === "" ? "" : "; "}keys: ${piece.keys.join(", ")}`}`
592
- }];
593
- }).sort((a, b) => b.score - a.score).slice(0, limit).map(({ piece, matches, in: where, snippet: text }) => ({
594
- piece,
595
- matches,
596
- in: where,
597
- snippet: text
598
- }));
599
- }
600
- const versionParameter = {
601
- type: "string",
602
- enum: ["current", "new"],
603
- description: "current (the default) is the card the world was made from; new is the newer version waiting to update it, when card_diff says there is one. Piece ids are those of that version."
604
- };
605
- const output = {
606
- schema: { type: "json" },
607
- render: (_args, value) => [{
608
- type: "text",
609
- text: JSON.stringify(value, null, 1)
610
- }]
611
- };
612
- const json = (value) => JSON.parse(JSON.stringify(value));
613
- const idOf = (exec) => {
614
- const chat = exec.agent?.session.id;
615
- const world = chat === void 0 ? void 0 : authoredWorldOf(chat);
616
- if (world === void 0) throw new Error("this tool is available only in a world authoring chat");
617
- return world;
618
- };
619
- /**
620
- * Read-only tools over the card a world was imported from, which stays in the world's `.import` folder: they work while that folder holds the card and say so when it does not.
621
- * `records` adds what the import made of the card (the role of each piece, who it was used for); it is off only when a test compares the agent with and without it.
622
- */
623
- function cardTools(worlds, options = {}) {
624
- const withRecords = options.records !== false;
625
- const source = async (exec, version = "current") => {
626
- const id = idOf(exec);
627
- const record = await worlds.find(id);
628
- if (record === void 0) throw new Error(`the authored world "${id}" no longer exists`);
629
- return await readSource(record.directory, withRecords, version);
630
- };
631
- const versionOf = (value) => {
632
- if (value === void 0 || value === "current") return "current";
633
- if (value === "new") return "new";
634
- throw new Error("version must be current or new");
635
- };
636
- const find = (pieces, id) => {
637
- const found = pieces.find((piece) => piece.id === id);
638
- if (found === void 0) throw new Error(`the card has no piece "${id}": use an id from card_overview or card_search`);
639
- return found;
640
- };
641
- return [
642
- defineTool({
643
- name: "card_overview",
644
- description: "The card this world was imported from, which is kept: its name, creator and tags, every piece of it (field, greeting or lorebook entry) with its size, and, from the import's own records, what each piece was taken to be and which characters, places and things were made from it. Start here when the person asks where something in the world came from.",
645
- parameters: {},
646
- output,
647
- isConcurrencySafe: () => true,
648
- async execute(_args, exec) {
649
- const { card, choices, pieces, records } = await source(exec);
650
- const madeFrom = entitiesByPiece({
651
- card,
652
- choices,
653
- pieces,
654
- records
655
- });
656
- const made = (id) => madeFrom.get(id) ?? [];
657
- return json({
658
- card: {
659
- name: card.name,
660
- creator: card.creator,
661
- version: card.characterVersion,
662
- tags: card.tags,
663
- format: card.sourceSpec,
664
- ignoredScripts: card.ignored.scripts
665
- },
666
- pieces: pieces.map((piece) => ({
667
- id: piece.id,
668
- label: piece.label,
669
- characters: piece.text.length,
670
- readByTheImport: piece.used,
671
- ...piece.enabled === void 0 ? {} : { switchedOnInCard: piece.enabled },
672
- ...withRecords ? {
673
- takenToBe: rolesOf(records.classified, piece.id),
674
- madeInto: made(piece.id)
675
- } : {}
676
- })),
677
- ...records.roster === void 0 ? {} : { imported: records.roster.map((entity) => ({
678
- name: entity.name,
679
- kind: entity.kind,
680
- aliases: entity.aliases,
681
- playedByThePlayer: entity.player
682
- })) },
683
- ...records.report === void 0 ? {} : {
684
- importNotes: records.report.notes,
685
- leftOut: records.report.leftOut
686
- },
687
- note: "The import's records are its own judgement and can be wrong or incomplete; check them against the text of the piece with card_read."
688
- });
689
- }
690
- }),
691
- defineTool({
692
- name: "card_search",
693
- description: "Searches everything the card says (fields, greetings, lorebook entries and their keys) for a name or phrase and returns the pieces that contain it, best first, each with a short snippet and whether it was found in the text or only in the title or keys of an entry. A hit is a pointer, not evidence: read the piece with card_read before you answer from it.",
694
- parameters: {
695
- query: {
696
- type: "string",
697
- required: true,
698
- description: "A name or phrase to look for, in the card's own language."
699
- },
700
- version: versionParameter,
701
- limit: {
702
- type: "number",
703
- description: `How many pieces to return, at most ${MAX_HITS} (default ${DEFAULT_HITS}).`
704
- }
705
- },
706
- output,
707
- isConcurrencySafe: () => true,
708
- async execute(args, exec) {
709
- const { pieces } = await source(exec, versionOf(args.version));
710
- const limit = Math.min(MAX_HITS, Math.max(1, Math.floor(typeof args.limit === "number" && Number.isFinite(args.limit) ? args.limit : DEFAULT_HITS)));
711
- const hits = searchPieces(pieces, args.query, limit);
712
- return json({
713
- query: args.query,
714
- found: hits.length,
715
- hits: hits.map(({ piece, matches, in: where, snippet: text }) => ({
716
- piece: piece.id,
717
- label: piece.label,
718
- matches,
719
- foundIn: where,
720
- snippet: text
721
- }))
722
- });
723
- }
724
- }),
725
- defineTool({
726
- name: "card_read",
727
- description: `The text of one piece of the card, word for word as the card has it (the card's own placeholders such as {{user}} included). A long piece is read in turns of ${READ_CHARS} characters: when "next" is given, call again with that offset.`,
728
- parameters: {
729
- piece: {
730
- type: "string",
731
- required: true,
732
- description: "A piece id from card_overview, card_search or card_diff, such as field:description or entry:3."
733
- },
734
- version: versionParameter,
735
- offset: {
736
- type: "number",
737
- description: "Where to start reading, in characters (default 0)."
738
- }
739
- },
740
- output,
741
- isConcurrencySafe: () => true,
742
- async execute(args, exec) {
743
- const { pieces } = await source(exec, versionOf(args.version));
744
- const piece = find(pieces, args.piece);
745
- const from = Math.min(piece.text.length, Math.max(0, Math.floor(typeof args.offset === "number" && Number.isFinite(args.offset) ? args.offset : 0)));
746
- const to = Math.min(piece.text.length, from + READ_CHARS);
747
- return json({
748
- piece: piece.id,
749
- label: piece.label,
750
- ...piece.keys.length === 0 ? {} : { keys: piece.keys },
751
- from,
752
- to,
753
- of: piece.text.length,
754
- ...to < piece.text.length ? { next: to } : {},
755
- text: piece.text.slice(from, to)
756
- });
757
- }
758
- }),
759
- defineTool({
760
- name: "card_origin",
761
- description: "Where a character, place, organisation or thing of this world came from: the pieces of the card the import read to make it (the pieces about it first, then those that only mention it), with what each was taken to be. For a name the import did not make anything of, the pieces of the card that mention it. Then read the pieces with card_read to answer from their text.",
762
- parameters: { name: {
763
- type: "string",
764
- required: true,
765
- description: "The name or an alias, as the world or the card has it."
766
- } },
767
- output,
768
- isConcurrencySafe: () => true,
769
- async execute(args, exec) {
770
- const { card, choices, pieces, records } = await source(exec);
771
- const entity = records.roster === void 0 ? void 0 : findEntity(records.roster, args.name);
772
- if (entity === void 0 || records.classified === void 0) return json({
773
- name: args.name,
774
- madeByTheImport: false,
775
- mentions: searchPieces(pieces, args.name, DEFAULT_HITS).map(({ piece, in: where, snippet: text }) => ({
776
- piece: piece.id,
777
- label: piece.label,
778
- foundIn: where,
779
- snippet: text
780
- }))
781
- });
782
- return json({
783
- name: entity.name,
784
- kind: entity.kind,
785
- aliases: entity.aliases,
786
- madeByTheImport: true,
787
- usedPieces: originOf(card, choices, pieces, records, entity.name).map((entry) => ({
788
- piece: entry.piece,
789
- label: entry.label,
790
- how: entry.how,
791
- takenToBe: rolesOf(records.classified, entry.piece)
792
- }))
793
- });
794
- }
795
- })
796
- ];
797
- }
798
- /** For each piece of the card, the names of the characters, places and things the import made from it. */
799
- function entitiesByPiece(source) {
800
- const made = /* @__PURE__ */ new Map();
801
- for (const entity of source.records.roster ?? []) for (const entry of originOf(source.card, source.choices, source.pieces, source.records, entity.name)) made.set(entry.piece, [...made.get(entry.piece) ?? [], entity.name]);
802
- return made;
803
- }
804
- /** The pieces an entity was made from, as the build chose them: the ones the survey said are about it, then those that name it. */
805
- function originOf(card, choices, pieces, records, name) {
806
- if (records.roster === void 0 || records.classified === void 0) return [];
807
- const entity = findEntity(records.roster, name);
808
- if (entity === void 0) return [];
809
- const names = [entity.name, ...entity.aliases].map(norm);
810
- const items = itemise(card, choices);
811
- const chosen = sourcesFor(entity, items, records.classified);
812
- const about = (id) => (records.classified?.[id]?.targets ?? []).some((target) => target.kind === entity.kind && names.includes(norm(target.name)));
813
- const seen = /* @__PURE__ */ new Set();
814
- return chosen.flatMap((item) => {
815
- const id = baseId(item.id);
816
- const piece = pieces.find((entry) => entry.id === id);
817
- if (piece === void 0 || seen.has(id)) return [];
818
- seen.add(id);
819
- return [{
820
- piece: id,
821
- label: piece.label,
822
- how: about(item.id) ? "about it" : "mentions it"
823
- }];
824
- });
825
- }
826
- //#endregion
827
- //#region src/host/import/card-diff.ts
828
- const MAX_SEGMENTS = 1500;
829
- const MAX_HUNK_CHARS = 700;
830
- /** Entries that kept neither their title nor their keys count as the same one only when this much of their words is shared. */
831
- const SAME_ENTRY = .5;
832
- const normalised = (text) => text.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
833
- const entryHead = (piece) => normalised([piece.title, ...piece.keys].join("|"));
834
- const words = (text) => new Set(text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []);
835
- function overlap$1(a, b) {
836
- const first = words(a);
837
- const second = words(b);
838
- if (first.size === 0 && second.size === 0) return 1;
839
- let shared = 0;
840
- for (const word of first) if (second.has(word)) shared += 1;
841
- return shared / (first.size + second.size - shared);
842
- }
843
- /**
844
- * Which piece of the old card is which piece of the new one. Fields and greetings are the same by their id; lorebook entries are numbered by position, which an edit
845
- * shifts, so they are found by what they are called and keyed on, then by their text, and only then by the number.
846
- */
847
- function matchPieces(before, after) {
848
- const pairs = [];
849
- const left = new Map(before.map((piece) => [piece.id, piece]));
850
- const right = new Map(after.map((piece) => [piece.id, piece]));
851
- const pair = (a, b) => {
852
- pairs.push({
853
- before: a,
854
- after: b
855
- });
856
- left.delete(a.id);
857
- right.delete(b.id);
858
- };
859
- const isEntry = (piece) => piece.id.startsWith("entry:");
860
- for (const piece of before) {
861
- const other = right.get(piece.id);
862
- if (!isEntry(piece) && other !== void 0) pair(piece, other);
863
- }
864
- const unmatched = (map) => [...map.values()].filter(isEntry);
865
- for (const keyOf of [entryHead, (piece) => normalised(piece.text)]) {
866
- const taken = /* @__PURE__ */ new Set();
867
- for (const piece of unmatched(left)) {
868
- const key = keyOf(piece);
869
- if (key === "" || key === "|") continue;
870
- const candidates = unmatched(right).filter((other) => !taken.has(other.id) && keyOf(other) === key);
871
- const same = candidates.find((other) => other.id === piece.id) ?? candidates[0];
872
- if (same !== void 0) {
873
- taken.add(same.id);
874
- pair(piece, same);
875
- }
876
- }
877
- }
878
- for (const piece of unmatched(left)) {
879
- const other = right.get(piece.id);
880
- if (other !== void 0 && overlap$1(piece.text, other.text) >= SAME_ENTRY) pair(piece, other);
881
- }
882
- const order = new Map(before.map((piece, index) => [piece.id, index]));
883
- return {
884
- pairs: pairs.sort((a, b) => (order.get(a.before.id) ?? 0) - (order.get(b.before.id) ?? 0)),
885
- added: [...right.values()],
886
- removed: [...left.values()]
887
- };
888
- }
889
- /** The sentences and lines of a text, each with the whitespace that follows it, so that joining them gives the text back. */
890
- function segments(text) {
891
- const parts = [];
892
- const endings = ".!?。!?\n";
893
- let start = 0;
894
- let at = 0;
895
- while (at < text.length) {
896
- if (!endings.includes(text[at])) {
897
- at += 1;
898
- continue;
899
- }
900
- while (at < text.length && endings.includes(text[at])) at += 1;
901
- while (at < text.length && /\s/u.test(text[at])) at += 1;
902
- parts.push(text.slice(start, at));
903
- start = at;
904
- }
905
- if (start < text.length) parts.push(text.slice(start));
906
- return parts;
907
- }
908
- const shorten = (text) => {
909
- const clean = text.replace(/\s+/g, " ").trim();
910
- return clean.length <= MAX_HUNK_CHARS ? clean : `${clean.slice(0, MAX_HUNK_CHARS)}…`;
911
- };
912
- /** Where two versions of a text differ, sentence by sentence; nothing when they are the same, and undefined when the texts are too long to compare (read both then). */
913
- function diffText(before, after) {
914
- if (before === after) return [];
915
- const a = segments(before).map((part) => part.trim());
916
- const b = segments(after).map((part) => part.trim());
917
- if (a.length > MAX_SEGMENTS || b.length > MAX_SEGMENTS) return void 0;
918
- const width = b.length + 1;
919
- const table = new Uint16Array((a.length + 1) * width);
920
- for (let i = a.length - 1; i >= 0; i -= 1) for (let j = b.length - 1; j >= 0; j -= 1) table[i * width + j] = a[i] === b[j] ? table[(i + 1) * width + j + 1] + 1 : Math.max(table[(i + 1) * width + j], table[i * width + j + 1]);
921
- const hunks = [];
922
- let i = 0;
923
- let j = 0;
924
- let last;
925
- let removed = [];
926
- let added = [];
927
- let before_;
928
- const close = () => {
929
- if (removed.length + added.length === 0) return;
930
- hunks.push({
931
- ...before_ === void 0 ? {} : { after: shorten(before_) },
932
- removed: shorten(removed.join(" ")),
933
- added: shorten(added.join(" "))
934
- });
935
- removed = [];
936
- added = [];
937
- };
938
- while (i < a.length || j < b.length) {
939
- if (i < a.length && j < b.length && a[i] === b[j]) {
940
- close();
941
- last = a[i];
942
- before_ = last;
943
- i += 1;
944
- j += 1;
945
- continue;
946
- }
947
- if (removed.length + added.length === 0) before_ = last;
948
- if (j < b.length && (i === a.length || table[i * width + j + 1] >= table[(i + 1) * width + j])) {
949
- added.push(b[j]);
950
- j += 1;
951
- } else {
952
- removed.push(a[i]);
953
- i += 1;
954
- }
955
- }
956
- close();
957
- return hunks;
958
- }
959
- /** What differs in what the card says about itself rather than in its pieces. */
960
- function cardChanges(before, after) {
961
- const lines = [];
962
- const compare = (label, a, b) => {
963
- if (a !== b) lines.push(`${label}: “${shorten(a)}” → “${shorten(b)}”`);
964
- };
965
- compare("name", before.name, after.name);
966
- compare("creator", before.creator, after.creator);
967
- compare("version", before.characterVersion, after.characterVersion);
968
- compare("tags", before.tags.join(", "), after.tags.join(", "));
969
- return lines;
970
- }
971
- /** What the newer card changes that the world keeps in its own file (the fields edit_world_info sets) rather than in a character, place, thing or entry. */
972
- function worldFieldChanges(before, after) {
973
- const changes = [];
974
- const differ = (a, b) => a.trim() !== b.trim();
975
- if (differ(before.card.description, after.card.description) || differ(before.card.scenario, after.card.scenario) || differ(before.card.creatorNotes, after.card.creatorNotes)) changes.push({
976
- field: "description",
977
- because: "the card's description, scenario or creator's notes changed, and the world's description summarises them"
978
- });
979
- if (before.card.tags.join("\n") !== after.card.tags.join("\n")) changes.push({
980
- field: "tags",
981
- because: `the card\'s tags are now: ${after.card.tags.join(", ") || "(none)"}; the world\'s tags follow them, and you add none of your own`
982
- });
983
- if (differ(before.card.creator, after.card.creator)) changes.push({
984
- field: "authorName",
985
- because: `the card\'s creator is now “${after.card.creator}”`
986
- });
987
- if (differ(openingText(before.card, before.choices.opening) ?? "", openingText(after.card, after.choices.opening) ?? "")) changes.push({
988
- field: "opening",
989
- because: "the greeting the world opens with changed; suggested is the new greeting as the import writes an opening (plain paragraphs, the card's markup removed, the player named by the world's player character where the card says {{user}})",
990
- suggested: openingMessage(openingText(after.card, after.choices.opening) ?? "", after.card.name)
991
- });
992
- if (JSON.stringify(alternateOpenings(before.card, before.choices.opening)) !== JSON.stringify(alternateOpenings(after.card, after.choices.opening))) changes.push({
993
- field: "alternateOpenings",
994
- because: "the card's other greetings changed; suggested is the whole list as the import writes it",
995
- suggested: alternateOpenings(after.card, after.choices.opening)
996
- });
997
- return changes;
998
- }
999
- //#endregion
1000
- //#region src/host/import/update.ts
467
+ // src/host/import/update.ts
1001
468
  const PREVIOUS_FOLDER = "previous";
1002
469
  const CLASSIFICATION = "classification.json";
1003
470
  const sameName = (a, b) => a.normalize("NFKC").trim().toLowerCase() === b.normalize("NFKC").trim().toLowerCase();
@@ -1039,7 +506,7 @@ async function findTargets(worlds, name) {
1039
506
  }
1040
507
  /** The message that sends the authoring chat to bring a world up to date with the newer card; it speaks the person's language, like the import command. */
1041
508
  function updateMessage(language) {
1042
- return translator(languageOf(language))("The character card this world was made from has a newer version, kept in this world's .import/update folder. Bring the world up to date with it. First call card_diff: it lists what changed between the two versions, which characters, places and things were made from each changed piece, and which files of the world have been edited since the import. Read the pieces you need with card_read (version current is the old card, version new is the new one). Then change only what the new card changed, with your editing tools, and keep what the person has edited since the import. What the card says about the world itself (its description, tags and opening) is changed with edit_world_info. Remove what only a dropped piece made unless the person edited it. Do not add what neither version of the card says. When the world matches the new card, call card_update_finish, then tell me briefly what you changed, what you left alone and why.");
509
+ return translator(languageOf(language))("The character card this world was made from has a newer version, kept in this world's .import/update folder. Bring the world up to date with it. First call card_diff: it lists what changed between the two versions, which characters, places and things were made from each changed piece, and which files of the world have been edited since the import. Read the pieces you need with card_read (version current is the old card, version new is the new one). Then change only what the new card changed, with your editing tools, and keep what the person has edited since the import. What the card says about the world itself (its description, tags and opening) is changed with edit_world_info. Remove what only a dropped piece made unless the person edited it. Do not add what neither version of the card says. When the world matches the new card, call check_card with version new: it lists what the new card changed that the world does not say yet; deal with each finding or say why you left it. Then call card_update_finish, and tell me briefly what you changed, what you left alone and why.");
1043
510
  }
1044
511
  /**
1045
512
  * Starts the update of a world from an uploaded card: the card waits in the world's import folder, the world's authoring chat is opened, and it is told to apply the difference.
@@ -1262,8 +729,7 @@ async function refreshPortrait(directory, picture, cardName) {
1262
729
  }))) return "kept";
1263
730
  return await writePortrait(directory, picture, documents, cardName) ? "replaced" : "kept";
1264
731
  }
1265
- //#endregion
1266
- //#region src/host/translate/terms.ts
732
+ // src/host/translate/terms.ts
1267
733
  const STOP = /* @__PURE__ */ new Set([
1268
734
  "the",
1269
735
  "and",
@@ -1351,8 +817,7 @@ function usesTerm(text, term) {
1351
817
  const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1352
818
  return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "u").test(text);
1353
819
  }
1354
- //#endregion
1355
- //#region src/host/translate/prose.ts
820
+ // src/host/translate/prose.ts
1356
821
  const rooted = (roots, paths) => roots.flatMap((root) => paths.map((path) => `${root}${path}`));
1357
822
  const INTENT = [
1358
823
  ".name",
@@ -1577,10 +1042,13 @@ async function readWorldDocuments(directory) {
1577
1042
  }
1578
1043
  return found;
1579
1044
  }
1580
- //#endregion
1581
- //#region src/host/translate/translate-world.ts
1045
+ // src/host/translate/translate-world.ts
1582
1046
  /** What is not carried over to a translation: the removed things of the editor and the card import's working files. */
1583
- const NOT_COPIED = /* @__PURE__ */ new Set([".trash", ".import"]);
1047
+ const NOT_COPIED = /* @__PURE__ */ new Set([
1048
+ ".trash",
1049
+ ".import",
1050
+ ".checks"
1051
+ ]);
1584
1052
  const TERMS_PER_JOB = 40;
1585
1053
  const TEXTS_PER_JOB = 30;
1586
1054
  const CHARS_PER_JOB = 5e3;
@@ -1825,8 +1293,7 @@ async function translateWorld(ctx, worlds, source, to, told) {
1825
1293
  ])
1826
1294
  };
1827
1295
  }
1828
- //#endregion
1829
- //#region src/host/translate/tools.ts
1296
+ // src/host/translate/tools.ts
1830
1297
  const TRANSLATE_TOOL = "translate_world";
1831
1298
  /** The message that has the authoring chat translate its world, in the language of the person who asked. */
1832
1299
  function translateMessage(text, to, language) {
@@ -1865,124 +1332,7 @@ function translateTools(worlds, settings, prompting) {
1865
1332
  }
1866
1333
  })];
1867
1334
  }
1868
- //#endregion
1869
- //#region src/host/worlds/world-info.ts
1870
- const textOf$1 = (value) => typeof value === "string" ? value : "";
1871
- const toolsOf = (value) => {
1872
- const board = value === void 0 ? {} : parseSwitchboard(value, "tools");
1873
- return typeof board === "string" ? {} : board;
1874
- };
1875
- function infoOf(document) {
1876
- const opening = document["opening_message"];
1877
- const parts = Array.isArray(opening) && opening.some((part) => typeof part === "object" && part !== null && part["type"] === "utterance");
1878
- const plain = typeof opening === "string" ? opening : Array.isArray(opening) ? opening.map((part) => textOf$1(part?.["text"])).filter((text) => text !== "").join("\n\n") : "";
1879
- const metadata = typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {};
1880
- const author = typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {};
1881
- const rules = document["rules"];
1882
- return {
1883
- name: textOf$1(document["name"]),
1884
- description: textOf$1(document["description"]),
1885
- tags: Array.isArray(metadata["tags"]) ? metadata["tags"].filter((tag) => typeof tag === "string") : [],
1886
- rules: typeof rules === "string" ? [rules] : Array.isArray(rules) ? rules.filter((rule) => typeof rule === "string") : [],
1887
- opening: plain,
1888
- openingParts: parts,
1889
- authorName: textOf$1(author["name"]),
1890
- authorUrl: textOf$1(author["url"]),
1891
- timeZone: textOf$1(document["time_zone"]),
1892
- startingTime: textOf$1(document["starting_time"]),
1893
- preset: textOf$1(document["preset"]),
1894
- lorebooks: Array.isArray(document["lorebooks"]) ? document["lorebooks"].filter((name) => typeof name === "string") : [],
1895
- version: typeof document["version"] === "number" ? String(document["version"]) : textOf$1(document["version"]),
1896
- sampling: parseSampling(document["sampling"], "sampling", []),
1897
- tools: toolsOf(document["tools"]),
1898
- alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
1899
- title: textOf$1(entry["title"]),
1900
- text: entry["text"],
1901
- ...textOf$1(entry["character"]) === "" ? {} : { character: textOf$1(entry["character"]) }
1902
- }] : []) : []
1903
- };
1904
- }
1905
- async function readDocument(directory) {
1906
- const text = await readFile(join(directory, WORLD_FILE_NAME), "utf8");
1907
- return {
1908
- text,
1909
- document: JSON.parse(text.replace(/^/, ""))
1910
- };
1911
- }
1912
- async function readWorldInfo(directory) {
1913
- return infoOf((await readDocument(directory)).document);
1914
- }
1915
- function setOrRemove(document, key, value) {
1916
- if (value === "") delete document[key];
1917
- else document[key] = value;
1918
- }
1919
- /**
1920
- * Changes the fields of `world.json` the edit names and nothing else, keeping the file's other fields and its indentation. The result is read
1921
- * back as the world will be read before it is written.
1922
- * @throws {InvalidEditProblems} when the world would no longer be valid.
1923
- */
1924
- function editWorldInfo(directory, edit) {
1925
- return serialized(directory, () => changeWorldInfo(directory, edit));
1926
- }
1927
- async function changeWorldInfo(directory, edit) {
1928
- const { text, document } = await readDocument(directory);
1929
- const before = infoOf(document);
1930
- 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"]);
1931
- if (edit.name !== void 0) document["name"] = edit.name;
1932
- if (edit.description !== void 0) document["description"] = edit.description;
1933
- if (edit.tags !== void 0) document["metadata"] = {
1934
- ...typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {},
1935
- tags: edit.tags
1936
- };
1937
- if (edit.rules !== void 0) {
1938
- if (edit.rules.length === 0) delete document["rules"];
1939
- else document["rules"] = edit.rules;
1940
- }
1941
- if (edit.opening !== void 0 && !before.openingParts) setOrRemove(document, "opening_message", edit.opening);
1942
- if (edit.authorName !== void 0 || edit.authorUrl !== void 0) {
1943
- const name = edit.authorName ?? before.authorName;
1944
- const url = edit.authorUrl ?? before.authorUrl;
1945
- if (name === "" && url !== "") throw new InvalidEditProblems(["an author link needs the author's name"]);
1946
- if (name === "") delete document["author"];
1947
- else document["author"] = {
1948
- ...typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {},
1949
- name,
1950
- ...url === "" ? {} : { url }
1951
- };
1952
- if (url === "" && typeof document["author"] === "object") delete document["author"]["url"];
1953
- }
1954
- if (edit.timeZone !== void 0) setOrRemove(document, "time_zone", edit.timeZone);
1955
- if (edit.startingTime !== void 0) setOrRemove(document, "starting_time", edit.startingTime);
1956
- if (edit.version !== void 0) setOrRemove(document, "version", edit.version);
1957
- if (edit.preset !== void 0) setOrRemove(document, "preset", edit.preset);
1958
- if (edit.lorebooks !== void 0) {
1959
- if (edit.lorebooks.length === 0) delete document["lorebooks"];
1960
- else document["lorebooks"] = edit.lorebooks;
1961
- }
1962
- if (edit.alternateOpenings !== void 0) {
1963
- if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
1964
- else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
1965
- title: entry.title === "" ? entry.text.slice(0, 40) : entry.title,
1966
- text: entry.text,
1967
- ...entry.character === void 0 || entry.character === "" ? {} : { character: entry.character }
1968
- }));
1969
- }
1970
- if (edit.sampling !== void 0) {
1971
- if (Object.keys(edit.sampling).length === 0) delete document["sampling"];
1972
- else document["sampling"] = edit.sampling;
1973
- }
1974
- if (edit.tools !== void 0) {
1975
- if (Object.keys(edit.tools).length === 0) delete document["tools"];
1976
- else document["tools"] = edit.tools;
1977
- }
1978
- const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
1979
- const parsed = parseWorldFile(next);
1980
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
1981
- await atomicWrite(join(directory, WORLD_FILE_NAME), next);
1982
- return infoOf(document);
1983
- }
1984
- //#endregion
1985
- //#region src/host/import/preset-tools.ts
1335
+ // src/host/import/preset-tools.ts
1986
1336
  const PRESET_TOOL = "import_preset";
1987
1337
  const PRESET_FILE = "preset.json";
1988
1338
  const PRESET_PATH = `${IMPORT_FOLDER}/${PRESET_FILE}`;
@@ -2040,37 +1390,7 @@ function presetTools(worlds, settings, prompting) {
2040
1390
  }
2041
1391
  })];
2042
1392
  }
2043
- //#endregion
2044
- //#region src/host/triggers/parts.ts
2045
- /** What the files of a world say it has, for checking what a trigger names. @throws {InvalidEditProblems} when those files have problems of their own: they are fixed first. */
2046
- async function loadWorldParts(directory) {
2047
- const { characters, problems: characterProblems } = await loadCharacters(directory);
2048
- const { locations, problems: locationProblems } = await loadLocations(directory);
2049
- const { items, slots, problems: itemProblems } = await loadItems(directory, {
2050
- characters: characters.map((character) => character.id),
2051
- locations
2052
- });
2053
- const { defs, problems: variableProblems } = await loadVariables(directory);
2054
- const { calendar, problems: calendarProblems } = await loadCalendar(directory);
2055
- const problems = [
2056
- ...characterProblems,
2057
- ...locationProblems,
2058
- ...itemProblems,
2059
- ...variableProblems,
2060
- ...calendarProblems
2061
- ];
2062
- if (problems.length > 0) throw new InvalidEditProblems([`the world's other files have problems that come first: ${problems.map((problem) => `${problem.path}: ${problem.message}`).join("; ")}`]);
2063
- return {
2064
- characters,
2065
- locations,
2066
- items,
2067
- slots,
2068
- variables: defs,
2069
- calendar
2070
- };
2071
- }
2072
- //#endregion
2073
- //#region src/host/triggers/check.ts
1393
+ // src/host/triggers/check.ts
2074
1394
  /**
2075
1395
  * What each trigger names that the world does not have (a character, place, item or variable in its condition, its cues or the words of a
2076
1396
  * cue), found as a session start finds it: against a scratch story made from the world's files. Triggers that wait for each other count
@@ -2079,38 +1399,16 @@ async function loadWorldParts(directory) {
2079
1399
  function triggerProblemsOf(parts, definitions) {
2080
1400
  const found = /* @__PURE__ */ new Map();
2081
1401
  if (definitions.length === 0) return found;
2082
- const scratch = createSessionStore(":memory:", {
2083
- id: "scratch",
2084
- name: "scratch",
2085
- world: {
2086
- id: "scratch",
2087
- name: "scratch"
2088
- }
2089
- }, { vectors: false });
2090
- try {
2091
- const session = scratch;
2092
- if (parts.calendar !== void 0) writeCalendar(scratch.metadata, parts.calendar);
2093
- populateLocations(session, parts.locations);
2094
- populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
2095
- populateItems(session, parts.items, parts.slots, parts.locations);
2096
- populateVariables(session, parts.variables, {
2097
- characters: parts.characters,
2098
- items: parts.items,
2099
- locations: parts.locations,
2100
- values: void 0
2101
- });
1402
+ withScratchStory(parts, (story) => {
2102
1403
  const keys = definitions.map((definition) => definition.key);
2103
1404
  for (const definition of definitions) {
2104
- const problems = triggerReferenceProblems(scratch, definition, keys).map((problem) => problem.slice(definition.key.length + 2));
1405
+ const problems = triggerReferenceProblems(story, definition, keys).map((problem) => problem.slice(definition.key.length + 2));
2105
1406
  if (problems.length > 0) found.set(definition.key, problems);
2106
1407
  }
2107
- } finally {
2108
- scratch.close();
2109
- }
1408
+ });
2110
1409
  return found;
2111
1410
  }
2112
- //#endregion
2113
- //#region src/host/triggers/files.ts
1411
+ // src/host/triggers/files.ts
2114
1412
  /** The fields of a trigger in the file; any other is a mistake that would otherwise be dropped without a word. */
2115
1413
  const FIELDS = /* @__PURE__ */ new Set([
2116
1414
  "key",
@@ -2203,8 +1501,7 @@ async function deleteTriggerDocument(directory, key) {
2203
1501
  await writeDocuments(directory, documents.filter((entry) => entry !== found));
2204
1502
  return kept;
2205
1503
  }
2206
- //#endregion
2207
- //#region src/host/worlds/world-editor.ts
1504
+ // src/host/worlds/world-editor.ts
2208
1505
  function stateOf(world, definition, names) {
2209
1506
  const { start } = definition;
2210
1507
  const portrait = referenceImagePath(world.directory, {
@@ -3092,8 +2389,7 @@ async function removeWorldTrigger(world, key) {
3092
2389
  await deleteTriggerDocument(world.directory, key);
3093
2390
  return await readWorldEditor(world);
3094
2391
  }
3095
- //#endregion
3096
- //#region src/host/authoring/documents.ts
2392
+ // src/host/authoring/documents.ts
3097
2393
  const AUTHORED_ENTITY_KINDS = [
3098
2394
  "character",
3099
2395
  "location",
@@ -3199,8 +2495,7 @@ async function deleteAuthoredEntity(world, kind, key) {
3199
2495
  await rename(dirname(found.file), destination);
3200
2496
  return destination;
3201
2497
  }
3202
- //#endregion
3203
- //#region src/host/interface/world-packs.ts
2498
+ // src/host/interface/world-packs.ts
3204
2499
  /** The kinds of file an assistant may write, as text. */
3205
2500
  const TEXT_EXTENSIONS = [
3206
2501
  "html",
@@ -3252,8 +2547,7 @@ async function deleteWorldPackFile(directory, pack, path) {
3252
2547
  }]
3253
2548
  };
3254
2549
  }
3255
- //#endregion
3256
- //#region src/host/authoring/pack-jail.ts
2550
+ // src/host/authoring/pack-jail.ts
3257
2551
  /** DSH's own file tools, which the world authoring chat uses on the interface packs and nothing else. */
3258
2552
  const PACK_FILE_TOOLS = [
3259
2553
  "read",
@@ -3343,7 +2637,6 @@ async function packJail(exec, next, deps) {
3343
2637
  function registerPackJail(ctx, deps) {
3344
2638
  ctx.on("tools/pre-execute", (exec, next) => packJail(exec, next, deps), { prepend: true });
3345
2639
  }
3346
- //#endregion
3347
- export { matchPieces as $, worldEntityImageFile as A, readWorldInfo as B, readWorldEditor as C, uploadWorldCharacterPortrait as D, replaceFile as E, loadWorldParts as F, findTargets as G, translateTools as H, PRESET_FILE as I, revertUpdate as J, finishUpdate as K, presetMessage as L, deleteTriggerDocument as M, readTriggerDocuments as N, uploadWorldEntityImage as O, writeTriggerDocument as P, diffText as Q, presetTools as R, generateWorldEntityImage as S, removeWorldTrigger as T, languageOfDocuments as U, translateMessage as V, readWorldDocuments as W, updateStatus as X, startUpdate as Y, cardChanges as Z, editWorldPlots as _, deleteWorldPackFile as a, authoringTitle as at, entityFolder as b, createAuthoredEntity as c, ensureAgentChat as ct, replaceAuthoredEntity as d, appendNarratedTurn as dt, worldFieldChanges as et, editWorldCharacter as f, storeAuthoringOpening as ft, editWorldPlace as g, editWorldNarrationVoice as h, checkWorldPack as i, AuthoringSessions as it, writeWorldTrigger as j, worldCharacterPortraitFile as k, deleteAuthoredEntity as l, isStored as lt, editWorldLore as m, packFileProblem as n, entitiesByPiece as nt, listWorldPacks as o, AgentSessions as ot, editWorldFaction as p, storeDoctorOpening as pt, pendingUpdate as q, registerPackJail as r, readSource as rt, AUTHORED_ENTITY_KINDS as s, agentServicesOf as st, MAX_PACK_TEXT as t, cardTools as tt, readAuthoredEntityDocument as u, appendEmptyTurn as ut, editWorldRelation as v, readWorldTrigger as w, generateWorldCharacterPortrait as x, editWorldThing as y, editWorldInfo as z };
2640
+ export { DOCTOR_OPENING_SOURCE as $, worldEntityImageFile as A, languageOfDocuments as B, readWorldEditor as C, uploadWorldCharacterPortrait as D, replaceFile as E, PRESET_FILE as F, revertUpdate as G, findTargets as H, presetMessage as I, AuthoringSessions as J, startUpdate as K, presetTools as L, deleteTriggerDocument as M, readTriggerDocuments as N, uploadWorldEntityImage as O, writeTriggerDocument as P, agentServicesOf as Q, translateMessage as R, generateWorldEntityImage as S, removeWorldTrigger as T, finishUpdate as U, readWorldDocuments as V, pendingUpdate as W, ensureAuthoringChat as X, authoringTitle as Y, AgentSessions as Z, editWorldPlots as _, deleteWorldPackFile as a, entityFolder as b, createAuthoredEntity as c, replaceAuthoredEntity as d, appendEmptyTurn as et, editWorldCharacter as f, editWorldPlace as g, editWorldNarrationVoice as h, checkWorldPack as i, writeWorldTrigger as j, worldCharacterPortraitFile as k, deleteAuthoredEntity as l, editWorldLore as m, packFileProblem as n, listWorldPacks as o, editWorldFaction as p, updateStatus as q, registerPackJail as r, AUTHORED_ENTITY_KINDS as s, MAX_PACK_TEXT as t, appendNarratedTurn as tt, readAuthoredEntityDocument as u, editWorldRelation as v, readWorldTrigger as w, generateWorldCharacterPortrait as x, editWorldThing as y, translateTools as z };
3348
2641
 
3349
- //# sourceMappingURL=pack-jail-5EJ-WYyW.js.map
2642
+ //# sourceMappingURL=pack-jail-BMy6NcCY.js.map