@dsh-agentic-roleplay/core 0.12.5 → 0.12.7

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 (35) hide show
  1. package/lib/{access-DjA0kvPM.js → access-5vtPAT3O.js} +2 -2
  2. package/lib/{authoring-tools-DqAttdUN.js → authoring-tools-Bi9YQ9QH.js} +52 -18
  3. package/lib/authoring.js +228 -35
  4. package/lib/{child-SMvjNsb8.js → child-Bfj7-Iuo.js} +11 -13
  5. package/lib/client.js +910 -526
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +4 -4
  8. package/lib/doctor.js +3 -3
  9. package/lib/{library-D6AcyxGZ.js → gallery-BT5lf-T5.js} +212 -7
  10. package/lib/helper.js +2 -2
  11. package/lib/{hooks-OLl-1AOS.js → hooks-DR-HqE50.js} +6 -4
  12. package/lib/images.js +3 -4
  13. package/lib/index.js +131 -23
  14. package/lib/{presenter-agent-CGCJrg7V.js → interpreter-BYNrjYZo.js} +155 -64
  15. package/lib/{jail-CDW5iymd.js → jail-D83JnxKg.js} +2 -2
  16. package/lib/{lorebook-author-tools-CXV1KD4Q.js → lorebook-author-tools-BI-r8fEt.js} +6 -6
  17. package/lib/lorebook-authoring.js +5 -5
  18. package/lib/{narration-Bnrvl0UQ.js → narration-CUZIXzab.js} +9 -3
  19. package/lib/orchestration.js +59 -19
  20. package/lib/{pack-jail-CZAmlgE1.js → pack-jail-Y1XPbqHw.js} +20 -14
  21. package/lib/{packs-DUVCSHqi.js → packs-DD-v-Epl.js} +2 -2
  22. package/lib/presenter-agent-00sOVGI9.js +59 -0
  23. package/lib/{preset-BYfXYvp0.js → preset-Bnx3jhUv.js} +4 -4
  24. package/lib/{preset-author-tools-DYxTLm9U.js → preset-author-tools-DYrBcieA.js} +6 -6
  25. package/lib/preset-authoring.js +5 -5
  26. package/lib/{reflection-C3zdufN9.js → reflection-DqxoV9xE.js} +10 -9
  27. package/lib/{serial-Bh6gqb3f.js → serial-CS46qAvI.js} +57 -11
  28. package/lib/{turn-guard-CNFvmz_F.js → turn-guard-bZkxzRXJ.js} +3 -3
  29. package/package.json +32 -31
  30. package/prompts/en/import/finish-ok.md +2 -0
  31. package/prompts/en/roleplay/image-worth.md +5 -0
  32. package/prompts/zh/import/finish-ok.md +2 -0
  33. package/prompts/zh/roleplay/image-worth.md +5 -0
  34. package/lib/gallery-Dahi5TkO.js +0 -190
  35. package/lib/generator-BvSZGpzy.js +0 -150
package/lib/compaction.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as liveSettings, t as decodeOutput } from "./narration-Bnrvl0UQ.js";
2
- import { j as roleplaySessionOf, k as tokensOf, l as runChild, n as childModel, r as childSampling } from "./child-SMvjNsb8.js";
3
- import { t as promptFor } from "./access-DjA0kvPM.js";
1
+ import { i as wordsOf, o as liveSettings, t as decodeOutput } from "./narration-CUZIXzab.js";
2
+ import { j as roleplaySessionOf, k as tokensOf, l as runChild, n as childModel, r as childSampling } from "./child-Bfj7-Iuo.js";
3
+ import { t as promptFor } from "./access-5vtPAT3O.js";
4
4
  import { join } from "node:path";
5
5
  import { sessionFolder } from "@dsh-agentic-roleplay/state";
6
6
  import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
@@ -216,7 +216,7 @@ function readFolded(messages) {
216
216
  told.push(`Player: ${text.trim()}`);
217
217
  } else if (message.role === "tool") {
218
218
  const output = decodeOutput(text);
219
- if (output !== void 0) told.push(output.segments.map((segment) => segment.type === "utterance" ? `${segment.name}: "${segment.text}"` : segment.text).join("\n"));
219
+ if (output !== void 0) told.push(wordsOf(output.segments, (segment) => `${segment.name}: "${segment.text}"`).join("\n"));
220
220
  }
221
221
  }
222
222
  return {
package/lib/doctor.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { n as silenceRuntimeContext, t as silenceHarnessDevContext } from "./dev-context-Cgv_wZbG.js";
2
- import { A as chatSessionId } from "./child-SMvjNsb8.js";
2
+ import { A as chatSessionId } from "./child-Bfj7-Iuo.js";
3
3
  import { n as doctorSessionOf } from "./doctor-chat-hL1a61hp.js";
4
- import { s as externalTools, t as externalToolLimit } from "./hooks-OLl-1AOS.js";
5
- import { a as liveSettings } from "./narration-Bnrvl0UQ.js";
4
+ import { s as externalTools, t as externalToolLimit } from "./hooks-DR-HqE50.js";
5
+ import { o as liveSettings } from "./narration-CUZIXzab.js";
6
6
  import { join } from "node:path";
7
7
  import { createTools, isSessionId, sessionDatabase, sessionFolder } from "@dsh-agentic-roleplay/state";
8
8
  import { existsSync } from "node:fs";
@@ -1,9 +1,9 @@
1
- import { n as atomicWrite } from "./access-DjA0kvPM.js";
1
+ import { n as atomicWrite } from "./access-5vtPAT3O.js";
2
2
  import { i as translator, n as withoutExtension, r as languageOf, t as trimCharacters } from "./text-B-HsLdb-.js";
3
- import { dirname, extname, join } from "node:path";
3
+ import { dirname, extname, join, sep } from "node:path";
4
4
  import { existsSync } from "node:fs";
5
5
  import { createHash } from "node:crypto";
6
- import { copyFile, link, mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
6
+ import { copyFile, link, lstat, mkdir, readFile, readdir, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
7
7
  // src/host/import/run.ts
8
8
  /** What `ImportContext.embed` rejects with when no embedding provider is selected or loaded: the checks that would use it go without. */
9
9
  var NoEmbeddingService = class extends Error {};
@@ -333,10 +333,11 @@ function libraryName(original, extension, taken) {
333
333
  * Puts a picture into the library unless the library already holds that picture (the same image, whatever metadata the file carries), whatever it came from: an upload, an address, a generation.
334
334
  * Metadata says where it came from and that it is reusable; what it shows is not known yet, and the interpreter fills that in.
335
335
  * @param known the hashes of the library when the caller has read them (kept up to date here), to avoid reading the library again for each picture.
336
+ * @param link the address of a card the picture was downloaded for, with the ids of the card pieces that held it; written into the picture.
336
337
  * @throws {Error} when the bytes are not a PNG, JPEG, WebP or GIF image.
337
338
  * @returns its path under `images/`, and whether it was added or an equal picture was there.
338
339
  */
339
- async function addToLibraryOnce(sessionFolder, bytes, originalName, known) {
340
+ async function addToLibraryOnce(sessionFolder, bytes, originalName, known, link) {
340
341
  const extension = imageExtensionOf(bytes);
341
342
  if (extension === void 0 || MEDIA_TYPES[extension] === void 0) throw new Error("only PNG, JPEG, WebP and GIF images can be added");
342
343
  const hashes = known ?? await libraryHashes(sessionFolder);
@@ -359,7 +360,8 @@ async function addToLibraryOnce(sessionFolder, bytes, originalName, known) {
359
360
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
360
361
  originalName,
361
362
  subjects: [],
362
- tags: []
363
+ tags: [],
364
+ ...link === void 0 ? {} : { cardLinks: [link] }
363
365
  });
364
366
  const path = `${LIBRARY_FOLDER}/${name}`;
365
367
  hashes.set(hash, path);
@@ -372,6 +374,209 @@ async function addToLibraryOnce(sessionFolder, bytes, originalName, known) {
372
374
  async function addToLibrary(sessionFolder, bytes, originalName) {
373
375
  return (await addToLibraryOnce(sessionFolder, bytes, originalName)).path;
374
376
  }
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 };
377
+ // src/host/images/gallery.ts
378
+ const READ_AT_ONCE = 8;
379
+ const SEGMENT = /^[\p{L}\p{N}][\p{L}\p{N}\p{M}._-]{0,199}$/u;
380
+ const CACHE_FILE = ".index.json";
381
+ const CACHE_VERSION = 1;
382
+ /** The images of the folder: every PNG, and the other raster formats inside the library, whose metadata is beside them. */
383
+ async function imageFiles(images, prefix = "") {
384
+ let entries;
385
+ try {
386
+ entries = await readdir(join(images, prefix), { withFileTypes: true });
387
+ } catch (error) {
388
+ if (error.code === "ENOENT") return [];
389
+ throw error;
390
+ }
391
+ const found = [];
392
+ for (const entry of entries) {
393
+ if (entry.isSymbolicLink()) continue;
394
+ const path = `${prefix}${entry.name}`;
395
+ if (entry.isDirectory()) found.push(...await imageFiles(images, `${path}/`));
396
+ else if (entry.isFile() && (entry.name.toLowerCase().endsWith(".png") || path.startsWith(`library/`) && mediaTypeOf(entry.name) !== void 0)) found.push(path);
397
+ }
398
+ return found;
399
+ }
400
+ async function factsOf(images, path) {
401
+ const file = join(images, ...path.split("/"));
402
+ const info = await lstat(file);
403
+ const beside = path.toLowerCase().endsWith(".png") ? void 0 : await stat(sidecarOf(file)).then((value) => value.mtimeMs, () => 0);
404
+ return {
405
+ path,
406
+ signature: `${info.mtimeMs}:${info.size}:${beside ?? ""}`
407
+ };
408
+ }
409
+ async function describe(images, path) {
410
+ const file = join(images, ...path.split("/"));
411
+ const { mtime } = await lstat(file);
412
+ const library = path.startsWith(`${LIBRARY_FOLDER}/`);
413
+ const metadata = await readImageFileMetadata(file);
414
+ if (metadata === void 0 || typeof metadata !== "object") return library ? {
415
+ path,
416
+ purpose: "uploaded",
417
+ origin: "uploaded",
418
+ reusable: true,
419
+ createdAt: mtime.toISOString(),
420
+ tags: [],
421
+ subjects: [],
422
+ pending: true
423
+ } : {
424
+ path,
425
+ purpose: path.startsWith("scenes/") ? "transient" : "reference",
426
+ origin: "generated",
427
+ reusable: false,
428
+ createdAt: mtime.toISOString(),
429
+ tags: [],
430
+ subjects: [],
431
+ unreadable: true
432
+ };
433
+ const origin = metadata.origin ?? (library ? "uploaded" : "generated");
434
+ const purpose = metadata.purpose ?? (origin === "uploaded" ? "uploaded" : path.startsWith("scenes/") ? "transient" : "reference");
435
+ return {
436
+ path,
437
+ purpose,
438
+ origin,
439
+ reusable: origin === "uploaded" ? true : metadata.reusable ?? purpose === "reference",
440
+ createdAt: metadata.createdAt ?? mtime.toISOString(),
441
+ ...metadata.prompt === void 0 ? {} : { prompt: metadata.prompt },
442
+ ...metadata.revisedPrompt === void 0 ? {} : { revisedPrompt: metadata.revisedPrompt },
443
+ ...metadata.description === void 0 ? {} : { description: metadata.description },
444
+ tags: metadata.tags ?? [],
445
+ ...metadata.provider === void 0 ? {} : { provider: metadata.provider },
446
+ ...metadata.model === void 0 ? {} : { model: metadata.model },
447
+ subjects: (metadata.subjects ?? []).map((subject) => ({
448
+ kind: subject.kind,
449
+ name: subject.name
450
+ })),
451
+ ...metadata.source === void 0 ? {} : { source: metadata.source },
452
+ ...metadata.originalName === void 0 ? {} : { originalName: metadata.originalName },
453
+ ...metadata.cardLinks === void 0 || metadata.cardLinks.length === 0 ? {} : { cardLinks: metadata.cardLinks },
454
+ ...origin === "uploaded" && metadata.description === void 0 ? { pending: true } : {}
455
+ };
456
+ }
457
+ async function describeGalleryImage(sessionFolder, path) {
458
+ return await describe(join(sessionFolder, "images"), path);
459
+ }
460
+ async function readCache(images) {
461
+ try {
462
+ const cache = JSON.parse(await readFile(join(images, CACHE_FILE), "utf8"));
463
+ if (cache.version === CACHE_VERSION && typeof cache.entries === "object" && cache.entries !== null) return cache;
464
+ } catch {}
465
+ return {
466
+ version: CACHE_VERSION,
467
+ entries: {}
468
+ };
469
+ }
470
+ async function writeCache(images, cache) {
471
+ await atomicWrite(join(images, CACHE_FILE), JSON.stringify(cache), { createDirectory: true });
472
+ }
473
+ /**
474
+ * Every image of a session folder with what its file says, newest first. The files are the truth; `images/.index.json` only remembers what
475
+ * was read from each, keyed by its size and time, so that a listing reads just the files that are new or changed. It can be deleted at any time.
476
+ */
477
+ async function listGallery(sessionFolder) {
478
+ const images = join(sessionFolder, "images");
479
+ const paths = await imageFiles(images);
480
+ if (paths.length === 0) return [];
481
+ const cache = await readCache(images);
482
+ const facts = await mapLimit(paths, READ_AT_ONCE, (path) => factsOf(images, path));
483
+ const entries = {};
484
+ let changed = Object.keys(cache.entries).length !== paths.length;
485
+ const described = await mapLimit(facts, READ_AT_ONCE, async ({ path, signature }) => {
486
+ const known = cache.entries[path];
487
+ if (known?.signature === signature) {
488
+ entries[path] = known;
489
+ return known.image;
490
+ }
491
+ changed = true;
492
+ const image = await describe(images, path);
493
+ entries[path] = {
494
+ signature,
495
+ image
496
+ };
497
+ return image;
498
+ });
499
+ if (changed) await writeCache(images, {
500
+ version: CACHE_VERSION,
501
+ entries
502
+ });
503
+ return described.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.path.localeCompare(b.path));
504
+ }
505
+ /**
506
+ * The file of a gallery image by its path, which must be one the listing gives: a raster image inside the session's images, not reached through a link.
507
+ * @throws {Error} when the path names no such image.
508
+ */
509
+ async function galleryFile(sessionFolder, path) {
510
+ const parts = path.split("/");
511
+ const mediaType = mediaTypeOf(path);
512
+ if (parts.length === 0 || mediaType === void 0 || mediaType !== "image/png" && parts[0] !== "library" || parts.some((part) => !SEGMENT.test(part) || part === "." || part === "..")) throw new Error("there is no such image");
513
+ const images = join(sessionFolder, "images");
514
+ const file = join(images, ...parts);
515
+ const info = await lstat(file).catch(() => void 0);
516
+ if (info === void 0 || !info.isFile()) throw new Error("there is no such image");
517
+ if (!(await realpath(file)).startsWith(`${await realpath(images)}${sep}`)) throw new Error("there is no such image");
518
+ return {
519
+ file,
520
+ size: info.size,
521
+ mediaType
522
+ };
523
+ }
524
+ /** Notes one more address a picture of the library came from, or more pieces of the card for an address it already has. */
525
+ async function addCardLink(sessionFolder, path, link) {
526
+ const { file } = await galleryFile(sessionFolder, path);
527
+ const existing = await readImageFileMetadata(file);
528
+ if (existing === void 0) return;
529
+ const links = [...existing.cardLinks ?? []];
530
+ const at = links.findIndex((entry) => entry.url === link.url);
531
+ if (at < 0) links.push({
532
+ url: link.url,
533
+ pieces: [...link.pieces]
534
+ });
535
+ else links[at] = {
536
+ url: link.url,
537
+ pieces: [.../* @__PURE__ */ new Set([...links[at].pieces, ...link.pieces])]
538
+ };
539
+ await writeImageFileMetadata(file, {
540
+ ...existing,
541
+ cardLinks: links
542
+ });
543
+ }
544
+ /**
545
+ * Changes what an image says about itself, in the file. An image the person brought is always reusable.
546
+ * @throws {Error} when the path names no image of the session, or an uploaded image is made not reusable.
547
+ */
548
+ async function updateImage(sessionFolder, path, update) {
549
+ const { file } = await galleryFile(sessionFolder, path);
550
+ const current = await describe(join(sessionFolder, "images"), path);
551
+ if (update.reusable === false && current.origin === "uploaded") throw new Error("an image you brought is always reusable: otherwise it would only sit there");
552
+ const existing = await readImageFileMetadata(file);
553
+ await writeImageFileMetadata(file, {
554
+ schema: "dsh-roleplay-image/v3",
555
+ purpose: current.purpose,
556
+ origin: current.origin,
557
+ reusable: current.reusable,
558
+ createdAt: current.createdAt,
559
+ tags: current.tags,
560
+ subjects: current.subjects.map((subject) => ({
561
+ kind: subject.kind,
562
+ localId: subject.name,
563
+ name: subject.name
564
+ })),
565
+ ...existing,
566
+ schema: "dsh-roleplay-image/v3",
567
+ origin: current.origin,
568
+ ...update.description === void 0 ? {} : { description: update.description },
569
+ ...update.tags === void 0 ? {} : { tags: update.tags },
570
+ ...update.subjects === void 0 ? {} : { subjects: update.subjects.map((subject) => ({
571
+ kind: subject.kind,
572
+ localId: subject.name,
573
+ name: subject.name
574
+ })) },
575
+ ...update.reusable === void 0 ? {} : { reusable: update.reusable },
576
+ ...update.interpretedBy === void 0 ? {} : { interpretedBy: update.interpretedBy }
577
+ });
578
+ return await describe(join(sessionFolder, "images"), path);
579
+ }
580
+ export { mapLimit as C, uniqueKey as D, trOf as E, NoEmbeddingService as S, slug as T, MEDIA_TYPES as _, updateImage as a, readPngMetadata as b, imageExtensionOf as c, inheritImages as d, nextSceneSerial as f, writeImage as g, sceneImagePath as h, listGallery as i, libraryHashes as l, referenceImagePath as m, describeGalleryImage as n, addToLibrary as o, readImageMetadata as p, galleryFile as r, addToLibraryOnce as s, addCardLink as t, entityImageDirectory as u, readImageFileMetadata as v, norm as w, withPngMetadata as x, writeImageFileMetadata as y };
376
581
 
377
- //# sourceMappingURL=library-D6AcyxGZ.js.map
582
+ //# sourceMappingURL=gallery-BT5lf-T5.js.map
package/lib/helper.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { n as silenceRuntimeContext, t as silenceHarnessDevContext } from "./dev-context-Cgv_wZbG.js";
2
- import { o as helpers } from "./child-SMvjNsb8.js";
2
+ import { o as helpers } from "./child-Bfj7-Iuo.js";
3
3
  import { a as workspaceOf, n as storyRoots } from "./service-mRKwpWjX.js";
4
- import { t as registerFoldersJail } from "./jail-CDW5iymd.js";
4
+ import { t as registerFoldersJail } from "./jail-D83JnxKg.js";
5
5
  import { join } from "node:path";
6
6
  import { sessionFolder } from "@dsh-agentic-roleplay/state";
7
7
  // src/helper.ts
@@ -1,6 +1,6 @@
1
- import { C as addTokens, D as finishOf, E as cutOff, O as estimateAnswer, S as NO_TOKENS, a as childTrace, b as estimateTokens, f as tracerOf, j as roleplaySessionOf, l as runChild, n as childModel, r as childSampling, u as TurnTraces, v as requestsOf, x as tokensOf, y as blockText } from "./child-SMvjNsb8.js";
2
- import { _ as emptyStats, a as liveSettings, h as DECISION_SITES, m as rulesOf, n as encodeOutput, p as WORLD_RULES_KEY, r as encodePreview } from "./narration-Bnrvl0UQ.js";
3
- import { t as promptFor } from "./access-DjA0kvPM.js";
1
+ import { C as addTokens, D as finishOf, E as cutOff, O as estimateAnswer, S as NO_TOKENS, a as childTrace, b as estimateTokens, f as tracerOf, j as roleplaySessionOf, l as runChild, n as childModel, r as childSampling, u as TurnTraces, v as requestsOf, x as tokensOf, y as blockText } from "./child-Bfj7-Iuo.js";
2
+ import { g as DECISION_SITES, h as rulesOf, m as WORLD_RULES_KEY, n as encodeOutput, o as liveSettings, r as encodePreview, v as emptyStats } from "./narration-CUZIXzab.js";
3
+ import { t as promptFor } from "./access-5vtPAT3O.js";
4
4
  import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-B-HsLdb-.js";
5
5
  import { n as storyRoots } from "./service-mRKwpWjX.js";
6
6
  import { dirname, join } from "node:path";
@@ -1574,6 +1574,7 @@ const exactUtterances = {
1574
1574
  let latest = 0;
1575
1575
  segments.forEach((segment, index) => {
1576
1576
  const at = `segment ${index + 1}`;
1577
+ if (segment.type === "image") return;
1577
1578
  if (segment.type === "narration") {
1578
1579
  if (segment.text.trim() === "") problems.push(`${at}: the narration is empty`);
1579
1580
  return;
@@ -1601,6 +1602,7 @@ const exactUtterances = {
1601
1602
  const used = /* @__PURE__ */ new Set();
1602
1603
  const kept = [];
1603
1604
  for (const segment of segments) {
1605
+ if (segment.type === "image") continue;
1604
1606
  if (segment.type === "narration") {
1605
1607
  if (segment.text.trim() !== "") kept.push({
1606
1608
  segment,
@@ -5049,4 +5051,4 @@ function installHooks(ctx, deps) {
5049
5051
  }
5050
5052
  export { copyWorldPrompts as $, plotProgressOf as A, parsePlotsFile as B, readNotes as C, referent as D, sameWords as E, textLanguage as F, readDocument as G, COMMANDS_KEY as H, wrongLanguage as I, errorMessage as J, Reader as K, readUsage as L, LANGUAGE_NAMES as M, STORY_LANGUAGES as N, RESULTS as O, isStoryLanguage as P, PromptLibrary as Q, PLOTS_FILE_NAME as R, notesOfSession as S, defaultBoundaries as T, commandFlagKey as U, plotReferenceProblems as V, commandsOf as W, LANGUAGE_TAG as X, LANGUAGE_FOLDER as Y, PROMPTS_FOLDER as Z, readTraces as _, ClockError as _t, MAX_OOC_ANSWER as a, shippedPromptsDirectory as at, readWithdrawn as b, AUTHORING_NEEDS as bt, externalWithheld as c, InvalidStartError as ct, record as d, SessionArchivedError as dt, inheritPrompts as et, toolEnabled as f, SessionNotFoundError as ft, readRunDetail as g, runCommandLine as gt, readActivity as h, registerCommands as ht, characterRunner as i, shippedLanguages as it, populatePlots as j, PLOTS_METADATA_KEY as k, PREVIEW_TOOL as l, InvalidWorldError as lt, readDecisionStats as m, CommandRefusedError as mt, installHooks as n, listFiles as nt, externalGiven as o, shippedText as ot, storesOf as p, WorldNotFoundError as pt, formatIssue as q, guardRepeatedCalls as r, promptProblem as rt, externalTools as s, AgentUnavailableError as st, externalToolLimit as t, languageOf as tt, createTools$1 as u, ReflectionRefusedError as ut, readVerdicts as v, describeWhen as vt, observeAsPlayer as w, addToNote as x, COMPARISONS as xt, writeVerdicts as y, zoneOf as yt, loadPlots as z };
5051
5053
 
5052
- //# sourceMappingURL=hooks-OLl-1AOS.js.map
5054
+ //# sourceMappingURL=hooks-DR-HqE50.js.map
package/lib/images.js CHANGED
@@ -1,5 +1,4 @@
1
- import { a as searchImages, c as presentedFor, n as interpretImage, o as tokensOf, r as imageTools, s as present, t as runImagePresenter } from "./presenter-agent-CGCJrg7V.js";
2
- import { i as updateImage, r as listGallery } from "./gallery-Dahi5TkO.js";
3
- import { c as nextSceneSerial, d as sceneImagePath, l as readImageMetadata, o as entityImageDirectory, s as inheritImages, t as addToLibrary, u as referenceImagePath, v as readPngMetadata, y as withPngMetadata } from "./library-D6AcyxGZ.js";
4
- import { i as transientPrompt, n as generateTransientImage, r as referencePrompt, t as generateReferenceImage } from "./generator-BvSZGpzy.js";
1
+ import { t as runImagePresenter } from "./presenter-agent-00sOVGI9.js";
2
+ import { a as searchImages, c as presentedFor, d as referencePrompt, f as transientPrompt, l as generateReferenceImage, n as interpretImage, o as tokensOf, r as imageTools, s as present, u as generateTransientImage } from "./interpreter-BYNrjYZo.js";
3
+ import { a as updateImage, b as readPngMetadata, d as inheritImages, f as nextSceneSerial, h as sceneImagePath, i as listGallery, m as referenceImagePath, o as addToLibrary, p as readImageMetadata, u as entityImageDirectory, x as withPngMetadata } from "./gallery-BT5lf-T5.js";
5
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,21 +1,20 @@
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-SMvjNsb8.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-DqAttdUN.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-CXV1KD4Q.js";
4
- import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-DYxTLm9U.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-OLl-1AOS.js";
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-Bnrvl0UQ.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-Bh6gqb3f.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-CZAmlgE1.js";
9
- import { i as atomicWriteSync, n as atomicWrite, r as atomicWriteJson } from "./access-DjA0kvPM.js";
1
+ import { A as chatSessionId, _ as RECOVERY_SHRINK, g as RECOVERY_FLOOR, h as sharedSamplingOf, i as childSamplingOf, j as roleplaySessionOf, m as parseSampling, r as childSampling, s as isUnfinishedCall, w as totalTokens } from "./child-Bfj7-Iuo.js";
2
+ import { $ as checkWorld, $t as authoredWorldOf, A as loadWorldParts, B as localChanges, Gt as ImportCardError, H as writeOrigin, J as guardedLookup, Jt as pictureOf, Kt as cardFormat, L as describeChanges, O as editWorldInfo, Ot as CHARACTERS_DIR, R as hashWorld, U as CatalogueError, V as readOrigin, X as vetUrl, Yt as readCard, _ as structureImport, _t as loadLocations, a as beginImport, at as populateClock, c as importTextFor, ct as populateItems, d as knownOutputCeiling, dt as populateLore, en as authoringChatSessionId, 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 isPng, rt as populateCalendar, st as populateFactions, t as AuthoringTools, ut as populateLocations, x as runChecks, z as isUnchanged } from "./authoring-tools-Bi9YQ9QH.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-BI-r8fEt.js";
4
+ import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-DYrBcieA.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-DR-HqE50.js";
6
+ import { a as InvalidSettingsError, c as useChildReasoning, d as SETTINGS_SPEC, f as parseSettings, l as writeSettings, m as WORLD_RULES_KEY, o as liveSettings, s as readSettings, u as DEFAULT_SETTINGS } from "./narration-CUZIXzab.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-CS46qAvI.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-Y1XPbqHw.js";
9
+ import { i as atomicWriteSync, n as atomicWrite, r as atomicWriteJson } from "./access-5vtPAT3O.js";
10
10
  import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-B-HsLdb-.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-C3zdufN9.js";
12
- import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-BYfXYvp0.js";
13
- import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-D6AcyxGZ.js";
11
+ import { _ as pathTo, c as BranchError, d as recordPreset, f as switchPreset, g as childrenOf, h as START_SNAPSHOT, i as reflectionStatus, l as copyPreset, m as writeTimeline, o as TimelineError, p as readTimeline, u as presetStatus, v as snapshotOf } from "./reflection-DqxoV9xE.js";
12
+ import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-Bnx3jhUv.js";
13
+ import { D as uniqueKey, T as slug, a as updateImage, d as inheritImages, h as sceneImagePath, i as listGallery, m as referenceImagePath, o as addToLibrary, r as galleryFile } from "./gallery-BT5lf-T5.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-DUVCSHqi.js";
17
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-BvSZGpzy.js";
18
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-Dahi5TkO.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-DD-v-Epl.js";
17
+ import { l as generateReferenceImage, n as interpretImage, p as uploadReferenceImage } from "./interpreter-BYNrjYZo.js";
19
18
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
20
19
  import { SESSION_DATABASE_FILE, addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, openSessionStore, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
21
20
  import { copyFileSync, cpSync, createReadStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
@@ -573,6 +572,7 @@ function speakingOf$1(timeline) {
573
572
  length: 0
574
573
  };
575
574
  for (const node of pathTo(timeline, timeline.head)) for (const segment of node.output?.segments ?? []) {
575
+ if (segment.type === "image") continue;
576
576
  if (segment.type === "narration") {
577
577
  narration.passages += 1;
578
578
  narration.length += lengthOf(segment.text);
@@ -2930,14 +2930,14 @@ var InterfaceService = class {
2930
2930
  return pathTo(timeline, timeline.head).filter((node) => node.output !== void 0).map((node, index) => ({
2931
2931
  turn: index + 1,
2932
2932
  player: node.player,
2933
- segments: (node.output?.segments ?? []).map((segment) => segment.type === "utterance" ? {
2933
+ segments: (node.output?.segments ?? []).flatMap((segment) => segment.type === "image" ? [] : [segment.type === "utterance" ? {
2934
2934
  type: "utterance",
2935
2935
  name: segment.name,
2936
2936
  text: segment.text
2937
2937
  } : {
2938
2938
  type: "narration",
2939
2939
  text: segment.text
2940
- }),
2940
+ }]),
2941
2941
  ...node.output?.ooc === void 0 ? {} : { note: node.output.ooc.note }
2942
2942
  })).slice(-Math.min(Math.max(1, limit), PACK_LIMITS.history.max));
2943
2943
  }
@@ -4243,6 +4243,13 @@ function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
4243
4243
  }
4244
4244
  }
4245
4245
  },
4246
+ "/worlds/gallery/describe": { POST: async (_req, res, url) => {
4247
+ try {
4248
+ sendJson(res, 200, await worldFiles.describeImage(url.searchParams.get("id") ?? "", url.searchParams.get("path") ?? ""));
4249
+ } catch (error) {
4250
+ return sendError(res, error instanceof WorldNotFoundError ? 404 : 409, error instanceof Error ? error.message : String(error));
4251
+ }
4252
+ } },
4246
4253
  "/worlds/gallery/upload": { POST: async (req, res, url) => {
4247
4254
  const name = decodeURIComponent(String(req.headers["x-file-name"] ?? url.searchParams.get("name") ?? "image"));
4248
4255
  try {
@@ -5131,6 +5138,19 @@ function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
5131
5138
  throw error;
5132
5139
  }
5133
5140
  } },
5141
+ "/sessions/branch": { POST: async (req, res) => {
5142
+ const body = await readJsonBody(req);
5143
+ const { chat, parent, atSeq } = typeof body === "object" && body !== null ? body : {};
5144
+ if (typeof chat !== "string" || typeof parent !== "string" || typeof atSeq !== "number" || !Number.isSafeInteger(atSeq) || atSeq < 0) return sendError(res, 400, "the request needs \"chat\", \"parent\" and a whole number \"atSeq\"");
5145
+ try {
5146
+ sendJson(res, 200, await sessions.branch(chat, parent, atSeq));
5147
+ } catch (error) {
5148
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
5149
+ if (error instanceof BranchError || error instanceof TimelineError) return sendError(res, 409, error.message);
5150
+ if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
5151
+ throw error;
5152
+ }
5153
+ } },
5134
5154
  "/sessions/timeline/move": { POST: async (_req, res, url) => {
5135
5155
  try {
5136
5156
  sendJson(res, 200, await sessions.moveTimeline(url.searchParams.get("id") ?? "", url.searchParams.get("to") ?? ""));
@@ -5694,6 +5714,32 @@ async function deleteSession(deps, id) {
5694
5714
  await deps.purgeChat(chatSessionId(id));
5695
5715
  deps.state.deleteSession(directory, id);
5696
5716
  }
5717
+ // src/host/sessions/branch-session.ts
5718
+ /**
5719
+ * Adopts the story of `parent` into the chat DSH forked for it.
5720
+ *
5721
+ * The fork already made a copy by the time this runs, so a branch that cannot be adopted would leave
5722
+ * a chat with no story behind: it cannot be opened as a story and nothing would ever adopt it. Such a
5723
+ * copy is discarded. An unavailable agent is the exception — the copy is intact and the branch can be
5724
+ * tried again — so it is left in place.
5725
+ *
5726
+ * @throws {SessionNotFoundError} when either chat is not a chat of a story.
5727
+ * @throws {AgentUnavailableError} when the orchestration or the chat of the branch is not running.
5728
+ */
5729
+ async function branchSession(deps, chat, parent, atSeq) {
5730
+ const id = roleplaySessionOf(chat);
5731
+ if (id === void 0 || roleplaySessionOf(parent) === void 0) throw new SessionNotFoundError(`"${chat}" and "${parent}" are not both chats of stories`);
5732
+ const timelines = deps.timelines;
5733
+ const forked = deps.agentOf(chat);
5734
+ if (timelines === void 0 || forked === void 0) throw new AgentUnavailableError("the branch cannot be made: the orchestration or the chat of the branch is not running");
5735
+ try {
5736
+ await timelines.adopt(chat, parent, atSeq, forked);
5737
+ } catch (error) {
5738
+ if (!(error instanceof AgentUnavailableError)) await deps.discard(chat).catch(() => void 0);
5739
+ throw error;
5740
+ }
5741
+ return { id };
5742
+ }
5697
5743
  // src/host/storage/root-path.ts
5698
5744
  /** Directories every roleplay root contains. */
5699
5745
  const ROOT_LAYOUT = [
@@ -6762,6 +6808,25 @@ async function addAvatarsToWorld(avatars, world, keys, locations) {
6762
6808
  }
6763
6809
  return brought.map((entry) => entry.id);
6764
6810
  }
6811
+ // src/host/images/world-describe.ts
6812
+ /** Describes one picture of a world's library with a model that reads images, and writes the answer into the picture's file. */
6813
+ async function describeWorldImage(deps, path) {
6814
+ if (deps.attachments === void 0) throw new Error("this DSH profile has no attachment service, so a picture cannot be shown to a model");
6815
+ if (deps.parent === void 0) throw new Error("the world's authoring chat is not running: open it with Author with AI once, then describe the picture again");
6816
+ const settings = DEFAULT_SETTINGS;
6817
+ return await interpretImage({
6818
+ parent: deps.parent,
6819
+ signal: new AbortController().signal,
6820
+ attachments: deps.attachments,
6821
+ subjects: deps.subjects,
6822
+ sessionFolder: deps.directory,
6823
+ path,
6824
+ language: deps.language,
6825
+ model: settings.images.interpreterModel,
6826
+ captioner: settings.images.captioner,
6827
+ sampling: childSampling(settings, "records")
6828
+ });
6829
+ }
6765
6830
  // src/host/agent/history.ts
6766
6831
  /** The unknown seq of a turn that is not in the log. */
6767
6832
  const NOT_IN_LOG = -1;
@@ -7072,6 +7137,13 @@ function speakingOf(world, parts, characters, where) {
7072
7137
  const problems = [];
7073
7138
  const segments = parts.map((segment) => {
7074
7139
  if (segment.type === "narration") return segment;
7140
+ if (segment.type === "image") {
7141
+ if (!existsSync(join(world.directory, "images", segment.path))) problems.push({
7142
+ path: join(world.directory, WORLD_FILE_NAME),
7143
+ message: `${where}: the picture "${segment.path}" is not in the world's images`
7144
+ });
7145
+ return segment;
7146
+ }
7075
7147
  const speaker = characters.find((character) => character.id === segment.character);
7076
7148
  if (speaker === void 0) problems.push({
7077
7149
  path: join(world.directory, WORLD_FILE_NAME),
@@ -7161,7 +7233,7 @@ async function restoreSession(deps, id) {
7161
7233
  writeStatus(folder, {});
7162
7234
  }
7163
7235
  // src/shared/transcript.ts
7164
- const segmentLine = (segment) => segment.type === "utterance" ? `**${segment.name}:** “${segment.text}”` : segment.text;
7236
+ const segmentLine = (segment) => segment.type === "image" ? `*(picture: ${segment.path})*` : segment.type === "utterance" ? `**${segment.name}:** “${segment.text}”` : segment.text;
7165
7237
  function outputLines(output, annotated) {
7166
7238
  if (output === void 0) return ["*(nothing was delivered)*"];
7167
7239
  const lines = output.segments.map(segmentLine);
@@ -9987,10 +10059,14 @@ function apply(ctx, config) {
9987
10059
  purgeChat
9988
10060
  }, id),
9989
10061
  rebuild: async (id) => {
9990
- if (await agent.has(id)) await openSession({
9991
- ...deps,
9992
- replaceChat: (chat, title, events) => agent.replace(chat, title, events, purgeChat)
9993
- }, id, { rebuild: true });
10062
+ try {
10063
+ await openSession({
10064
+ ...deps,
10065
+ replaceChat: (chat, title, events) => agent.replace(chat, title, events, purgeChat)
10066
+ }, id, { rebuild: true });
10067
+ } catch (error) {
10068
+ if (!(error instanceof SessionArchivedError)) throw error;
10069
+ }
9994
10070
  }
9995
10071
  });
9996
10072
  prompts.frozen = () => sync.gate.isLocked("prompts");
@@ -10219,7 +10295,32 @@ function apply(ctx, config) {
10219
10295
  }),
10220
10296
  galleryFile: async (worldId, path) => await galleryFile((await editableWorld(worlds, worldId, root.path)).directory, path),
10221
10297
  uploadImage: async (worldId, name, bytes) => await addToLibrary((await editableWorld(worlds, worldId, root.path)).directory, bytes, name),
10222
- updateImage: async (worldId, path, update) => await updateImage((await editableWorld(worlds, worldId, root.path)).directory, path, update)
10298
+ updateImage: async (worldId, path, update) => await updateImage((await editableWorld(worlds, worldId, root.path)).directory, path, update),
10299
+ describeImage: async (worldId, path) => {
10300
+ const world = await editableWorld(worlds, worldId, root.path);
10301
+ const state = await readWorldEditor(world);
10302
+ const chat = await authoring.ensure(world.id, (await worlds.find(world.id))?.summary.name ?? world.id);
10303
+ return await describeWorldImage({
10304
+ directory: world.directory,
10305
+ parent: ctx.get("agents")?.get(SessionId(chat)),
10306
+ attachments: ctx.get("attachments"),
10307
+ language: languages.get(world.id),
10308
+ subjects: [
10309
+ ...state.characters.map((entry) => ({
10310
+ kind: "character",
10311
+ name: entry.name
10312
+ })),
10313
+ ...state.places.map((entry) => ({
10314
+ kind: "location",
10315
+ name: entry.name
10316
+ })),
10317
+ ...state.things.map((entry) => ({
10318
+ kind: "item",
10319
+ name: entry.name
10320
+ }))
10321
+ ]
10322
+ }, path);
10323
+ }
10223
10324
  },
10224
10325
  worldEditor: {
10225
10326
  read: async (worldId) => await readWorldEditor(await editableWorld(worlds, worldId, root.path)),
@@ -10344,6 +10445,13 @@ function apply(ctx, config) {
10344
10445
  readSettings: (id) => readChatSettings(settingsDeps, id),
10345
10446
  writeSettings: (id, value) => writeChatSettings(settingsDeps, id, value),
10346
10447
  timeline: (id) => timelinesOf(ctx, deps.sessionsDir, id).view(id),
10448
+ branch: async (chat, parent, atSeq) => {
10449
+ return await branchSession({
10450
+ timelines: ctx.roleplayOrchestration.timelines,
10451
+ agentOf: (chat) => ctx.get("agents")?.get(SessionId(chat)),
10452
+ discard: purgeChat
10453
+ }, chat, parent, atSeq);
10454
+ },
10347
10455
  moveTimeline: (id, to) => timelinesOf(ctx, deps.sessionsDir, id).move(chatSessionId(id), to === "start" ? null : to),
10348
10456
  markCheckpoint: (id, turn, label, note) => label.trim() === "" ? timelinesOf(ctx, deps.sessionsDir, id).unmark(chatSessionId(id), turn) : timelinesOf(ctx, deps.sessionsDir, id).mark(chatSessionId(id), turn, label, note),
10349
10457
  statistics: (id) => statisticsOfSession({