@dsh-agentic-roleplay/core 0.3.1 → 0.3.3

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 (39) hide show
  1. package/lib/authoring.js +13 -2
  2. package/lib/child-lPncV1ps.js +380 -0
  3. package/lib/client.js +1526 -356
  4. package/lib/client.js.map +1 -1
  5. package/lib/compaction.js +1 -1
  6. package/lib/deliver-De62a8i9.js +1929 -0
  7. package/lib/doctor-chat-ByDfCMeo.js +17 -0
  8. package/lib/doctor.js +95 -0
  9. package/lib/{documents-DtlY2IRt.js → documents-Do4lz4SB.js} +549 -64
  10. package/lib/{gallery-DACG5eh2.js → gallery-CtFDL22W.js} +2 -2
  11. package/lib/{generator-DGYcLMp7.js → generator-B6FxlKOV.js} +2 -378
  12. package/lib/hooks-Ka22sFNy.js +1019 -0
  13. package/lib/images.js +3 -3
  14. package/lib/index.js +303 -190
  15. package/lib/language-DWVwi1R7.js +520 -0
  16. package/lib/narration-DK2kiIjE.js +141 -0
  17. package/lib/orchestration.js +777 -2542
  18. package/lib/{packs-CkRZDCsV.js → packs-BYjrAen6.js} +4 -518
  19. package/lib/{presenter-agent-PK9JYExk.js → presenter-agent-Dt21K96b.js} +4 -3
  20. package/lib/{deliver-BDW5WZvc.js → reflection-md7BCYCl.js} +350 -769
  21. package/lib/{narration-5ig7Dg28.js → settings-CA6icLL_.js} +156 -141
  22. package/package.json +3 -2
  23. package/prompts/en/doctor/persona.md +1 -0
  24. package/prompts/en/doctor/procedure.md +5 -0
  25. package/prompts/en/doctor/welcome.md +1 -0
  26. package/prompts/en/import/character.md +1 -0
  27. package/prompts/en/roleplay/dice.md +7 -0
  28. package/prompts/en/roleplay/game-master.md +2 -0
  29. package/prompts/en/roleplay/reflection-check.md +5 -0
  30. package/prompts/en/roleplay/reflection.md +5 -1
  31. package/prompts/zh/doctor/persona.md +1 -0
  32. package/prompts/zh/doctor/procedure.md +5 -0
  33. package/prompts/zh/doctor/welcome.md +1 -0
  34. package/prompts/zh/import/character.md +1 -0
  35. package/prompts/zh/roleplay/dice.md +7 -0
  36. package/prompts/zh/roleplay/game-master.md +2 -0
  37. package/prompts/zh/roleplay/reflection-check.md +5 -0
  38. package/prompts/zh/roleplay/reflection.md +5 -1
  39. package/lib/src-CWTNeL6Y.js +0 -128
package/lib/index.js CHANGED
@@ -1,18 +1,21 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf } from "./access-EbNdZFbk.js";
2
- import { $ as subfolders, B as populateLore, Ct as parseThingEdit, D as authoringChatSessionId, F as populateClock, G as TRIGGERS_FILE_NAME, H as populateTriggers, I as populateFactions, J as parseCalendarFile, K as CALENDAR_FILE_NAME, L as populateItems, M as loadValidatedWorld, N as populateCalendar, O as languageOfDocuments, P as populateCharacters, Q as loadCharacters, R as populateKnowledge, S as translateMessage, St as parseRelationEdit, U as populateVariables, V as populateRoutines, W as routineProblems, X as loadItems, Y as loadLocations, Z as CHARACTERS_DIR, _ as replaceFile$1, _t as InvalidEditProblems, at as VARIABLES_FILE_NAME, bt as parseLoreEdit, c as editWorldLore$1, ct as CHARACTER_FILE_NAME, d as editWorldPlots$1, dt as ImportNotFoundError, f as editWorldRelation$1, ft as ImportStore, g as readWorldEditor, gt as parseWorldInfoEdit, h as generateWorldCharacterPortrait, ht as parseWorldFile, i as readAuthoredEntityDocument, it as writeWorldPrompt, j as markReady, k as readWorldDocuments, l as editWorldNarrationVoice, lt as parseCharacterFile, m as entityFolder, mt as WORLD_FILE_NAME, n as createAuthoredEntity, nt as listWorldPrompts, o as editWorldCharacter$1, ot as parseVariablesFile, p as editWorldThing$1, pt as parseChoices, q as loadCalendar, r as deleteAuthoredEntity, rt as readWorldPrompt, s as editWorldFaction$1, st as variableProblems, tt as deleteWorldPrompt, u as editWorldPlace$1, ut as IMPORT_FOLDER, v as uploadWorldCharacterPortrait, vt as parseCharacterEdit, wt as IMPORT_COMMAND, x as loadWorldParts, xt as parsePlaceEdit, y as worldCharacterPortraitFile, yt as parseFactionEdit, z as populateLocations } from "./documents-DtlY2IRt.js";
3
- import { A as formatIssue, D as readDocument$1, E as plotReferenceProblems, F as languageOf, G as SessionArchivedError, H as InvalidStartError, K as SessionNotFoundError, M as PromptLibrary, N as copyWorldPrompts, O as errorMessage, T as parsePlotsFile, U as InvalidWorldError, V as AgentUnavailableError, W as ReflectionRefusedError, _ as API_PREFIX, a as packIds, c as describePack, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, q as WorldNotFoundError, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-CkRZDCsV.js";
4
- import { A as readTimeline, C as notesOfSession, E as observeAsPlayer, M as defaultBoundaries, O as TimelineError, T as readNotes, V as zoneOf, a as readActivity, d as reflectionStatus, j as pathTo, n as readWithdrawn, o as readRunDetail, p as PLOTS_METADATA_KEY, v as plotProgressOf, x as addToNote, y as populatePlots } from "./deliver-BDW5WZvc.js";
5
- import { a as liveSettings, c as writeSettings, d as parseSettings, f as WORLD_RULES_KEY, i as InvalidSettingsError, l as DEFAULT_SETTINGS, n as encodeOutput, o as readSettings, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-5ig7Dg28.js";
6
- import { n as VARIABLE_SUBJECTS, r as VARIABLE_VISIBILITIES, t as VARIABLE_KINDS } from "./src-CWTNeL6Y.js";
7
- import { O as childSamplingOf, T as uniqueKey, a as uploadReferenceImage, m as sceneImagePath, o as addToLibrary, p as referenceImagePath, t as generateReferenceImage, u as inheritImages, w as slug } from "./generator-DGYcLMp7.js";
8
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-DACG5eh2.js";
2
+ import { $ as parseDiceFile, At as parsePlaceEdit, B as populateDice, Bt as DICE_RESULTS, C as presetMessage, Ct as WORLD_FILE_NAME, Dt as parseCharacterEdit, E as translateMessage, Et as InvalidEditProblems, F as markReady, Ft as isPng, G as populateLore, H as populateItems, I as loadValidatedWorld, It as pictureOf, J as populateVariables, K as populateRoutines, L as populateCalendar, Lt as readCard, M as languageOfDocuments, Mt as parseThingEdit, N as readWorldDocuments, Nt as IMPORT_COMMAND, Ot as parseFactionEdit, Pt as ImportCardError, Q as loadDice, R as populateCharacters, Rt as DICE_COMPARISONS, S as PRESET_FILE, St as parseChoices, T as readPreset, Tt as parseWorldInfoEdit, U as populateKnowledge, V as populateFactions, W as populateLocations, X as TRIGGERS_FILE_NAME, Y as routineProblems, Z as DICE_FILE_NAME, _ as replaceFile$1, _t as CHARACTER_FILE_NAME, at as CHARACTERS_DIR, bt as ImportNotFoundError, c as editWorldLore$1, d as editWorldPlots$1, dt as readWorldPrompt, et as CALENDAR_FILE_NAME, f as editWorldRelation$1, ft as writeWorldPrompt, g as readWorldEditor, gt as variableProblems, h as generateWorldCharacterPortrait, ht as parseVariablesFile, i as readAuthoredEntityDocument, it as loadItems, j as authoringChatSessionId, jt as parseRelationEdit, kt as parseLoreEdit, l as editWorldNarrationVoice, lt as deleteWorldPrompt, m as entityFolder, mt as loadVariables, n as createAuthoredEntity, nt as parseCalendarFile, o as editWorldCharacter$1, ot as loadCharacters, p as editWorldThing$1, pt as VARIABLES_FILE_NAME, q as populateTriggers, r as deleteAuthoredEntity, rt as loadLocations, s as editWorldFaction$1, st as subfolders, tt as loadCalendar, u as editWorldPlace$1, ut as listWorldPrompts, v as uploadWorldCharacterPortrait, vt as parseCharacterFile, wt as parseWorldFile, x as loadWorldParts, xt as ImportStore, y as worldCharacterPortraitFile, yt as IMPORT_FOLDER, z as populateClock, zt as DICE_READINGS } from "./documents-Do4lz4SB.js";
3
+ import { _ as API_PREFIX, a as packIds, c as describePack, 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-BYjrAen6.js";
4
+ import { c as readTimeline, i as reflectionStatus, l as pathTo, o as TimelineError, u as defaultBoundaries } from "./reflection-md7BCYCl.js";
5
+ import { a as WORLD_RULES_KEY, c as VARIABLE_SUBJECTS, i as parseSwitchboard, l as VARIABLE_VISIBILITIES, n as SETTINGS_SPEC, r as parseSettings, s as VARIABLE_KINDS, t as DEFAULT_SETTINGS } from "./settings-CA6icLL_.js";
6
+ import { A as WorldNotFoundError, D as ReflectionRefusedError, E as InvalidWorldError, O as SessionArchivedError, T as InvalidStartError, c as parsePlotsFile, d as errorMessage, g as copyWorldPrompts, h as PromptLibrary, k as SessionNotFoundError, l as plotReferenceProblems, p as formatIssue, u as readDocument$1, v as languageOf, w as AgentUnavailableError } from "./language-DWVwi1R7.js";
7
+ import { C as addToNote, D as readNotes, L as zoneOf, O as observeAsPlayer, T as notesOfSession, _ as plotProgressOf, a as readActivity, l as externalTools, n as readWithdrawn, o as readRunDetail, p as PLOTS_METADATA_KEY, v as populatePlots } from "./deliver-De62a8i9.js";
8
+ import { a as liveSettings, c as writeSettings, i as InvalidSettingsError, n as encodeOutput, o as readSettings, s as useChildReasoning } from "./narration-DK2kiIjE.js";
9
+ import { r as childSamplingOf } from "./child-lPncV1ps.js";
10
+ import { T as uniqueKey, a as uploadReferenceImage, m as sceneImagePath, o as addToLibrary, p as referenceImagePath, t as generateReferenceImage, u as inheritImages, w as slug } from "./generator-B6FxlKOV.js";
11
+ import { t as doctorChatSessionId } from "./doctor-chat-ByDfCMeo.js";
12
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-CtFDL22W.js";
9
13
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
10
14
  import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
11
15
  import { createHash, randomBytes, randomUUID } from "node:crypto";
12
16
  import { Session, SessionId } from "@deepseek-ai/dsh-session";
13
17
  import { ToolCallId, createMessage, createSystemMessage, createToolResultMessage } from "@deepseek-ai/dsh-llm";
14
18
  import { setApprovalPolicy } from "@deepseek-ai/dsh-user-approval";
15
- import { inflateSync } from "node:zlib";
16
19
  import { fileURLToPath } from "node:url";
17
20
  import { Service } from "@deepseek-ai/cordis";
18
21
  import { chmod, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
@@ -30,6 +33,10 @@ const AUTHORING_OPENING_SOURCE = {
30
33
  provider: "world-authoring",
31
34
  model: "opening"
32
35
  };
36
+ const DOCTOR_OPENING_SOURCE = {
37
+ provider: "session-doctor",
38
+ model: "opening"
39
+ };
33
40
  const NARRATE_TOOL = "narrate";
34
41
  /**
35
42
  * The first node of a conversation's surface is the system prompt, even an empty one: the log format refuses a system prompt that
@@ -124,7 +131,7 @@ function openingEvents(segments) {
124
131
  return session.snapshotEvents();
125
132
  }
126
133
  /** A visible first turn makes a newly created authoring chat a full conversation immediately. */
127
- function authoringOpeningEvents(welcome) {
134
+ function authoringOpeningEvents(welcome, source = AUTHORING_OPENING_SOURCE) {
128
135
  const session = Session.create(SessionId("authoring-opening"));
129
136
  setApprovalPolicy(session, "ask");
130
137
  const turn = 1;
@@ -147,7 +154,7 @@ function authoringOpeningEvents(welcome) {
147
154
  }],
148
155
  source: {
149
156
  kind: "model",
150
- ...AUTHORING_OPENING_SOURCE
157
+ ...source
151
158
  }
152
159
  })
153
160
  }, { surfaceOp: "append" });
@@ -172,6 +179,9 @@ async function storeOpening(persistence, chat, segments) {
172
179
  async function storeAuthoringOpening(persistence, chat, welcome) {
173
180
  await storeInitialEvents(persistence, chat, authoringOpeningEvents(welcome));
174
181
  }
182
+ async function storeDoctorOpening(persistence, chat, welcome) {
183
+ await storeInitialEvents(persistence, chat, authoringOpeningEvents(welcome, DOCTOR_OPENING_SOURCE));
184
+ }
175
185
  async function storeInitialEvents(persistence, chat, events) {
176
186
  const header = {
177
187
  version: 4,
@@ -312,179 +322,6 @@ var AgentSessions = class {
312
322
  }
313
323
  };
314
324
  //#endregion
315
- //#region src/host/import/card.ts
316
- /** The file is not a character card this importer reads. The message says why, for the person who uploaded it. */
317
- var ImportCardError = class extends Error {};
318
- const PNG_SIGNATURE = Buffer.from([
319
- 137,
320
- 80,
321
- 78,
322
- 71,
323
- 13,
324
- 10,
325
- 26,
326
- 10
327
- ]);
328
- const TEXT_CHUNKS = /* @__PURE__ */ new Set([
329
- "tEXt",
330
- "iTXt",
331
- "zTXt"
332
- ]);
333
- /** The keywords a card's data is stored under, the newer one first. */
334
- const CARD_KEYWORDS = ["ccv3", "chara"];
335
- function chunksOf(file) {
336
- const chunks = [];
337
- let at = PNG_SIGNATURE.length;
338
- while (at + 12 <= file.length) {
339
- const length = file.readUInt32BE(at);
340
- const end = at + 12 + length;
341
- if (end > file.length) throw new ImportCardError("the PNG file is damaged: a part of it is cut off");
342
- chunks.push({
343
- type: file.toString("latin1", at + 4, at + 8),
344
- data: file.subarray(at + 8, at + 8 + length),
345
- raw: file.subarray(at, end)
346
- });
347
- at = end;
348
- }
349
- return chunks;
350
- }
351
- /** The keyword and text of a PNG text chunk. */
352
- function textOf$1(chunk) {
353
- const end = chunk.data.indexOf(0);
354
- if (end < 0) return void 0;
355
- const keyword = chunk.data.toString("latin1", 0, end);
356
- const rest = chunk.data.subarray(end + 1);
357
- if (chunk.type === "tEXt") return {
358
- keyword,
359
- text: rest.toString("latin1")
360
- };
361
- if (chunk.type === "zTXt") return {
362
- keyword,
363
- text: inflateSync(rest.subarray(1)).toString("latin1")
364
- };
365
- const compressed = rest[0] === 1;
366
- let from = 2;
367
- for (let skipped = 0; skipped < 2; skipped += 1) from = rest.indexOf(0, from) + 1;
368
- if (from <= 0) return void 0;
369
- const body = rest.subarray(from);
370
- return {
371
- keyword,
372
- text: (compressed ? inflateSync(body) : body).toString("utf8")
373
- };
374
- }
375
- /** The PNG without its text chunks: the picture, with none of the card's data in it. */
376
- function pictureOf(file) {
377
- return Buffer.concat([PNG_SIGNATURE, ...chunksOf(file).filter((chunk) => !TEXT_CHUNKS.has(chunk.type)).map((chunk) => chunk.raw)]);
378
- }
379
- function jsonOf(file, name) {
380
- if (file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) {
381
- const found = /* @__PURE__ */ new Map();
382
- for (const chunk of chunksOf(file)) {
383
- if (!TEXT_CHUNKS.has(chunk.type)) continue;
384
- const text = textOf$1(chunk);
385
- if (text !== void 0 && CARD_KEYWORDS.includes(text.keyword) && !found.has(text.keyword)) found.set(text.keyword, text.text);
386
- }
387
- const keyword = CARD_KEYWORDS.find((candidate) => found.has(candidate));
388
- if (keyword === void 0) throw new ImportCardError(`${name} is a PNG picture with no character card in it`);
389
- try {
390
- return JSON.parse(Buffer.from(found.get(keyword).trim(), "base64").toString("utf8"));
391
- } catch {
392
- throw new ImportCardError(`the card data in ${name} is not readable`);
393
- }
394
- }
395
- try {
396
- return JSON.parse(file.toString("utf8").replace(/^/, ""));
397
- } catch {
398
- throw new ImportCardError(`${name} is neither a PNG picture with a card in it nor a JSON card`);
399
- }
400
- }
401
- const URL_PATTERN = /https?:\/\/[^\s"'`<>()[\]{}\\|^]+/gi;
402
- /** Every web address in the strings of a document, at any depth; template placeholders and trailing punctuation are not part of one. */
403
- function urlsOf(value) {
404
- const found = /* @__PURE__ */ new Set();
405
- const visit = (node, depth) => {
406
- if (depth > 32) return;
407
- if (typeof node === "string") for (const match of node.matchAll(URL_PATTERN)) {
408
- const url = match[0].replace(/[.,;:!?*_~]+$/, "");
409
- if (!url.includes("$") && url.length <= 2e3) found.add(url);
410
- }
411
- else if (Array.isArray(node)) for (const entry of node) visit(entry, depth + 1);
412
- else if (typeof node === "object" && node !== null) for (const entry of Object.values(node)) visit(entry, depth + 1);
413
- };
414
- visit(value, 0);
415
- return [...found];
416
- }
417
- const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
418
- const text = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
419
- const texts = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" ? [entry] : typeof entry === "number" ? [String(entry)] : []) : [];
420
- function entryOf(value, index) {
421
- const entry = object(value);
422
- if (entry === void 0) return void 0;
423
- const position = entry["position"];
424
- return {
425
- id: `entry:${index}`,
426
- title: text(entry["comment"]).trim() || text(entry["name"]).trim(),
427
- keys: texts(entry["keys"]),
428
- secondaryKeys: texts(entry["secondary_keys"]),
429
- content: text(entry["content"]),
430
- enabled: entry["enabled"] !== false,
431
- constant: entry["constant"] === true,
432
- selective: entry["selective"] === true,
433
- position: typeof position === "string" ? position : typeof position === "number" ? String(position) : ""
434
- };
435
- }
436
- /**
437
- * Reads a character card: a PNG with the card in its text chunk (the newer `ccv3` chunk when there is one), or the JSON of a card.
438
- * Only V2 and V3 cards are read; a V2 card is carried over into the V3 shape, whose fields are a superset.
439
- * @throws {ImportCardError} when the file is not such a card.
440
- */
441
- function readCard(file, name) {
442
- const root = object(jsonOf(file, name));
443
- const spec = root === void 0 ? void 0 : root["spec"];
444
- if (spec !== "chara_card_v2" && spec !== "chara_card_v3") throw new ImportCardError(spec === void 0 ? `${name} is not a V2 or V3 character card (it has no "spec")` : `${name} is a "${text(spec)}" card: only V2 and V3 cards are read`);
445
- const data = object(root?.["data"]);
446
- if (data === void 0) throw new ImportCardError(`${name} has no card data`);
447
- const cardName = text(data["name"]).trim();
448
- if (cardName === "") throw new ImportCardError(`${name} has a card with no name`);
449
- const book = object(data["character_book"]);
450
- const entries = Array.isArray(book?.["entries"]) ? book["entries"].flatMap((entry, index) => entryOf(entry, index) ?? []) : [];
451
- const extensions = object(data["extensions"]) ?? {};
452
- const scripts = [extensions["regex_scripts"], object(extensions["tavern_helper"])?.["scripts"]].reduce((count, list) => count + (Array.isArray(list) ? list.length : 0), 0);
453
- return {
454
- sourceSpec: spec,
455
- name: cardName,
456
- description: text(data["description"]),
457
- personality: text(data["personality"]),
458
- scenario: text(data["scenario"]),
459
- firstMessage: text(data["first_mes"]),
460
- alternateGreetings: texts(data["alternate_greetings"]),
461
- messageExample: text(data["mes_example"]),
462
- creatorNotes: text(data["creator_notes"]),
463
- systemPrompt: text(data["system_prompt"]),
464
- postHistoryInstructions: text(data["post_history_instructions"]),
465
- tags: texts(data["tags"]),
466
- creator: text(data["creator"]),
467
- characterVersion: text(data["character_version"]),
468
- ...book === void 0 ? {} : { book: {
469
- name: text(book["name"]),
470
- description: text(book["description"]),
471
- entries
472
- } },
473
- ignored: {
474
- scripts,
475
- extensions: Object.keys(extensions).filter((key) => ![
476
- "talkativeness",
477
- "fav",
478
- "world",
479
- "depth_prompt"
480
- ].includes(key))
481
- },
482
- urls: urlsOf(data)
483
- };
484
- }
485
- /** Whether a file looks like a PNG, so that its picture can be kept. */
486
- const isPng = (file) => file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE);
487
- //#endregion
488
325
  //#region src/host/worlds/authoring-language.ts
489
326
  /**
490
327
  * The language the person was using when they last worked on a world with the authoring assistant. The assistant's instructions
@@ -648,6 +485,32 @@ async function startTranslation(deps, id, to, title, language) {
648
485
  }
649
486
  }
650
487
  //#endregion
488
+ //#region src/host/import/upload-preset.ts
489
+ /**
490
+ * Keeps an uploaded narration preset in the world's import folder and has the world's authoring chat apply it, which asks the person before it changes a prompt.
491
+ * @throws {ImportCardError} when the file is not a preset. @throws {WorldNotFoundError} when the world does not exist.
492
+ */
493
+ async function uploadPreset(deps, worldId, file, name, language) {
494
+ const world = await deps.worlds.find(worldId);
495
+ if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
496
+ const preset = readPreset(file, name);
497
+ await mkdir(join(world.directory, IMPORT_FOLDER), { recursive: true });
498
+ await writeFile(join(world.directory, IMPORT_FOLDER, PRESET_FILE), file);
499
+ const chatSessionId = await deps.authoring.ensure(world.summary.id, world.summary.name, `Authoring ${world.summary.name}`, language);
500
+ let failure;
501
+ try {
502
+ await deps.authoring.send(chatSessionId, presetMessage());
503
+ } catch (error) {
504
+ failure = error instanceof Error ? error.message : String(error);
505
+ }
506
+ return {
507
+ chatSessionId,
508
+ preset: preset.name,
509
+ started: failure === void 0,
510
+ ...failure === void 0 ? {} : { failure }
511
+ };
512
+ }
513
+ //#endregion
651
514
  //#region src/host/agent/authoring-sessions.ts
652
515
  const AUTHORING_PROJECT_TITLE = "World Authoring";
653
516
  const AUTHORING_AGENT_PRESET = "world-authoring";
@@ -702,6 +565,42 @@ var AuthoringSessions = class {
702
565
  }
703
566
  };
704
567
  //#endregion
568
+ //#region src/host/agent/doctor-sessions.ts
569
+ const DOCTOR_PROJECT_TITLE = "Session Doctor";
570
+ const DOCTOR_AGENT_PRESET = "session-doctor";
571
+ /** Creates or reopens the chat in which a bystander reads one session's records and proposes fixes. */
572
+ var DoctorSessions = class {
573
+ services;
574
+ roleplayRoot;
575
+ prompts;
576
+ constructor(services, roleplayRoot, prompts) {
577
+ this.services = services;
578
+ this.roleplayRoot = roleplayRoot;
579
+ this.prompts = prompts;
580
+ }
581
+ async ensure(session, title, language) {
582
+ const services = this.services();
583
+ const projectPath = join(this.roleplayRoot(), "sessions");
584
+ const project = await services.registry.create(projectPath, DOCTOR_PROJECT_TITLE);
585
+ const sessionId = doctorChatSessionId(session.id);
586
+ if (!project.sessionIds.includes(sessionId) && !await isStored(services.persistence, sessionId)) {
587
+ if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of a session doctor chat");
588
+ await storeDoctorOpening(services.persistence, {
589
+ id: sessionId,
590
+ cwd: project.path,
591
+ agentPreset: DOCTOR_AGENT_PRESET
592
+ }, this.prompts.text("doctor/welcome", language, { session: session.name }));
593
+ }
594
+ return await ensureAgentChat(services, {
595
+ projectPath,
596
+ projectTitle: DOCTOR_PROJECT_TITLE,
597
+ sessionId,
598
+ agentPreset: DOCTOR_AGENT_PRESET,
599
+ title
600
+ }, project);
601
+ }
602
+ };
603
+ //#endregion
705
604
  //#region src/host/orchestration/service.ts
706
605
  /**
707
606
  * The extension points of a roleplay turn. Another plugin changes how the turn
@@ -740,6 +639,96 @@ var RoleplayOrchestration = class extends Service {
740
639
  }
741
640
  };
742
641
  //#endregion
642
+ //#region src/shared/world-dice.ts
643
+ const isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
644
+ const CHECK_FIELDS = [
645
+ "key",
646
+ "name",
647
+ "use",
648
+ "dice",
649
+ "reading",
650
+ "hit",
651
+ "compare",
652
+ "modifier",
653
+ "bands"
654
+ ];
655
+ const BAND_FIELDS = [
656
+ "min",
657
+ "max",
658
+ "label",
659
+ "result",
660
+ "critical"
661
+ ];
662
+ /** Reads a body that came from the browser: the shape of every field is checked here, and what the checks mean when the world is validated. */
663
+ function parseDiceEdit(value) {
664
+ const problems = [];
665
+ if (!isObject$1(value) || !Array.isArray(value["checks"])) throw new InvalidEditProblems(["the dice must be { checks: [...] }"]);
666
+ const checks = value["checks"].map((entry, index) => {
667
+ const at = `checks[${index}]`;
668
+ const empty = {
669
+ key: "",
670
+ name: "",
671
+ use: "",
672
+ dice: "",
673
+ bands: []
674
+ };
675
+ if (!isObject$1(entry)) {
676
+ problems.push(`${at} must be an object`);
677
+ return empty;
678
+ }
679
+ for (const key of Object.keys(entry)) if (!CHECK_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a check`);
680
+ for (const key of [
681
+ "key",
682
+ "name",
683
+ "use",
684
+ "dice"
685
+ ]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
686
+ if (entry["reading"] !== void 0 && !DICE_READINGS.includes(entry["reading"])) problems.push(`${at}.reading must be one of: ${DICE_READINGS.join(", ")}`);
687
+ if (entry["compare"] !== void 0 && !DICE_COMPARISONS.includes(entry["compare"])) problems.push(`${at}.compare must be one of: ${DICE_COMPARISONS.join(", ")}`);
688
+ if (entry["hit"] !== void 0 && (typeof entry["hit"] !== "number" || !Number.isInteger(entry["hit"]))) problems.push(`${at}.hit must be a whole number`);
689
+ if (entry["modifier"] !== void 0 && typeof entry["modifier"] !== "string") problems.push(`${at}.modifier must be text`);
690
+ const bands = Array.isArray(entry["bands"]) ? entry["bands"] : void 0;
691
+ if (bands === void 0) problems.push(`${at}.bands must be a list`);
692
+ const text = (field) => typeof field === "string" ? field.trim() : "";
693
+ const hit = entry["hit"];
694
+ return {
695
+ key: text(entry["key"]),
696
+ name: text(entry["name"]),
697
+ use: text(entry["use"]),
698
+ dice: text(entry["dice"]),
699
+ ...entry["reading"] === void 0 ? {} : { reading: entry["reading"] },
700
+ ...typeof hit === "number" ? { hit } : {},
701
+ ...entry["compare"] === void 0 ? {} : { compare: entry["compare"] },
702
+ ...text(entry["modifier"]) === "" ? {} : { modifier: text(entry["modifier"]) },
703
+ bands: (bands ?? []).map((band, bandIndex) => {
704
+ const where = `${at}.bands[${bandIndex}]`;
705
+ if (!isObject$1(band)) {
706
+ problems.push(`${where} must be an object`);
707
+ return {
708
+ label: "",
709
+ result: "failed"
710
+ };
711
+ }
712
+ for (const key of Object.keys(band)) if (!BAND_FIELDS.includes(key)) problems.push(`${where}.${key} is not a field of a band`);
713
+ for (const key of ["min", "max"]) if (band[key] !== void 0 && (typeof band[key] !== "number" || !Number.isFinite(band[key]))) problems.push(`${where}.${key} must be a number`);
714
+ if (typeof band["label"] !== "string") problems.push(`${where}.label must be text`);
715
+ if (!DICE_RESULTS.includes(band["result"])) problems.push(`${where}.result must be one of: ${DICE_RESULTS.join(", ")}`);
716
+ const min = band["min"];
717
+ const max = band["max"];
718
+ return {
719
+ label: text(band["label"]),
720
+ result: band["result"],
721
+ ...typeof min === "number" ? { min } : {},
722
+ ...typeof max === "number" ? { max } : {},
723
+ ...band["critical"] === true ? { critical: true } : {}
724
+ };
725
+ })
726
+ };
727
+ });
728
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
729
+ return { checks };
730
+ }
731
+ //#endregion
743
732
  //#region src/shared/world-daily.ts
744
733
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
745
734
  const ROUTINE_FIELDS = [
@@ -1842,7 +1831,7 @@ function languageField(value) {
1842
1831
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
1843
1832
  }
1844
1833
  }
1845
- function createApiHandler({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, connection, speech }) {
1834
+ function createApiHandler({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, connection, speech, externalTools }) {
1846
1835
  const routes = {
1847
1836
  "/speech/capabilities": { GET: async (_req, res) => {
1848
1837
  sendJson(res, 200, { streaming: speech.streaming() });
@@ -1907,6 +1896,15 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
1907
1896
  return importFailure(res, error);
1908
1897
  }
1909
1898
  } },
1899
+ "/worlds/import/preset": { POST: async (req, res, url) => {
1900
+ const name = decodeURIComponent(String(req.headers["x-file-name"] ?? url.searchParams.get("name") ?? "preset"));
1901
+ try {
1902
+ sendJson(res, 200, await importer.uploadPreset(url.searchParams.get("id") ?? "", await readBinaryBody(req, importer.maxUploadBytes), name, languageField(url.searchParams.get("language") ?? void 0)));
1903
+ } catch (error) {
1904
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
1905
+ return importFailure(res, error);
1906
+ }
1907
+ } },
1910
1908
  "/worlds/import": {
1911
1909
  GET: async (_req, res, url) => {
1912
1910
  try {
@@ -2168,6 +2166,28 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
2168
2166
  throw error;
2169
2167
  }
2170
2168
  } },
2169
+ "/worlds/dice": {
2170
+ GET: async (_req, res, url) => {
2171
+ try {
2172
+ sendJson(res, 200, await worldFiles.dice(url.searchParams.get("id") ?? ""));
2173
+ } catch (error) {
2174
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2175
+ throw error;
2176
+ }
2177
+ },
2178
+ PUT: async (req, res, url) => {
2179
+ try {
2180
+ sendJson(res, 200, await worldFiles.editDice(url.searchParams.get("id") ?? "", parseDiceEdit(await readJsonBody(req))));
2181
+ } catch (error) {
2182
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2183
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2184
+ message: error.message,
2185
+ problems: error.problems
2186
+ });
2187
+ throw error;
2188
+ }
2189
+ }
2190
+ },
2171
2191
  "/worlds/calendar": {
2172
2192
  GET: async (_req, res, url) => {
2173
2193
  try {
@@ -2498,6 +2518,9 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
2498
2518
  }
2499
2519
  await sendImage(res, image);
2500
2520
  } },
2521
+ "/tools": { GET: async (_req, res) => {
2522
+ sendJson(res, 200, { tools: externalTools?.() ?? [] });
2523
+ } },
2501
2524
  "/sessions/settings": {
2502
2525
  GET: async (_req, res, url) => {
2503
2526
  try {
@@ -2689,6 +2712,17 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
2689
2712
  throw error;
2690
2713
  }
2691
2714
  } },
2715
+ "/sessions/doctor": { POST: async (req, res, url) => {
2716
+ const body = await readJsonBody(req);
2717
+ if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
2718
+ try {
2719
+ sendJson(res, 200, await sessions.doctor(url.searchParams.get("id") ?? "", body.title.trim(), languageField(body.language) ?? "en"));
2720
+ } catch (error) {
2721
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2722
+ if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
2723
+ throw error;
2724
+ }
2725
+ } },
2692
2726
  "/sessions/reflect": { POST: async (_req, res, url) => {
2693
2727
  try {
2694
2728
  await sessions.reflect(url.searchParams.get("id") ?? "");
@@ -2811,6 +2845,7 @@ function registerApi(ctx, deps) {
2811
2845
  async function deleteSession(deps, id) {
2812
2846
  const directory = deps.sessionsDir();
2813
2847
  if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
2848
+ await deps.purgeChat(doctorChatSessionId(id));
2814
2849
  await deps.purgeChat(chatSessionId(id));
2815
2850
  deps.state.deleteSession(directory, id);
2816
2851
  }
@@ -3085,6 +3120,36 @@ async function editCalendar(world, calendar) {
3085
3120
  else await replaceFileOrCreate(join(world.directory, CALENDAR_FILE_NAME), text);
3086
3121
  return await readCalendarDocument(world);
3087
3122
  }
3123
+ /** The checks of a world as its `dice.json` has them; none without the file. */
3124
+ async function readDiceDocument(world) {
3125
+ const { checks } = await loadDice(world.directory);
3126
+ return { checks };
3127
+ }
3128
+ /**
3129
+ * Replaces the world's checks. They are read as a story start reads them, and a quality of the character that a check adds must be a number the world
3130
+ * declares for characters. No checks is no file at all.
3131
+ * @throws {InvalidEditProblems} naming each problem; nothing is written.
3132
+ */
3133
+ async function editDice(world, dice) {
3134
+ const written = dice.checks.map(({ reading, compare, ...check }) => ({
3135
+ ...check,
3136
+ ...reading === void 0 || reading === "total" ? {} : { reading },
3137
+ ...compare === void 0 || compare === "absolute" ? {} : { compare }
3138
+ }));
3139
+ const text = `${JSON.stringify({ checks: written }, null, 2)}\n`;
3140
+ const parsed = parseDiceFile(text);
3141
+ if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
3142
+ const declared = await loadVariables(world.directory);
3143
+ const problems = parsed.value.flatMap((check) => {
3144
+ if (check.modifier === void 0) return [];
3145
+ const variable = declared.defs.find((def) => def.key === check.modifier);
3146
+ return variable === void 0 || variable.kind !== "number" || variable.subject !== "character" ? [`the check "${check.key}" adds "${check.modifier}", which the world does not declare as a number about characters (Tracked values)`] : [];
3147
+ });
3148
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
3149
+ if (dice.checks.length === 0) await rm(join(world.directory, DICE_FILE_NAME), { force: true });
3150
+ else await replaceFileOrCreate(join(world.directory, DICE_FILE_NAME), text);
3151
+ return await readDiceDocument(world);
3152
+ }
3088
3153
  //#endregion
3089
3154
  //#region src/host/worlds/lore-entries.ts
3090
3155
  const MAX_TITLE = 200;
@@ -3905,6 +3970,10 @@ async function replaceFile(file, text) {
3905
3970
  }
3906
3971
  }
3907
3972
  const textOf = (value) => typeof value === "string" ? value : "";
3973
+ const toolsOf = (value) => {
3974
+ const board = value === void 0 ? {} : parseSwitchboard(value, "tools");
3975
+ return typeof board === "string" ? {} : board;
3976
+ };
3908
3977
  function infoOf(document) {
3909
3978
  const opening = document["opening_message"];
3910
3979
  const parts = Array.isArray(opening) && opening.some((part) => typeof part === "object" && part !== null && part["type"] === "utterance");
@@ -3924,9 +3993,11 @@ function infoOf(document) {
3924
3993
  timeZone: textOf(document["time_zone"]),
3925
3994
  startingTime: textOf(document["starting_time"]),
3926
3995
  version: typeof document["version"] === "number" ? String(document["version"]) : textOf(document["version"]),
3996
+ tools: toolsOf(document["tools"]),
3927
3997
  alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
3928
3998
  title: textOf(entry["title"]),
3929
- text: entry["text"]
3999
+ text: entry["text"],
4000
+ ...textOf(entry["character"]) === "" ? {} : { character: textOf(entry["character"]) }
3930
4001
  }] : []) : []
3931
4002
  };
3932
4003
  }
@@ -3983,9 +4054,14 @@ async function editWorldInfo(directory, edit) {
3983
4054
  if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
3984
4055
  else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
3985
4056
  title: entry.title === "" ? entry.text.slice(0, 40) : entry.title,
3986
- text: entry.text
4057
+ text: entry.text,
4058
+ ...entry.character === void 0 || entry.character === "" ? {} : { character: entry.character }
3987
4059
  }));
3988
4060
  }
4061
+ if (edit.tools !== void 0) {
4062
+ if (Object.keys(edit.tools).length === 0) delete document["tools"];
4063
+ else document["tools"] = edit.tools;
4064
+ }
3989
4065
  const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
3990
4066
  const parsed = parseWorldFile(next);
3991
4067
  if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
@@ -4012,7 +4088,7 @@ function worldFindings(session) {
4012
4088
  async function startSession(deps, request) {
4013
4089
  const world = await deps.worlds.find(request.worldId);
4014
4090
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${request.worldId}"`);
4015
- const { characters: authored, factions, locations, items, slots, authoredLore, declared, scripted, authoredPlots, calendar } = await loadValidatedWorld(world);
4091
+ const { characters: authored, factions, locations, items, slots, authoredLore, declared, scripted, authoredPlots, calendar, checks } = await loadValidatedWorld(world);
4016
4092
  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)}`);
4017
4093
  const opening = request.opening === void 0 ? openingOf(world, authored) : [{
4018
4094
  type: "narration",
@@ -4028,6 +4104,13 @@ async function startSession(deps, request) {
4028
4104
  const player = characters.find((character) => character.id === playerId);
4029
4105
  if (player === void 0) throw new InvalidStartError(request.playerAvatar === void 0 ? `"${world.summary.name}" has no character "${request.playerCharacterId}"` : `the avatar "${request.playerAvatar}" is not among the avatars brought along`);
4030
4106
  if (player.role !== "playable") throw new InvalidStartError(`${player.name} cannot be played`);
4107
+ const openingProblems = (world.alternateOpenings ?? []).flatMap((entry, index) => entry.character === void 0 || authored.some((character) => character.id === entry.character && character.role === "playable") ? [] : [{
4108
+ path: `alternate_openings[${index}].character`,
4109
+ message: `"${entry.character}" is not a playable character of this world`
4110
+ }]);
4111
+ if (openingProblems.length > 0) throw new InvalidWorldError(`the alternate openings of "${world.summary.name}" have ${openingProblems.length} problem(s)`, openingProblems);
4112
+ const forCharacter = request.opening === void 0 ? void 0 : world.alternateOpenings[request.opening].character;
4113
+ 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}`);
4031
4114
  const name = request.name?.trim() || world.summary.name;
4032
4115
  if (name.length > 200) throw new InvalidStartError(`the name must be at most 200 characters`);
4033
4116
  let settings = DEFAULT_SETTINGS;
@@ -4037,12 +4120,17 @@ async function startSession(deps, request) {
4037
4120
  settings = parsed.value;
4038
4121
  }
4039
4122
  const timeZone = settings.clock.timeZone !== "" ? settings.clock.timeZone : settings.clock.mode === "real" ? systemTimeZone() : world.clock?.timeZone ?? "UTC";
4123
+ const tools = Object.fromEntries([.../* @__PURE__ */ new Set([...Object.keys(world.tools ?? {}), ...Object.keys(settings.tools)])].map((agent) => [agent, {
4124
+ ...world.tools?.[agent],
4125
+ ...settings.tools[agent]
4126
+ }]));
4040
4127
  settings = {
4041
4128
  ...settings,
4042
4129
  clock: {
4043
4130
  ...settings.clock,
4044
4131
  timeZone
4045
- }
4132
+ },
4133
+ tools
4046
4134
  };
4047
4135
  let startsAt = world.clock?.startingTime;
4048
4136
  if (request.startingTime !== void 0 && request.startingTime.trim() !== "") {
@@ -4071,6 +4159,7 @@ async function startSession(deps, request) {
4071
4159
  populateCharacters(session, characters, player.id);
4072
4160
  populateFactions(session, factions);
4073
4161
  populateCalendar(session, calendar);
4162
+ populateDice(session, checks);
4074
4163
  populateRoutines(session, characters);
4075
4164
  populateItems(session, items, slots, locations);
4076
4165
  populateLore(session, authoredLore.lore);
@@ -4400,7 +4489,10 @@ async function worldCharacters(worlds, worldId) {
4400
4489
  tier,
4401
4490
  kind
4402
4491
  })),
4403
- openings: (world.alternateOpenings ?? []).map((opening) => opening.title),
4492
+ openings: (world.alternateOpenings ?? []).map((opening) => ({
4493
+ title: opening.title,
4494
+ ...opening.character === void 0 ? {} : { character: opening.character }
4495
+ })),
4404
4496
  startingTime: world.clock?.startingTime === void 0 ? "" : localInstant(world.clock.startingTime, world.clock.timeZone ?? "UTC"),
4405
4497
  timeZone: world.clock?.timeZone ?? "",
4406
4498
  problems
@@ -4574,6 +4666,7 @@ async function loadWorld(folder, dir, file, problems) {
4574
4666
  ...world.variables === void 0 ? {} : { variables: world.variables },
4575
4667
  ...world.alternateOpenings === void 0 ? {} : { alternateOpenings: world.alternateOpenings },
4576
4668
  ...world.rules === void 0 ? {} : { rules: world.rules },
4669
+ ...world.tools === void 0 ? {} : { tools: world.tools },
4577
4670
  ...world.narrationVoice === void 0 ? {} : { narrationVoice: world.narrationVoice }
4578
4671
  };
4579
4672
  if (world.coverMediaId !== void 0) try {
@@ -4810,6 +4903,7 @@ function apply(ctx, config) {
4810
4903
  const languages = new AuthoringLanguages(ctx, () => join(root.path, "worlds"));
4811
4904
  const agent = new AgentSessions(agentServicesOf(ctx), () => root.path);
4812
4905
  const authoring = new AuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
4906
+ const doctors = new DoctorSessions(agentServicesOf(ctx), () => root.path, prompts);
4813
4907
  const imports = new ImportStore(() => root.path);
4814
4908
  new RoleplayImport(ctx, {
4815
4909
  maxUploadBytes: config.importMaxUploadBytes,
@@ -4882,7 +4976,11 @@ function apply(ctx, config) {
4882
4976
  authoring,
4883
4977
  chatTitle: (name) => `Authoring ${name}`
4884
4978
  }, id, choices, language),
4885
- picture: (id) => imports.picture(id)
4979
+ picture: (id) => imports.picture(id),
4980
+ uploadPreset: (worldId, file, name, language) => uploadPreset({
4981
+ worlds,
4982
+ authoring
4983
+ }, worldId, file, name, language)
4886
4984
  },
4887
4985
  worldCharacters: (worldId) => worldCharacters(worlds, worldId),
4888
4986
  avatars: {
@@ -4896,6 +4994,10 @@ function apply(ctx, config) {
4896
4994
  return await addAvatarsToWorld(await avatarsWorld(root.path), world, keys, locations);
4897
4995
  }
4898
4996
  },
4997
+ externalTools: () => {
4998
+ const registry = ctx.get("tools");
4999
+ return registry === void 0 ? [] : externalTools(registry);
5000
+ },
4899
5001
  worldFiles: {
4900
5002
  info: async (worldId) => await readWorldInfo((await editableWorld(worlds, worldId, root.path)).directory),
4901
5003
  editInfo: async (worldId, edit) => {
@@ -4905,6 +5007,8 @@ function apply(ctx, config) {
4905
5007
  },
4906
5008
  routines: async (worldId) => await readRoutines(await editableWorld(worlds, worldId, root.path)),
4907
5009
  editRoutine: async (worldId, key, windows) => await editRoutine(await editableWorld(worlds, worldId, root.path), key, windows),
5010
+ dice: async (worldId) => await readDiceDocument(await editableWorld(worlds, worldId, root.path)),
5011
+ editDice: async (worldId, dice) => await editDice(await editableWorld(worlds, worldId, root.path), dice),
4908
5012
  calendar: async (worldId) => await readCalendarDocument(await editableWorld(worlds, worldId, root.path)),
4909
5013
  editCalendar: async (worldId, calendar) => await editCalendar(await editableWorld(worlds, worldId, root.path), calendar),
4910
5014
  variables: async (worldId) => await readVariables(await editableWorld(worlds, worldId, root.path)),
@@ -5025,9 +5129,18 @@ function apply(ctx, config) {
5025
5129
  if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
5026
5130
  return readRunDetail(sessionFolder(sessions, id), run);
5027
5131
  },
5132
+ doctor: async (id, title, language) => {
5133
+ const sessions = join(root.path, "sessions");
5134
+ if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
5135
+ return { chatSessionId: await doctors.ensure({
5136
+ id,
5137
+ name: ctx.roleplayState.openSession(sessions, id).metadata.get().name
5138
+ }, title, language) };
5139
+ },
5028
5140
  reflect: async (id) => {
5029
5141
  const sessions = join(root.path, "sessions");
5030
5142
  if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
5143
+ await agent.ensure(id, ctx.roleplayState.openSession(sessions, id).metadata.get().name);
5031
5144
  await ctx.roleplayOrchestration.reflect(chatSessionId(id));
5032
5145
  },
5033
5146
  resetVectors: (id) => {