@dsh-agentic-roleplay/core 0.3.2 → 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.
package/lib/images.js CHANGED
@@ -1,4 +1,4 @@
1
- import { b as readPngMetadata, d as nextSceneSerial, f as readImageMetadata, i as transientPrompt, l as entityImageDirectory, m as sceneImagePath, n as generateTransientImage, o as addToLibrary, p as referenceImagePath, r as referencePrompt, t as generateReferenceImage, u as inheritImages, x as withPngMetadata } from "./generator-BzeepLd2.js";
2
- import { i as updateImage, r as listGallery } from "./gallery-DS5-qH9F.js";
3
- import { a as tokensOf, i as searchImages, n as interpretImage, o as present, r as imageTools, s as presentedFor, t as runImagePresenter } from "./presenter-agent-Cp-J0onD.js";
1
+ import { b as readPngMetadata, d as nextSceneSerial, f as readImageMetadata, i as transientPrompt, l as entityImageDirectory, m as sceneImagePath, n as generateTransientImage, o as addToLibrary, p as referenceImagePath, r as referencePrompt, t as generateReferenceImage, u as inheritImages, x as withPngMetadata } from "./generator-B6FxlKOV.js";
2
+ import { i as updateImage, r as listGallery } from "./gallery-CtFDL22W.js";
3
+ import { a as tokensOf, i as searchImages, n as interpretImage, o as present, r as imageTools, s as presentedFor, t as runImagePresenter } from "./presenter-agent-Dt21K96b.js";
4
4
  export { addToLibrary, entityImageDirectory, generateReferenceImage, generateTransientImage, imageTools, inheritImages, interpretImage, listGallery, nextSceneSerial, present, presentedFor, readImageMetadata, readPngMetadata, referenceImagePath, referencePrompt, runImagePresenter, sceneImagePath, searchImages, tokensOf, transientPrompt, updateImage, withPngMetadata };
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 loadLocations, At as DICE_COMPARISONS, B as populateLocations, Ct as parseCharacterEdit, D as authoringChatSessionId, Dt as parseRelationEdit, Et as parsePlaceEdit, F as populateClock, G as routineProblems, H as populateRoutines, I as populateDice, J as loadDice, K as TRIGGERS_FILE_NAME, L as populateFactions, M as loadValidatedWorld, Mt as DICE_RESULTS, N as populateCalendar, O as languageOfDocuments, Ot as parseThingEdit, P as populateCharacters, Q as parseCalendarFile, R as populateItems, S as translateMessage, St as InvalidEditProblems, Tt as parseLoreEdit, U as populateTriggers, V as populateLore, W as populateVariables, X as CALENDAR_FILE_NAME, Y as parseDiceFile, Z as loadCalendar, _ as replaceFile$1, _t as ImportStore, at as deleteWorldPrompt, bt as parseWorldFile, c as editWorldLore$1, ct as writeWorldPrompt, d as editWorldPlots$1, dt as parseVariablesFile, et as loadItems, f as editWorldRelation$1, ft as variableProblems, g as readWorldEditor, gt as ImportNotFoundError, h as generateWorldCharacterPortrait, ht as IMPORT_FOLDER, i as readAuthoredEntityDocument, j as markReady, jt as DICE_READINGS, k as readWorldDocuments, kt as IMPORT_COMMAND, l as editWorldNarrationVoice, lt as VARIABLES_FILE_NAME, m as entityFolder, mt as parseCharacterFile, n as createAuthoredEntity, nt as loadCharacters, o as editWorldCharacter$1, ot as listWorldPrompts, p as editWorldThing$1, pt as CHARACTER_FILE_NAME, q as DICE_FILE_NAME, r as deleteAuthoredEntity, rt as subfolders, s as editWorldFaction$1, st as readWorldPrompt, tt as CHARACTERS_DIR, u as editWorldPlace$1, ut as loadVariables, v as uploadWorldCharacterPortrait, vt as parseChoices, wt as parseFactionEdit, x as loadWorldParts, xt as parseWorldInfoEdit, y as worldCharacterPortraitFile, yt as WORLD_FILE_NAME, z as populateKnowledge } from "./documents-B5XAdfo2.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-BCGK9KZV.js";
4
- import { A as notesOfSession, C as plotProgressOf, F as TimelineError, L as readTimeline, M as readNotes, N as observeAsPlayer, O as addToNote, R as pathTo, a as readActivity, d as reflectionStatus, m as externalTools, n as readWithdrawn, o as readRunDetail, q as zoneOf, w as populatePlots, y as PLOTS_METADATA_KEY, z as defaultBoundaries } from "./deliver-BSsDtF6X.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
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";
6
8
  import { a as liveSettings, c as writeSettings, i as InvalidSettingsError, n as encodeOutput, o as readSettings, s as useChildReasoning } from "./narration-DK2kiIjE.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-BzeepLd2.js";
8
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-DS5-qH9F.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
@@ -1997,6 +1896,15 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
1997
1896
  return importFailure(res, error);
1998
1897
  }
1999
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
+ } },
2000
1908
  "/worlds/import": {
2001
1909
  GET: async (_req, res, url) => {
2002
1910
  try {
@@ -2804,6 +2712,17 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
2804
2712
  throw error;
2805
2713
  }
2806
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
+ } },
2807
2726
  "/sessions/reflect": { POST: async (_req, res, url) => {
2808
2727
  try {
2809
2728
  await sessions.reflect(url.searchParams.get("id") ?? "");
@@ -2926,6 +2845,7 @@ function registerApi(ctx, deps) {
2926
2845
  async function deleteSession(deps, id) {
2927
2846
  const directory = deps.sessionsDir();
2928
2847
  if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
2848
+ await deps.purgeChat(doctorChatSessionId(id));
2929
2849
  await deps.purgeChat(chatSessionId(id));
2930
2850
  deps.state.deleteSession(directory, id);
2931
2851
  }
@@ -4076,7 +3996,8 @@ function infoOf(document) {
4076
3996
  tools: toolsOf(document["tools"]),
4077
3997
  alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
4078
3998
  title: textOf(entry["title"]),
4079
- text: entry["text"]
3999
+ text: entry["text"],
4000
+ ...textOf(entry["character"]) === "" ? {} : { character: textOf(entry["character"]) }
4080
4001
  }] : []) : []
4081
4002
  };
4082
4003
  }
@@ -4133,7 +4054,8 @@ async function editWorldInfo(directory, edit) {
4133
4054
  if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
4134
4055
  else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
4135
4056
  title: entry.title === "" ? entry.text.slice(0, 40) : entry.title,
4136
- text: entry.text
4057
+ text: entry.text,
4058
+ ...entry.character === void 0 || entry.character === "" ? {} : { character: entry.character }
4137
4059
  }));
4138
4060
  }
4139
4061
  if (edit.tools !== void 0) {
@@ -4182,6 +4104,13 @@ async function startSession(deps, request) {
4182
4104
  const player = characters.find((character) => character.id === playerId);
4183
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`);
4184
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}`);
4185
4114
  const name = request.name?.trim() || world.summary.name;
4186
4115
  if (name.length > 200) throw new InvalidStartError(`the name must be at most 200 characters`);
4187
4116
  let settings = DEFAULT_SETTINGS;
@@ -4560,7 +4489,10 @@ async function worldCharacters(worlds, worldId) {
4560
4489
  tier,
4561
4490
  kind
4562
4491
  })),
4563
- 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
+ })),
4564
4496
  startingTime: world.clock?.startingTime === void 0 ? "" : localInstant(world.clock.startingTime, world.clock.timeZone ?? "UTC"),
4565
4497
  timeZone: world.clock?.timeZone ?? "",
4566
4498
  problems
@@ -4971,6 +4903,7 @@ function apply(ctx, config) {
4971
4903
  const languages = new AuthoringLanguages(ctx, () => join(root.path, "worlds"));
4972
4904
  const agent = new AgentSessions(agentServicesOf(ctx), () => root.path);
4973
4905
  const authoring = new AuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
4906
+ const doctors = new DoctorSessions(agentServicesOf(ctx), () => root.path, prompts);
4974
4907
  const imports = new ImportStore(() => root.path);
4975
4908
  new RoleplayImport(ctx, {
4976
4909
  maxUploadBytes: config.importMaxUploadBytes,
@@ -5043,7 +4976,11 @@ function apply(ctx, config) {
5043
4976
  authoring,
5044
4977
  chatTitle: (name) => `Authoring ${name}`
5045
4978
  }, id, choices, language),
5046
- 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)
5047
4984
  },
5048
4985
  worldCharacters: (worldId) => worldCharacters(worlds, worldId),
5049
4986
  avatars: {
@@ -5192,6 +5129,14 @@ function apply(ctx, config) {
5192
5129
  if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
5193
5130
  return readRunDetail(sessionFolder(sessions, id), run);
5194
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
+ },
5195
5140
  reflect: async (id) => {
5196
5141
  const sessions = join(root.path, "sessions");
5197
5142
  if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);