@dsh-agentic-roleplay/core 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,25 +1,28 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf } from "./access-EbNdZFbk.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";
2
+ import { $ as populateCalendar, $t as readCard, A as worldEntityImageFile, At as loadVariables, B as translateMessage, Bt as parseWorldFile, C as readWorldEditor, Ct as subfolders, D as uploadWorldCharacterPortrait, Dt as readWorldPrompt, E as replaceFile$1, Et as listWorldPrompts, F as loadWorldParts, Ft as IMPORT_FOLDER, G as authoringChatSessionId, Gt as parseLoreEdit, Ht as InvalidEditProblems, I as PRESET_FILE, It as ImportNotFoundError, Jt as parseThingEdit, K as languageOfDocuments, Kt as parsePlaceEdit, L as presetMessage, Lt as ImportStore, Mt as variableProblems, Nt as CHARACTER_FILE_NAME, O as uploadWorldEntityImage, Ot as writeWorldPrompt, Pt as parseCharacterFile, Q as loadValidatedWorld, Qt as pictureOf, Rt as parseChoices, S as generateWorldEntityImage, St as loadCharacters, T as removeWorldTrigger, Tt as deleteWorldPrompt, Ut as parseCharacterEdit, Vt as parseWorldInfoEdit, Wt as parseFactionEdit, X as guardedLookup, Xt as ImportCardError, Y as markReady, Yt as IMPORT_COMMAND, Z as vetUrl, Zt as isPng, _ as editWorldPlots$1, _t as loadCalendar, a as deleteWorldPackFile, at as populateKnowledge, b as entityFolder, bt as loadItems, c as createAuthoredEntity, ct as populateRoutines, dt as routineProblems, en as DICE_COMPARISONS, et as populateCharacters, f as editWorldCharacter$1, ft as TRIGGERS_FILE_NAME, g as editWorldPlace$1, gt as CALENDAR_FILE_NAME, h as editWorldNarrationVoice, ht as parseDiceFile, it as populateItems, j as writeWorldTrigger, jt as parseVariablesFile, k as worldCharacterPortraitFile, kt as VARIABLES_FILE_NAME, l as deleteAuthoredEntity, lt as populateTriggers, m as editWorldLore$1, mt as loadDice, n as packFileProblem, nn as DICE_RESULTS, nt as populateDice, ot as populateLocations, p as editWorldFaction$1, pt as DICE_FILE_NAME, q as readWorldDocuments, qt as parseRelationEdit, rt as populateFactions, st as populateLore, t as MAX_PACK_TEXT, tn as DICE_READINGS, tt as populateClock, u as readAuthoredEntityDocument, ut as populateVariables, v as editWorldRelation$1, vt as parseCalendarFile, w as readWorldTrigger, x as generateWorldCharacterPortrait, xt as CHARACTERS_DIR, y as editWorldThing$1, yt as loadLocations, z as readPreset, zt as WORLD_FILE_NAME } from "./pack-jail-CybSNzxr.js";
3
+ 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-BYjrAen6.js";
4
+ import { c as readTimeline, i as reflectionStatus, l as pathTo, o as TimelineError, u as defaultBoundaries } from "./reflection-waxFg1x-.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
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";
7
+ import { A as observeAsPlayer, D as notesOfSession, T as addToNote, b as populatePlots, c as readRunDetail, d as externalTools, h as PLOTS_METADATA_KEY, i as readUsage, k as readNotes, n as readWithdrawn, s as readActivity, y as plotProgressOf, z as zoneOf } from "./deliver-CpZOxBX5.js";
8
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";
9
+ import { r as childSamplingOf } from "./child-CFjnaTZt.js";
10
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
11
  import { t as doctorChatSessionId } from "./doctor-chat-ByDfCMeo.js";
12
12
  import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-CtFDL22W.js";
13
- import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
13
+ import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
14
14
  import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
15
15
  import { createHash, randomBytes, randomUUID } from "node:crypto";
16
16
  import { Session, SessionId } from "@deepseek-ai/dsh-session";
17
17
  import { ToolCallId, createMessage, createSystemMessage, createToolResultMessage } from "@deepseek-ai/dsh-llm";
18
18
  import { setApprovalPolicy } from "@deepseek-ai/dsh-user-approval";
19
+ import { inflateRawSync } from "node:zlib";
19
20
  import { fileURLToPath } from "node:url";
20
21
  import { Service } from "@deepseek-ai/cordis";
21
22
  import { chmod, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
22
23
  import { addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
24
+ import { request } from "node:http";
25
+ import { request as request$1 } from "node:https";
23
26
  import { pipeline } from "node:stream/promises";
24
27
  import { homedir } from "node:os";
25
28
  import z from "@deepseek-ai/schemastery";
@@ -994,6 +997,17 @@ async function addStarterWorld(catalog, folder, directory = starterDirectory())
994
997
  return added;
995
998
  }
996
999
  //#endregion
1000
+ //#region src/host/catalogue/errors.ts
1001
+ var CatalogueError = class extends Error {
1002
+ failure;
1003
+ detail;
1004
+ constructor(message, failure, detail) {
1005
+ super(message);
1006
+ this.failure = failure;
1007
+ this.detail = detail;
1008
+ }
1009
+ };
1010
+ //#endregion
997
1011
  //#region src/host/http/respond.ts
998
1012
  function sendJson(res, status, payload) {
999
1013
  res.statusCode = status;
@@ -1809,6 +1823,21 @@ async function sendImage(res, image) {
1809
1823
  res.setHeader("cache-control", "private, max-age=31536000, immutable");
1810
1824
  await pipeline(createReadStream(image.file), res);
1811
1825
  }
1826
+ const CATALOGUE_STATUS = {
1827
+ input: 400,
1828
+ unknown: 404,
1829
+ upstream: 502,
1830
+ invalid: 422,
1831
+ conflict: 409
1832
+ };
1833
+ /** A catalogue failure with the status that says whose fault it is; anything else is not ours to describe. */
1834
+ function catalogueFailure(res, error) {
1835
+ if (error instanceof CatalogueError) return error.detail === void 0 ? sendError(res, CATALOGUE_STATUS[error.failure], error.message) : sendJson(res, CATALOGUE_STATUS[error.failure], {
1836
+ message: error.message,
1837
+ ...error.detail
1838
+ });
1839
+ throw error;
1840
+ }
1812
1841
  /** The status an import failure is shown with: what is wrong with the card or the choices is the person's to fix. */
1813
1842
  function importFailure(res, error) {
1814
1843
  if (error instanceof ImportCardError) return sendError(res, 422, error.message);
@@ -1831,7 +1860,7 @@ function languageField(value) {
1831
1860
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
1832
1861
  }
1833
1862
  }
1834
- function createApiHandler({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, connection, speech, externalTools }) {
1863
+ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, connection, speech, externalTools }) {
1835
1864
  const routes = {
1836
1865
  "/speech/capabilities": { GET: async (_req, res) => {
1837
1866
  sendJson(res, 200, { streaming: speech.streaming() });
@@ -1872,6 +1901,81 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
1872
1901
  }
1873
1902
  }
1874
1903
  },
1904
+ "/catalogue/sources": { GET: async (_req, res) => {
1905
+ sendJson(res, 200, catalogue.sources());
1906
+ } },
1907
+ "/catalogue/worlds": { GET: async (_req, res, url) => {
1908
+ const offset = Number(url.searchParams.get("offset") ?? 0);
1909
+ const sort = url.searchParams.get("sort") === "popular" ? "popular" : "recent";
1910
+ try {
1911
+ sendJson(res, 200, await catalogue.worlds(url.searchParams.get("source") ?? "", {
1912
+ kind: url.searchParams.get("kind") === "card" ? "card" : "world",
1913
+ search: url.searchParams.get("search") ?? "",
1914
+ offset: Number.isFinite(offset) ? offset : 0,
1915
+ sort
1916
+ }));
1917
+ } catch (error) {
1918
+ return catalogueFailure(res, error);
1919
+ }
1920
+ } },
1921
+ "/catalogue/world": { GET: async (_req, res, url) => {
1922
+ try {
1923
+ sendJson(res, 200, await catalogue.world(url.searchParams.get("source") ?? "", url.searchParams.get("id") ?? ""));
1924
+ } catch (error) {
1925
+ return catalogueFailure(res, error);
1926
+ }
1927
+ } },
1928
+ "/catalogue/cover": { GET: async (_req, res, url) => {
1929
+ try {
1930
+ const cover = await catalogue.cover(url.searchParams.get("source") ?? "", url.searchParams.get("id") ?? "");
1931
+ res.statusCode = 200;
1932
+ res.setHeader("content-type", cover.type);
1933
+ res.setHeader("content-length", cover.body.length);
1934
+ res.setHeader("x-content-type-options", "nosniff");
1935
+ res.setHeader("cache-control", "private, no-cache");
1936
+ res.end(cover.body);
1937
+ } catch (error) {
1938
+ return catalogueFailure(res, error);
1939
+ }
1940
+ } },
1941
+ "/catalogue/updates": { GET: async (_req, res, url) => {
1942
+ try {
1943
+ sendJson(res, 200, await catalogue.updates(url.searchParams.get("source") ?? ""));
1944
+ } catch (error) {
1945
+ return catalogueFailure(res, error);
1946
+ }
1947
+ } },
1948
+ "/catalogue/install": { POST: async (req, res) => {
1949
+ const body = await readJsonBody(req);
1950
+ if (typeof body.url !== "string") return sendError(res, 400, "url must be text");
1951
+ if (body.sha256 !== void 0 && typeof body.sha256 !== "string") return sendError(res, 400, "sha256 must be text");
1952
+ if (body.mode !== void 0 && body.mode !== "new" && body.mode !== "update" && body.mode !== "copy") return sendError(res, 400, "mode must be new, update or copy");
1953
+ if (body.overwriteChanges !== void 0 && typeof body.overwriteChanges !== "boolean") return sendError(res, 400, "overwriteChanges must be true or false");
1954
+ try {
1955
+ sendJson(res, 201, await catalogue.install({
1956
+ url: body.url,
1957
+ ...body.sha256 === void 0 ? {} : { sha256: body.sha256 },
1958
+ ...body.mode === void 0 ? {} : { mode: body.mode },
1959
+ ...body.overwriteChanges === void 0 ? {} : { overwriteChanges: body.overwriteChanges }
1960
+ }));
1961
+ } catch (error) {
1962
+ return catalogueFailure(res, error);
1963
+ }
1964
+ } },
1965
+ "/catalogue/convert": { POST: async (req, res) => {
1966
+ const body = await readJsonBody(req);
1967
+ if (typeof body.source !== "string" || typeof body.versionId !== "string") return sendError(res, 400, "source and versionId must be text");
1968
+ try {
1969
+ const language = languageField(body.language);
1970
+ sendJson(res, 201, await catalogue.convert({
1971
+ source: body.source,
1972
+ versionId: body.versionId,
1973
+ ...language === void 0 ? {} : { language }
1974
+ }));
1975
+ } catch (error) {
1976
+ return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
1977
+ }
1978
+ } },
1875
1979
  "/worlds/starter": {
1876
1980
  GET: async (_req, res) => {
1877
1981
  sendJson(res, 200, await starter.list());
@@ -2120,6 +2224,93 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
2120
2224
  }
2121
2225
  }
2122
2226
  },
2227
+ "/worlds/interface/file": {
2228
+ GET: async (_req, res, url) => {
2229
+ try {
2230
+ sendJson(res, 200, { text: await worldEditor.readPackFile(url.searchParams.get("id") ?? "", url.searchParams.get("pack") ?? "", url.searchParams.get("path") ?? "") });
2231
+ } catch (error) {
2232
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2233
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2234
+ message: error.message,
2235
+ problems: error.problems
2236
+ });
2237
+ throw error;
2238
+ }
2239
+ },
2240
+ PUT: async (req, res, url) => {
2241
+ try {
2242
+ const body = await readJsonBody(req);
2243
+ if (typeof body?.text !== "string") throw new InvalidEditProblems(["text must be text"]);
2244
+ sendJson(res, 200, { problems: await worldEditor.writePackFile(url.searchParams.get("id") ?? "", url.searchParams.get("pack") ?? "", url.searchParams.get("path") ?? "", body.text) });
2245
+ } catch (error) {
2246
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2247
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2248
+ message: error.message,
2249
+ problems: error.problems
2250
+ });
2251
+ throw error;
2252
+ }
2253
+ },
2254
+ DELETE: async (_req, res, url) => {
2255
+ try {
2256
+ sendJson(res, 200, { problems: await worldEditor.deletePackFile(url.searchParams.get("id") ?? "", url.searchParams.get("pack") ?? "", url.searchParams.get("path") ?? "") });
2257
+ } catch (error) {
2258
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2259
+ return sendError(res, 422, error instanceof Error ? error.message : String(error));
2260
+ }
2261
+ }
2262
+ },
2263
+ "/worlds/interface/pack": { POST: async (req, res, url) => {
2264
+ try {
2265
+ const body = await readJsonBody(req);
2266
+ sendJson(res, 201, { problems: await worldEditor.createPack(url.searchParams.get("id") ?? "", url.searchParams.get("pack") ?? "", typeof body?.name === "string" ? body.name : "") });
2267
+ } catch (error) {
2268
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2269
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2270
+ message: error.message,
2271
+ problems: error.problems
2272
+ });
2273
+ throw error;
2274
+ }
2275
+ } },
2276
+ "/worlds/state/trigger": {
2277
+ GET: async (_req, res, url) => {
2278
+ try {
2279
+ sendJson(res, 200, await worldEditor.readTrigger(url.searchParams.get("id") ?? "", url.searchParams.get("key") ?? ""));
2280
+ } catch (error) {
2281
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2282
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2283
+ message: error.message,
2284
+ problems: error.problems
2285
+ });
2286
+ throw error;
2287
+ }
2288
+ },
2289
+ PUT: async (req, res, url) => {
2290
+ try {
2291
+ sendJson(res, 200, await worldEditor.writeTrigger(url.searchParams.get("id") ?? "", url.searchParams.get("key") ?? "", await readJsonBody(req)));
2292
+ } catch (error) {
2293
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2294
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2295
+ message: error.message,
2296
+ problems: error.problems
2297
+ });
2298
+ throw error;
2299
+ }
2300
+ },
2301
+ DELETE: async (_req, res, url) => {
2302
+ try {
2303
+ sendJson(res, 200, await worldEditor.removeTrigger(url.searchParams.get("id") ?? "", url.searchParams.get("key") ?? ""));
2304
+ } catch (error) {
2305
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2306
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2307
+ message: error.message,
2308
+ problems: error.problems
2309
+ });
2310
+ throw error;
2311
+ }
2312
+ }
2313
+ },
2123
2314
  "/worlds/state/plots": { PUT: async (req, res, url) => {
2124
2315
  try {
2125
2316
  const body = await readJsonBody(req);
@@ -2361,6 +2552,72 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
2361
2552
  return sendError(res, 404, error instanceof Error ? error.message : String(error));
2362
2553
  }
2363
2554
  } },
2555
+ ...Object.fromEntries(["place", "thing"].flatMap((kind) => [
2556
+ [`/worlds/state/${kind}/image`, { POST: async (_req, res, url) => {
2557
+ try {
2558
+ sendJson(res, 200, await worldEditor.generateEntityImage(url.searchParams.get("id") ?? "", kind, url.searchParams.get("key") ?? ""));
2559
+ } catch (error) {
2560
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2561
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2562
+ message: error.message,
2563
+ problems: error.problems
2564
+ });
2565
+ return sendError(res, 409, error instanceof Error ? error.message : String(error));
2566
+ }
2567
+ } }],
2568
+ [`/worlds/state/${kind}/image/upload`, { POST: async (req, res, url) => {
2569
+ const name = decodeURIComponent(String(req.headers["x-file-name"] ?? "image.png"));
2570
+ try {
2571
+ sendJson(res, 200, await worldEditor.uploadEntityImage(url.searchParams.get("id") ?? "", kind, url.searchParams.get("key") ?? "", await readBinaryBody(req, MAX_UPLOAD_BYTES), name));
2572
+ } catch (error) {
2573
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2574
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2575
+ message: error.message,
2576
+ problems: error.problems
2577
+ });
2578
+ throw error;
2579
+ }
2580
+ } }],
2581
+ [`/worlds/state/${kind}/image/file`, { GET: async (_req, res, url) => {
2582
+ try {
2583
+ await sendImage(res, await worldEditor.entityImageFile(url.searchParams.get("id") ?? "", kind, url.searchParams.get("key") ?? ""));
2584
+ } catch (error) {
2585
+ return sendError(res, 404, error instanceof Error ? error.message : String(error));
2586
+ }
2587
+ } }],
2588
+ [`/sessions/world/${kind}/image`, { POST: async (_req, res, url) => {
2589
+ try {
2590
+ sendJson(res, 200, await sessions.generateEntityImage(url.searchParams.get("id") ?? "", kind, url.searchParams.get("key") ?? ""));
2591
+ } catch (error) {
2592
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2593
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2594
+ message: error.message,
2595
+ problems: error.problems
2596
+ });
2597
+ return sendError(res, 409, error instanceof Error ? error.message : String(error));
2598
+ }
2599
+ } }],
2600
+ [`/sessions/world/${kind}/image/upload`, { POST: async (req, res, url) => {
2601
+ const name = decodeURIComponent(String(req.headers["x-file-name"] ?? "image.png"));
2602
+ try {
2603
+ sendJson(res, 200, await sessions.uploadEntityImage(url.searchParams.get("id") ?? "", kind, url.searchParams.get("key") ?? "", await readBinaryBody(req, MAX_UPLOAD_BYTES), name));
2604
+ } catch (error) {
2605
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2606
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2607
+ message: error.message,
2608
+ problems: error.problems
2609
+ });
2610
+ throw error;
2611
+ }
2612
+ } }],
2613
+ [`/sessions/world/${kind}/image/file`, { GET: async (_req, res, url) => {
2614
+ try {
2615
+ await sendImage(res, await sessions.entityImageFile(url.searchParams.get("id") ?? "", kind, url.searchParams.get("key") ?? ""));
2616
+ } catch (error) {
2617
+ return sendError(res, 404, error instanceof Error ? error.message : String(error));
2618
+ }
2619
+ } }]
2620
+ ])),
2364
2621
  "/worlds/characters": { GET: async (_req, res, url) => {
2365
2622
  try {
2366
2623
  sendJson(res, 200, await worldCharacters(url.searchParams.get("id") ?? ""));
@@ -3203,7 +3460,7 @@ function sessionOf(deps, id) {
3203
3460
  return deps.state.openSession(directory, id);
3204
3461
  }
3205
3462
  const keyOf = (character) => character.sourceId ?? String(character.id);
3206
- function worldOf(session, sessionsDir) {
3463
+ function worldOf$1(session, sessionsDir) {
3207
3464
  const narrationVoice = session.metadata.getValue("roleplay.tts.narrationVoice");
3208
3465
  const characters = session.characters.list().map((character) => {
3209
3466
  const state = session.characterStates.get(character.id);
@@ -3267,6 +3524,7 @@ function worldOf(session, sessionsDir) {
3267
3524
  key: location.sourceId ?? String(location.id),
3268
3525
  name: location.name,
3269
3526
  description: location.description,
3527
+ ...imageOf(session, sessionsDir, "place", location),
3270
3528
  ...location.parentId === void 0 ? {} : { parent: {
3271
3529
  key: session.locations.get(location.parentId)?.sourceId ?? String(location.parentId),
3272
3530
  name: locationName(location.parentId)
@@ -3288,6 +3546,7 @@ function worldOf(session, sessionsDir) {
3288
3546
  key: item.sourceId ?? String(item.id),
3289
3547
  name: item.name,
3290
3548
  description: item.description,
3549
+ ...imageOf(session, sessionsDir, "thing", item),
3291
3550
  quantity: item.quantity,
3292
3551
  unique: item.unique,
3293
3552
  quality: item.quality,
@@ -3490,7 +3749,7 @@ function editWorldLore(deps, id, key, edit) {
3490
3749
  const entry = session.lore.list().find((candidate) => (candidate.sourceId ?? String(candidate.id)) === key);
3491
3750
  if (entry === void 0) throw new InvalidEditProblems([`there is no lore "${key}"`]);
3492
3751
  session.lore.update(entry.id, edit);
3493
- return worldOf(session, deps.sessionsDir());
3752
+ return worldOf$1(session, deps.sessionsDir());
3494
3753
  }
3495
3754
  function editWorldPlots(deps, id, edit) {
3496
3755
  const parsed = parsePlotsFile(JSON.stringify(edit.plots));
@@ -3518,13 +3777,13 @@ function editWorldPlots(deps, id, edit) {
3518
3777
  });
3519
3778
  }
3520
3779
  session.metadata.setValue(PLOTS_METADATA_KEY, merged);
3521
- return worldOf(session, deps.sessionsDir());
3780
+ return worldOf$1(session, deps.sessionsDir());
3522
3781
  }
3523
3782
  function editSessionNarrationVoice(deps, id, voice) {
3524
3783
  const session = sessionOf(deps, id);
3525
3784
  if (voice.trim() === "") session.metadata.deleteValue("roleplay.tts.narrationVoice");
3526
3785
  else session.metadata.setValue("roleplay.tts.narrationVoice", voice.trim());
3527
- return worldOf(session, deps.sessionsDir());
3786
+ return worldOf$1(session, deps.sessionsDir());
3528
3787
  }
3529
3788
  const relationKey = (...parts) => parts.map((part) => encodeURIComponent(part)).join(":");
3530
3789
  const relationParts = (key) => key.split(":").map((part) => decodeURIComponent(part));
@@ -3533,7 +3792,7 @@ const relationParts = (key) => key.split(":").map((part) => decodeURIComponent(p
3533
3792
  * @throws {SessionNotFoundError} when the id names no session.
3534
3793
  */
3535
3794
  function readWorldState(deps, id) {
3536
- return worldOf(sessionOf(deps, id), deps.sessionsDir());
3795
+ return worldOf$1(sessionOf(deps, id), deps.sessionsDir());
3537
3796
  }
3538
3797
  /**
3539
3798
  * Change a character of a session, all of it or none of it, and say how the world stands after.
@@ -3577,7 +3836,7 @@ function editWorldCharacter(deps, id, key, edit) {
3577
3836
  if (error instanceof Error && error.name === "InvalidValueError") throw new InvalidEditProblems([error.message]);
3578
3837
  throw error;
3579
3838
  }
3580
- return worldOf(session, deps.sessionsDir());
3839
+ return worldOf$1(session, deps.sessionsDir());
3581
3840
  }
3582
3841
  function editWorldPlace(deps, id, key, edit) {
3583
3842
  const session = sessionOf(deps, id);
@@ -3600,7 +3859,7 @@ function editWorldPlace(deps, id, key, edit) {
3600
3859
  if (error instanceof Error && (error.name === "InvalidValueError" || error.name === "ConflictError")) throw new InvalidEditProblems([error.message]);
3601
3860
  throw error;
3602
3861
  }
3603
- return worldOf(session, deps.sessionsDir());
3862
+ return worldOf$1(session, deps.sessionsDir());
3604
3863
  }
3605
3864
  function editWorldThing(deps, id, key, edit) {
3606
3865
  const session = sessionOf(deps, id);
@@ -3624,7 +3883,7 @@ function editWorldThing(deps, id, key, edit) {
3624
3883
  if (error instanceof Error && (error.name === "InvalidValueError" || error.name === "ConflictError")) throw new InvalidEditProblems([error.message]);
3625
3884
  throw error;
3626
3885
  }
3627
- return worldOf(session, deps.sessionsDir());
3886
+ return worldOf$1(session, deps.sessionsDir());
3628
3887
  }
3629
3888
  function editWorldFaction(deps, id, key, edit) {
3630
3889
  const session = sessionOf(deps, id);
@@ -3644,7 +3903,7 @@ function editWorldFaction(deps, id, key, edit) {
3644
3903
  if (error instanceof Error && (error.name === "InvalidValueError" || error.name === "ConflictError")) throw new InvalidEditProblems([error.message]);
3645
3904
  throw error;
3646
3905
  }
3647
- return worldOf(session, deps.sessionsDir());
3906
+ return worldOf$1(session, deps.sessionsDir());
3648
3907
  }
3649
3908
  function editWorldRelation(deps, id, edit) {
3650
3909
  const session = sessionOf(deps, id);
@@ -3703,7 +3962,7 @@ function editWorldRelation(deps, id, edit) {
3703
3962
  ].includes(error.name)) throw new InvalidEditProblems([error.message]);
3704
3963
  throw error;
3705
3964
  }
3706
- return worldOf(session, deps.sessionsDir());
3965
+ return worldOf$1(session, deps.sessionsDir());
3707
3966
  }
3708
3967
  const isNewRelation = (edit) => "create" in edit && edit.create === true;
3709
3968
  function createSessionRelation(session, sessionsDir, edit) {
@@ -3755,13 +4014,79 @@ function createSessionRelation(session, sessionsDir, edit) {
3755
4014
  ].includes(error.name)) throw new InvalidEditProblems([error.message]);
3756
4015
  throw error;
3757
4016
  }
3758
- return worldOf(session, sessionsDir);
4017
+ return worldOf$1(session, sessionsDir);
3759
4018
  }
3760
4019
  function characterOf(session, key) {
3761
4020
  const character = session.characters.list().find((candidate) => keyOf(candidate) === key);
3762
4021
  if (character === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
3763
4022
  return character;
3764
4023
  }
4024
+ const IMAGE_SUBJECT = {
4025
+ place: "location",
4026
+ thing: "item"
4027
+ };
4028
+ function addressOf(session, kind, entity) {
4029
+ const identity = session.visualIdentities.get(IMAGE_SUBJECT[kind], entity.id);
4030
+ return {
4031
+ kind: IMAGE_SUBJECT[kind],
4032
+ localId: entity.sourceId ?? entity.id,
4033
+ ...identity?.globalId === void 0 ? {} : { globalId: identity.globalId }
4034
+ };
4035
+ }
4036
+ function imageOf(session, sessionsDir, kind, entity) {
4037
+ const id = session.metadata.get().id;
4038
+ const file = referenceImagePath(sessionFolder(sessionsDir, id), addressOf(session, kind, entity));
4039
+ return existsSync(file) ? { image: `/${API_PREFIX}/sessions/world/${kind}/image/file?id=${encodeURIComponent(id)}&key=${encodeURIComponent(entity.sourceId ?? String(entity.id))}&v=${statSync(file).mtimeMs}` } : {};
4040
+ }
4041
+ function entityOf(session, kind, key) {
4042
+ const found = (kind === "place" ? session.locations.list() : session.items.list()).find((candidate) => (candidate.sourceId ?? String(candidate.id)) === key);
4043
+ if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
4044
+ return found;
4045
+ }
4046
+ /** Generate or replace the reference picture of a session's place or thing from its copied identity. */
4047
+ async function generateSessionEntityImage(deps, id, kind, key, service) {
4048
+ const session = sessionOf(deps, id);
4049
+ const entity = entityOf(session, kind, key);
4050
+ const identity = session.visualIdentities.get(IMAGE_SUBJECT[kind], entity.id);
4051
+ if (identity === void 0) throw new InvalidEditProblems([`${entity.name} needs a visual identity before a picture can be generated`]);
4052
+ await generateReferenceImage(service, {
4053
+ root: sessionFolder(deps.sessionsDir(), id),
4054
+ subject: {
4055
+ ...addressOf(session, kind, entity),
4056
+ name: entity.name
4057
+ },
4058
+ identity
4059
+ });
4060
+ return worldOf$1(session, deps.sessionsDir());
4061
+ }
4062
+ /** The picture the player brought becomes the place's or thing's reference picture. */
4063
+ async function uploadSessionEntityImage(deps, id, kind, key, png, originalName) {
4064
+ const session = sessionOf(deps, id);
4065
+ const entity = entityOf(session, kind, key);
4066
+ try {
4067
+ await uploadReferenceImage({
4068
+ root: sessionFolder(deps.sessionsDir(), id),
4069
+ subject: {
4070
+ ...addressOf(session, kind, entity),
4071
+ name: entity.name
4072
+ },
4073
+ png,
4074
+ ...originalName === void 0 ? {} : { originalName }
4075
+ });
4076
+ } catch (error) {
4077
+ throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
4078
+ }
4079
+ return worldOf$1(session, deps.sessionsDir());
4080
+ }
4081
+ /** Resolve the picture through session state so request parameters cannot select arbitrary files. */
4082
+ async function sessionEntityImageFile(deps, id, kind, key) {
4083
+ const session = sessionOf(deps, id);
4084
+ const file = referenceImagePath(sessionFolder(deps.sessionsDir(), id), addressOf(session, kind, entityOf(session, kind, key)));
4085
+ return {
4086
+ file,
4087
+ size: (await stat(file)).size
4088
+ };
4089
+ }
3765
4090
  /** Generate or replace a session character's stable reference portrait from its copied identity. */
3766
4091
  async function generateSessionCharacterPortrait(deps, id, key, service) {
3767
4092
  const session = sessionOf(deps, id);
@@ -3778,7 +4103,7 @@ async function generateSessionCharacterPortrait(deps, id, key, service) {
3778
4103
  },
3779
4104
  identity
3780
4105
  });
3781
- return worldOf(session, deps.sessionsDir());
4106
+ return worldOf$1(session, deps.sessionsDir());
3782
4107
  }
3783
4108
  /** The picture the player brought becomes the session character's portrait. */
3784
4109
  async function uploadSessionCharacterPortrait(deps, id, key, png, originalName) {
@@ -3800,7 +4125,7 @@ async function uploadSessionCharacterPortrait(deps, id, key, png, originalName)
3800
4125
  } catch (error) {
3801
4126
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
3802
4127
  }
3803
- return worldOf(session, deps.sessionsDir());
4128
+ return worldOf$1(session, deps.sessionsDir());
3804
4129
  }
3805
4130
  /** Resolve a portrait through session state so request parameters cannot select arbitrary files. */
3806
4131
  async function sessionCharacterPortraitFile(deps, id, key) {
@@ -4327,6 +4652,7 @@ function payloadOf(deps, id, settings) {
4327
4652
  pendingRecords: deps.pendingRecords(id),
4328
4653
  pendingConsolidation: deps.pendingConsolidation(id),
4329
4654
  activity: deps.activity(id),
4655
+ usage: deps.usage(id),
4330
4656
  interventions: deps.interventions(id),
4331
4657
  vectors: deps.vectors(id),
4332
4658
  reflection: deps.reflection(id),
@@ -4385,6 +4711,65 @@ function resetVectors(session) {
4385
4711
  session.recallIndex.reset();
4386
4712
  }
4387
4713
  //#endregion
4714
+ //#region src/host/authoring/pack-files.ts
4715
+ /** Where a text file of a pack is, once the pack name and the path are known to be allowed; otherwise why not. */
4716
+ function placeOf(directory, pack, path, tool, text = "") {
4717
+ if (!isPackId(pack)) throw new InvalidEditProblems([`"${pack}" is not a usable pack name (letters, digits, "-" and "_")`]);
4718
+ const relative = packPath(path);
4719
+ if (relative === void 0) throw new InvalidEditProblems([`"${path}" is not a path inside a pack`]);
4720
+ const file = join(directory, "ui", pack, ...relative.split("/"));
4721
+ const problem = packFileProblem(tool, file, directory, [text]);
4722
+ if (problem !== void 0) throw new InvalidEditProblems([problem]);
4723
+ return file;
4724
+ }
4725
+ const problemsOf = (directory, pack) => {
4726
+ const folder = join(directory, "ui", pack);
4727
+ return existsSync(join(folder, "pack.json")) ? readPack(folder, pack, (file) => file).problems : [{
4728
+ file: "pack.json",
4729
+ message: "the pack has no pack.json"
4730
+ }];
4731
+ };
4732
+ /** The text of one file of a pack, as the editor shows it. @throws {InvalidEditProblems} when the file is not a text file of a pack or is not there. */
4733
+ async function readWorldPackFile(directory, pack, path) {
4734
+ const file = placeOf(directory, pack, path, "read");
4735
+ try {
4736
+ return await readFile(file, "utf8");
4737
+ } catch (error) {
4738
+ if (error.code === "ENOENT") throw new InvalidEditProblems([`the pack "${pack}" has no file "${path}"`]);
4739
+ throw error;
4740
+ }
4741
+ }
4742
+ /**
4743
+ * Writes one text file of a pack, making the pack's folder when it is not there yet. The file is written whole (to a temporary file that is renamed), and the pack is read
4744
+ * again as a story start reads it.
4745
+ * @returns what is wrong with the pack now; the file is kept even then, so that it can be put right.
4746
+ * @throws {InvalidEditProblems} when the name, the path, the kind of file or the size is not allowed.
4747
+ */
4748
+ async function writeWorldPackFile(directory, pack, path, text) {
4749
+ if (Buffer.byteLength(text) > 204800) throw new InvalidEditProblems([`a file holds at most ${MAX_PACK_TEXT / 1024} KB of text`]);
4750
+ const file = placeOf(directory, pack, path, "write", text);
4751
+ await mkdir(dirname(file), { recursive: true });
4752
+ const temporary = join(dirname(file), `.${process.pid}.${randomUUID()}.tmp`);
4753
+ try {
4754
+ await writeFile(temporary, text);
4755
+ await rename(temporary, file);
4756
+ } catch (error) {
4757
+ await rm(temporary, { force: true });
4758
+ throw error;
4759
+ }
4760
+ return problemsOf(directory, pack);
4761
+ }
4762
+ /** Makes a pack with a manifest that names it and nothing else yet. @throws {InvalidEditProblems} when the name is not usable or the pack exists. */
4763
+ async function createWorldPack(directory, pack, name) {
4764
+ if (!isPackId(pack)) throw new InvalidEditProblems([`"${pack}" is not a usable pack name (letters, digits, "-" and "_")`]);
4765
+ if (existsSync(join(directory, "ui", pack))) throw new InvalidEditProblems([`the world already carries a pack "${pack}"`]);
4766
+ return await writeWorldPackFile(directory, pack, "pack.json", `${JSON.stringify({
4767
+ name: name.trim() === "" ? pack : name.trim(),
4768
+ version: "1",
4769
+ api: 1
4770
+ }, null, 2)}\n`);
4771
+ }
4772
+ //#endregion
4388
4773
  //#region src/host/sessions/interventions.ts
4389
4774
  /** What the story's triggers delivered lately and what became of each, oldest first. */
4390
4775
  function readInterventions(session) {
@@ -4795,6 +5180,796 @@ var WorldCatalog = class extends Service {
4795
5180
  }
4796
5181
  };
4797
5182
  //#endregion
5183
+ //#region src/shared/catalogue.ts
5184
+ const CATALOGUE_CARD_TYPE = "sillytavern/character";
5185
+ const CATALOGUE_WORLD_TYPE = "dsh-agentic-roleplay/world";
5186
+ //#endregion
5187
+ //#region src/host/catalogue/origin.ts
5188
+ const ORIGIN_FILE = ".catalogue.json";
5189
+ const MAX_LISTED_CHANGES = 12;
5190
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5191
+ /** The origin recorded in a world's folder, or nothing when it has none. @throws {CatalogueError} when the record is damaged. */
5192
+ async function readOrigin(directory) {
5193
+ let text;
5194
+ try {
5195
+ text = await readFile(join(directory, ORIGIN_FILE), "utf8");
5196
+ } catch (error) {
5197
+ if (error.code === "ENOENT") return void 0;
5198
+ throw error;
5199
+ }
5200
+ const damaged = () => new CatalogueError(`${ORIGIN_FILE} in ${directory} is damaged`, "invalid");
5201
+ let value;
5202
+ try {
5203
+ value = JSON.parse(text);
5204
+ } catch {
5205
+ throw damaged();
5206
+ }
5207
+ if (!isRecord(value)) throw damaged();
5208
+ const { kind, root, resourceId, versionId, version, files } = value;
5209
+ if (kind !== "release" && kind !== "card" || typeof root !== "string" || typeof resourceId !== "string" || typeof versionId !== "string" || typeof version !== "string") throw damaged();
5210
+ if (kind === "card") return {
5211
+ kind,
5212
+ root,
5213
+ resourceId,
5214
+ versionId,
5215
+ version
5216
+ };
5217
+ if (!isRecord(files) || !Object.values(files).every((hash) => typeof hash === "string")) throw damaged();
5218
+ return {
5219
+ kind,
5220
+ root,
5221
+ resourceId,
5222
+ versionId,
5223
+ version,
5224
+ files
5225
+ };
5226
+ }
5227
+ async function writeOrigin(directory, origin) {
5228
+ const file = join(directory, ORIGIN_FILE);
5229
+ const temporary = `${file}.${randomUUID()}.tmp`;
5230
+ await writeFile(temporary, JSON.stringify(origin, null, 2));
5231
+ await rename(temporary, file);
5232
+ }
5233
+ /** SHA-256 of every file in a world folder; entries whose names start with a dot (this record, the trash, import state) are not the world's own. */
5234
+ async function hashWorld(directory) {
5235
+ const hashes = {};
5236
+ const walk = async (relative) => {
5237
+ for (const entry of await readdir(join(directory, relative), { withFileTypes: true })) {
5238
+ if (relative === "" && entry.name.startsWith(".")) continue;
5239
+ const path = relative === "" ? entry.name : `${relative}/${entry.name}`;
5240
+ if (entry.isDirectory()) await walk(path);
5241
+ else if (entry.isFile()) hashes[path] = createHash("sha256").update(await readFile(join(directory, path))).digest("hex");
5242
+ }
5243
+ };
5244
+ await walk("");
5245
+ return hashes;
5246
+ }
5247
+ function compare(recorded, current) {
5248
+ return {
5249
+ changed: Object.keys(recorded).filter((path) => current[path] !== void 0 && current[path] !== recorded[path]),
5250
+ added: Object.keys(current).filter((path) => recorded[path] === void 0),
5251
+ removed: Object.keys(recorded).filter((path) => current[path] === void 0)
5252
+ };
5253
+ }
5254
+ const isUnchanged = (changes) => changes.changed.length + changes.added.length + changes.removed.length === 0;
5255
+ /** The differences as short lines for a person to read, capped. */
5256
+ function describeChanges(changes) {
5257
+ const lines = [
5258
+ ...changes.changed.map((path) => `changed: ${path}`),
5259
+ ...changes.added.map((path) => `added: ${path}`),
5260
+ ...changes.removed.map((path) => `removed: ${path}`)
5261
+ ];
5262
+ return lines.length <= MAX_LISTED_CHANGES ? lines : [...lines.slice(0, MAX_LISTED_CHANGES), `and ${lines.length - MAX_LISTED_CHANGES} more`];
5263
+ }
5264
+ /** How a world's files compare with the release it came from: the differences, or `unverified` when no record of the release exists. */
5265
+ async function localChanges(directory) {
5266
+ const origin = await readOrigin(directory);
5267
+ if (origin?.kind !== "release") return "unverified";
5268
+ return compare(origin.files, await hashWorld(directory));
5269
+ }
5270
+ //#endregion
5271
+ //#region src/host/catalogue/zip.ts
5272
+ const END_SIGNATURE = 101010256;
5273
+ const CENTRAL_SIGNATURE = 33639248;
5274
+ const LOCAL_SIGNATURE = 67324752;
5275
+ const MAX_FILES = 5e3;
5276
+ const SYMBOLIC_LINK = 40960;
5277
+ const TYPE_MASK = 61440;
5278
+ const invalid = (message) => new CatalogueError(message, "invalid");
5279
+ /** An archive path that stays inside the folder it is unpacked to, or the reason it does not. */
5280
+ function archivePathProblem(name) {
5281
+ if (name.includes("\\") || name.includes("\0")) return "has a backslash or a NUL character";
5282
+ if (name.startsWith("/") || /^[A-Za-z]:/.test(name)) return "is absolute";
5283
+ const parts = name.split("/");
5284
+ if (parts.some((part) => part === "..")) return "climbs out of the folder";
5285
+ if (parts.some((part, index) => part === "." || part === "" && index !== parts.length - 1)) return "is ambiguous";
5286
+ }
5287
+ /**
5288
+ * Reads the files of a ZIP archive, refusing anything that could write outside the target or exhaust the machine: unsafe or repeated paths
5289
+ * (also by case), links, encryption, ZIP64, methods other than stored and deflate, too many files, and a total size past the limit
5290
+ * (checked from the sizes the archive declares and again from what inflating really produced).
5291
+ * @throws {CatalogueError} (`invalid`) when the archive is not acceptable.
5292
+ */
5293
+ function readZip(archive, limits) {
5294
+ let end = -1;
5295
+ for (let at = archive.length - 22; at >= Math.max(0, archive.length - 22 - 65535); at -= 1) if (archive.readUInt32LE(at) === END_SIGNATURE) {
5296
+ end = at;
5297
+ break;
5298
+ }
5299
+ if (end < 0) throw invalid("the file is not a ZIP archive");
5300
+ const count = archive.readUInt16LE(end + 10);
5301
+ const directorySize = archive.readUInt32LE(end + 12);
5302
+ let at = archive.readUInt32LE(end + 16);
5303
+ if (count === 65535 || directorySize === 4294967295 || at === 4294967295) throw invalid("ZIP64 archives are not supported");
5304
+ if (count > MAX_FILES) throw invalid(`the archive holds more than ${MAX_FILES} files`);
5305
+ const files = /* @__PURE__ */ new Map();
5306
+ const folded = /* @__PURE__ */ new Set();
5307
+ let declared = 0;
5308
+ let produced = 0;
5309
+ for (let index = 0; index < count; index += 1) {
5310
+ if (at + 46 > archive.length || archive.readUInt32LE(at) !== CENTRAL_SIGNATURE) throw invalid("the archive directory is damaged");
5311
+ const flags = archive.readUInt16LE(at + 8);
5312
+ const method = archive.readUInt16LE(at + 10);
5313
+ const compressed = archive.readUInt32LE(at + 20);
5314
+ const size = archive.readUInt32LE(at + 24);
5315
+ const nameLength = archive.readUInt16LE(at + 28);
5316
+ const extraLength = archive.readUInt16LE(at + 30);
5317
+ const commentLength = archive.readUInt16LE(at + 32);
5318
+ const attributes = archive.readUInt32LE(at + 38);
5319
+ const local = archive.readUInt32LE(at + 42);
5320
+ if (at + 46 + nameLength > archive.length) throw invalid("the archive directory is damaged");
5321
+ const name = archive.toString("utf8", at + 46, at + 46 + nameLength);
5322
+ at += 46 + nameLength + extraLength + commentLength;
5323
+ const problem = archivePathProblem(name);
5324
+ if (problem !== void 0) throw invalid(`the archive path "${name}" ${problem}`);
5325
+ if (name.endsWith("/")) continue;
5326
+ if ((attributes >>> 16 & TYPE_MASK) === SYMBOLIC_LINK) throw invalid(`the archive holds a link: ${name}`);
5327
+ if ((flags & 1) !== 0) throw invalid("encrypted archives are not supported");
5328
+ if (method !== 0 && method !== 8) throw invalid(`the archive entry ${name} uses an unsupported compression method`);
5329
+ if (compressed === 4294967295 || size === 4294967295) throw invalid("ZIP64 archives are not supported");
5330
+ const key = name.toLowerCase();
5331
+ if (files.has(name) || folded.has(key)) throw invalid(`the archive repeats a path (or differs only by case): ${name}`);
5332
+ declared += size;
5333
+ if (declared > limits.maxBytes) throw invalid(`the archive unpacks to more than ${limits.maxBytes} bytes`);
5334
+ if (local + 30 > archive.length || archive.readUInt32LE(local) !== LOCAL_SIGNATURE) throw invalid(`the archive entry ${name} is damaged`);
5335
+ const start = local + 30 + archive.readUInt16LE(local + 26) + archive.readUInt16LE(local + 28);
5336
+ if (start + compressed > archive.length) throw invalid(`the archive entry ${name} is cut short`);
5337
+ const raw = archive.subarray(start, start + compressed);
5338
+ let content;
5339
+ try {
5340
+ content = method === 0 ? Buffer.from(raw) : inflateRawSync(raw, { maxOutputLength: Math.max(size, 1) });
5341
+ } catch {
5342
+ throw invalid(`the archive entry ${name} cannot be unpacked`);
5343
+ }
5344
+ if (content.length !== size) throw invalid(`the archive entry ${name} does not match its declared size`);
5345
+ produced += content.length;
5346
+ if (produced > limits.maxBytes) throw invalid(`the archive unpacks to more than ${limits.maxBytes} bytes`);
5347
+ files.set(name, content);
5348
+ folded.add(key);
5349
+ }
5350
+ return files;
5351
+ }
5352
+ //#endregion
5353
+ //#region src/host/catalogue/install.ts
5354
+ const FOLDER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
5355
+ const MAX_FOLDER_COPIES = 99;
5356
+ /** The one top-level folder of a world archive and the files in it, or why the archive is not a world. */
5357
+ function worldFolder(files) {
5358
+ const marks = [...files.keys()].filter((path) => path.split("/").pop() === WORLD_FILE_NAME);
5359
+ if (marks.length !== 1 || marks[0].split("/").length !== 2) throw new CatalogueError(`the archive must hold one top-level world folder with ${WORLD_FILE_NAME}`, "invalid");
5360
+ const folder = marks[0].split("/")[0];
5361
+ if (!FOLDER_NAME.test(folder)) throw new CatalogueError(`the world folder "${folder}" has an unsafe or unsupported name`, "invalid");
5362
+ const stray = [...files.keys()].find((path) => path.split("/")[0] !== folder);
5363
+ if (stray !== void 0) throw new CatalogueError(`every file must be inside the "${folder}" folder: ${stray}`, "invalid");
5364
+ return folder;
5365
+ }
5366
+ function freeFolder(directory, wanted) {
5367
+ for (let copy = 1; copy <= 100; copy += 1) {
5368
+ const candidate = copy === 1 ? wanted : `${wanted}-${copy}`;
5369
+ if (!existsSync(join(directory, candidate))) return candidate;
5370
+ }
5371
+ throw new CatalogueError(`there are already ${MAX_FOLDER_COPIES} world folders named like "${wanted}"`, "conflict");
5372
+ }
5373
+ /** The world file of a second copy: its own identity and a name that tells it from the first. */
5374
+ function asCopy(text, id, name) {
5375
+ const { id: _previous, name: _name, ...rest } = JSON.parse(text.replace(/^\uFEFF/, ""));
5376
+ return JSON.stringify({
5377
+ id,
5378
+ name,
5379
+ ...rest
5380
+ }, null, indentOf(text)) + (text.endsWith("\n") ? "\n" : "");
5381
+ }
5382
+ const stamp = () => (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
5383
+ /**
5384
+ * Unpacks a world archive into the person's worlds, after the same checks the worlds list makes of a world: it is written beside the
5385
+ * worlds first and only moved in when whole, and removed again if the catalogue then refuses it.
5386
+ *
5387
+ * `new` never replaces a world the person has. `update` replaces the world with the same identity, keeping its folder, after moving the
5388
+ * old files to `<root>/.trash/worlds/` so nothing is lost, and only when the files still match the release they came from (or the person
5389
+ * said to overwrite). `copy` gives the release a new identity and installs it beside the world the person has.
5390
+ * @throws {CatalogueError} `invalid` when the archive is not a valid world, `conflict` when the person has the world (`new`) or changed it (`update`).
5391
+ */
5392
+ async function installWorld(catalog, archive, maxBytes, options) {
5393
+ const files = readZip(archive, { maxBytes });
5394
+ const folder = worldFolder(files);
5395
+ const worldText = files.get(`${folder}/${WORLD_FILE_NAME}`).toString("utf8");
5396
+ const parsed = parseWorldFile(worldText.replace(/^\uFEFF/, ""));
5397
+ if (!parsed.ok) throw new CatalogueError(`${WORLD_FILE_NAME} is not valid: ${parsed.issues.map(formatIssue).join("; ")}`, "invalid");
5398
+ const world = parsed.value;
5399
+ const known = await catalog.list({ refresh: true });
5400
+ const existing = world.id === void 0 ? void 0 : known.worlds.find((candidate) => candidate.id === world.id);
5401
+ const record = existing === void 0 ? void 0 : await catalog.find(existing.id);
5402
+ if (existing !== void 0 && options.mode === "new") throw new CatalogueError(`you already have "${existing.name}"`, "conflict", { reason: "exists" });
5403
+ if (record !== void 0 && options.mode === "update" && !options.overwriteChanges) {
5404
+ const changes = await localChanges(record.directory);
5405
+ if (changes === "unverified") throw new CatalogueError(`"${existing.name}" has no record of the release it came from, so there is no telling whether you changed it`, "conflict", { reason: "unverified" });
5406
+ if (!isUnchanged(changes)) throw new CatalogueError(`you changed "${existing.name}" since you installed it`, "conflict", {
5407
+ reason: "modified",
5408
+ changes: describeChanges(changes)
5409
+ });
5410
+ }
5411
+ const replacing = options.mode === "update" ? record : void 0;
5412
+ const copyId = options.mode === "copy" && existing !== void 0 ? randomUUID() : void 0;
5413
+ const root = dirname(catalog.directory);
5414
+ const staging = join(root, ".install", randomUUID());
5415
+ const stagedFolder = join(staging, folder);
5416
+ let placed;
5417
+ let backup;
5418
+ try {
5419
+ for (const [path, content] of files) {
5420
+ const target = resolve(staging, path);
5421
+ if (!target.startsWith(`${resolve(stagedFolder)}${sep}`)) throw new CatalogueError(`the archive path "${path}" leaves the world folder`, "invalid");
5422
+ await mkdir(dirname(target), { recursive: true });
5423
+ await writeFile(target, path === `${folder}/world.json` && copyId !== void 0 ? asCopy(worldText, copyId, `${world.name} (copy)`) : content);
5424
+ }
5425
+ await mkdir(catalog.directory, { recursive: true });
5426
+ if (replacing !== void 0) {
5427
+ placed = basename(replacing.directory);
5428
+ backup = join(".trash", "worlds", `${placed}-${stamp()}`);
5429
+ await mkdir(join(root, dirname(backup)), { recursive: true });
5430
+ await rename(replacing.directory, join(root, backup));
5431
+ } else placed = freeFolder(catalog.directory, folder);
5432
+ await rename(stagedFolder, join(catalog.directory, placed));
5433
+ const payload = await catalog.list({ refresh: true });
5434
+ const wanted = copyId ?? world.id;
5435
+ const added = wanted === void 0 ? payload.worlds.find((candidate) => candidate.name === world.name) : payload.worlds.find((candidate) => candidate.id === wanted);
5436
+ if (added === void 0) {
5437
+ await rm(join(catalog.directory, placed), {
5438
+ recursive: true,
5439
+ force: true
5440
+ });
5441
+ if (replacing !== void 0 && backup !== void 0) await rename(join(root, backup), replacing.directory);
5442
+ await catalog.list({ refresh: true });
5443
+ const reasons = payload.problems.filter((problem) => problem.path.includes(placed)).map((problem) => problem.message);
5444
+ throw new CatalogueError(`the world was refused: ${reasons.length === 0 ? "it was not found when the worlds were read" : reasons.join("; ")}`, "invalid");
5445
+ }
5446
+ const tracked = options.provenance !== void 0 && copyId === void 0;
5447
+ if (tracked) {
5448
+ const directory = join(catalog.directory, placed);
5449
+ await writeOrigin(directory, {
5450
+ kind: "release",
5451
+ ...options.provenance,
5452
+ files: await hashWorld(directory)
5453
+ });
5454
+ }
5455
+ return {
5456
+ world: added,
5457
+ packs: [...files.keys()].map((path) => path.split("/")).filter((parts) => parts.length === 4 && parts[1] === "ui" && parts[3] === "pack.json").map((parts) => parts[2]),
5458
+ tracked,
5459
+ ...backup === void 0 ? {} : { backup }
5460
+ };
5461
+ } finally {
5462
+ await rm(staging, {
5463
+ recursive: true,
5464
+ force: true
5465
+ });
5466
+ }
5467
+ }
5468
+ //#endregion
5469
+ //#region src/host/catalogue/transport.ts
5470
+ const TIMEOUT_MS = 6e4;
5471
+ const MAX_REDIRECTS = 5;
5472
+ const nodeTransport = (url, ask) => new Promise((resolveReply, reject) => {
5473
+ const request$2 = (url.protocol === "https:" ? request$1 : request)(url, {
5474
+ method: "GET",
5475
+ signal: ask.signal,
5476
+ timeout: TIMEOUT_MS,
5477
+ agent: false,
5478
+ headers: {
5479
+ "user-agent": "dsh-agentic-roleplay",
5480
+ "accept-encoding": "identity",
5481
+ ...ask.headers
5482
+ },
5483
+ ...ask.guarded ? { lookup: guardedLookup } : {}
5484
+ }, (response) => {
5485
+ const status = response.statusCode ?? 0;
5486
+ const location = typeof response.headers.location === "string" ? response.headers.location : void 0;
5487
+ const type = String(response.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase();
5488
+ if (status >= 300 && status < 400 && location !== void 0) {
5489
+ response.destroy();
5490
+ resolveReply({
5491
+ status,
5492
+ type,
5493
+ location,
5494
+ body: Buffer.alloc(0)
5495
+ });
5496
+ return;
5497
+ }
5498
+ if (Number(response.headers["content-length"] ?? 0) > ask.maxBytes) {
5499
+ response.destroy();
5500
+ reject(new CatalogueError(`the answer is larger than ${ask.maxBytes} bytes`, "upstream"));
5501
+ return;
5502
+ }
5503
+ const chunks = [];
5504
+ let size = 0;
5505
+ response.on("data", (chunk) => {
5506
+ size += chunk.length;
5507
+ if (size > ask.maxBytes) {
5508
+ response.destroy();
5509
+ reject(new CatalogueError(`the answer is larger than ${ask.maxBytes} bytes`, "upstream"));
5510
+ return;
5511
+ }
5512
+ chunks.push(chunk);
5513
+ });
5514
+ response.on("end", () => {
5515
+ resolveReply({
5516
+ status,
5517
+ type,
5518
+ location,
5519
+ body: Buffer.concat(chunks)
5520
+ });
5521
+ });
5522
+ response.on("error", reject);
5523
+ });
5524
+ request$2.on("timeout", () => {
5525
+ request$2.destroy(/* @__PURE__ */ new Error("timed out"));
5526
+ });
5527
+ request$2.on("error", reject);
5528
+ request$2.end();
5529
+ });
5530
+ /**
5531
+ * Asks for an address. An address on a configured catalogue's site carries that catalogue's API key and may be a local address (the person
5532
+ * named that site); any other address is asked for plainly and only if it is a public one. A redirect is judged like a first address, so
5533
+ * the key never goes to another site.
5534
+ * @throws {CatalogueError} when the address cannot be used or the answer is not a success.
5535
+ */
5536
+ async function fetchAddress(address, options) {
5537
+ const transport = options.transport ?? nodeTransport;
5538
+ const signal = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS * 4), ...options.signal === void 0 ? [] : [options.signal]]);
5539
+ let url = new URL(address);
5540
+ for (let hop = 0;; hop += 1) {
5541
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new CatalogueError(`${url.href} is not a web address`, "input");
5542
+ if (url.username !== "" || url.password !== "") throw new CatalogueError(`${url.origin} must not carry a user name or password: use the API key field`, "input");
5543
+ const source = options.sources.match(url);
5544
+ if (source === void 0) {
5545
+ const vetted = vetUrl(url.href);
5546
+ if (typeof vetted === "string") throw new CatalogueError(`${url.href} ${vetted}`, "input");
5547
+ }
5548
+ const key = source?.apiKey;
5549
+ let reply;
5550
+ try {
5551
+ reply = await transport(url, {
5552
+ headers: {
5553
+ accept: options.accept,
5554
+ ...key === void 0 ? {} : { authorization: `Bearer ${key}` }
5555
+ },
5556
+ guarded: source === void 0,
5557
+ maxBytes: options.maxBytes,
5558
+ signal
5559
+ });
5560
+ } catch (error) {
5561
+ if (error instanceof CatalogueError) throw error;
5562
+ throw new CatalogueError(`could not reach ${url.origin}: ${error instanceof Error ? error.message : String(error)}`, "upstream");
5563
+ }
5564
+ if (reply.status >= 300 && reply.status < 400 && reply.location !== void 0) {
5565
+ if (hop >= MAX_REDIRECTS) throw new CatalogueError("too many redirects", "upstream");
5566
+ url = new URL(reply.location, url);
5567
+ continue;
5568
+ }
5569
+ if (reply.status >= 200 && reply.status < 300) return reply;
5570
+ throw new CatalogueError(refusal(url, reply.status, source !== void 0, key !== void 0), reply.status === 404 ? "unknown" : "upstream");
5571
+ }
5572
+ }
5573
+ function refusal(url, status, known, keyed) {
5574
+ if (status === 401 || status === 403) {
5575
+ if (keyed) return `${url.origin} refused the API key (answered ${status}): check it in Settings, Role Play`;
5576
+ return known ? `${url.origin} needs an API key (answered ${status}): add one for this catalogue in Settings, Role Play` : `${url.origin} needs a sign-in (answered ${status}): add its catalogue with an API key in Settings, Role Play`;
5577
+ }
5578
+ if (status === 404) return `${url.href} was not found${keyed ? "" : ", or it is private and needs an API key"}`;
5579
+ return `${url.origin} answered ${status} for ${url.pathname}`;
5580
+ }
5581
+ const MAX_JSON_BYTES = 8388608;
5582
+ const MAX_COVER_BYTES = 20971520;
5583
+ const ID = /^[A-Za-z0-9_-]{1,100}$/;
5584
+ const VISIBILITY = [
5585
+ "public",
5586
+ "authenticated",
5587
+ "private"
5588
+ ];
5589
+ const CHECKED_AT_ONCE = 4;
5590
+ const unexpected = (what) => new CatalogueError(`the catalogue answered with something unexpected: ${what}`, "upstream");
5591
+ const object = (value, what) => {
5592
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw unexpected(what);
5593
+ return value;
5594
+ };
5595
+ const text = (value) => typeof value === "string" ? value : "";
5596
+ const count = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
5597
+ function worldOf(value) {
5598
+ const item = object(value, "a world entry");
5599
+ const metadata = object(item["metadata"], "a world entry without metadata");
5600
+ const id = text(item["id"]);
5601
+ if (!ID.test(id)) throw unexpected("a world entry without an id");
5602
+ const visibility = text(metadata["visibility"]);
5603
+ return {
5604
+ id,
5605
+ kind: text(item["resourceType"]) === "sillytavern/character" ? "card" : "world",
5606
+ name: text(metadata["name"]),
5607
+ description: text(metadata["description"]),
5608
+ tags: Array.isArray(metadata["tags"]) ? metadata["tags"].filter((tag) => typeof tag === "string") : [],
5609
+ author: text(item["authorUsername"]),
5610
+ visibility: VISIBILITY.includes(visibility) ? visibility : "private",
5611
+ language: text(metadata["language"]),
5612
+ views: count(item["viewCount"]),
5613
+ downloads: count(item["downloadCount"]),
5614
+ hasCover: typeof item["coverImageResourceId"] === "string" && item["coverImageResourceId"] !== ""
5615
+ };
5616
+ }
5617
+ function versionOf(value) {
5618
+ const item = object(value, "a version entry");
5619
+ const id = text(item["id"]);
5620
+ if (!ID.test(id)) throw unexpected("a version entry without an id");
5621
+ const visibility = text(item["visibility"]);
5622
+ return {
5623
+ number: count(item["versionNumber"]),
5624
+ version: {
5625
+ id,
5626
+ version: text(item["version"]),
5627
+ publishedAt: text(item["publishedAt"]),
5628
+ visibility: VISIBILITY.includes(visibility) ? visibility : "private",
5629
+ ...typeof item["artifactByteSize"] === "number" ? { byteSize: item["artifactByteSize"] } : {},
5630
+ ...typeof item["artifactSha256"] === "string" ? { sha256: item["artifactSha256"] } : {}
5631
+ }
5632
+ };
5633
+ }
5634
+ /** Browsing the worlds a catalogue holds and installing one; the catalogue's API key goes with every request that belongs to its site. */
5635
+ var Catalogue = class {
5636
+ deps;
5637
+ constructor(deps) {
5638
+ this.deps = deps;
5639
+ }
5640
+ sources() {
5641
+ return this.deps.sources.status();
5642
+ }
5643
+ async worlds(name, query) {
5644
+ const source = this.deps.sources.get(name);
5645
+ const offset = Math.max(0, Math.floor(query.offset ?? 0));
5646
+ const params = {
5647
+ resourceType: query.kind === "card" ? CATALOGUE_CARD_TYPE : CATALOGUE_WORLD_TYPE,
5648
+ publishedOnly: "true",
5649
+ limit: String(24),
5650
+ offset: String(offset),
5651
+ sort: query.sort ?? "recent"
5652
+ };
5653
+ const search = query.search?.trim() ?? "";
5654
+ if (search !== "") params["search_string"] = search.slice(0, 200);
5655
+ const answer = object(await this.json(source, "/resources", params), "the list of worlds");
5656
+ if (!Array.isArray(answer["items"])) throw unexpected("the list of worlds has no items");
5657
+ const next = answer["nextOffset"];
5658
+ return {
5659
+ items: answer["items"].map(worldOf),
5660
+ ...typeof next === "number" ? { nextOffset: next } : {},
5661
+ withKey: source.apiKey !== void 0
5662
+ };
5663
+ }
5664
+ async world(name, id) {
5665
+ const source = this.deps.sources.get(name);
5666
+ const world = worldOf(await this.json(source, `/resources/${this.identifier(id)}`));
5667
+ const listed = await this.json(source, `/versions/resource/${this.identifier(id)}`);
5668
+ if (!Array.isArray(listed)) throw unexpected("the list of versions");
5669
+ const versions = listed.map(versionOf).sort((a, b) => b.number - a.number).map((entry) => entry.version);
5670
+ if (world.kind === "card") {
5671
+ const converted = (await this.origins()).filter(({ origin }) => origin?.kind === "card" && origin.resourceId === id && this.deps.sources.match(new URL(origin.root))?.name === source.name);
5672
+ return {
5673
+ ...world,
5674
+ versions,
5675
+ converted: converted.map(({ name: worldName, worldId, origin }) => ({
5676
+ worldId,
5677
+ name: worldName,
5678
+ version: origin?.version ?? ""
5679
+ }))
5680
+ };
5681
+ }
5682
+ const latest = versions[0];
5683
+ let installed;
5684
+ if (latest !== void 0) {
5685
+ const data = object(object(await this.json(source, `/versions/${latest.id}/data`), "the data of a version")["data"], "the data of a version");
5686
+ const worldId = text(data["worldId"]);
5687
+ const mine = worldId === "" ? void 0 : (await this.deps.worlds.list()).worlds.find((existing) => existing.id === worldId);
5688
+ if (mine !== void 0) {
5689
+ const record = await this.deps.worlds.find(mine.id);
5690
+ const origin = record === void 0 ? void 0 : await readOrigin(record.directory);
5691
+ const changes = record === void 0 ? "unverified" : await localChanges(record.directory);
5692
+ installed = {
5693
+ worldId: mine.id,
5694
+ name: mine.name,
5695
+ ...mine.version === void 0 ? {} : { version: mine.version },
5696
+ ...origin?.kind === "release" ? { versionId: origin.versionId } : {},
5697
+ modified: changes === "unverified" ? "unknown" : !isUnchanged(changes)
5698
+ };
5699
+ }
5700
+ }
5701
+ return {
5702
+ ...world,
5703
+ versions,
5704
+ ...installed === void 0 ? {} : { installed }
5705
+ };
5706
+ }
5707
+ /** Installed worlds with a newer release in the catalogue, and the worlds that could not be checked. */
5708
+ async updates(name) {
5709
+ const source = this.deps.sources.get(name);
5710
+ const mine = (await this.origins()).filter(({ origin, problem }) => problem !== void 0 || origin?.kind === "release" && this.deps.sources.match(new URL(origin.root))?.name === source.name);
5711
+ const result = {
5712
+ updates: [],
5713
+ problems: []
5714
+ };
5715
+ for (let from = 0; from < mine.length; from += CHECKED_AT_ONCE) await Promise.all(mine.slice(from, from + CHECKED_AT_ONCE).map(async ({ worldId, name: worldName, directory, origin, problem }) => {
5716
+ try {
5717
+ if (problem !== void 0) throw new CatalogueError(problem, "invalid");
5718
+ if (origin?.kind !== "release") return;
5719
+ const listed = await this.json(source, `/versions/resource/${this.identifier(origin.resourceId)}`);
5720
+ if (!Array.isArray(listed)) throw unexpected("the list of versions");
5721
+ const entries = listed.map(versionOf).sort((a, b) => b.number - a.number);
5722
+ const latest = entries[0];
5723
+ const installed = entries.find((entry) => entry.version.id === origin.versionId);
5724
+ if (latest === void 0 || latest.version.id === origin.versionId || installed !== void 0 && latest.number <= installed.number) return;
5725
+ const changes = await localChanges(directory);
5726
+ const update = {
5727
+ worldId,
5728
+ worldName,
5729
+ resourceId: origin.resourceId,
5730
+ installedVersion: origin.version,
5731
+ latest: latest.version,
5732
+ modified: changes === "unverified" ? true : !isUnchanged(changes)
5733
+ };
5734
+ result.updates.push(update);
5735
+ } catch (error) {
5736
+ result.problems.push({
5737
+ worldName,
5738
+ message: error instanceof Error ? error.message : String(error)
5739
+ });
5740
+ }
5741
+ }));
5742
+ result.updates.sort((a, b) => a.worldName.localeCompare(b.worldName));
5743
+ return result;
5744
+ }
5745
+ async cover(name, id) {
5746
+ const source = this.deps.sources.get(name);
5747
+ const reply = await fetchAddress(this.address(source, `/images/covers/resources/${this.identifier(id)}`), {
5748
+ sources: this.deps.sources,
5749
+ maxBytes: MAX_COVER_BYTES,
5750
+ accept: "image/*",
5751
+ ...this.deps.transport === void 0 ? {} : { transport: this.deps.transport }
5752
+ });
5753
+ if (!reply.type.startsWith("image/")) throw unexpected("the cover is not a picture");
5754
+ return {
5755
+ type: reply.type,
5756
+ body: reply.body
5757
+ };
5758
+ }
5759
+ /**
5760
+ * Downloads a world archive from an address and installs it. The address may be any ZIP link: one on a configured catalogue's site is asked
5761
+ * for with that catalogue's key, any other plainly (and only when it is a public address).
5762
+ * @throws {CatalogueError} when the address cannot be fetched, is not a world archive, or names a world the person has.
5763
+ */
5764
+ async install(request) {
5765
+ const address = request.url.trim();
5766
+ if (address === "") throw new CatalogueError("give the address of a world archive", "input");
5767
+ let url;
5768
+ try {
5769
+ url = new URL(address);
5770
+ } catch {
5771
+ throw new CatalogueError(`"${address}" is not an address`, "input");
5772
+ }
5773
+ const reply = await fetchAddress(url.href, {
5774
+ sources: this.deps.sources,
5775
+ maxBytes: this.deps.maxBytes(),
5776
+ accept: "application/zip, application/octet-stream;q=0.9, */*;q=0.1",
5777
+ ...this.deps.transport === void 0 ? {} : { transport: this.deps.transport }
5778
+ });
5779
+ if (reply.body.length < 4 || reply.body.readUInt32LE(0) !== 67324752) throw new CatalogueError(`${url.href} did not answer with a ZIP archive${reply.type === "" ? "" : ` (it sent ${reply.type})`}`, "invalid");
5780
+ if (request.sha256 !== void 0 && createHash("sha256").update(reply.body).digest("hex") !== request.sha256.toLowerCase()) throw new CatalogueError("the download does not match the checksum the catalogue published for it", "invalid");
5781
+ const provenance = await this.provenance(url);
5782
+ return await installWorld(this.deps.worlds, reply.body, this.deps.maxBytes(), {
5783
+ mode: request.mode ?? "new",
5784
+ overwriteChanges: request.overwriteChanges === true,
5785
+ ...provenance === void 0 ? {} : { provenance }
5786
+ });
5787
+ }
5788
+ /**
5789
+ * Turns a character card of a catalogue into a new world: the card is downloaded with the catalogue's key and handed to the importer, whose
5790
+ * authoring chat does the conversion. The conversion is made by an agent and differs from run to run, so it never replaces a world: converting
5791
+ * again makes another one.
5792
+ */
5793
+ async convert(request) {
5794
+ const source = this.deps.sources.get(request.source);
5795
+ const versionId = this.identifier(request.versionId);
5796
+ const version = object(await this.json(source, `/versions/${versionId}`), "a version");
5797
+ if (text(version["resourceType"]) !== "sillytavern/character") throw new CatalogueError("that release is not a character card", "invalid");
5798
+ const resourceId = text(version["resourceId"]);
5799
+ if (!ID.test(resourceId)) throw unexpected("a version without a resource id");
5800
+ const reply = await fetchAddress(this.address(source, `/versions/${versionId}/download`), {
5801
+ sources: this.deps.sources,
5802
+ maxBytes: this.deps.maxCardBytes(),
5803
+ accept: "*/*",
5804
+ ...this.deps.transport === void 0 ? {} : { transport: this.deps.transport }
5805
+ });
5806
+ const sha256 = text(version["artifactSha256"]);
5807
+ if (sha256 !== "" && createHash("sha256").update(reply.body).digest("hex") !== sha256.toLowerCase()) throw new CatalogueError("the download does not match the checksum the catalogue published for it", "invalid");
5808
+ const png = reply.body.subarray(0, 4).equals(Buffer.from([
5809
+ 137,
5810
+ 80,
5811
+ 78,
5812
+ 71
5813
+ ]));
5814
+ const converted = await this.deps.importCard(reply.body, `${versionId}${png ? ".png" : ".json"}`, request.language);
5815
+ const record = await this.deps.worlds.find(converted.worldId);
5816
+ if (record === void 0) throw new CatalogueError("the world was made but cannot be found", "upstream");
5817
+ await writeOrigin(record.directory, {
5818
+ kind: "card",
5819
+ root: source.root,
5820
+ resourceId,
5821
+ versionId,
5822
+ version: text(version["version"])
5823
+ });
5824
+ return converted;
5825
+ }
5826
+ /** The catalogue release an address names, when it is a release download on a configured catalogue. */
5827
+ async provenance(url) {
5828
+ const source = this.deps.sources.match(url);
5829
+ if (source === void 0) return void 0;
5830
+ const named = /^\/versions\/([A-Za-z0-9_-]{1,100})\/download$/.exec(url.pathname.slice(source.prefix.length));
5831
+ if (named === null) return void 0;
5832
+ const version = object(await this.json(source, `/versions/${named[1]}`), "a version");
5833
+ const resourceId = text(version["resourceId"]);
5834
+ if (!ID.test(resourceId)) throw unexpected("a version without a resource id");
5835
+ return {
5836
+ root: source.root,
5837
+ resourceId,
5838
+ versionId: named[1],
5839
+ version: text(version["version"])
5840
+ };
5841
+ }
5842
+ /** Every world with the record of where it came from, or why that record cannot be read. */
5843
+ async origins() {
5844
+ const found = [];
5845
+ for (const summary of (await this.deps.worlds.list()).worlds) {
5846
+ const record = await this.deps.worlds.find(summary.id);
5847
+ if (record === void 0) continue;
5848
+ try {
5849
+ const origin = await readOrigin(record.directory);
5850
+ found.push({
5851
+ worldId: summary.id,
5852
+ name: summary.name,
5853
+ directory: record.directory,
5854
+ ...origin === void 0 ? {} : { origin }
5855
+ });
5856
+ } catch (error) {
5857
+ found.push({
5858
+ worldId: summary.id,
5859
+ name: summary.name,
5860
+ directory: record.directory,
5861
+ problem: error instanceof Error ? error.message : String(error)
5862
+ });
5863
+ }
5864
+ }
5865
+ return found;
5866
+ }
5867
+ identifier(id) {
5868
+ if (!ID.test(id)) throw new CatalogueError("that is not a catalogue id", "input");
5869
+ return id;
5870
+ }
5871
+ address(source, path, params = {}) {
5872
+ const url = new URL(`${source.root}${path}`);
5873
+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
5874
+ return url.href;
5875
+ }
5876
+ async json(source, path, params = {}) {
5877
+ const reply = await fetchAddress(this.address(source, path, params), {
5878
+ sources: this.deps.sources,
5879
+ maxBytes: MAX_JSON_BYTES,
5880
+ accept: "application/json",
5881
+ ...this.deps.transport === void 0 ? {} : { transport: this.deps.transport }
5882
+ });
5883
+ try {
5884
+ return JSON.parse(reply.body.toString("utf8"));
5885
+ } catch {
5886
+ throw unexpected("it is not JSON: is the address the catalogue's API root?");
5887
+ }
5888
+ }
5889
+ };
5890
+ //#endregion
5891
+ //#region src/host/catalogue/sources.ts
5892
+ /** A web address with no credentials, query or fragment, or the reason it is not one. */
5893
+ function parseBase(text) {
5894
+ let url;
5895
+ try {
5896
+ url = new URL(text.trim());
5897
+ } catch {
5898
+ return "is not an address";
5899
+ }
5900
+ if (url.protocol !== "http:" && url.protocol !== "https:") return "is not a web address";
5901
+ if (url.username !== "" || url.password !== "") return "must not carry a user name or password: use the API key field";
5902
+ if (url.search !== "" || url.hash !== "") return "must not have a query or fragment";
5903
+ return url;
5904
+ }
5905
+ const prefixLength = (prefix, path) => prefix === "" || path === prefix || path.startsWith(`${prefix}/`) ? prefix.length : -1;
5906
+ /** The catalogues the person configured, read afresh on every use so an edit applies at once. */
5907
+ var Sources = class {
5908
+ read;
5909
+ constructor(read) {
5910
+ this.read = read;
5911
+ }
5912
+ resolved() {
5913
+ const seen = /* @__PURE__ */ new Set();
5914
+ return this.read().map((source) => {
5915
+ const name = source.name.trim();
5916
+ if (name === "") return {
5917
+ source,
5918
+ problem: "has no name"
5919
+ };
5920
+ if (seen.has(name)) return {
5921
+ source,
5922
+ problem: "repeats the name of an earlier catalogue"
5923
+ };
5924
+ seen.add(name);
5925
+ const base = parseBase(source.baseUrl);
5926
+ if (typeof base === "string") return {
5927
+ source,
5928
+ problem: `address ${base}`
5929
+ };
5930
+ const prefix = base.pathname.replace(/\/+$/, "");
5931
+ return {
5932
+ source,
5933
+ resolved: {
5934
+ name,
5935
+ root: `${base.origin}${prefix}`,
5936
+ origin: base.origin,
5937
+ prefix,
5938
+ apiKey: source.apiKey.trim() === "" ? void 0 : source.apiKey.trim()
5939
+ }
5940
+ };
5941
+ });
5942
+ }
5943
+ status() {
5944
+ return this.resolved().map(({ source, resolved, problem }) => ({
5945
+ name: source.name.trim(),
5946
+ baseUrl: source.baseUrl.trim(),
5947
+ hasKey: source.apiKey.trim() !== "",
5948
+ ...resolved === void 0 ? { problem: problem ?? "cannot be used" } : {}
5949
+ }));
5950
+ }
5951
+ /** @throws {CatalogueError} when no usable catalogue has the name. */
5952
+ get(name) {
5953
+ const entry = this.resolved().find((candidate) => candidate.source.name.trim() === name);
5954
+ if (entry === void 0) throw new CatalogueError(`there is no catalogue named "${name}"`, "unknown");
5955
+ if (entry.resolved === void 0) throw new CatalogueError(`the catalogue "${name}" ${entry.problem ?? "cannot be used"}`, "invalid");
5956
+ return entry.resolved;
5957
+ }
5958
+ /** The catalogue an address belongs to: the same site, preferring the one whose address is the longest start of the path. */
5959
+ match(url) {
5960
+ let best;
5961
+ for (const { resolved } of this.resolved()) {
5962
+ if (resolved === void 0 || resolved.origin !== url.origin) continue;
5963
+ const length = prefixLength(resolved.prefix, url.pathname);
5964
+ if (best === void 0 || length > best.length) best = {
5965
+ source: resolved,
5966
+ length
5967
+ };
5968
+ }
5969
+ return best?.source;
5970
+ }
5971
+ };
5972
+ //#endregion
4798
5973
  //#region src/host/speech/service.ts
4799
5974
  async function voicesOf(service) {
4800
5975
  return await service.voices();
@@ -4866,6 +6041,12 @@ function mergeWav(buffers) {
4866
6041
  const Config = z.object({
4867
6042
  rootPath: z.string().default("~/dsh-roleplay").volatile(),
4868
6043
  sessionStorePath: z.string().default("~/.dsh/sessions"),
6044
+ catalogues: z.array(z.object({
6045
+ name: z.string().required(),
6046
+ baseUrl: z.string().required(),
6047
+ apiKey: z.string().default("")
6048
+ })).default([]).volatile(),
6049
+ catalogueMaxBytes: z.number().min(1024).default(268435456),
4869
6050
  importMaxUploadBytes: z.number().min(1024).default(104857600),
4870
6051
  importConcurrency: z.number().min(1).max(16).default(4),
4871
6052
  importReasoning: z.string().default(""),
@@ -4920,6 +6101,7 @@ function apply(ctx, config) {
4920
6101
  vectors: (id) => vectorStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
4921
6102
  reflection: (id) => reflectionStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id), ctx.roleplayOrchestration.reflecting(chatSessionId(id))),
4922
6103
  activity: (id) => readActivity(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
6104
+ usage: (id) => readUsage(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
4923
6105
  interventions: (id) => readInterventions(ctx.roleplayState.openSession(join(root.path, "sessions"), id))
4924
6106
  };
4925
6107
  const purgeChat = purgeOf(ctx, config.sessionStorePath);
@@ -4931,6 +6113,21 @@ function apply(ctx, config) {
4931
6113
  avatars: () => avatarsWorld(root.path)
4932
6114
  };
4933
6115
  registerApi(ctx, {
6116
+ catalogue: new Catalogue({
6117
+ sources: new Sources(() => config.catalogues.get()),
6118
+ worlds,
6119
+ maxBytes: () => config.catalogueMaxBytes,
6120
+ maxCardBytes: () => config.importMaxUploadBytes,
6121
+ importCard: async (file, name, language) => {
6122
+ const preview = await imports.create(readCard(file, name), isPng(file) ? pictureOf(file) : void 0);
6123
+ return await startImport({
6124
+ store: imports,
6125
+ worlds,
6126
+ authoring,
6127
+ chatTitle: (title) => `Authoring ${title}`
6128
+ }, preview.id, preview.choices, language);
6129
+ }
6130
+ }),
4934
6131
  packs: new InterfaceService({
4935
6132
  open: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
4936
6133
  root: () => root.path,
@@ -5038,14 +6235,36 @@ function apply(ctx, config) {
5038
6235
  editLore: async (worldId, key, edit) => await editWorldLore$1(await editableWorld(worlds, worldId, root.path), key, edit),
5039
6236
  addLore: async (worldId, title) => (await addWorldLore(await editableWorld(worlds, worldId, root.path), title)).state,
5040
6237
  removeLore: async (worldId, key) => await removeWorldLore(await editableWorld(worlds, worldId, root.path), key),
6238
+ readPackFile: async (worldId, pack, path) => await readWorldPackFile((await editableWorld(worlds, worldId, root.path)).directory, pack, path),
6239
+ writePackFile: async (worldId, pack, path, text) => await writeWorldPackFile((await editableWorld(worlds, worldId, root.path)).directory, pack, path, text),
6240
+ deletePackFile: async (worldId, pack, path) => (await deleteWorldPackFile((await editableWorld(worlds, worldId, root.path)).directory, pack, path)).problems,
6241
+ createPack: async (worldId, pack, name) => await createWorldPack((await editableWorld(worlds, worldId, root.path)).directory, pack, name),
6242
+ readTrigger: async (worldId, key) => await readWorldTrigger(await editableWorld(worlds, worldId, root.path), key),
6243
+ writeTrigger: async (worldId, key, document) => await writeWorldTrigger(await editableWorld(worlds, worldId, root.path), key, document),
6244
+ removeTrigger: async (worldId, key) => await removeWorldTrigger(await editableWorld(worlds, worldId, root.path), key),
5041
6245
  editPlots: async (worldId, edit) => await editWorldPlots$1(await editableWorld(worlds, worldId, root.path), edit),
5042
6246
  editRelation: async (worldId, edit) => await editWorldRelation$1(await editableWorld(worlds, worldId, root.path), edit),
5043
6247
  editNarrationVoice: async (worldId, voice) => await editWorldNarrationVoice(await editableWorld(worlds, worldId, root.path), voice),
5044
6248
  generatePortrait: async (worldId, key) => await generateWorldCharacterPortrait(await editableWorld(worlds, worldId, root.path), key, imageGenerationOf(ctx)),
5045
6249
  portraitFile: async (worldId, key) => await worldCharacterPortraitFile(await editableWorld(worlds, worldId, root.path), key),
5046
- uploadPortrait: async (worldId, key, png, name) => await uploadWorldCharacterPortrait(await editableWorld(worlds, worldId, root.path), key, png, name)
6250
+ uploadPortrait: async (worldId, key, png, name) => await uploadWorldCharacterPortrait(await editableWorld(worlds, worldId, root.path), key, png, name),
6251
+ generateEntityImage: async (worldId, kind, key) => await generateWorldEntityImage(await editableWorld(worlds, worldId, root.path), kind, key, imageGenerationOf(ctx)),
6252
+ entityImageFile: async (worldId, kind, key) => await worldEntityImageFile(await editableWorld(worlds, worldId, root.path), kind, key),
6253
+ uploadEntityImage: async (worldId, kind, key, png, name) => await uploadWorldEntityImage(await editableWorld(worlds, worldId, root.path), kind, key, png, name)
5047
6254
  },
5048
6255
  sessions: {
6256
+ generateEntityImage: (id, kind, key) => generateSessionEntityImage({
6257
+ state: ctx.roleplayState,
6258
+ sessionsDir: deps.sessionsDir
6259
+ }, id, kind, key, imageGenerationOf(ctx)),
6260
+ entityImageFile: (id, kind, key) => sessionEntityImageFile({
6261
+ state: ctx.roleplayState,
6262
+ sessionsDir: deps.sessionsDir
6263
+ }, id, kind, key),
6264
+ uploadEntityImage: (id, kind, key, png, name) => uploadSessionEntityImage({
6265
+ state: ctx.roleplayState,
6266
+ sessionsDir: deps.sessionsDir
6267
+ }, id, kind, key, png, name),
5049
6268
  list: () => listSessions(deps),
5050
6269
  start: (request) => startSession(deps, request),
5051
6270
  open: (id) => openSession(deps, id),