@dsh-agentic-roleplay/core 0.10.1 → 0.10.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 (29) hide show
  1. package/icon.svg +13 -0
  2. package/lib/{authoring-tools-C6Hzy8jU.js → authoring-tools-C9cmcUbD.js} +424 -31
  3. package/lib/authoring.js +6 -6
  4. package/lib/{child-C8r8AFpm.js → child-C9nPIy9j.js} +7 -3
  5. package/lib/client.js +2196 -728
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +1 -1
  8. package/lib/doctor.js +2 -2
  9. package/lib/helper.js +8 -1
  10. package/lib/{hooks-BuQ61nvQ.js → hooks-BpLN_hhT.js} +180 -153
  11. package/lib/images.js +1 -1
  12. package/lib/index.js +456 -61
  13. package/lib/{lorebook-author-tools-B6_Jj8oe.js → lorebook-author-tools-Cg7QQemi.js} +4 -4
  14. package/lib/lorebook-authoring.js +4 -4
  15. package/lib/orchestration.js +65 -15
  16. package/lib/{pack-jail-OZSgU85i.js → pack-jail-D5j5mIq6.js} +12 -8
  17. package/lib/{packs-B88bxt8E.js → packs-Cc05FrId.js} +2 -2
  18. package/lib/{presenter-agent-D-WNs626.js → presenter-agent-UKbKYXMO.js} +3 -3
  19. package/lib/{preset-DNuqvMan.js → preset-Be4lz6vB.js} +4 -4
  20. package/lib/{preset-author-tools-CDwavcTb.js → preset-author-tools-C3s0iSfv.js} +5 -5
  21. package/lib/preset-authoring.js +5 -5
  22. package/lib/{presets-9_MNxwaw.js → presets-Cl9sU3Qs.js} +52 -10
  23. package/lib/{reflection-BvM0w1R4.js → reflection-I9z-PvFK.js} +8 -6
  24. package/lib/{turn-guard-Ygdww1Wt.js → turn-guard-B9pGCeir.js} +3 -3
  25. package/package.json +4 -2
  26. package/prompts/en/checks/decide-opening.md +7 -1
  27. package/prompts/en/roleplay/record-keeper.md +2 -1
  28. package/prompts/zh/checks/decide-opening.md +7 -1
  29. package/prompts/zh/roleplay/record-keeper.md +2 -1
package/lib/index.js CHANGED
@@ -1,35 +1,114 @@
1
1
  import { a as VARIABLE_KINDS, c as chatSessionId, i as atomicWriteSync, l as roleplaySessionOf, n as atomicWrite, o as VARIABLE_SUBJECTS, r as atomicWriteJson, s as VARIABLE_VISIBILITIES } from "./access-CXtaZNbx.js";
2
- import { $t as ImportCardError, At as populateTriggers, Bt as loadItems, Ct as populateDice, Dt as populateLocations, E as loadWorldParts, Et as populateKnowledge, F as localChanges, G as vetUrl, Gt as parseDiceFile, I as readOrigin, Jt as parseCalendarFile, Kt as CALENDAR_FILE_NAME, L as writeOrigin, M as describeChanges, Mt as routineProblems, N as hashWorld, Nt as TRIGGERS_FILE_NAME, Ot as populateLore, P as isUnchanged, Qt as knownOutputCeiling, R as CatalogueError, Rt as loadLocations, St as populateClock, T as readWorldInfo, Tt as populateItems, U as guardedLookup, Ut as DICE_FILE_NAME, Wt as loadDice, Xt as loadCharacters, Yt as CHARACTERS_DIR, Zt as subfolders, _ as runChecks, _t as loadValidatedWorld, an as DICE_RESULTS, at as deleteLorebook, bt as populateCalendar, c as importPhase, ct as isLorebookName, d as markReady, dt as lorebookDirectory, en as isPng, et as WORLD_FILE_NAME, f as settleDraft, gt as checkWorld, ht as writeLorebookEntry, in as DICE_READINGS, it as createLorebook, jt as populateVariables, kt as populateRoutines, lt as listLorebooks, mt as updateLorebookInfo, nn as readCard, nt as parseWorldInfoEdit, on as authoredWorldOf, ot as deleteLorebookEntry, p as structureImport, pt as reserveLorebook, qt as loadCalendar, rn as DICE_COMPARISONS, rt as addLorebookEntries, st as entriesOf, t as AuthoringTools, tn as pictureOf, tt as parseWorldFile, u as keepDraft, ut as loadLorebook, w as editWorldInfo, wt as populateFactions, xt as populateCharacters, yt as knowsCharacter } from "./authoring-tools-C6Hzy8jU.js";
3
- import { a as lorebookImportMessage, c as readLorebook, d as lorebookOfChat, l as selectEntries, s as previewLorebook, t as LOREBOOK_UPLOAD, u as lorebookChatSessionId } from "./lorebook-author-tools-B6_Jj8oe.js";
4
- import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-CDwavcTb.js";
2
+ import { $t as subfolders, At as populateLore, Bt as loadLocations, Ct as populateCharacters, Dt as populateItems, E as loadWorldParts, Et as populateFactions, F as localChanges, Ft as TRIGGERS_FILE_NAME, G as vetUrl, Gt as DICE_FILE_NAME, Ht as loadItems, I as readOrigin, Jt as CALENDAR_FILE_NAME, Kt as loadDice, L as writeOrigin, M as describeChanges, Mt as populateTriggers, N as hashWorld, Nt as populateVariables, Ot as populateKnowledge, P as isUnchanged, Pt as routineProblems, Qt as loadCharacters, R as CatalogueError, St as populateCalendar, T as readWorldInfo, Tt as populateDice, U as guardedLookup, Xt as parseCalendarFile, Yt as loadCalendar, Zt as CHARACTERS_DIR, _ as runChecks, _t as writeLorebookEntry, an as readCard, at as addLorebookEntries, c as importPhase, cn as DICE_RESULTS, ct as deleteLorebookEntry, d as markReady, dt as listLorebooks, en as knownOutputCeiling, et as WORLD_FILE_NAME, f as settleDraft, ft as loadLorebook, gt as updateLorebookInfo, ht as reserveLorebook, in as pictureOf, it as questionView, jt as populateRoutines, kt as populateLocations, ln as authoredWorldOf, lt as entriesOf, nn as cardFormat, nt as parseWorldInfoEdit, on as DICE_COMPARISONS, ot as createLorebook, p as structureImport, pt as lorebookDirectory, qt as parseDiceFile, rn as isPng, rt as combineAnswers, sn as DICE_READINGS, st as deleteLorebook, t as AuthoringTools, tn as ImportCardError, tt as parseWorldFile, u as keepDraft, ut as isLorebookName, vt as checkWorld, w as editWorldInfo, wt as populateClock, xt as knowsCharacter, yt as loadValidatedWorld } from "./authoring-tools-C9cmcUbD.js";
3
+ import { a as lorebookImportMessage, c as readLorebook, d as lorebookOfChat, l as selectEntries, s as previewLorebook, t as LOREBOOK_UPLOAD, u as lorebookChatSessionId } from "./lorebook-author-tools-Cg7QQemi.js";
4
+ import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-C3s0iSfv.js";
5
+ import { $ as listFiles, B as COMMANDS_KEY, C as readNotes, D as PLOTS_METADATA_KEY, F as readUsage, G as formatIssue, J as PROMPTS_FOLDER, K as errorMessage, O as plotProgressOf, Q as languageOf, R as parsePlotsFile, S as notesOfSession, U as readDocument, X as copyWorldPrompts, Y as PromptLibrary, _ as readTraces, at as InvalidStartError, b as readWithdrawn, ct as SessionArchivedError, et as promptProblem, g as readRunDetail, h as readActivity, i as externalTools, it as AgentUnavailableError, k as populatePlots, lt as SessionNotFoundError, m as readDecisionStats, mt as zoneOf, ot as InvalidWorldError, q as LANGUAGE_FOLDER, st as ReflectionRefusedError, tt as shippedLanguages, ut as WorldNotFoundError, w as observeAsPlayer, x as addToNote, z as plotReferenceProblems } from "./hooks-BpLN_hhT.js";
5
6
  import { a as liveSettings, c as writeSettings, d as parseSettings, i as InvalidSettingsError, l as DEFAULT_SETTINGS, o as readSettings, p as WORLD_RULES_KEY, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-B0hConSw.js";
6
- import { $ as DOCTOR_OPENING_SOURCE, A as worldEntityImageFile, B as languageOfDocuments, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as PRESET_FILE, G as revertUpdate, H as findTargets, I as presetMessage, J as AuthoringSessions, K as startUpdate, O as uploadWorldEntityImage, Q as agentServicesOf, R as translateMessage, S as generateWorldEntityImage, T as removeWorldTrigger, V as readWorldDocuments, X as ensureAuthoringChat, Y as authoringTitle, Z as AgentSessions, _ as editWorldPlots$1, a as deleteWorldPackFile, b as entityFolder, c as createAuthoredEntity, et as appendEmptyTurn, f as editWorldCharacter$1, g as editWorldPlace$1, h as editWorldNarrationVoice, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, m as editWorldLore$1, n as packFileProblem, p as editWorldFaction$1, q as updateStatus, t as MAX_PACK_TEXT, tt as appendNarratedTurn, u as readAuthoredEntityDocument, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1 } from "./pack-jail-OZSgU85i.js";
7
- import { d as sharedSamplingOf, i as childSamplingOf, u as parseSampling, v as totalTokens } from "./child-C8r8AFpm.js";
8
- import { $ as PromptLibrary, C as readNotes, H as parsePlotsFile, M as plotProgressOf, N as populatePlots, O as zoneOf, S as notesOfSession, U as plotReferenceProblems, W as COMMANDS_KEY, X as errorMessage, Y as formatIssue, _ as readTraces, at as shippedLanguages, b as readWithdrawn, ct as AgentUnavailableError, dt as ReflectionRefusedError, et as copyWorldPrompts, ft as SessionArchivedError, g as readRunDetail, h as readActivity, i as externalTools, j as PLOTS_METADATA_KEY, lt as InvalidStartError, m as readDecisionStats, mt as WorldNotFoundError, nt as languageOf, pt as SessionNotFoundError, q as readDocument, ut as InvalidWorldError, w as observeAsPlayer, x as addToNote, z as readUsage } from "./hooks-BuQ61nvQ.js";
9
- import { $ as IMPORT_FOLDER, At as InvalidEditProblems, Dt as parseCharacterFile, Et as CHARACTER_FILE_NAME, Ft as parseRelationEdit, G as deleteWorldPrompt, It as parseThingEdit, J as writeWorldPrompt, K as listWorldPrompts, Lt as LORE_KINDS, Mt as parseFactionEdit, Nt as parseLoreEdit, Pt as parsePlaceEdit, Q as withPlayer, Rt as LORE_SCOPES, Z as partsOf, a as isPresetName, at as readImportFolder, c as presetDirectory, ct as sourceSummary, d as savePresetFromWorld, et as ImportNotFoundError, ft as VARIABLES_FILE_NAME, ht as variableProblems, i as deletePreset, it as parseChoices, jt as parseCharacterEdit, lt as IMPORT_COMMAND, mt as parseVariablesFile, o as listPresets, p as updatePresetInfo, pt as loadVariables, q as readWorldPrompt, r as createPresetFromShipped, s as loadPreset, t as PRESET_FILE$1, tt as ImportStore, u as reservePreset } from "./presets-9_MNxwaw.js";
7
+ import { $ as DOCTOR_OPENING_SOURCE, A as worldEntityImageFile, B as languageOfDocuments, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as PRESET_FILE, G as revertUpdate, H as findTargets, I as presetMessage, J as AuthoringSessions, K as startUpdate, O as uploadWorldEntityImage, Q as agentServicesOf, R as translateMessage, S as generateWorldEntityImage, T as removeWorldTrigger, V as readWorldDocuments, X as ensureAuthoringChat, Y as authoringTitle, Z as AgentSessions, _ as editWorldPlots$1, a as deleteWorldPackFile, b as entityFolder, c as createAuthoredEntity, et as appendEmptyTurn, f as editWorldCharacter$1, g as editWorldPlace$1, h as editWorldNarrationVoice, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, m as editWorldLore$1, n as packFileProblem, p as editWorldFaction$1, q as updateStatus, t as MAX_PACK_TEXT, tt as appendNarratedTurn, u as readAuthoredEntityDocument, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1 } from "./pack-jail-D5j5mIq6.js";
8
+ import { d as parseSampling, f as sharedSamplingOf, i as childSamplingOf, m as RECOVERY_SHRINK, p as RECOVERY_FLOOR, s as isUnfinishedCall, x as totalTokens } from "./child-C9nPIy9j.js";
9
+ import { $ as IMPORT_FOLDER, At as InvalidEditProblems, Dt as parseCharacterFile, Et as CHARACTER_FILE_NAME, Ft as parseRelationEdit, G as deleteWorldPrompt, It as parseThingEdit, J as writeWorldPrompt, K as listWorldPrompts, Lt as LORE_KINDS, Mt as parseFactionEdit, Nt as parseLoreEdit, Pt as parsePlaceEdit, Q as withPlayer, Rt as LORE_SCOPES, Z as partsOf, a as isPresetName, at as readImportFolder, c as presetDirectory, ct as sourceSummary, d as savePresetFromWorld, et as ImportNotFoundError, ft as VARIABLES_FILE_NAME, ht as variableProblems, i as deletePreset, it as parseChoices, jt as parseCharacterEdit, lt as IMPORT_COMMAND, mt as parseVariablesFile, o as listPresets, p as updatePresetInfo, pt as loadVariables, q as readWorldPrompt, r as createPresetFromShipped, s as loadPreset, t as PRESET_FILE$1, tt as ImportStore, u as reservePreset } from "./presets-Cl9sU3Qs.js";
10
10
  import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-CzqhC8sT.js";
11
- import { _ as START_SNAPSHOT, b as snapshotOf, c as copyPreset, d as switchPreset, f as defaultBoundaries, g as writeTimeline, h as readTimeline, i as reflectionStatus, l as presetStatus, o as TimelineError, u as recordPreset, v as childrenOf, y as pathTo } from "./reflection-BvM0w1R4.js";
12
- import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-DNuqvMan.js";
11
+ import { _ as START_SNAPSHOT, b as snapshotOf, c as copyPreset, d as switchPreset, f as defaultBoundaries, g as writeTimeline, h as readTimeline, i as reflectionStatus, l as presetStatus, o as TimelineError, u as recordPreset, v as childrenOf, y as pathTo } from "./reflection-I9z-PvFK.js";
12
+ import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-Be4lz6vB.js";
13
13
  import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-CH-ahlm0.js";
14
14
  import { t as doctorChatSessionId } from "./doctor-chat-hL1a61hp.js";
15
- import { _ as API_PREFIX, a as packIds, c as describePack, d as packPath, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-B88bxt8E.js";
15
+ import { _ as API_PREFIX, a as packIds, c as describePack, d as packPath, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-Cc05FrId.js";
16
16
  import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-nLoPM5MF.js";
17
17
  import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-CtG-bDzz.js";
18
18
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
19
- import { cpSync, createReadStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
19
+ import { SESSION_DATABASE_FILE, addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, openSessionStore, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
20
+ import { copyFileSync, cpSync, createReadStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
20
21
  import { createHash, randomBytes, randomUUID } from "node:crypto";
21
22
  import { copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
22
23
  import { Session, SessionId } from "@deepseek-ai/dsh-session";
23
24
  import { crc32, deflateRawSync, inflateRawSync } from "node:zlib";
24
25
  import { fileURLToPath } from "node:url";
25
26
  import { Service } from "@deepseek-ai/cordis";
26
- import { SESSION_DATABASE_FILE, addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, openSessionStore, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
27
27
  import { request } from "node:http";
28
28
  import { request as request$1 } from "node:https";
29
29
  import { homedir } from "node:os";
30
30
  import { pipeline } from "node:stream/promises";
31
31
  import { spawn } from "node:child_process";
32
32
  import z from "@deepseek-ai/schemastery";
33
+ // src/host/prompts/manage.ts
34
+ /** A prompt the person asked for does not exist or cannot be written; the message says why. */
35
+ var PromptEditError = class extends Error {};
36
+ const normal = (text) => text.replace(/\r\n/g, "\n").trimEnd();
37
+ const VARIABLE = /\$\{([A-Za-z]+)\}/g;
38
+ const variablesOf = (text) => [...new Set([...text.matchAll(VARIABLE)].map((match) => match[1]))];
39
+ const ID$1 = /^[a-z0-9-]+(\/[a-z0-9-]+)*$/;
40
+ /**
41
+ * The prompts of the roleplay root, for the person to look at and edit: what each file says, whether it differs from the shipped text, the shipped text itself
42
+ * to compare with, and replacing a file by it. Nothing is replaced by itself and no record is kept of what was shipped when, so a different file may be an edit or a
43
+ * shipped text that moved on: the person decides.
44
+ */
45
+ var PromptManager = class {
46
+ library;
47
+ now;
48
+ constructor(library, now = () => /* @__PURE__ */ new Date()) {
49
+ this.library = library;
50
+ this.now = now;
51
+ }
52
+ list() {
53
+ return this.library.languages.flatMap((language) => listFiles(join(this.library.shipped, language)).map((id) => this.entry(id, language))).sort((a, b) => a.id.localeCompare(b.id) || a.language.localeCompare(b.language));
54
+ }
55
+ /** @throws {PromptEditError} for a prompt the package does not ship. */
56
+ read(id, language) {
57
+ const shipped = this.shipped(id, language);
58
+ const current = this.current(id, language) ?? shipped;
59
+ return {
60
+ id,
61
+ language,
62
+ state: normal(current) === normal(shipped) ? "default" : "different",
63
+ current,
64
+ shipped,
65
+ variables: variablesOf(shipped)
66
+ };
67
+ }
68
+ /** Saves a text as the prompt, keeping the file it replaces in the trash when that was not the shipped text. @throws {PromptEditError} when the text cannot be the prompt or the folder is syncing. */
69
+ async write(id, language, text) {
70
+ this.shipped(id, language);
71
+ if (this.library.frozen()) throw new PromptEditError("the prompts are being synced: try again when that is done");
72
+ const problem = text.includes("{{") ? "holds \"{{\", which DSH reads as a variable of its own" : promptProblem(language, id, text, this.library.shipped);
73
+ if (problem !== void 0) throw new PromptEditError(`prompt ${id} (${language}) ${problem}`);
74
+ const target = this.file(id, language);
75
+ const body = text.endsWith("\n") ? text : `${text}\n`;
76
+ const before = this.current(id, language);
77
+ if (before !== void 0 && normal(before) !== normal(body) && normal(before) !== normal(this.shipped(id, language))) this.keep(id, language, target);
78
+ await atomicWrite(target, body, { createDirectory: true });
79
+ return this.entry(id, language);
80
+ }
81
+ /** Puts the shipped text in the file. The file it replaces goes to the trash unless it already was the shipped text. */
82
+ async reset(id, language) {
83
+ return await this.write(id, language, this.shipped(id, language));
84
+ }
85
+ entry(id, language) {
86
+ const { state } = this.read(id, language);
87
+ return {
88
+ id,
89
+ language,
90
+ state
91
+ };
92
+ }
93
+ shipped(id, language) {
94
+ const file = ID$1.test(id) ? join(this.library.shipped, language, `${id}.md`) : void 0;
95
+ if (file === void 0 || !LANGUAGE_FOLDER.test(language) || !existsSync(file)) throw new PromptEditError(`there is no shipped prompt "${id}" in "${language}"`);
96
+ return readFileSync(file, "utf8");
97
+ }
98
+ file(id, language) {
99
+ return join(this.library.directory, language, `${id}.md`);
100
+ }
101
+ current(id, language) {
102
+ const file = this.file(id, language);
103
+ return existsSync(file) ? readFileSync(file, "utf8") : void 0;
104
+ }
105
+ keep(id, language, file) {
106
+ const stamp = this.now().toISOString().replace(/[:.]/g, "-");
107
+ const target = join(dirname(this.library.directory), ".trash", PROMPTS_FOLDER, stamp, language, `${id}.md`);
108
+ mkdirSync(dirname(target), { recursive: true });
109
+ copyFileSync(file, target);
110
+ }
111
+ };
33
112
  // src/host/worlds/authoring-language.ts
34
113
  /**
35
114
  * The language the person was using when they last worked on a world with the authoring assistant. The assistant's instructions
@@ -424,15 +503,46 @@ function compareStates(first, second) {
424
503
  }
425
504
  // src/host/playtest/playtest.ts
426
505
  /** The test player's words when the story offered no suggestion to take. */
427
- const FALLBACK_MOVES = [
428
- "I look around and take stock of where I am.",
429
- "I speak to the nearest person.",
430
- "I go somewhere else."
431
- ];
506
+ const FALLBACK_MOVES = {
507
+ en: [
508
+ "I look around and take stock of where I am.",
509
+ "I speak to the nearest person.",
510
+ "I go somewhere else."
511
+ ],
512
+ zh: [
513
+ "我环顾四周,看看自己身处何地。",
514
+ "我和离我最近的人说话。",
515
+ "我去别的地方看看。"
516
+ ]
517
+ };
518
+ const movesIn = (language) => language?.toLowerCase().startsWith("zh") === true ? FALLBACK_MOVES.zh : FALLBACK_MOVES.en;
432
519
  const POLL_MS = 1e3;
433
520
  const SUGGESTION_WAIT_MS = 9e4;
434
521
  /** A turn that takes this many times the median is named as slow. */
435
522
  const SLOW_FACTOR = 3;
523
+ /** The most refused calls a report lists. */
524
+ const MAX_REFUSED = 12;
525
+ /** The most missing look-ups a report lists. */
526
+ const MAX_MISSING = 20;
527
+ function refusals(traces) {
528
+ return traces.flatMap((trace) => (trace.calls ?? []).filter((call) => call.failed).map((call) => ({
529
+ turn: trace.turn,
530
+ tool: call.tool,
531
+ note: call.note
532
+ }))).slice(0, MAX_REFUSED);
533
+ }
534
+ function lacks(traces) {
535
+ const seen = /* @__PURE__ */ new Set();
536
+ return traces.flatMap((trace) => (trace.missing ?? []).map((entry) => ({
537
+ turn: trace.turn,
538
+ ...entry
539
+ }))).filter((entry) => {
540
+ const key = `${entry.character}\n${entry.tool}\n${entry.about.toLowerCase()}`;
541
+ if (seen.has(key)) return false;
542
+ seen.add(key);
543
+ return true;
544
+ }).slice(0, MAX_MISSING);
545
+ }
436
546
  const sideOf$1 = (label, story) => ({
437
547
  label,
438
548
  turns: story.metadata.get().turns,
@@ -509,6 +619,7 @@ var Playtests = class {
509
619
  name: `Playtest ${new Date(began).toISOString().slice(0, 16).replace("T", " ")}`,
510
620
  playerCharacterId: player,
511
621
  ...request.opening === void 0 ? {} : { opening: request.opening },
622
+ ...request.startingTime === void 0 ? {} : { startingTime: request.startingTime },
512
623
  settings: {
513
624
  ...request.language === void 0 ? {} : { prompts: { language: request.language } },
514
625
  images: { mode: "off" },
@@ -526,7 +637,7 @@ var Playtests = class {
526
637
  if (placeOf() !== "") visited.add(placeOf());
527
638
  for (let turn = 1; turn <= request.turns && !abort.signal.aborted; turn += 1) {
528
639
  status.step = `turn ${turn} of ${request.turns}: choosing the player's move`;
529
- const move = await this.moveFor(session, turn, problems, abort.signal);
640
+ const move = await this.moveFor(session, turn, problems, abort.signal, request.language);
530
641
  if (abort.signal.aborted) break;
531
642
  status.step = `turn ${turn} of ${request.turns}: playing`;
532
643
  const sentAt = deps.now();
@@ -570,6 +681,8 @@ var Playtests = class {
570
681
  },
571
682
  changes: compareStates(first, last).changes,
572
683
  findings: await deps.check(request.worldId),
684
+ refused: refusals(deps.trace(session)),
685
+ missing: lacks(deps.trace(session)),
573
686
  problems
574
687
  };
575
688
  status.state = abort.signal.aborted ? "stopped" : "done";
@@ -582,8 +695,9 @@ var Playtests = class {
582
695
  }
583
696
  }
584
697
  /** What the test player says: one of the story's own suggestions, in turn, or a plain move when none came. */
585
- async moveFor(session, turn, problems, signal) {
586
- if (turn === 1) return FALLBACK_MOVES[0];
698
+ async moveFor(session, turn, problems, signal, language) {
699
+ const moves = movesIn(language);
700
+ if (turn === 1) return moves[0];
587
701
  const until = this.deps.now() + SUGGESTION_WAIT_MS;
588
702
  while (this.deps.now() < until && !signal.aborted) {
589
703
  const lines = this.deps.notes(session).find((note) => note.kind === "suggestions")?.lines ?? [];
@@ -591,7 +705,7 @@ var Playtests = class {
591
705
  await this.deps.sleep(POLL_MS);
592
706
  }
593
707
  if (!signal.aborted) problems.push(`no suggestion came before turn ${turn}, so the test player took a plain move`);
594
- return FALLBACK_MOVES[(turn - 1) % FALLBACK_MOVES.length];
708
+ return moves[(turn - 1) % moves.length];
595
709
  }
596
710
  async waitForTurn(session, chat, turn, signal) {
597
711
  const until = this.deps.now() + this.deps.turnTimeoutMs();
@@ -1189,6 +1303,35 @@ var DoctorSessions = class {
1189
1303
  });
1190
1304
  }
1191
1305
  };
1306
+ // src/host/orchestration/recovery.ts
1307
+ /**
1308
+ * Runs the game master's step again when the model's tool call could not be read, instead of ending the turn with nothing. The first try is the same request
1309
+ * (a model is not the same twice), later ones leave a smaller output, so a call that runs on is cut sooner. Past the last the failure stands.
1310
+ */
1311
+ var MasterRecovery = class {
1312
+ used = /* @__PURE__ */ new Map();
1313
+ /** Whether the step is to be run again; counts it. */
1314
+ retry(chat, turn, failure) {
1315
+ if (!isUnfinishedCall(new Error(failure.message))) return false;
1316
+ const seen = this.used.get(chat);
1317
+ const count = seen?.turn === turn ? seen.count : 0;
1318
+ if (count >= 3) return false;
1319
+ this.used.set(chat, {
1320
+ turn,
1321
+ count: count + 1
1322
+ });
1323
+ return true;
1324
+ }
1325
+ /** The output cap of the chat's next request: as set until a step was run again, then shrinking with each recovery. */
1326
+ budget(chat, cap) {
1327
+ const count = this.used.get(chat)?.count ?? 0;
1328
+ return count < 2 ? cap : Math.max(Math.min(cap, RECOVERY_FLOOR), Math.floor(cap * RECOVERY_SHRINK ** (count - 1)));
1329
+ }
1330
+ /** A turn that ended starts the next from the full cap. */
1331
+ clear(chat) {
1332
+ this.used.delete(chat);
1333
+ }
1334
+ };
1192
1335
  // src/host/orchestration/service.ts
1193
1336
  /**
1194
1337
  * The extension points of a roleplay turn. Another plugin changes how the turn
@@ -1196,6 +1339,8 @@ var DoctorSessions = class {
1196
1339
  */
1197
1340
  var RoleplayOrchestration = class extends Service {
1198
1341
  current = defaultBoundaries();
1342
+ /** The game master's steps that were run again after a call that could not be read, and the output they were left. */
1343
+ recovery = new MasterRecovery();
1199
1344
  /** Resolves once the records of a chat's recorded rounds are written (or have failed): the writing goes on behind the story, so what needs them waits here. */
1200
1345
  settle = () => Promise.resolve();
1201
1346
  /** Resolves once the chat's story is free: a turn waits here while the story is being synced. */
@@ -1805,6 +1950,50 @@ function lorebookRoutes(api) {
1805
1950
  } }
1806
1951
  };
1807
1952
  }
1953
+ // src/host/prompts/routes.ts
1954
+ function promptRoutes(api) {
1955
+ const fail = (res, error) => {
1956
+ if (error instanceof PromptEditError) return sendError(res, 422, error.message);
1957
+ throw error;
1958
+ };
1959
+ const target = (url) => ({
1960
+ id: url.searchParams.get("id") ?? "",
1961
+ language: url.searchParams.get("language") ?? ""
1962
+ });
1963
+ return {
1964
+ "/prompts": { GET: async (_req, res) => {
1965
+ sendJson(res, 200, api.list());
1966
+ } },
1967
+ "/prompts/item": {
1968
+ GET: async (_req, res, url) => {
1969
+ try {
1970
+ const { id, language } = target(url);
1971
+ sendJson(res, 200, api.read(id, language));
1972
+ } catch (error) {
1973
+ fail(res, error);
1974
+ }
1975
+ },
1976
+ PUT: async (req, res, url) => {
1977
+ const { text } = await readJsonBody(req);
1978
+ if (typeof text !== "string") return sendError(res, 400, "\"text\" must be text");
1979
+ try {
1980
+ const { id, language } = target(url);
1981
+ sendJson(res, 200, await api.write(id, language, text));
1982
+ } catch (error) {
1983
+ fail(res, error);
1984
+ }
1985
+ }
1986
+ },
1987
+ "/prompts/item/reset": { POST: async (_req, res, url) => {
1988
+ try {
1989
+ const { id, language } = target(url);
1990
+ sendJson(res, 200, await api.reset(id, language));
1991
+ } catch (error) {
1992
+ fail(res, error);
1993
+ }
1994
+ } }
1995
+ };
1996
+ }
1808
1997
  // src/shared/catalogue.ts
1809
1998
  /** What a credential reference is: letters, digits and `_`, not starting with a digit (DSH's grammar). */
1810
1999
  const CREDENTIAL_REF = /^[A-Za-z_][A-Za-z0-9_]*$/;
@@ -2883,12 +3072,14 @@ function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation,
2883
3072
  if (typeof body.turns !== "number") return sendError(res, 400, "turns must be a number");
2884
3073
  if (body.playerCharacterId !== void 0 && typeof body.playerCharacterId !== "string") return sendError(res, 400, "playerCharacterId must be text");
2885
3074
  if (body.opening !== void 0 && typeof body.opening !== "number") return sendError(res, 400, "opening must be a number");
3075
+ if (body.startingTime !== void 0 && typeof body.startingTime !== "string") return sendError(res, 400, "startingTime must be text");
2886
3076
  try {
2887
3077
  sendJson(res, 202, playtest.start({
2888
3078
  worldId: url.searchParams.get("id") ?? "",
2889
3079
  turns: body.turns,
2890
3080
  ...body.playerCharacterId === void 0 ? {} : { playerCharacterId: body.playerCharacterId },
2891
3081
  ...body.opening === void 0 ? {} : { opening: body.opening },
3082
+ ...body.startingTime === void 0 || body.startingTime.trim() === "" ? {} : { startingTime: body.startingTime.trim() },
2892
3083
  ...languageField(body.language) === void 0 ? {} : { language: languageField(body.language) }
2893
3084
  }));
2894
3085
  } catch (error) {
@@ -3039,6 +3230,15 @@ function catalogueRoutes({ catalogue }) {
3039
3230
  return catalogueFailure(res, error);
3040
3231
  }
3041
3232
  } },
3233
+ "/catalogue/link": { POST: async (req, res) => {
3234
+ const { url } = await readJsonBody(req);
3235
+ if (typeof url !== "string") return sendError(res, 400, "url must be text");
3236
+ try {
3237
+ sendJson(res, 200, { link: await catalogue.link(url) ?? null });
3238
+ } catch (error) {
3239
+ return catalogueFailure(res, error);
3240
+ }
3241
+ } },
3042
3242
  "/catalogue/install": { POST: async (req, res) => {
3043
3243
  const body = await readJsonBody(req);
3044
3244
  if (typeof body.url !== "string") return sendError(res, 400, "url must be text");
@@ -3160,6 +3360,15 @@ function importsRoutes({ importer }) {
3160
3360
  return importFailure(res, error);
3161
3361
  }
3162
3362
  } },
3363
+ "/worlds/import/card/url": { POST: async (req, res) => {
3364
+ const { url } = await readJsonBody(req);
3365
+ if (typeof url !== "string") return sendError(res, 400, "url must be text");
3366
+ try {
3367
+ sendJson(res, 200, await importer.fromAddress(url));
3368
+ } catch (error) {
3369
+ return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
3370
+ }
3371
+ } },
3163
3372
  "/worlds/import/update": {
3164
3373
  GET: async (_req, res, url) => {
3165
3374
  try {
@@ -4450,7 +4659,8 @@ const REFERENCE_SECTIONS = [
4450
4659
  "profile",
4451
4660
  "people",
4452
4661
  "places",
4453
- "things"
4662
+ "things",
4663
+ "quests"
4454
4664
  ];
4455
4665
  const isReferenceSection = (value) => REFERENCE_SECTIONS.includes(value);
4456
4666
  // src/host/reference/profile.ts
@@ -4642,12 +4852,54 @@ function things(session) {
4642
4852
  }));
4643
4853
  return [...carried, ...around];
4644
4854
  }
4855
+ /**
4856
+ * What the player's character has been told of or taken on: the story's threads that are marked as known to them (the others are the story's
4857
+ * own notes and are never shown) and the promises and appointments they are part of, soonest first.
4858
+ */
4859
+ function quests(session, options) {
4860
+ const stand = standpoint(session);
4861
+ if (stand === void 0) return [];
4862
+ const zone = options.zone ?? "UTC";
4863
+ const language = options.language ?? "en";
4864
+ const nameOf = (id) => session.characters.get(id)?.name;
4865
+ const commitments = session.engagements.list({
4866
+ status: "pending",
4867
+ participant: stand.player.id
4868
+ }).map((engagement) => {
4869
+ const place = engagement.locationId === void 0 ? void 0 : session.locations.get(engagement.locationId)?.name;
4870
+ const others = engagement.participants.filter((id) => id !== stand.player.id).flatMap((id) => nameOf(id) ?? []);
4871
+ return {
4872
+ kind: "commitment",
4873
+ text: engagement.title,
4874
+ status: "open",
4875
+ when: describeInstant(engagement.at, zone, language),
4876
+ ...engagement.until === void 0 ? {} : { until: describeInstant(engagement.until, zone, language) },
4877
+ ...place === void 0 ? {} : { place },
4878
+ ...others.length === 0 ? {} : { with: others },
4879
+ ...engagement.note === "" ? {} : { note: engagement.note },
4880
+ turn: engagement.createdTurn
4881
+ };
4882
+ });
4883
+ const threads = session.threads.list().filter((thread) => thread.playerKnows).map((thread) => ({
4884
+ kind: "story",
4885
+ text: thread.text,
4886
+ status: thread.status,
4887
+ turn: thread.openedTurn,
4888
+ ...thread.resolvedTurn === void 0 ? {} : { resolvedTurn: thread.resolvedTurn }
4889
+ }));
4890
+ return [
4891
+ ...commitments,
4892
+ ...threads.filter((thread) => thread.status === "open"),
4893
+ ...threads.filter((thread) => thread.status === "resolved").reverse()
4894
+ ];
4895
+ }
4645
4896
  /** One page per section; a new page is a new entry here and in `REFERENCE_SECTIONS`. */
4646
4897
  const PAGES = {
4647
4898
  profile,
4648
4899
  people,
4649
4900
  places,
4650
- things
4901
+ things,
4902
+ quests
4651
4903
  };
4652
4904
  function referencePage(session, section, options = {}) {
4653
4905
  if (!isReferenceSection(section)) throw new UnknownSectionError(`no reference section "${section}"`);
@@ -4659,7 +4911,10 @@ function referencePage(session, section, options = {}) {
4659
4911
  /** @throws {SessionNotFoundError} when the id names no session. */
4660
4912
  function referenceOfSession(deps, id, section, options = {}) {
4661
4913
  if (!isSessionId(id) || !existsSync(sessionDatabase(deps.sessionsDir(), id))) throw new SessionNotFoundError(`no session "${id}"`);
4662
- return referencePage(deps.open(id), section, options);
4914
+ return referencePage(deps.open(id), section, {
4915
+ ...deps.timing?.(id),
4916
+ ...options
4917
+ });
4663
4918
  }
4664
4919
  // src/shared/recall-preview.ts
4665
4920
  /** The longest situation accepted. */
@@ -4673,7 +4928,7 @@ function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
4673
4928
  sendJson(res, 200, sessions.list());
4674
4929
  },
4675
4930
  POST: async (req, res) => {
4676
- const { worldId, playerCharacterId, playerAvatar, avatars: brought, name, settings, opening, startingTime, preset, lorebooks } = await readJsonBody(req);
4931
+ const { worldId, playerCharacterId, playerAvatar, avatars: brought, name, settings, opening, startingTime, preset, lorebooks, answers } = await readJsonBody(req);
4677
4932
  if (typeof worldId !== "string" || worldId.trim() === "") return sendError(res, 400, "\"worldId\" is required");
4678
4933
  if (playerCharacterId === void 0 && playerAvatar === void 0) return sendError(res, 400, "\"playerCharacterId\" or \"playerAvatar\" is required");
4679
4934
  if (playerCharacterId !== void 0 && (typeof playerCharacterId !== "string" || playerCharacterId.trim() === "")) return sendError(res, 400, "\"playerCharacterId\" must be text");
@@ -4682,10 +4937,12 @@ function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
4682
4937
  if (name !== void 0 && typeof name !== "string") return sendError(res, 400, "\"name\" must be a string");
4683
4938
  if (opening !== void 0 && (typeof opening !== "number" || !Number.isInteger(opening))) return sendError(res, 400, "\"opening\" must be a whole number");
4684
4939
  if (startingTime !== void 0 && typeof startingTime !== "string") return sendError(res, 400, "\"startingTime\" must be text");
4940
+ if (answers !== void 0 && (typeof answers !== "object" || answers === null || Array.isArray(answers) || !Object.values(answers).every((entry) => typeof entry === "string"))) return sendError(res, 400, "\"answers\" must map question ids to answer ids");
4685
4941
  if (preset !== void 0 && typeof preset !== "string") return sendError(res, 400, "\"preset\" must be text");
4686
4942
  if (lorebooks !== void 0 && (!Array.isArray(lorebooks) || !lorebooks.every((entry) => typeof entry === "string"))) return sendError(res, 400, "\"lorebooks\" must be a list of lorebook names");
4687
4943
  try {
4688
4944
  sendJson(res, 201, await sessions.start({
4945
+ ...answers === void 0 ? {} : { answers },
4689
4946
  ...preset === void 0 || preset === "" ? {} : { preset },
4690
4947
  ...lorebooks === void 0 ? {} : { lorebooks },
4691
4948
  ...opening === void 0 ? {} : { opening },
@@ -5232,6 +5489,7 @@ function createApiHandler(deps) {
5232
5489
  ...interfaceRoutes(packs),
5233
5490
  ...presetRoutes(presets),
5234
5491
  ...lorebookRoutes(lorebooks),
5492
+ ...promptRoutes(deps.prompts),
5235
5493
  ...syncRoutes(sync)
5236
5494
  };
5237
5495
  return async (req, res) => {
@@ -6597,10 +6855,17 @@ async function startSession(deps, request) {
6597
6855
  const world = await deps.worlds.find(request.worldId);
6598
6856
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${request.worldId}"`);
6599
6857
  const { characters: authored, factions, locations, items, slots, authoredLore, declared, scripted, authoredPlots, calendar, checks, commands } = await loadValidatedWorld(world);
6600
- if (request.opening !== void 0 && (!Number.isInteger(request.opening) || request.opening < 0 || request.opening >= (world.alternateOpenings?.length ?? 0))) throw new InvalidStartError(`the world has no alternate opening ${String(request.opening)}`);
6601
- const opening = request.opening === void 0 ? openingOf(world, authored) : [{
6858
+ const answered = combineAnswers(world.startQuestions ?? [], request.answers ?? {});
6859
+ if (answered.problems.length > 0) throw new InvalidStartError(answered.problems.join("; "));
6860
+ const answers = answered.effect;
6861
+ const unknownPlot = Object.keys(answers.plots ?? {}).find((id) => !authoredPlots.plots.some((plot) => plot.id === id));
6862
+ if (unknownPlot !== void 0) throw new InvalidStartError(`an answer names the plot "${unknownPlot}", which the world does not have`);
6863
+ const openingIndex = request.opening ?? answers.opening;
6864
+ const startingTimeAsked = request.startingTime?.trim() || answers.startingTime;
6865
+ if (openingIndex !== void 0 && (!Number.isInteger(openingIndex) || openingIndex < 0 || openingIndex >= (world.alternateOpenings?.length ?? 0))) throw new InvalidStartError(`the world has no alternate opening ${String(openingIndex)}`);
6866
+ const opening = openingIndex === void 0 ? openingOf(world, authored) : [{
6602
6867
  type: "narration",
6603
- text: world.alternateOpenings[request.opening].text
6868
+ text: world.alternateOpenings[openingIndex].text
6604
6869
  }];
6605
6870
  const keys = [...new Set(request.avatars ?? [])];
6606
6871
  if (keys.length > 0 && deps.avatars === void 0) throw new InvalidStartError("player avatars are not available");
@@ -6617,7 +6882,7 @@ async function startSession(deps, request) {
6617
6882
  message: `"${entry.character}" is not a playable character of this world`
6618
6883
  }]);
6619
6884
  if (openingProblems.length > 0) throw new InvalidWorldError(`the alternate openings of "${world.summary.name}" have ${openingProblems.length} problem(s)`, openingProblems);
6620
- const forCharacter = request.opening === void 0 ? void 0 : world.alternateOpenings[request.opening].character;
6885
+ const forCharacter = openingIndex === void 0 ? void 0 : world.alternateOpenings[openingIndex].character;
6621
6886
  if (forCharacter !== void 0 && forCharacter !== player.id) throw new InvalidStartError(`this opening is for ${authored.find((character) => character.id === forCharacter)?.name ?? forCharacter}, not for ${player.name}`);
6622
6887
  const name = request.name?.trim() || world.summary.name;
6623
6888
  if (name.length > 200) throw new InvalidStartError(`the name must be at most 200 characters`);
@@ -6627,9 +6892,22 @@ async function startSession(deps, request) {
6627
6892
  if (!parsed.ok) throw new InvalidStartError(`the settings are not acceptable: ${parsed.problems.join("; ")}`);
6628
6893
  settings = parsed.value;
6629
6894
  }
6895
+ const givenClock = (request.settings?.clock)?.mode;
6896
+ if (answers.clockMode !== void 0 && givenClock === void 0) settings = {
6897
+ ...settings,
6898
+ clock: {
6899
+ ...settings.clock,
6900
+ mode: answers.clockMode
6901
+ }
6902
+ };
6630
6903
  const timeZone = settings.clock.timeZone !== "" ? settings.clock.timeZone : settings.clock.mode === "real" ? systemTimeZone() : world.clock?.timeZone ?? "UTC";
6631
- const tools = Object.fromEntries([.../* @__PURE__ */ new Set([...Object.keys(world.tools ?? {}), ...Object.keys(settings.tools)])].map((agent) => [agent, {
6904
+ const tools = Object.fromEntries([.../* @__PURE__ */ new Set([
6905
+ ...Object.keys(world.tools ?? {}),
6906
+ ...Object.keys(answers.tools ?? {}),
6907
+ ...Object.keys(settings.tools)
6908
+ ])].map((agent) => [agent, {
6632
6909
  ...world.tools?.[agent],
6910
+ ...answers.tools?.[agent],
6633
6911
  ...settings.tools[agent]
6634
6912
  }]));
6635
6913
  settings = {
@@ -6670,14 +6948,16 @@ async function startSession(deps, request) {
6670
6948
  }
6671
6949
  };
6672
6950
  let startsAt = world.clock?.startingTime;
6673
- if (request.startingTime !== void 0 && request.startingTime.trim() !== "") {
6951
+ if (startingTimeAsked !== void 0 && startingTimeAsked.trim() !== "") {
6674
6952
  if (settings.clock.mode === "real") throw new InvalidStartError("the story's time follows the wall clock, so it has no starting time to choose");
6675
6953
  try {
6676
- startsAt = parseInstant(request.startingTime.trim(), timeZone);
6954
+ startsAt = parseInstant(startingTimeAsked.trim(), timeZone);
6677
6955
  } catch (error) {
6678
6956
  throw new InvalidStartError(`the starting time is not acceptable: ${error instanceof Error ? error.message : String(error)}`);
6679
6957
  }
6680
6958
  }
6959
+ const storyRules = [...world.rules ?? [], ...answers.rules ?? []];
6960
+ if (storyRules.length > 30) throw new InvalidStartError(`the world's rules and the answers' rules come to ${storyRules.length}, and a story holds at most 30`);
6681
6961
  const sessionsDir = deps.sessionsDir();
6682
6962
  const session = deps.state.createSession(sessionsDir, {
6683
6963
  name,
@@ -6709,10 +6989,13 @@ async function startSession(deps, request) {
6709
6989
  values: world.variables
6710
6990
  });
6711
6991
  populateTriggers(session, scripted.triggers);
6712
- populatePlots(session.metadata, authoredPlots.plots);
6992
+ populatePlots(session.metadata, authoredPlots.plots.map((plot) => answers.plots?.[plot.id] === void 0 ? plot : {
6993
+ ...plot,
6994
+ start: answers.plots[plot.id]
6995
+ }));
6713
6996
  populateClock(session, settings.clock, startsAt === void 0 ? void 0 : { startingTime: startsAt }, (deps.now ?? Date.now)());
6714
6997
  if (commands.length > 0) session.metadata.setValue(COMMANDS_KEY, commands.map((command) => ({ ...command })));
6715
- if (world.rules !== void 0) session.metadata.setValue(WORLD_RULES_KEY, world.rules);
6998
+ if (storyRules.length > 0) session.metadata.setValue(WORLD_RULES_KEY, storyRules);
6716
6999
  if (world.narrationVoice !== void 0) session.metadata.setValue("roleplay.tts.narrationVoice", world.narrationVoice);
6717
7000
  });
6718
7001
  await inheritImages(world.directory, sessionFolder(sessionsDir, id), []);
@@ -7229,6 +7512,7 @@ async function worldCharacters(worlds, worldId) {
7229
7512
  })),
7230
7513
  startingTime: world.clock?.startingTime === void 0 ? "" : localInstant(world.clock.startingTime, world.clock.timeZone ?? "UTC"),
7231
7514
  timeZone: world.clock?.timeZone ?? "",
7515
+ ...world.startQuestions === void 0 ? {} : { questions: world.startQuestions.map(questionView) },
7232
7516
  ...world.preset === void 0 ? {} : { preset: world.preset },
7233
7517
  ...world.lorebooks === void 0 ? {} : { lorebooks: world.lorebooks },
7234
7518
  problems
@@ -7393,6 +7677,7 @@ async function loadWorld(folder, dir, file, problems) {
7393
7677
  ...world.clock === void 0 ? {} : { clock: world.clock },
7394
7678
  ...world.variables === void 0 ? {} : { variables: world.variables },
7395
7679
  ...world.alternateOpenings === void 0 ? {} : { alternateOpenings: world.alternateOpenings },
7680
+ ...world.startQuestions === void 0 ? {} : { startQuestions: world.startQuestions },
7396
7681
  ...world.rules === void 0 ? {} : { rules: world.rules },
7397
7682
  ...world.tools === void 0 ? {} : { tools: world.tools },
7398
7683
  ...world.narrationVoice === void 0 ? {} : { narrationVoice: world.narrationVoice },
@@ -7693,7 +7978,7 @@ const TIMEOUT_MS = 6e4;
7693
7978
  const MAX_REDIRECTS = 5;
7694
7979
  const nodeTransport = (url, ask) => new Promise((resolveReply, reject) => {
7695
7980
  const request$2 = (url.protocol === "https:" ? request$1 : request)(url, {
7696
- method: "GET",
7981
+ method: ask.method ?? "GET",
7697
7982
  signal: ask.signal,
7698
7983
  timeout: TIMEOUT_MS,
7699
7984
  agent: false,
@@ -7777,7 +8062,8 @@ async function fetchAddress(address, options) {
7777
8062
  },
7778
8063
  guarded: source === void 0,
7779
8064
  maxBytes: options.maxBytes,
7780
- signal
8065
+ signal,
8066
+ ...options.method === void 0 ? {} : { method: options.method }
7781
8067
  });
7782
8068
  } catch (error) {
7783
8069
  if (error instanceof CatalogueError) throw error;
@@ -7809,6 +8095,24 @@ const VISIBILITY = [
7809
8095
  "private"
7810
8096
  ];
7811
8097
  const CHECKED_AT_ONCE = 4;
8098
+ const PAGE = /^\/(characters|presets|lorebooks|agentic-worlds)\/([A-Za-z0-9_-]{1,100})\/?$/;
8099
+ const PAGE_KINDS = {
8100
+ characters: "card",
8101
+ presets: "preset",
8102
+ lorebooks: "lorebook",
8103
+ "agentic-worlds": "world"
8104
+ };
8105
+ /** Types a sender may name for a card: JSON or PNG, or nothing a card could not be (servers often send plain text for a JSON file and a generic type for any file). */
8106
+ const CARD_TYPES = /* @__PURE__ */ new Set([
8107
+ "",
8108
+ "application/json",
8109
+ "text/json",
8110
+ "image/png",
8111
+ "application/octet-stream",
8112
+ "binary/octet-stream",
8113
+ "text/plain"
8114
+ ]);
8115
+ const MAX_NAME = 100;
7812
8116
  const unexpected = (what) => new CatalogueError(`the catalogue answered with something unexpected: ${what}`, "upstream");
7813
8117
  const object = (value, what) => {
7814
8118
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw unexpected(what);
@@ -7860,6 +8164,17 @@ function versionOf(value) {
7860
8164
  }
7861
8165
  };
7862
8166
  }
8167
+ /** A file name for a downloaded card: the last part of the address, or "card", with the extension its first bytes call for. */
8168
+ function cardName(url, format) {
8169
+ let last = "";
8170
+ try {
8171
+ last = decodeURIComponent(url.pathname.split("/").filter((part) => part !== "").pop() ?? "");
8172
+ } catch {
8173
+ last = "";
8174
+ }
8175
+ const base = Array.from(last.replace(/[\u0000-\u001f\u007f/\\]/g, "")).slice(0, MAX_NAME).join("") || "card";
8176
+ return format === void 0 || base.toLowerCase().endsWith(`.${format}`) ? base : `${base}.${format}`;
8177
+ }
7863
8178
  /** Browsing the worlds a catalogue holds and installing one; the catalogue's API key goes with every request that belongs to its site. */
7864
8179
  var Catalogue = class {
7865
8180
  deps;
@@ -7979,6 +8294,62 @@ var Catalogue = class {
7979
8294
  result.updates.sort((a, b) => a.worldName.localeCompare(b.worldName));
7980
8295
  return result;
7981
8296
  }
8297
+ /**
8298
+ * The resource a web page address of a configured catalogue's site names (its `/characters/<id>`, `/presets/<id>`, `/lorebooks/<id>` or
8299
+ * `/agentic-worlds/<id>` page), or nothing when the address is not such a page.
8300
+ * @throws {CatalogueError} when the address is not a web address, or the page names a resource of another kind or one that does not exist.
8301
+ */
8302
+ async link(address) {
8303
+ return await this.pageOf(this.parse(address));
8304
+ }
8305
+ async pageOf(url) {
8306
+ const source = this.deps.sources.match(url);
8307
+ const named = source === void 0 ? null : PAGE.exec(url.pathname);
8308
+ if (source === void 0 || named === null) return void 0;
8309
+ const kind = PAGE_KINDS[named[1]];
8310
+ const id = named[2];
8311
+ const resource = object(await this.json(source, `/resources/${id}`), "a resource");
8312
+ if (text(resource["resourceType"]) !== TYPES[kind]) throw new CatalogueError(`${url.href} is the page of another kind of resource than the address says`, "invalid");
8313
+ return {
8314
+ source: source.name,
8315
+ id,
8316
+ kind,
8317
+ name: text(object(resource["metadata"], "a resource without metadata")["name"])
8318
+ };
8319
+ }
8320
+ /**
8321
+ * Fetches a character card from an address and hands it over for reading. A catalogue's page for a card is resolved to the card's latest
8322
+ * release. Any address first gets a HEAD request: an answer that names a type other than JSON or PNG is refused before the file is
8323
+ * downloaded, and a server that does not support HEAD (or fails it) is asked for the file anyway. The file is judged by its first bytes by
8324
+ * the card reader, not by the type the server named.
8325
+ * @throws {CatalogueError} when the address cannot be used, cannot be reached or names another type; the reader refuses what is no card.
8326
+ */
8327
+ async fetchCard(address) {
8328
+ let url = this.parse(address);
8329
+ const page = await this.pageOf(url);
8330
+ if (page !== void 0) {
8331
+ if (page.kind !== "card") throw new CatalogueError(`${url.href} is not the page of a character card`, "input");
8332
+ const source = this.deps.sources.get(page.source);
8333
+ url = new URL(this.address(source, `/versions/${(await this.latest(source, page.id)).id}/download`));
8334
+ }
8335
+ const options = {
8336
+ sources: this.deps.sources,
8337
+ maxBytes: this.deps.maxCardBytes(),
8338
+ accept: "application/json, image/png;q=0.9, */*;q=0.1",
8339
+ ...this.deps.transport === void 0 ? {} : { transport: this.deps.transport }
8340
+ };
8341
+ const head = await fetchAddress(url.href, {
8342
+ ...options,
8343
+ method: "HEAD"
8344
+ }).catch(() => void 0);
8345
+ if (head !== void 0 && !CARD_TYPES.has(head.type)) throw new CatalogueError(`${url.href} reports ${head.type}, not a PNG picture or a JSON file`, "invalid");
8346
+ const reply = await fetchAddress(url.href, options);
8347
+ const format = cardFormat(reply.body);
8348
+ return {
8349
+ body: reply.body,
8350
+ name: cardName(url, format)
8351
+ };
8352
+ }
7982
8353
  async cover(name, id) {
7983
8354
  const source = this.deps.sources.get(name);
7984
8355
  const reply = await fetchAddress(this.address(source, `/images/covers/resources/${this.identifier(id)}`), {
@@ -8001,11 +8372,12 @@ var Catalogue = class {
8001
8372
  async install(request) {
8002
8373
  const address = request.url.trim();
8003
8374
  if (address === "") throw new CatalogueError("give the address of a world archive", "input");
8004
- let url;
8005
- try {
8006
- url = new URL(address);
8007
- } catch {
8008
- throw new CatalogueError(`"${address}" is not an address`, "input");
8375
+ let url = this.parse(address);
8376
+ const page = await this.pageOf(url);
8377
+ if (page !== void 0) {
8378
+ if (page.kind !== "world") throw new CatalogueError(`${url.href} is the page of ${page.kind === "card" ? "a character card" : page.kind === "preset" ? "a preset" : "a lorebook"}, not of a world: open it from the catalogue list`, "input");
8379
+ const source = this.deps.sources.get(page.source);
8380
+ url = new URL(this.address(source, `/versions/${(await this.latest(source, page.id)).id}/download`));
8009
8381
  }
8010
8382
  const reply = await fetchAddress(url.href, {
8011
8383
  sources: this.deps.sources,
@@ -8161,6 +8533,23 @@ var Catalogue = class {
8161
8533
  }
8162
8534
  return found;
8163
8535
  }
8536
+ /** The newest published release of a resource. */
8537
+ async latest(source, id) {
8538
+ const listed = await this.json(source, `/versions/resource/${this.identifier(id)}`);
8539
+ if (!Array.isArray(listed)) throw unexpected("the list of versions");
8540
+ const newest = listed.map(versionOf).sort((a, b) => b.number - a.number)[0];
8541
+ if (newest === void 0) throw new CatalogueError("that resource has no release yet", "unknown");
8542
+ return newest.version;
8543
+ }
8544
+ parse(address) {
8545
+ const trimmed = address.trim();
8546
+ if (trimmed === "") throw new CatalogueError("give an address", "input");
8547
+ try {
8548
+ return new URL(trimmed);
8549
+ } catch {
8550
+ throw new CatalogueError(`"${trimmed}" is not an address`, "input");
8551
+ }
8552
+ }
8164
8553
  identifier(id) {
8165
8554
  if (!ID.test(id)) throw new CatalogueError("that is not a catalogue id", "input");
8166
8555
  return id;
@@ -8239,39 +8628,32 @@ var Sources = class {
8239
8628
  root: `${base.origin}${prefix}`,
8240
8629
  origin: base.origin,
8241
8630
  prefix,
8242
- keyRef,
8243
- legacyKey: source.apiKey.trim() === "" ? void 0 : source.apiKey.trim()
8631
+ keyRef
8244
8632
  }
8245
8633
  };
8246
8634
  });
8247
8635
  }
8248
- /** The catalogue's key: the credential store's value for its reference, else the one an earlier version wrote in the configuration. */
8636
+ /** The catalogue's key: the credential store's value for its reference; none when the profile has no store or the store holds none. */
8249
8637
  async key(source) {
8250
8638
  const store = this.store();
8251
- if (store !== void 0) {
8252
- let found;
8253
- try {
8254
- found = await store.resolve(source.keyRef);
8255
- } catch (error) {
8256
- throw new CatalogueError(`could not read the key "${source.keyRef}" of the catalogue "${source.name}": ${error instanceof Error ? error.message : String(error)}`, "invalid");
8257
- }
8258
- if (found !== void 0) return found.value;
8639
+ if (store === void 0) return void 0;
8640
+ try {
8641
+ return (await store.resolve(source.keyRef))?.value;
8642
+ } catch (error) {
8643
+ throw new CatalogueError(`could not read the key "${source.keyRef}" of the catalogue "${source.name}": ${error instanceof Error ? error.message : String(error)}`, "invalid");
8259
8644
  }
8260
- return source.legacyKey;
8261
8645
  }
8262
8646
  async status() {
8263
8647
  const store = this.store();
8264
8648
  return await Promise.all(this.resolved().map(async ({ source, resolved, problem }) => {
8265
8649
  const keyRef = resolved?.keyRef ?? (source.apiKeyRef.trim() === "" ? catalogueKeyRef(source.name) : source.apiKeyRef.trim());
8266
8650
  const stored = resolved === void 0 || store === void 0 ? void 0 : await store.describe(keyRef);
8267
- const legacy = source.apiKey.trim() !== "";
8268
8651
  return {
8269
8652
  name: source.name.trim(),
8270
8653
  baseUrl: source.baseUrl.trim(),
8271
8654
  keyRef,
8272
- hasKey: stored?.configured === true || legacy,
8273
- ...stored?.configured === true && stored.source !== void 0 ? { keySource: stored.source } : legacy ? { keySource: "configuration" } : {},
8274
- ...legacy ? { legacyKey: true } : {},
8655
+ hasKey: stored?.configured === true,
8656
+ ...stored?.configured === true && stored.source !== void 0 ? { keySource: stored.source } : {},
8275
8657
  ...resolved === void 0 ? { problem: problem ?? "cannot be used" } : {}
8276
8658
  };
8277
8659
  }));
@@ -9145,6 +9527,7 @@ async function unitsOf(url, worlds) {
9145
9527
  }
9146
9528
  if (path.startsWith("/presets")) units.push("presets");
9147
9529
  if (path.startsWith("/lorebooks")) units.push("lorebooks");
9530
+ if (path.startsWith("/prompts")) units.push("prompts");
9148
9531
  if (path.startsWith("/avatars") || path.startsWith("/worlds/avatars")) units.push("avatars");
9149
9532
  return units;
9150
9533
  }
@@ -9320,8 +9703,7 @@ const Config = z.object({
9320
9703
  catalogues: z.array(z.object({
9321
9704
  name: z.string().required(),
9322
9705
  baseUrl: z.string().required(),
9323
- apiKeyRef: z.string().default(""),
9324
- apiKey: z.string().default("")
9706
+ apiKeyRef: z.string().default("")
9325
9707
  })).default([]).volatile(),
9326
9708
  authoringTools: z.dict(z.dict(z.boolean())).default({}).volatile(),
9327
9709
  sync: z.object({
@@ -9372,7 +9754,7 @@ function apply(ctx, config) {
9372
9754
  return {
9373
9755
  temperature: sampling.master,
9374
9756
  ...sharedSamplingOf(sampling),
9375
- maxTokens: sampling.masterMaxTokens,
9757
+ maxTokens: orchestration.recovery.budget(id, sampling.masterMaxTokens),
9376
9758
  priority: "foreground"
9377
9759
  };
9378
9760
  }), "roleplay: request controls");
@@ -9536,6 +9918,7 @@ function apply(ctx, config) {
9536
9918
  open: (sessionId) => ctx.roleplayState.openSession(deps.sessionsDir(), sessionId)
9537
9919
  }, id),
9538
9920
  story: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
9921
+ trace: (id) => readTraces(ctx.roleplayState.openSession(deps.sessionsDir(), id)),
9539
9922
  halt: (chat) => orchestration.halt(chat),
9540
9923
  remove: (id) => deleteSession({
9541
9924
  state: ctx.roleplayState,
@@ -9568,6 +9951,7 @@ function apply(ctx, config) {
9568
9951
  catalogue,
9569
9952
  presets: presetLibrary,
9570
9953
  lorebooks: lorebookLibrary,
9954
+ prompts: new PromptManager(prompts),
9571
9955
  packs: new InterfaceService({
9572
9956
  open: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
9573
9957
  root: () => root.path,
@@ -9606,6 +9990,10 @@ function apply(ctx, config) {
9606
9990
  const card = readCard(file, name);
9607
9991
  return await withTargets(await imports.create(card, isPng(file) ? pictureOf(file) : void 0));
9608
9992
  },
9993
+ fromAddress: async (address) => {
9994
+ const { body, name } = await catalogue.fetchCard(address);
9995
+ return await withTargets(await imports.create(readCard(body, name), isPng(body) ? pictureOf(body) : void 0));
9996
+ },
9609
9997
  read: async (id) => await withTargets(await imports.read(id)),
9610
9998
  choose: (id, choices) => imports.choose(id, choices),
9611
9999
  discard: (id) => imports.discard(id),
@@ -9899,7 +10287,14 @@ function apply(ctx, config) {
9899
10287
  }, id),
9900
10288
  reference: (id, section, character) => referenceOfSession({
9901
10289
  sessionsDir: deps.sessionsDir,
9902
- open: (sessionId) => ctx.roleplayState.openSession(deps.sessionsDir(), sessionId)
10290
+ open: (sessionId) => ctx.roleplayState.openSession(deps.sessionsDir(), sessionId),
10291
+ timing: (sessionId) => {
10292
+ const settings = liveSettings(sessionFolder(deps.sessionsDir(), sessionId));
10293
+ return {
10294
+ zone: zoneOf(settings.clock),
10295
+ language: settings.prompts.language === "zh" ? "zh" : "en"
10296
+ };
10297
+ }
9903
10298
  }, id, section, character === void 0 ? {} : { character }),
9904
10299
  readJournal: (id) => readJournal(deps.sessionsDir(), id),
9905
10300
  writeJournal: (id, body) => writeJournal(deps.sessionsDir(), id, body),