@dsh-agentic-roleplay/core 0.12.2 → 0.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/lib/{authoring-tools-BZr4bgBy.js → authoring-tools-B_qYKK8c.js} +2135 -1863
  2. package/lib/authoring.js +208 -35
  3. package/lib/client.js +850 -491
  4. package/lib/client.js.map +1 -1
  5. package/lib/doctor.js +1 -1
  6. package/lib/{gallery-BNg0rPTp.js → gallery-Bu6eZMKk.js} +2 -2
  7. package/lib/{generator-9-5at9cZ.js → generator-CTWQWbSW.js} +2 -2
  8. package/lib/{hooks-Dtq5KZQX.js → hooks-YXQZ9G2d.js} +200 -41
  9. package/lib/images.js +4 -4
  10. package/lib/index.js +62 -42
  11. package/lib/{library-DTxakw0z.js → library-BmlHNCah.js} +2 -2
  12. package/lib/{lorebook-author-tools-BjcEUo22.js → lorebook-author-tools-C3rRpMt7.js} +6 -6
  13. package/lib/lorebook-authoring.js +5 -5
  14. package/lib/orchestration.js +8 -8
  15. package/lib/{pack-jail-Dt0VTsu0.js → pack-jail-VbcXiukr.js} +42 -14
  16. package/lib/{packs-DWfR2Ted.js → packs-CzVh2ZNe.js} +2 -2
  17. package/lib/{presenter-agent-vFOxIuWv.js → presenter-agent-CF3fneuJ.js} +4 -4
  18. package/lib/{preset-Dv5YF2qj.js → preset-C595KRUM.js} +3 -3
  19. package/lib/{preset-author-tools-BUzO9mTW.js → preset-author-tools-CF_JKKTE.js} +6 -6
  20. package/lib/preset-authoring.js +5 -5
  21. package/lib/{reflection-Dd3pEiZB.js → reflection-ByIQSOKC.js} +6 -6
  22. package/lib/{serial-BUaJGwVy.js → serial-ULGUKWsu.js} +1136 -1056
  23. package/lib/{text-Dfv8S8eq.js → text-hiKTooVb.js} +3 -1
  24. package/lib/{turn-guard-87NE-Cnp.js → turn-guard-DXMeAJdv.js} +2 -2
  25. package/package.json +3 -2
  26. package/prompts/en/import/opening.md +17 -0
  27. package/prompts/en/roleplay/decide-opening.md +1 -0
  28. package/prompts/en/world/procedure.md +1 -1
  29. package/prompts/zh/import/opening.md +17 -0
  30. package/prompts/zh/roleplay/decide-opening.md +1 -0
  31. package/prompts/zh/world/procedure.md +1 -1
package/lib/index.js CHANGED
@@ -1,21 +1,21 @@
1
1
  import { A as chatSessionId, _ as RECOVERY_SHRINK, g as RECOVERY_FLOOR, h as sharedSamplingOf, i as childSamplingOf, j as roleplaySessionOf, m as parseSampling, s as isUnfinishedCall, w as totalTokens } from "./child-DTdY14S9.js";
2
- import { Bt as isPng, E as loadWorldParts, F as localChanges, Ft as CHARACTERS_DIR, G as vetUrl, Ht as readCard, I as readOrigin, It as loadCharacters, Kt as authoredWorldOf, L as writeOrigin, Lt as knownOutputCeiling, M as describeChanges, N as hashWorld, P as isUnchanged, R as CatalogueError, Rt as ImportCardError, T as readWorldInfo, U as guardedLookup, Vt as pictureOf, _ as runChecks, at as populateCharacters, bt as loadLocations, c as importPhase, ct as populateFactions, d as markReady, dt as populateLocations, et as checkWorld, f as settleDraft, ft as populateLore, ht as populateVariables, it as populateCalendar, lt as populateItems, mt as populateTriggers, ot as populateClock, p as structureImport, pt as populateRoutines, qt as authoringChatSessionId, rt as knowsCharacter, st as populateDice, t as AuthoringTools, tt as loadValidatedWorld, u as keepDraft, ut as populateKnowledge, w as editWorldInfo, zt as cardFormat } from "./authoring-tools-BZr4bgBy.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-BjcEUo22.js";
4
- import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-BUzO9mTW.js";
5
- import { $ as copyWorldPrompts, A as plotProgressOf, B as parsePlotsFile, C as readNotes, G as readDocument, H as COMMANDS_KEY, J as errorMessage, L as readUsage, Q as PromptLibrary, S as notesOfSession, T as defaultBoundaries, V as plotReferenceProblems, Y as LANGUAGE_FOLDER, Z as PROMPTS_FOLDER, _ as readTraces, b as readWithdrawn, ct as InvalidStartError, dt as SessionArchivedError, ft as SessionNotFoundError, g as readRunDetail, gt as zoneOf, h as readActivity, it as shippedLanguages, j as populatePlots, k as PLOTS_METADATA_KEY, lt as InvalidWorldError, m as readDecisionStats, nt as listFiles, o as externalTools, pt as WorldNotFoundError, q as formatIssue, rt as promptProblem, st as AgentUnavailableError, tt as languageOf, ut as ReflectionRefusedError, w as observeAsPlayer, x as addToNote } from "./hooks-Dtq5KZQX.js";
2
+ import { $ as checkWorld, $t as authoringChatSessionId, A as loadWorldParts, B as localChanges, Gt as cardFormat, H as writeOrigin, J as guardedLookup, Jt as readCard, Kt as isPng, L as describeChanges, O as editWorldInfo, Ot as CHARACTERS_DIR, Qt as authoredWorldOf, R as hashWorld, U as CatalogueError, V as readOrigin, Wt as ImportCardError, X as vetUrl, _ as structureImport, _t as loadLocations, a as beginImport, at as populateClock, c as importTextFor, ct as populateItems, d as knownOutputCeiling, dt as populateLore, et as loadValidatedWorld, f as importPhase, ft as populateRoutines, g as settleDraft, h as markReady, i as ImportState, it as populateCharacters, k as readWorldInfo, kt as loadCharacters, lt as populateKnowledge, m as keepDraft, mt as populateVariables, nt as knowsCharacter, ot as populateDice, pt as populateTriggers, qt as pictureOf, rt as populateCalendar, st as populateFactions, t as AuthoringTools, ut as populateLocations, x as runChecks, z as isUnchanged } from "./authoring-tools-B_qYKK8c.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-C3rRpMt7.js";
4
+ import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-CF_JKKTE.js";
5
+ import { $ as copyWorldPrompts, A as plotProgressOf, B as parsePlotsFile, C as readNotes, G as readDocument, H as COMMANDS_KEY, J as errorMessage, L as readUsage, Q as PromptLibrary, S as notesOfSession, T as defaultBoundaries, V as plotReferenceProblems, Y as LANGUAGE_FOLDER, Z as PROMPTS_FOLDER, _ as readTraces, b as readWithdrawn, ct as InvalidStartError, dt as SessionArchivedError, ft as SessionNotFoundError, g as readRunDetail, h as readActivity, it as shippedLanguages, j as populatePlots, k as PLOTS_METADATA_KEY, lt as InvalidWorldError, m as readDecisionStats, mt as CommandRefusedError, nt as listFiles, pt as WorldNotFoundError, q as formatIssue, rt as promptProblem, s as externalTools, st as AgentUnavailableError, tt as languageOf, ut as ReflectionRefusedError, w as observeAsPlayer, x as addToNote, yt as zoneOf } from "./hooks-YXQZ9G2d.js";
6
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--K2XVIHI.js";
7
- import { $ as deleteWorldPrompt, $t as subfolders, Et as readImportFolder, F as parseWorldInfoEdit, G as loadPreset, H as deletePreset, I as combineAnswers, J as reservePreset, K as presetDirectory, L as questionView, M as WORLD_FILE_NAME, N as parseWorldFile, Ot as IMPORT_COMMAND, Pt as sourceSummary, Qt as parseCharacterFile, St as ImportStore, Tt as parseChoices, U as isPresetName, V as createPresetFromShipped, W as listPresets, Y as savePresetFromWorld, Z as updatePresetInfo, an as parseRelationEdit, at as deleteLorebook, bt as IMPORT_FOLDER, cn as LORE_KINDS, ct as isLorebookName, dt as lorebookDirectory, en as InvalidEditProblems, et as listWorldPrompts, ht as writeLorebookEntry, in as parsePlaceEdit, it as createLorebook, ln as LORE_SCOPES, lt as listLorebooks, mt as updateLorebookInfo, nn as parseFactionEdit, nt as writeWorldPrompt, on as parseThingEdit, ot as deleteLorebookEntry, pt as reserveLorebook, rn as parseLoreEdit, rt as addLorebookEntries, sn as guarded, st as entriesOf, tn as parseCharacterEdit, tt as readWorldPrompt, ut as loadLorebook, vt as partsOf, xt as ImportNotFoundError, yt as withPlayer, z as PRESET_FILE } from "./serial-BUaJGwVy.js";
8
- import { $ as languageOfDocuments, A as generateWorldCharacterPortrait, C as editWorldFaction$1, D as editWorldPlots$1, E as editWorldPlace$1, F as uploadWorldCharacterPortrait, G as parseVariablesEdit, I as uploadWorldEntityImage, J as PRESET_FILE$1, K as parseDiceEdit, L as worldCharacterPortraitFile, M as readWorldEditor, N as readWorldTrigger, O as editWorldRelation$1, P as removeWorldTrigger, R as worldEntityImageFile, S as editWorldCharacter$1, T as editWorldNarrationVoice, U as parseCalendarEdit, W as parseRoutineEdit, Y as presetMessage, Z as translateMessage, _ as readCalendarDocument, a as deleteWorldPackFile, at as startUpdate, b as readRoutines, c as createAuthoredEntity, ct as authoringTitle, dt as agentServicesOf, et as readWorldDocuments, f as editCalendar, ft as DOCTOR_OPENING_SOURCE, g as editVariables, h as editRoutine, it as revertUpdate, j as generateWorldEntityImage, k as editWorldThing$1, l as deleteAuthoredEntity, lt as ensureAuthoringChat, m as editDice, mt as appendNarratedTurn, n as packFileProblem, ot as updateStatus, p as editCommands, pt as appendEmptyTurn, q as parseCommandsEdit, st as AuthoringSessions, t as MAX_PACK_TEXT, tt as findTargets, u as readAuthoredEntityDocument, ut as AgentSessions, v as readCommandsDocument, w as editWorldLore$1, x as readVariables, y as readDiceDocument, z as writeWorldTrigger } from "./pack-jail-Dt0VTsu0.js";
7
+ import { B as questionView, Bt as parseThingEdit, Dt as ImportNotFoundError, Et as IMPORT_FOLDER, F as parseWorldInfoEdit, Ft as parseCharacterEdit, G as deletePreset, H as PRESET_FILE, It as parseFactionEdit, J as loadPreset, K as isPresetName, Kt as sourceSummary, Lt as parseLoreEdit, M as WORLD_FILE_NAME, Mt as readImportFolder, N as parseWorldFile, Ot as ImportStore, Pt as InvalidEditProblems, Q as savePresetFromWorld, Rt as parsePlaceEdit, Tt as withPlayer, W as createPresetFromShipped, Y as presetDirectory, Z as reservePreset, _t as updateLorebookInfo, at as writeWorldPrompt, cn as parseCharacterFile, ct as deleteLorebook, dn as LORE_SCOPES, dt as isLorebookName, et as updatePresetInfo, ft as listLorebooks, gt as reserveLorebook, it as readWorldPrompt, jt as parseChoices, ln as guarded, lt as deleteLorebookEntry, mt as lorebookDirectory, nt as deleteWorldPrompt, ot as addLorebookEntries, pt as loadLorebook, q as listPresets, rt as listWorldPrompts, st as createLorebook, un as LORE_KINDS, ut as entriesOf, vt as writeLorebookEntry, wt as partsOf, xt as subfolders, z as combineAnswers, zt as parseRelationEdit } from "./serial-ULGUKWsu.js";
8
+ import { $ as languageOfDocuments, A as generateWorldCharacterPortrait, C as editWorldFaction$1, D as editWorldPlots$1, E as editWorldPlace$1, F as uploadWorldCharacterPortrait, G as parseVariablesEdit, I as uploadWorldEntityImage, J as PRESET_FILE$1, K as parseDiceEdit, L as worldCharacterPortraitFile, M as readWorldEditor, N as readWorldTrigger, O as editWorldRelation$1, P as removeWorldTrigger, R as worldEntityImageFile, S as editWorldCharacter$1, T as editWorldNarrationVoice, U as parseCalendarEdit, W as parseRoutineEdit, Y as presetMessage, Z as translateMessage, _ as readCalendarDocument, a as deleteWorldPackFile, at as startUpdate, b as readRoutines, c as createAuthoredEntity, ct as authoringTitle, dt as agentServicesOf, et as readWorldDocuments, f as editCalendar, ft as DOCTOR_OPENING_SOURCE, g as editVariables, h as editRoutine, it as revertUpdate, j as generateWorldEntityImage, k as editWorldThing$1, l as deleteAuthoredEntity, lt as ensureAuthoringChat, m as editDice, mt as appendNarratedTurn, n as packFileProblem, ot as updateStatus, p as editCommands, pt as appendEmptyTurn, q as parseCommandsEdit, st as AuthoringSessions, t as MAX_PACK_TEXT, tt as findTargets, u as readAuthoredEntityDocument, ut as AgentSessions, v as readCommandsDocument, w as editWorldLore$1, x as readVariables, y as readDiceDocument, z as writeWorldTrigger } from "./pack-jail-VbcXiukr.js";
9
9
  import { i as atomicWriteSync, n as atomicWrite, r as atomicWriteJson } from "./access-Csp80TFX.js";
10
- import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-Dfv8S8eq.js";
11
- import { _ as snapshotOf, c as copyPreset, d as switchPreset, f as readTimeline, g as pathTo, h as childrenOf, i as reflectionStatus, l as presetStatus, m as START_SNAPSHOT, o as TimelineError, p as writeTimeline, u as recordPreset } from "./reflection-Dd3pEiZB.js";
12
- import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-Dv5YF2qj.js";
13
- import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-DTxakw0z.js";
10
+ import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-hiKTooVb.js";
11
+ import { _ as snapshotOf, c as copyPreset, d as switchPreset, f as readTimeline, g as pathTo, h as childrenOf, i as reflectionStatus, l as presetStatus, m as START_SNAPSHOT, o as TimelineError, p as writeTimeline, u as recordPreset } from "./reflection-ByIQSOKC.js";
12
+ import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-C595KRUM.js";
13
+ import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-BmlHNCah.js";
14
14
  import { o as FOLDER_ACCESS, r as InvalidFoldersError, t as StoryFoldersService } from "./service-mRKwpWjX.js";
15
15
  import { t as doctorChatSessionId } from "./doctor-chat-hL1a61hp.js";
16
- 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-DWfR2Ted.js";
17
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-9-5at9cZ.js";
18
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-BNg0rPTp.js";
16
+ 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-CzVh2ZNe.js";
17
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-CTWQWbSW.js";
18
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-Bu6eZMKk.js";
19
19
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
20
20
  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";
21
21
  import { copyFileSync, cpSync, createReadStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
@@ -330,6 +330,16 @@ var AuthoringLanguages = class extends Service {
330
330
  return join(this.worldsDirectory(), ".authoring", `${encodeURIComponent(worldId)}.json`);
331
331
  }
332
332
  };
333
+ // src/host/worlds/draft.ts
334
+ /** Whether the world is an import that was written but would not start yet: its import state (kept in the world's `.import` folder) says it is being repaired. */
335
+ async function isDraftWorld(directory) {
336
+ try {
337
+ return JSON.parse(await readFile(join(directory, ".import", "state.json"), "utf8")).phase === "repair";
338
+ } catch (error) {
339
+ if (error.code === "ENOENT") return false;
340
+ throw error;
341
+ }
342
+ }
333
343
  // src/host/import/service.ts
334
344
  /** What an import is configured to do, for the parts of the plugin that run in other scopes (the authoring chat's tools). */
335
345
  var RoleplayImport = class extends Service {
@@ -339,6 +349,8 @@ var RoleplayImport = class extends Service {
339
349
  this.read = read;
340
350
  }
341
351
  turns = /* @__PURE__ */ new Map();
352
+ /** The imports the authoring chats are running; shared by the chats' command and gate and by the plugin's own starts. */
353
+ state = new ImportState();
342
354
  /** Notes that a turn of a chat ended; the authoring chats are the ones that report here. */
343
355
  turnEnded(chat) {
344
356
  this.turns.set(chat, (this.turns.get(chat) ?? 0) + 1);
@@ -352,16 +364,6 @@ var RoleplayImport = class extends Service {
352
364
  return this.read();
353
365
  }
354
366
  };
355
- // src/host/worlds/draft.ts
356
- /** Whether the world is an import that was written but would not start yet: its import state (kept in the world's `.import` folder) says it is being repaired. */
357
- async function isDraftWorld(directory) {
358
- try {
359
- return JSON.parse(await readFile(join(directory, ".import", "state.json"), "utf8")).phase === "repair";
360
- } catch (error) {
361
- if (error.code === "ENOENT") return false;
362
- throw error;
363
- }
364
- }
365
367
  // src/host/worlds/create-world.ts
366
368
  const FOLDER = /^[\p{L}\p{N}][\p{L}\p{N}._ -]{0,99}$/u;
367
369
  var WorldFolderExistsError = class extends Error {};
@@ -413,10 +415,10 @@ function folderNameOf(name) {
413
415
  const folder = trimCharacters(cleaned, ". ", "end").slice(0, 90).trim();
414
416
  return folder === "" ? "imported world" : folder;
415
417
  }
416
- /** The command that starts the import, for a card kept in the world's import folder. */
417
- function importMessage(language, card) {
418
+ /** What the person asks of the import of the card kept in the world's import folder: the request, and a summary of the card when it can be read. */
419
+ function importRequest(language, card) {
418
420
  const request = translator(languageOf$1(language))("Import this card into this newly created world.");
419
- return `${IMPORT_COMMAND} ${IMPORT_FOLDER}/card.json ${card === void 0 ? request : `${request} ${sourceSummary(card, language)}`}`;
421
+ return card === void 0 ? request : `${request} ${sourceSummary(card, language)}`;
420
422
  }
421
423
  /** The card kept in a world's import folder, when it can be read; the message then carries a summary of it. */
422
424
  async function cardOf(directory) {
@@ -427,7 +429,7 @@ async function cardOf(directory) {
427
429
  }
428
430
  }
429
431
  /**
430
- * Has the chat of a world whose import stopped before it was done carry on from the step it reached (the import hooks tell the chat which step that is). An import is lost
432
+ * Has the chat of a world whose import stopped before it was done carry on from the step it reached (the import command tells the chat which step that is). An import is lost
431
433
  * to a server restart, a refused finish or a chat that ended early; the card and what was extracted stay in the world's import folder.
432
434
  * @throws {WorldNotFoundError} when the world is gone. @throws {InvalidEditProblems} when no import is waiting in it.
433
435
  */
@@ -439,7 +441,7 @@ async function resumeImport(deps, worldId, language) {
439
441
  const chatSessionId = await deps.authoring.ensure(record.summary.id, record.summary.name, authoringTitle(record.summary.name, language), language);
440
442
  let failure;
441
443
  try {
442
- await deps.authoring.send(chatSessionId, importMessage(language, await cardOf(record.directory)));
444
+ await deps.authoring.startImport(chatSessionId, importRequest(language, await cardOf(record.directory)));
443
445
  } catch (error) {
444
446
  failure = error instanceof Error ? error.message : String(error);
445
447
  }
@@ -484,7 +486,7 @@ async function startImport(deps, id, choices, language) {
484
486
  const chatSessionId = await deps.authoring.ensure(world.id, world.name, authoringTitle(world.name, language), language);
485
487
  let failure;
486
488
  try {
487
- await deps.authoring.send(chatSessionId, importMessage(language, await cardOf(directory)));
489
+ await deps.authoring.startImport(chatSessionId, importRequest(language, await cardOf(directory)));
488
490
  } catch (error) {
489
491
  failure = error instanceof Error ? error.message : String(error);
490
492
  }
@@ -564,7 +566,7 @@ function lengthOf(text) {
564
566
  return (text.match(CJK)?.length ?? 0) + (text.replace(CJK, " ").match(/[\p{L}\p{N}]+/gu)?.length ?? 0);
565
567
  }
566
568
  /** Voices of the delivered turns on the way the story went: who spoke how often and how much, and what the narration came to. */
567
- function speakingOf(timeline) {
569
+ function speakingOf$1(timeline) {
568
570
  const voices = /* @__PURE__ */ new Map();
569
571
  const narration = {
570
572
  passages: 0,
@@ -629,7 +631,7 @@ function statisticsOfSession(deps, id) {
629
631
  ...first === void 0 || now === void 0 ? {} : { elapsedSeconds: Math.max(0, Math.round((now - first.to) / 1e3)) }
630
632
  },
631
633
  scenes: places.filter((place, index) => index === 0 || place !== places[index - 1]).length,
632
- ...speakingOf(timeline),
634
+ ...speakingOf$1(timeline),
633
635
  threads: {
634
636
  open: threads.filter((thread) => thread.status === "open").length,
635
637
  resolved: threads.filter((thread) => thread.status !== "open").length
@@ -3348,6 +3350,7 @@ function worldsRoutes({ worlds, createWorld, starter, authorWorld, sayToAuthor,
3348
3350
  } catch (error) {
3349
3351
  if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
3350
3352
  if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
3353
+ if (error instanceof CommandRefusedError) return sendError(res, 422, error.message);
3351
3354
  throw error;
3352
3355
  }
3353
3356
  } },
@@ -5101,6 +5104,7 @@ function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
5101
5104
  if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
5102
5105
  if (error instanceof SessionArchivedError) return sendError(res, 409, error.message);
5103
5106
  if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
5107
+ if (error instanceof CommandRefusedError) return sendError(res, 422, error.message);
5104
5108
  throw error;
5105
5109
  }
5106
5110
  } },
@@ -6846,10 +6850,10 @@ async function startSession(deps, request) {
6846
6850
  const openingIndex = request.opening ?? answers.opening;
6847
6851
  const startingTimeAsked = request.startingTime?.trim() || answers.startingTime;
6848
6852
  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)}`);
6849
- const opening = openingIndex === void 0 ? openingOf(world, authored) : [{
6853
+ const opening = openingIndex === void 0 ? openingOf(world, authored) : speakingOf(world, world.alternateOpenings[openingIndex].parts ?? [{
6850
6854
  type: "narration",
6851
6855
  text: world.alternateOpenings[openingIndex].text
6852
- }];
6856
+ }], authored, `alternate_openings[${openingIndex}]`);
6853
6857
  const keys = [...new Set(request.avatars ?? [])];
6854
6858
  if (keys.length > 0 && deps.avatars === void 0) throw new InvalidStartError("player avatars are not available");
6855
6859
  const avatars = keys.length === 0 ? void 0 : await deps.avatars();
@@ -6864,6 +6868,11 @@ async function startSession(deps, request) {
6864
6868
  path: `alternate_openings[${index}].character`,
6865
6869
  message: `"${entry.character}" is not a playable character of this world`
6866
6870
  }]);
6871
+ const speakerProblems = (world.alternateOpenings ?? []).flatMap((entry, index) => (entry.parts ?? []).flatMap((part) => part.type === "utterance" && !authored.some((character) => character.id === part.character) ? [{
6872
+ path: `alternate_openings[${index}].parts`,
6873
+ message: `"${part.character}" is not a character of this world`
6874
+ }] : []));
6875
+ openingProblems.push(...speakerProblems);
6867
6876
  if (openingProblems.length > 0) throw new InvalidWorldError(`the alternate openings of "${world.summary.name}" have ${openingProblems.length} problem(s)`, openingProblems);
6868
6877
  const forCharacter = openingIndex === void 0 ? void 0 : world.alternateOpenings[openingIndex].character;
6869
6878
  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}`);
@@ -7054,19 +7063,15 @@ function presetFor(deps, asked, suggested) {
7054
7063
  return { unavailable: [`The world suggests the preset "${name}", which cannot be used here (${reason}), so the story is told in the default style.`] };
7055
7064
  }
7056
7065
  }
7057
- /** The opening of the world with each speaker's name, or the reason it cannot be used. */
7058
- function openingOf(world, characters) {
7059
- if (world.opening === void 0) return [{
7060
- type: "narration",
7061
- text: DEFAULT_OPENING
7062
- }];
7066
+ /** The parts of an opening with each speaker's name, or the reason it cannot be used: a speaker the world does not have. */
7067
+ function speakingOf(world, parts, characters, where) {
7063
7068
  const problems = [];
7064
- const segments = world.opening.map((segment) => {
7069
+ const segments = parts.map((segment) => {
7065
7070
  if (segment.type === "narration") return segment;
7066
7071
  const speaker = characters.find((character) => character.id === segment.character);
7067
7072
  if (speaker === void 0) problems.push({
7068
7073
  path: join(world.directory, WORLD_FILE_NAME),
7069
- message: `opening_message: "${segment.character}" is not a character of this world`
7074
+ message: `${where}: "${segment.character}" is not a character of this world`
7070
7075
  });
7071
7076
  return {
7072
7077
  type: "utterance",
@@ -7078,6 +7083,14 @@ function openingOf(world, characters) {
7078
7083
  if (problems.length > 0) throw new InvalidWorldError(`the opening of "${world.summary.name}" has ${problems.length} problem(s)`, problems);
7079
7084
  return segments;
7080
7085
  }
7086
+ /** The opening of the world with each speaker's name, or the reason it cannot be used. */
7087
+ function openingOf(world, characters) {
7088
+ if (world.opening === void 0) return [{
7089
+ type: "narration",
7090
+ text: DEFAULT_OPENING
7091
+ }];
7092
+ return speakingOf(world, world.opening, characters, "opening_message");
7093
+ }
7081
7094
  // src/host/sessions/rename-session.ts
7082
7095
  /**
7083
7096
  * Give a session a new name, and its chat the same one.
@@ -9827,7 +9840,14 @@ function apply(ctx, config) {
9827
9840
  if (timer !== void 0) clearTimeout(timer);
9828
9841
  };
9829
9842
  }, "roleplay: stories that go on while the player is away");
9830
- const authoring = new AuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
9843
+ const authoring = new AuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages, (chat, request) => beginImport({
9844
+ worlds: ctx.roleplayWorlds,
9845
+ text: importTextFor({
9846
+ prompts: () => prompts,
9847
+ languages: () => languages
9848
+ }),
9849
+ state: ctx.roleplayImport.state
9850
+ }, chat, request));
9831
9851
  const presetAuthoring = new PresetAuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
9832
9852
  const lorebookAuthoring = new LorebookAuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
9833
9853
  const doctors = new DoctorSessions(agentServicesOf(ctx), () => root.path, prompts);
@@ -1,5 +1,5 @@
1
1
  import { n as atomicWrite } from "./access-Csp80TFX.js";
2
- import { i as translator, n as withoutExtension, r as languageOf, t as trimCharacters } from "./text-Dfv8S8eq.js";
2
+ import { i as translator, n as withoutExtension, r as languageOf, t as trimCharacters } from "./text-hiKTooVb.js";
3
3
  import { dirname, extname, join } from "node:path";
4
4
  import { existsSync } from "node:fs";
5
5
  import { createHash } from "node:crypto";
@@ -374,4 +374,4 @@ async function addToLibrary(sessionFolder, bytes, originalName) {
374
374
  }
375
375
  export { slug as C, norm as S, uniqueKey as T, writeImageFileMetadata as _, LIBRARY_FOLDER as a, NoEmbeddingService as b, nextSceneSerial as c, sceneImagePath as d, writeImage as f, sidecarOf as g, readImageFileMetadata as h, libraryHashes as i, readImageMetadata as l, mediaTypeOf as m, addToLibraryOnce as n, entityImageDirectory as o, MEDIA_TYPES as p, imageExtensionOf as r, inheritImages as s, addToLibrary as t, referenceImagePath as u, readPngMetadata as v, trOf as w, mapLimit as x, withPngMetadata as y };
376
376
 
377
- //# sourceMappingURL=library-DTxakw0z.js.map
377
+ //# sourceMappingURL=library-BmlHNCah.js.map
@@ -1,9 +1,9 @@
1
1
  import "./access-Csp80TFX.js";
2
- import { Rt as ImportCardError, i as contextOf, r as MAX_PREVIEW_TEXT } from "./authoring-tools-BZr4bgBy.js";
3
- import { B as createPresetFromGuidance, bt as IMPORT_FOLDER, cn as LORE_KINDS, dt as lorebookDirectory, ft as readLorebook$1, gt as cleanText, ht as writeLorebookEntry, ln as LORE_SCOPES, mt as updateLorebookInfo, ot as deleteLorebookEntry, st as entriesOf, ut as loadLorebook, vt as partsOf, yt as withPlayer } from "./serial-BUaJGwVy.js";
4
- import { F as textLanguage, I as wrongLanguage, at as shippedPromptsDirectory } from "./hooks-Dtq5KZQX.js";
5
- import { i as translator, r as languageOf } from "./text-Dfv8S8eq.js";
6
- import { C as slug, T as uniqueKey, w as trOf, x as mapLimit } from "./library-DTxakw0z.js";
2
+ import { Wt as ImportCardError, o as contextOf, r as MAX_PREVIEW_TEXT } from "./authoring-tools-B_qYKK8c.js";
3
+ import { Et as IMPORT_FOLDER, St as cleanText, Tt as withPlayer, U as createPresetFromGuidance, _t as updateLorebookInfo, dn as LORE_SCOPES, ht as readLorebook$1, lt as deleteLorebookEntry, mt as lorebookDirectory, pt as loadLorebook, un as LORE_KINDS, ut as entriesOf, vt as writeLorebookEntry, wt as partsOf } from "./serial-ULGUKWsu.js";
4
+ import { F as textLanguage, I as wrongLanguage, at as shippedPromptsDirectory } from "./hooks-YXQZ9G2d.js";
5
+ import { i as translator, r as languageOf } from "./text-hiKTooVb.js";
6
+ import { C as slug, T as uniqueKey, w as trOf, x as mapLimit } from "./library-BmlHNCah.js";
7
7
  import { join } from "node:path";
8
8
  import { existsSync, readFileSync } from "node:fs";
9
9
  import { readFile, rm, writeFile } from "node:fs/promises";
@@ -709,4 +709,4 @@ async function lorebookApproval(exec, next, state) {
709
709
  }
710
710
  export { lorebookImportMessage as a, readLorebook as c, lorebookOfChat as d, lorebookAuthorTools as i, selectEntries as l, LorebookReader as n, pendingTargets as o, lorebookApproval as r, previewLorebook as s, LOREBOOK_UPLOAD as t, lorebookChatSessionId as u };
711
711
 
712
- //# sourceMappingURL=lorebook-author-tools-BjcEUo22.js.map
712
+ //# sourceMappingURL=lorebook-author-tools-C3rRpMt7.js.map
@@ -1,9 +1,9 @@
1
- import { n as limitAuthoringAgents } from "./authoring-tools-BZr4bgBy.js";
2
- import { t as guardAuthoringTurns } from "./turn-guard-87NE-Cnp.js";
1
+ import { n as limitAuthoringAgents } from "./authoring-tools-B_qYKK8c.js";
2
+ import { t as guardAuthoringTurns } from "./turn-guard-DXMeAJdv.js";
3
3
  import { n as silenceRuntimeContext, t as silenceHarnessDevContext } from "./dev-context-Cgv_wZbG.js";
4
- import { d as lorebookOfChat, i as lorebookAuthorTools, n as LorebookReader, o as pendingTargets, r as lorebookApproval } from "./lorebook-author-tools-BjcEUo22.js";
5
- import "./hooks-Dtq5KZQX.js";
6
- import { dt as lorebookDirectory } from "./serial-BUaJGwVy.js";
4
+ import { d as lorebookOfChat, i as lorebookAuthorTools, n as LorebookReader, o as pendingTargets, r as lorebookApproval } from "./lorebook-author-tools-C3rRpMt7.js";
5
+ import "./hooks-YXQZ9G2d.js";
6
+ import { mt as lorebookDirectory } from "./serial-ULGUKWsu.js";
7
7
  import { join } from "node:path";
8
8
  import { existsSync, readdirSync } from "node:fs";
9
9
  // src/lorebook-authoring.ts
@@ -1,17 +1,17 @@
1
1
  import { t as silenceHarnessDevContext } from "./dev-context-Cgv_wZbG.js";
2
2
  import { t as promptFor } from "./access-Csp80TFX.js";
3
- import { D as referent, E as sameWords, H as COMMANDS_KEY, I as wrongLanguage, O as RESULTS, U as commandFlagKey, W as commandsOf, _t as AUTHORING_NEEDS, a as externalGiven, c as PREVIEW_TOOL, d as toolEnabled, f as MAX_OOC_ANSWER, gt as zoneOf, ht as describeWhen, i as characterRunner, l as createTools$1, mt as ClockError, n as installHooks, ot as shippedText, p as storesOf, tt as languageOf, u as record, ut as ReflectionRefusedError, v as readVerdicts, y as writeVerdicts } from "./hooks-Dtq5KZQX.js";
3
+ import { D as referent, E as sameWords, H as COMMANDS_KEY, I as wrongLanguage, O as RESULTS, U as commandFlagKey, W as commandsOf, _t as ClockError, a as MAX_OOC_ANSWER, bt as AUTHORING_NEEDS, d as record, f as toolEnabled, i as characterRunner, l as PREVIEW_TOOL, n as installHooks, o as externalGiven, ot as shippedText, p as storesOf, tt as languageOf, u as createTools$1, ut as ReflectionRefusedError, v as readVerdicts, vt as describeWhen, y as writeVerdicts, yt as zoneOf } from "./hooks-YXQZ9G2d.js";
4
4
  import { A as chatSessionId, O as estimateAnswer, T as currentTurn, a as childTrace, d as sessionOfChat, f as tracerOf, j as roleplaySessionOf, k as tokensOf, l as runChild, n as childModel, r as childSampling, u as TurnTraces } from "./child-DTdY14S9.js";
5
- import { a as whereabouts, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-Dd3pEiZB.js";
6
- import { A as routeVerdicts, E as askYesNo, Mt as splitPanels, O as modeFor, T as announceProblem, fn as INTENT_STATUSES, j as yesAt, k as noAt, n as STANDING_PROMPT, sn as guarded } from "./serial-BUaJGwVy.js";
7
- import { i as translator, r as languageOf$1 } from "./text-Dfv8S8eq.js";
5
+ import { a as whereabouts, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-ByIQSOKC.js";
6
+ import { A as routeVerdicts, E as askYesNo, O as modeFor, T as announceProblem, Wt as splitPanels, j as yesAt, k as noAt, ln as guarded, mn as INTENT_STATUSES, n as STANDING_PROMPT } from "./serial-ULGUKWsu.js";
7
+ import { i as translator, r as languageOf$1 } from "./text-hiKTooVb.js";
8
8
  import { a as liveSettings, g as GATE_SITES, n as encodeOutput } from "./narration--K2XVIHI.js";
9
9
  import { t as registerFoldersJail } from "./jail-DVbPSC0R.js";
10
10
  import { a as workspaceOf, n as storyRoots } from "./service-mRKwpWjX.js";
11
- import { C as slug, T as uniqueKey, t as addToLibrary } from "./library-DTxakw0z.js";
12
- import { _ as API_PREFIX } from "./packs-DWfR2Ted.js";
13
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-BNg0rPTp.js";
14
- import { c as presentedFor, i as findImages, n as interpretImage, s as present, t as runImagePresenter } from "./presenter-agent-vFOxIuWv.js";
11
+ import { C as slug, T as uniqueKey, t as addToLibrary } from "./library-BmlHNCah.js";
12
+ import { _ as API_PREFIX } from "./packs-CzVh2ZNe.js";
13
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-Bu6eZMKk.js";
14
+ import { c as presentedFor, i as findImages, n as interpretImage, s as present, t as runImagePresenter } from "./presenter-agent-CF3fneuJ.js";
15
15
  import { join } from "node:path";
16
16
  import { InvalidEditError, characterKey, createDiceTools, createTools, dayPart, describeDuration, describeHolder, describeInstant, describeValue, itemKey, judgedStatements, lintWorld, localTime, locationKey, mentioned, parseRecordsEdit, rollForCheck, seededRoll, sessionDatabase, sessionFolder, systemRoller } from "@dsh-agentic-roleplay/state";
17
17
  import { existsSync } from "node:fs";
@@ -1,14 +1,14 @@
1
1
  import { A as chatSessionId } from "./child-DTdY14S9.js";
2
- import { A as editsSince, At as loadCommands, B as addressesToFetch, C as worldFieldChanges, Ct as FACTIONS_DIR, Dt as parseDiceFile, E as loadWorldParts, Et as loadDice, Ft as CHARACTERS_DIR, Gt as DICE_RESULTS, H as fetchPictures, It as loadCharacters, J as UPDATE_FOLDER, K as cardCharacter, Kt as authoredWorldOf, Mt as CALENDAR_FILE_NAME, Nt as loadCalendar, Ot as COMMANDS_FILE_NAME, Pt as parseCalendarFile, St as loadItems, Tt as DICE_FILE_NAME, Ut as DICE_COMPARISONS, V as candidateUrls, W as mergeReports, Wt as DICE_READINGS, X as cardPieces, Y as baseId, _t as TRIGGERS_FILE_NAME, bt as loadLocations, c as importPhase, gt as routineProblems, i as contextOf, j as writeSnapshot, jt as parseCommandsFile, k as recordProvenance, kt as commandVariable, nt as withScratchStory, q as writePortrait, qt as authoringChatSessionId, rt as knowsCharacter, s as worldOf, tt as loadValidatedWorld, vt as loadTriggers, w as editWorldInfo, wt as loadFactions, x as matchPieces, xt as ITEMS_DIR, yt as LOCATIONS_DIR, z as addressKey } from "./authoring-tools-BZr4bgBy.js";
3
- import { $t as subfolders, Bt as loadLore, Ct as PICTURE_FILE, Dt as writeChoices, Et as readImportFolder, Ft as VARIABLES_FILE_NAME, Gt as ITEM_FILE_NAME, Ht as parseLoreFile, It as loadVariables, Lt as parseVariablesFile, M as WORLD_FILE_NAME, N as parseWorldFile, Qt as parseCharacterFile, Rt as variableProblems, Ut as LOCATION_FILE_NAME, Vt as LORE_FILE_NAME, Wt as parseLocationFile, Xt as parseFactionFile, Yt as FACTION_FILE_NAME, Zt as CHARACTER_FILE_NAME, bt as IMPORT_FOLDER, en as InvalidEditProblems, l as extractStyleFrom, nt as writeWorldPrompt, qt as parseItemFile, yt as withPlayer, zt as LORE_DIR } from "./serial-BUaJGwVy.js";
2
+ import { $t as authoringChatSessionId, A as loadWorldParts, Bt as loadCommands, Ct as loadDice, D as worldFieldChanges, Dt as parseCalendarFile, Et as loadCalendar, F as editsSince, G as addressesToFetch, Ht as TRIGGERS_FILE_NAME, I as writeSnapshot, K as candidateUrls, Mt as UPDATE_FOLDER, Nt as baseId, O as editWorldInfo, Ot as CHARACTERS_DIR, P as recordProvenance, Pt as cardPieces, Q as writePortrait, Qt as authoredWorldOf, Rt as COMMANDS_FILE_NAME, St as DICE_FILE_NAME, T as matchPieces, Tt as CALENDAR_FILE_NAME, Ut as loadTriggers, Vt as parseCommandsFile, W as addressKey, Xt as DICE_READINGS, Y as mergeReports, Yt as DICE_COMPARISONS, Z as cardCharacter, Zt as DICE_RESULTS, _t as loadLocations, bt as FACTIONS_DIR, et as loadValidatedWorld, f as importPhase, gt as LOCATIONS_DIR, ht as routineProblems, kt as loadCharacters, nt as knowsCharacter, o as contextOf, q as fetchPictures, tt as withScratchStory, u as worldOf, vt as ITEMS_DIR, wt as parseDiceFile, xt as loadFactions, yt as loadItems, zt as commandVariable } from "./authoring-tools-B_qYKK8c.js";
3
+ import { $t as LOCATION_FILE_NAME, Et as IMPORT_FOLDER, Jt as loadVariables, M as WORLD_FILE_NAME, Mt as readImportFolder, N as parseWorldFile, Nt as writeChoices, Pt as InvalidEditProblems, Qt as parseLoreFile, Tt as withPlayer, Xt as variableProblems, Yt as parseVariablesFile, Zt as LORE_FILE_NAME, an as FACTION_FILE_NAME, at as writeWorldPrompt, bt as loadLore, cn as parseCharacterFile, en as parseLocationFile, kt as PICTURE_FILE, l as extractStyleFrom, on as parseFactionFile, qt as VARIABLES_FILE_NAME, rn as parseItemFile, sn as CHARACTER_FILE_NAME, tn as ITEM_FILE_NAME, xt as subfolders, yt as LORE_DIR } from "./serial-ULGUKWsu.js";
4
4
  import { n as encodeOutput } from "./narration--K2XVIHI.js";
5
5
  import { a as VARIABLE_KINDS, n as atomicWrite, o as VARIABLE_SUBJECTS, r as atomicWriteJson, s as VARIABLE_VISIBILITIES } from "./access-Csp80TFX.js";
6
- import { B as parsePlotsFile, F as textLanguage, K as Reader, M as LANGUAGE_NAMES, N as STORY_LANGUAGES, P as isStoryLanguage, R as PLOTS_FILE_NAME, V as plotReferenceProblems, Z as PROMPTS_FOLDER, it as shippedLanguages, lt as InvalidWorldError, pt as WorldNotFoundError, q as formatIssue, st as AgentUnavailableError, z as loadPlots } from "./hooks-Dtq5KZQX.js";
7
- import { i as translator, r as languageOf } from "./text-Dfv8S8eq.js";
8
- import { h as readImageFileMetadata, u as referenceImagePath, x as mapLimit } from "./library-DTxakw0z.js";
9
- import { n as readPreset } from "./preset-Dv5YF2qj.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-DWfR2Ted.js";
11
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-9-5at9cZ.js";
6
+ import { B as parsePlotsFile, F as textLanguage, K as Reader, M as LANGUAGE_NAMES, N as STORY_LANGUAGES, P as isStoryLanguage, R as PLOTS_FILE_NAME, V as plotReferenceProblems, Z as PROMPTS_FOLDER, gt as runCommandLine, it as shippedLanguages, lt as InvalidWorldError, mt as CommandRefusedError, pt as WorldNotFoundError, q as formatIssue, st as AgentUnavailableError, z as loadPlots } from "./hooks-YXQZ9G2d.js";
7
+ import { i as translator, r as languageOf } from "./text-hiKTooVb.js";
8
+ import { h as readImageFileMetadata, u as referenceImagePath, x as mapLimit } from "./library-BmlHNCah.js";
9
+ import { n as readPreset } from "./preset-C595KRUM.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-CzVh2ZNe.js";
11
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-CTWQWbSW.js";
12
12
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
13
13
  import { readTriggerDefinition, triggerReferenceProblems } from "@dsh-agentic-roleplay/state";
14
14
  import { existsSync, lstatSync, statSync } from "node:fs";
@@ -256,11 +256,16 @@ function agentServicesOf(ctx) {
256
256
  if (controller === void 0 || registry === void 0) throw new AgentUnavailableError("this DSH profile has no session services, so a roleplay chat cannot be opened");
257
257
  const persistence = ctx.get("sessionPersistence");
258
258
  const agents = ctx.get("agents");
259
+ const command = agents === void 0 ? void 0 : async (chat, line) => {
260
+ const live = agents.get(chat);
261
+ return live === void 0 ? void 0 : await runCommandLine(ctx, live, line, new AbortController().signal);
262
+ };
259
263
  return {
260
264
  controller,
261
265
  registry,
262
266
  ...persistence === void 0 ? {} : { persistence },
263
- ...agents === void 0 ? {} : { unload: unloader(ctx, agents) }
267
+ ...agents === void 0 ? {} : { unload: unloader(ctx, agents) },
268
+ ...command === void 0 ? {} : { command }
264
269
  };
265
270
  };
266
271
  }
@@ -373,9 +378,16 @@ var AgentSessions = class {
373
378
  }
374
379
  /** Says something in the chat of a session as the player would; it is queued behind what the chat is doing. The chat must exist (`ensure`). */
375
380
  async send(sessionId, text) {
376
- await this.services().controller.prompt({
381
+ const services = this.services();
382
+ const chat = chatSessionId(sessionId);
383
+ const ran = text.startsWith("/") ? await services.command?.(chat, text) : void 0;
384
+ if (ran !== void 0) {
385
+ if (ran.kind === "error") throw new CommandRefusedError(ran.text);
386
+ return;
387
+ }
388
+ await services.controller.prompt({
377
389
  requestId: randomUUID(),
378
- sessionId: chatSessionId(sessionId),
390
+ sessionId: chat,
379
391
  mode: "queue",
380
392
  content: [{
381
393
  type: "text",
@@ -460,11 +472,13 @@ var AuthoringSessions = class {
460
472
  roleplayRoot;
461
473
  prompts;
462
474
  languages;
463
- constructor(services, roleplayRoot, prompts, languages) {
475
+ beginImport;
476
+ constructor(services, roleplayRoot, prompts, languages, beginImport) {
464
477
  this.services = services;
465
478
  this.roleplayRoot = roleplayRoot;
466
479
  this.prompts = prompts;
467
480
  this.languages = languages;
481
+ this.beginImport = beginImport;
468
482
  }
469
483
  async ensure(worldId, worldName, title, language) {
470
484
  return await ensureAuthoringChat(this.services(), this.roleplayRoot(), this.prompts, this.languages, KIND, {
@@ -476,9 +490,22 @@ var AuthoringSessions = class {
476
490
  renameExisting: true
477
491
  });
478
492
  }
493
+ /** Has the chat import the card waiting in its world, as the `/import-st` command does. */
494
+ async startImport(sessionId, request) {
495
+ if (this.beginImport === void 0) throw new Error("imports cannot be started here");
496
+ const begun = await this.beginImport(sessionId, request);
497
+ if (!begun.ok) throw new Error(begun.reason);
498
+ await this.send(sessionId, begun.message);
499
+ }
479
500
  /** Sends a message into a chat as if the person had written it. */
480
501
  async send(sessionId, text) {
481
- await this.services().controller.prompt({
502
+ const services = this.services();
503
+ const ran = text.startsWith("/") ? await services.command?.(sessionId, text) : void 0;
504
+ if (ran !== void 0) {
505
+ if (ran.kind === "error") throw new CommandRefusedError(ran.text);
506
+ return;
507
+ }
508
+ await services.controller.prompt({
482
509
  requestId: randomUUID(),
483
510
  sessionId,
484
511
  mode: "queue",
@@ -862,6 +889,7 @@ const FIELDS$1 = {
862
889
  "opening_message[].text",
863
890
  "alternate_openings[].title",
864
891
  "alternate_openings[].text",
892
+ "alternate_openings[].parts[].text",
865
893
  "start_questions[].text",
866
894
  "start_questions[].options[].label",
867
895
  "start_questions[].options[].description",
@@ -3199,4 +3227,4 @@ function registerPackJail(ctx, deps) {
3199
3227
  }
3200
3228
  export { languageOfDocuments as $, generateWorldCharacterPortrait as A, deleteTriggerDocument as B, editWorldFaction as C, editWorldPlots as D, editWorldPlace as E, uploadWorldCharacterPortrait as F, parseVariablesEdit as G, writeTriggerDocument as H, uploadWorldEntityImage as I, PRESET_FILE as J, parseDiceEdit as K, worldCharacterPortraitFile as L, readWorldEditor as M, readWorldTrigger as N, editWorldRelation as O, removeWorldTrigger as P, translateTools as Q, worldEntityImageFile as R, editWorldCharacter as S, editWorldNarrationVoice as T, parseCalendarEdit as U, readTriggerDocuments as V, parseRoutineEdit as W, presetTools as X, presetMessage as Y, translateMessage as Z, readCalendarDocument as _, deleteWorldPackFile as a, startUpdate as at, readRoutines as b, createAuthoredEntity as c, authoringTitle as ct, replaceAuthoredEntity as d, agentServicesOf as dt, readWorldDocuments as et, editCalendar as f, DOCTOR_OPENING_SOURCE as ft, editVariables as g, editRoutine as h, checkWorldPack as i, revertUpdate as it, generateWorldEntityImage as j, editWorldThing as k, deleteAuthoredEntity as l, ensureAuthoringChat as lt, editDice as m, appendNarratedTurn as mt, packFileProblem as n, finishUpdate as nt, listWorldPacks as o, updateStatus as ot, editCommands as p, appendEmptyTurn as pt, parseCommandsEdit as q, registerPackJail as r, pendingUpdate as rt, AUTHORED_ENTITY_KINDS as s, AuthoringSessions as st, MAX_PACK_TEXT as t, findTargets as tt, readAuthoredEntityDocument as u, AgentSessions as ut, readCommandsDocument as v, editWorldLore as w, readVariables as x, readDiceDocument as y, writeWorldTrigger as z };
3201
3229
 
3202
- //# sourceMappingURL=pack-jail-Dt0VTsu0.js.map
3230
+ //# sourceMappingURL=pack-jail-VbcXiukr.js.map
@@ -1,4 +1,4 @@
1
- import { K as Reader } from "./hooks-Dtq5KZQX.js";
1
+ import { K as Reader } from "./hooks-YXQZ9G2d.js";
2
2
  import { dirname, extname, join, posix, sep } from "node:path";
3
3
  import { copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync } from "node:fs";
4
4
  import { createHash } from "node:crypto";
@@ -836,4 +836,4 @@ function anyTab(bases) {
836
836
  }
837
837
  export { API_PREFIX as _, packIds as a, describePack as c, packPath as d, readPack as f, SURFACE_NAMES as g, PACK_MEDIA_TYPES as h, inheritPacks as i, isPackId as l, PACK_LIMITS as m, anyTab as n, syncWorldPacks as o, PACK_ACTIONS as p, copyWorldPacks as r, worldPackStates as s, activePack as t, packFile as u };
838
838
 
839
- //# sourceMappingURL=packs-DWfR2Ted.js.map
839
+ //# sourceMappingURL=packs-CzVh2ZNe.js.map
@@ -1,8 +1,8 @@
1
1
  import { n as atomicWrite, t as promptFor } from "./access-Csp80TFX.js";
2
2
  import { l as runChild } from "./child-DTdY14S9.js";
3
- import { n as generateTransientImage, t as generateReferenceImage } from "./generator-9-5at9cZ.js";
4
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-BNg0rPTp.js";
5
- import { c as nextSceneSerial, u as referenceImagePath } from "./library-DTxakw0z.js";
3
+ import { n as generateTransientImage, t as generateReferenceImage } from "./generator-CTWQWbSW.js";
4
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-Bu6eZMKk.js";
5
+ import { c as nextSceneSerial, u as referenceImagePath } from "./library-BmlHNCah.js";
6
6
  import { join, relative, sep } from "node:path";
7
7
  import { characterKey, itemKey, locationKey } from "@dsh-agentic-roleplay/state";
8
8
  import { existsSync } from "node:fs";
@@ -844,4 +844,4 @@ async function runImagePresenter(job) {
844
844
  }
845
845
  export { searchImages as a, presentedFor as c, findImages as i, interpretImage as n, tokensOf as o, imageTools as r, present as s, runImagePresenter as t };
846
846
 
847
- //# sourceMappingURL=presenter-agent-vFOxIuWv.js.map
847
+ //# sourceMappingURL=presenter-agent-CF3fneuJ.js.map
@@ -1,6 +1,6 @@
1
- import { Rt as ImportCardError, r as MAX_PREVIEW_TEXT } from "./authoring-tools-BZr4bgBy.js";
1
+ import { Wt as ImportCardError, r as MAX_PREVIEW_TEXT } from "./authoring-tools-B_qYKK8c.js";
2
2
  import { p as SAMPLING_RANGES } from "./child-DTdY14S9.js";
3
- import { gt as cleanText } from "./serial-BUaJGwVy.js";
3
+ import { St as cleanText } from "./serial-ULGUKWsu.js";
4
4
  // src/host/import/preset.ts
5
5
  /** The older preset layout keeps its texts under fixed keys. */
6
6
  const LEGACY_KEYS = [
@@ -239,4 +239,4 @@ function selectPrompts(file, enabled, keepSampling) {
239
239
  }
240
240
  export { readPreset as n, selectPrompts as r, previewPreset as t };
241
241
 
242
- //# sourceMappingURL=preset-Dv5YF2qj.js.map
242
+ //# sourceMappingURL=preset-C595KRUM.js.map
@@ -1,9 +1,9 @@
1
1
  import "./access-Csp80TFX.js";
2
- import { $ as deleteWorldPrompt, K as presetDirectory, Q as PROSE_PROMPTS, Z as updatePresetInfo, bt as IMPORT_FOLDER, et as listWorldPrompts, l as extractStyleFrom, nt as writeWorldPrompt, q as readPreset, tt as readWorldPrompt, yt as withPlayer, z as PRESET_FILE } from "./serial-BUaJGwVy.js";
3
- import { n as readPreset$1 } from "./preset-Dv5YF2qj.js";
4
- import { i as contextOf } from "./authoring-tools-BZr4bgBy.js";
5
- import { i as translator, r as languageOf } from "./text-Dfv8S8eq.js";
6
- import { at as shippedPromptsDirectory, it as shippedLanguages, tt as languageOf$1 } from "./hooks-Dtq5KZQX.js";
2
+ import { Et as IMPORT_FOLDER, H as PRESET_FILE, Tt as withPlayer, X as readPreset, Y as presetDirectory, at as writeWorldPrompt, et as updatePresetInfo, it as readWorldPrompt, l as extractStyleFrom, nt as deleteWorldPrompt, rt as listWorldPrompts, tt as PROSE_PROMPTS } from "./serial-ULGUKWsu.js";
3
+ import { n as readPreset$1 } from "./preset-C595KRUM.js";
4
+ import { o as contextOf } from "./authoring-tools-B_qYKK8c.js";
5
+ import { i as translator, r as languageOf } from "./text-hiKTooVb.js";
6
+ import { at as shippedPromptsDirectory, it as shippedLanguages, tt as languageOf$1 } from "./hooks-YXQZ9G2d.js";
7
7
  import { join } from "node:path";
8
8
  import { existsSync } from "node:fs";
9
9
  import { readFile, rm } from "node:fs/promises";
@@ -279,4 +279,4 @@ async function presetApproval(exec, next, carries, auto = () => false) {
279
279
  }
280
280
  export { presetChatSessionId as a, presetAuthorTools as i, narrationImportMessage as n, presetOfChat as o, presetApproval as r, PresetReader as t };
281
281
 
282
- //# sourceMappingURL=preset-author-tools-BUzO9mTW.js.map
282
+ //# sourceMappingURL=preset-author-tools-CF_JKKTE.js.map
@@ -1,9 +1,9 @@
1
- import { n as limitAuthoringAgents } from "./authoring-tools-BZr4bgBy.js";
2
- import { t as guardAuthoringTurns } from "./turn-guard-87NE-Cnp.js";
1
+ import { n as limitAuthoringAgents } from "./authoring-tools-B_qYKK8c.js";
2
+ import { t as guardAuthoringTurns } from "./turn-guard-DXMeAJdv.js";
3
3
  import { n as silenceRuntimeContext, t as silenceHarnessDevContext } from "./dev-context-Cgv_wZbG.js";
4
- import { i as presetAuthorTools, o as presetOfChat, r as presetApproval, t as PresetReader } from "./preset-author-tools-BUzO9mTW.js";
5
- import "./hooks-Dtq5KZQX.js";
6
- import { K as presetDirectory } from "./serial-BUaJGwVy.js";
4
+ import { i as presetAuthorTools, o as presetOfChat, r as presetApproval, t as PresetReader } from "./preset-author-tools-CF_JKKTE.js";
5
+ import "./hooks-YXQZ9G2d.js";
6
+ import { Y as presetDirectory } from "./serial-ULGUKWsu.js";
7
7
  import { join } from "node:path";
8
8
  import { existsSync } from "node:fs";
9
9
  // src/preset-authoring.ts
@@ -1,10 +1,10 @@
1
1
  import { O as estimateAnswer, a as childTrace, j as roleplaySessionOf, l as runChild, n as childModel, r as childSampling } from "./child-DTdY14S9.js";
2
- import { A as routeVerdicts, D as mergeReports, E as askYesNo, G as loadPreset, T as announceProblem, W as listPresets, X as sha, j as yesAt, k as noAt, t as SerialQueue } from "./serial-BUaJGwVy.js";
2
+ import { $ as sha, A as routeVerdicts, D as mergeReports, E as askYesNo, J as loadPreset, T as announceProblem, j as yesAt, k as noAt, q as listPresets, t as SerialQueue } from "./serial-ULGUKWsu.js";
3
3
  import { t as promptFor } from "./access-Csp80TFX.js";
4
- import { D as referent, I as wrongLanguage, Z as PROMPTS_FOLDER, et as inheritPrompts, ht as describeWhen } from "./hooks-Dtq5KZQX.js";
5
- import { i as translator, r as languageOf } from "./text-Dfv8S8eq.js";
6
- import { s as inheritImages } from "./library-DTxakw0z.js";
7
- import { i as inheritPacks } from "./packs-DWfR2Ted.js";
4
+ import { D as referent, I as wrongLanguage, Z as PROMPTS_FOLDER, et as inheritPrompts, vt as describeWhen } from "./hooks-YXQZ9G2d.js";
5
+ import { i as translator, r as languageOf } from "./text-hiKTooVb.js";
6
+ import { s as inheritImages } from "./library-BmlHNCah.js";
7
+ import { i as inheritPacks } from "./packs-CzVh2ZNe.js";
8
8
  import { dirname, join } from "node:path";
9
9
  import { characterKey, locationKey, sessionDatabase, sessionFolder, tokens } from "@dsh-agentic-roleplay/state";
10
10
  import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
@@ -1504,4 +1504,4 @@ function memoryReflector(deps) {
1504
1504
  }
1505
1505
  export { snapshotOf as _, whereabouts as a, copyPreset as c, switchPreset as d, readTimeline as f, pathTo as g, childrenOf as h, reflectionStatus as i, presetStatus as l, START_SNAPSHOT as m, memoryReflector as n, TimelineError as o, writeTimeline as p, recordFailure as r, Timelines as s, dueReflection as t, recordPreset as u };
1506
1506
 
1507
- //# sourceMappingURL=reflection-Dd3pEiZB.js.map
1507
+ //# sourceMappingURL=reflection-ByIQSOKC.js.map