@dsh-agentic-roleplay/core 0.3.2 → 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/authoring.js +15 -255
- package/lib/child-CFjnaTZt.js +435 -0
- package/lib/client.js +2852 -586
- package/lib/client.js.map +1 -1
- package/lib/{deliver-BSsDtF6X.js → deliver-CpZOxBX5.js} +145 -1622
- package/lib/doctor-chat-ByDfCMeo.js +17 -0
- package/lib/doctor.js +171 -0
- package/lib/{gallery-DS5-qH9F.js → gallery-CtFDL22W.js} +2 -2
- package/lib/{generator-BzeepLd2.js → generator-B6FxlKOV.js} +2 -378
- package/lib/hooks-KTCR3fNJ.js +1060 -0
- package/lib/images.js +3 -3
- package/lib/index.js +1365 -201
- package/lib/language-DWVwi1R7.js +520 -0
- package/lib/orchestration.js +142 -1146
- package/lib/{documents-B5XAdfo2.js → pack-jail-CybSNzxr.js} +869 -80
- package/lib/{packs-BCGK9KZV.js → packs-BYjrAen6.js} +4 -518
- package/lib/{presenter-agent-Cp-J0onD.js → presenter-agent-CiEVKcjJ.js} +4 -3
- package/lib/reflection-waxFg1x-.js +1843 -0
- package/package.json +3 -2
- package/prompts/en/doctor/persona.md +1 -0
- package/prompts/en/doctor/procedure.md +5 -0
- package/prompts/en/doctor/welcome.md +1 -0
- package/prompts/en/import/character.md +1 -0
- package/prompts/en/roleplay/record-keeper.md +2 -2
- package/prompts/en/roleplay/reflection-check.md +5 -0
- package/prompts/en/roleplay/reflection.md +2 -0
- package/prompts/zh/doctor/persona.md +1 -0
- package/prompts/zh/doctor/procedure.md +5 -0
- package/prompts/zh/doctor/welcome.md +1 -0
- package/prompts/zh/import/character.md +1 -0
- package/prompts/zh/roleplay/record-keeper.md +2 -2
- package/prompts/zh/roleplay/reflection-check.md +5 -0
- package/prompts/zh/roleplay/reflection.md +2 -0
package/lib/index.js
CHANGED
|
@@ -1,22 +1,28 @@
|
|
|
1
1
|
import { n as chatSessionId, r as roleplaySessionOf } from "./access-EbNdZFbk.js";
|
|
2
|
-
import { $ as
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
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
|
+
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 { 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";
|
|
6
8
|
import { a as liveSettings, c as writeSettings, i as InvalidSettingsError, n as encodeOutput, o as readSettings, s as useChildReasoning } from "./narration-DK2kiIjE.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
9
|
+
import { r as childSamplingOf } from "./child-CFjnaTZt.js";
|
|
10
|
+
import { T as uniqueKey, a as uploadReferenceImage, m as sceneImagePath, o as addToLibrary, p as referenceImagePath, t as generateReferenceImage, u as inheritImages, w as slug } from "./generator-B6FxlKOV.js";
|
|
11
|
+
import { t as doctorChatSessionId } from "./doctor-chat-ByDfCMeo.js";
|
|
12
|
+
import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-CtFDL22W.js";
|
|
13
|
+
import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
|
|
10
14
|
import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
11
15
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
12
16
|
import { Session, SessionId } from "@deepseek-ai/dsh-session";
|
|
13
17
|
import { ToolCallId, createMessage, createSystemMessage, createToolResultMessage } from "@deepseek-ai/dsh-llm";
|
|
14
18
|
import { setApprovalPolicy } from "@deepseek-ai/dsh-user-approval";
|
|
15
|
-
import {
|
|
19
|
+
import { inflateRawSync } from "node:zlib";
|
|
16
20
|
import { fileURLToPath } from "node:url";
|
|
17
21
|
import { Service } from "@deepseek-ai/cordis";
|
|
18
22
|
import { chmod, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
19
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";
|
|
20
26
|
import { pipeline } from "node:stream/promises";
|
|
21
27
|
import { homedir } from "node:os";
|
|
22
28
|
import z from "@deepseek-ai/schemastery";
|
|
@@ -30,6 +36,10 @@ const AUTHORING_OPENING_SOURCE = {
|
|
|
30
36
|
provider: "world-authoring",
|
|
31
37
|
model: "opening"
|
|
32
38
|
};
|
|
39
|
+
const DOCTOR_OPENING_SOURCE = {
|
|
40
|
+
provider: "session-doctor",
|
|
41
|
+
model: "opening"
|
|
42
|
+
};
|
|
33
43
|
const NARRATE_TOOL = "narrate";
|
|
34
44
|
/**
|
|
35
45
|
* The first node of a conversation's surface is the system prompt, even an empty one: the log format refuses a system prompt that
|
|
@@ -124,7 +134,7 @@ function openingEvents(segments) {
|
|
|
124
134
|
return session.snapshotEvents();
|
|
125
135
|
}
|
|
126
136
|
/** A visible first turn makes a newly created authoring chat a full conversation immediately. */
|
|
127
|
-
function authoringOpeningEvents(welcome) {
|
|
137
|
+
function authoringOpeningEvents(welcome, source = AUTHORING_OPENING_SOURCE) {
|
|
128
138
|
const session = Session.create(SessionId("authoring-opening"));
|
|
129
139
|
setApprovalPolicy(session, "ask");
|
|
130
140
|
const turn = 1;
|
|
@@ -147,7 +157,7 @@ function authoringOpeningEvents(welcome) {
|
|
|
147
157
|
}],
|
|
148
158
|
source: {
|
|
149
159
|
kind: "model",
|
|
150
|
-
...
|
|
160
|
+
...source
|
|
151
161
|
}
|
|
152
162
|
})
|
|
153
163
|
}, { surfaceOp: "append" });
|
|
@@ -172,6 +182,9 @@ async function storeOpening(persistence, chat, segments) {
|
|
|
172
182
|
async function storeAuthoringOpening(persistence, chat, welcome) {
|
|
173
183
|
await storeInitialEvents(persistence, chat, authoringOpeningEvents(welcome));
|
|
174
184
|
}
|
|
185
|
+
async function storeDoctorOpening(persistence, chat, welcome) {
|
|
186
|
+
await storeInitialEvents(persistence, chat, authoringOpeningEvents(welcome, DOCTOR_OPENING_SOURCE));
|
|
187
|
+
}
|
|
175
188
|
async function storeInitialEvents(persistence, chat, events) {
|
|
176
189
|
const header = {
|
|
177
190
|
version: 4,
|
|
@@ -312,179 +325,6 @@ var AgentSessions = class {
|
|
|
312
325
|
}
|
|
313
326
|
};
|
|
314
327
|
//#endregion
|
|
315
|
-
//#region src/host/import/card.ts
|
|
316
|
-
/** The file is not a character card this importer reads. The message says why, for the person who uploaded it. */
|
|
317
|
-
var ImportCardError = class extends Error {};
|
|
318
|
-
const PNG_SIGNATURE = Buffer.from([
|
|
319
|
-
137,
|
|
320
|
-
80,
|
|
321
|
-
78,
|
|
322
|
-
71,
|
|
323
|
-
13,
|
|
324
|
-
10,
|
|
325
|
-
26,
|
|
326
|
-
10
|
|
327
|
-
]);
|
|
328
|
-
const TEXT_CHUNKS = /* @__PURE__ */ new Set([
|
|
329
|
-
"tEXt",
|
|
330
|
-
"iTXt",
|
|
331
|
-
"zTXt"
|
|
332
|
-
]);
|
|
333
|
-
/** The keywords a card's data is stored under, the newer one first. */
|
|
334
|
-
const CARD_KEYWORDS = ["ccv3", "chara"];
|
|
335
|
-
function chunksOf(file) {
|
|
336
|
-
const chunks = [];
|
|
337
|
-
let at = PNG_SIGNATURE.length;
|
|
338
|
-
while (at + 12 <= file.length) {
|
|
339
|
-
const length = file.readUInt32BE(at);
|
|
340
|
-
const end = at + 12 + length;
|
|
341
|
-
if (end > file.length) throw new ImportCardError("the PNG file is damaged: a part of it is cut off");
|
|
342
|
-
chunks.push({
|
|
343
|
-
type: file.toString("latin1", at + 4, at + 8),
|
|
344
|
-
data: file.subarray(at + 8, at + 8 + length),
|
|
345
|
-
raw: file.subarray(at, end)
|
|
346
|
-
});
|
|
347
|
-
at = end;
|
|
348
|
-
}
|
|
349
|
-
return chunks;
|
|
350
|
-
}
|
|
351
|
-
/** The keyword and text of a PNG text chunk. */
|
|
352
|
-
function textOf$1(chunk) {
|
|
353
|
-
const end = chunk.data.indexOf(0);
|
|
354
|
-
if (end < 0) return void 0;
|
|
355
|
-
const keyword = chunk.data.toString("latin1", 0, end);
|
|
356
|
-
const rest = chunk.data.subarray(end + 1);
|
|
357
|
-
if (chunk.type === "tEXt") return {
|
|
358
|
-
keyword,
|
|
359
|
-
text: rest.toString("latin1")
|
|
360
|
-
};
|
|
361
|
-
if (chunk.type === "zTXt") return {
|
|
362
|
-
keyword,
|
|
363
|
-
text: inflateSync(rest.subarray(1)).toString("latin1")
|
|
364
|
-
};
|
|
365
|
-
const compressed = rest[0] === 1;
|
|
366
|
-
let from = 2;
|
|
367
|
-
for (let skipped = 0; skipped < 2; skipped += 1) from = rest.indexOf(0, from) + 1;
|
|
368
|
-
if (from <= 0) return void 0;
|
|
369
|
-
const body = rest.subarray(from);
|
|
370
|
-
return {
|
|
371
|
-
keyword,
|
|
372
|
-
text: (compressed ? inflateSync(body) : body).toString("utf8")
|
|
373
|
-
};
|
|
374
|
-
}
|
|
375
|
-
/** The PNG without its text chunks: the picture, with none of the card's data in it. */
|
|
376
|
-
function pictureOf(file) {
|
|
377
|
-
return Buffer.concat([PNG_SIGNATURE, ...chunksOf(file).filter((chunk) => !TEXT_CHUNKS.has(chunk.type)).map((chunk) => chunk.raw)]);
|
|
378
|
-
}
|
|
379
|
-
function jsonOf(file, name) {
|
|
380
|
-
if (file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) {
|
|
381
|
-
const found = /* @__PURE__ */ new Map();
|
|
382
|
-
for (const chunk of chunksOf(file)) {
|
|
383
|
-
if (!TEXT_CHUNKS.has(chunk.type)) continue;
|
|
384
|
-
const text = textOf$1(chunk);
|
|
385
|
-
if (text !== void 0 && CARD_KEYWORDS.includes(text.keyword) && !found.has(text.keyword)) found.set(text.keyword, text.text);
|
|
386
|
-
}
|
|
387
|
-
const keyword = CARD_KEYWORDS.find((candidate) => found.has(candidate));
|
|
388
|
-
if (keyword === void 0) throw new ImportCardError(`${name} is a PNG picture with no character card in it`);
|
|
389
|
-
try {
|
|
390
|
-
return JSON.parse(Buffer.from(found.get(keyword).trim(), "base64").toString("utf8"));
|
|
391
|
-
} catch {
|
|
392
|
-
throw new ImportCardError(`the card data in ${name} is not readable`);
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
try {
|
|
396
|
-
return JSON.parse(file.toString("utf8").replace(/^/, ""));
|
|
397
|
-
} catch {
|
|
398
|
-
throw new ImportCardError(`${name} is neither a PNG picture with a card in it nor a JSON card`);
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
const URL_PATTERN = /https?:\/\/[^\s"'`<>()[\]{}\\|^]+/gi;
|
|
402
|
-
/** Every web address in the strings of a document, at any depth; template placeholders and trailing punctuation are not part of one. */
|
|
403
|
-
function urlsOf(value) {
|
|
404
|
-
const found = /* @__PURE__ */ new Set();
|
|
405
|
-
const visit = (node, depth) => {
|
|
406
|
-
if (depth > 32) return;
|
|
407
|
-
if (typeof node === "string") for (const match of node.matchAll(URL_PATTERN)) {
|
|
408
|
-
const url = match[0].replace(/[.,;:!?*_~]+$/, "");
|
|
409
|
-
if (!url.includes("$") && url.length <= 2e3) found.add(url);
|
|
410
|
-
}
|
|
411
|
-
else if (Array.isArray(node)) for (const entry of node) visit(entry, depth + 1);
|
|
412
|
-
else if (typeof node === "object" && node !== null) for (const entry of Object.values(node)) visit(entry, depth + 1);
|
|
413
|
-
};
|
|
414
|
-
visit(value, 0);
|
|
415
|
-
return [...found];
|
|
416
|
-
}
|
|
417
|
-
const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
418
|
-
const text = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
|
|
419
|
-
const texts = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" ? [entry] : typeof entry === "number" ? [String(entry)] : []) : [];
|
|
420
|
-
function entryOf(value, index) {
|
|
421
|
-
const entry = object(value);
|
|
422
|
-
if (entry === void 0) return void 0;
|
|
423
|
-
const position = entry["position"];
|
|
424
|
-
return {
|
|
425
|
-
id: `entry:${index}`,
|
|
426
|
-
title: text(entry["comment"]).trim() || text(entry["name"]).trim(),
|
|
427
|
-
keys: texts(entry["keys"]),
|
|
428
|
-
secondaryKeys: texts(entry["secondary_keys"]),
|
|
429
|
-
content: text(entry["content"]),
|
|
430
|
-
enabled: entry["enabled"] !== false,
|
|
431
|
-
constant: entry["constant"] === true,
|
|
432
|
-
selective: entry["selective"] === true,
|
|
433
|
-
position: typeof position === "string" ? position : typeof position === "number" ? String(position) : ""
|
|
434
|
-
};
|
|
435
|
-
}
|
|
436
|
-
/**
|
|
437
|
-
* Reads a character card: a PNG with the card in its text chunk (the newer `ccv3` chunk when there is one), or the JSON of a card.
|
|
438
|
-
* Only V2 and V3 cards are read; a V2 card is carried over into the V3 shape, whose fields are a superset.
|
|
439
|
-
* @throws {ImportCardError} when the file is not such a card.
|
|
440
|
-
*/
|
|
441
|
-
function readCard(file, name) {
|
|
442
|
-
const root = object(jsonOf(file, name));
|
|
443
|
-
const spec = root === void 0 ? void 0 : root["spec"];
|
|
444
|
-
if (spec !== "chara_card_v2" && spec !== "chara_card_v3") throw new ImportCardError(spec === void 0 ? `${name} is not a V2 or V3 character card (it has no "spec")` : `${name} is a "${text(spec)}" card: only V2 and V3 cards are read`);
|
|
445
|
-
const data = object(root?.["data"]);
|
|
446
|
-
if (data === void 0) throw new ImportCardError(`${name} has no card data`);
|
|
447
|
-
const cardName = text(data["name"]).trim();
|
|
448
|
-
if (cardName === "") throw new ImportCardError(`${name} has a card with no name`);
|
|
449
|
-
const book = object(data["character_book"]);
|
|
450
|
-
const entries = Array.isArray(book?.["entries"]) ? book["entries"].flatMap((entry, index) => entryOf(entry, index) ?? []) : [];
|
|
451
|
-
const extensions = object(data["extensions"]) ?? {};
|
|
452
|
-
const scripts = [extensions["regex_scripts"], object(extensions["tavern_helper"])?.["scripts"]].reduce((count, list) => count + (Array.isArray(list) ? list.length : 0), 0);
|
|
453
|
-
return {
|
|
454
|
-
sourceSpec: spec,
|
|
455
|
-
name: cardName,
|
|
456
|
-
description: text(data["description"]),
|
|
457
|
-
personality: text(data["personality"]),
|
|
458
|
-
scenario: text(data["scenario"]),
|
|
459
|
-
firstMessage: text(data["first_mes"]),
|
|
460
|
-
alternateGreetings: texts(data["alternate_greetings"]),
|
|
461
|
-
messageExample: text(data["mes_example"]),
|
|
462
|
-
creatorNotes: text(data["creator_notes"]),
|
|
463
|
-
systemPrompt: text(data["system_prompt"]),
|
|
464
|
-
postHistoryInstructions: text(data["post_history_instructions"]),
|
|
465
|
-
tags: texts(data["tags"]),
|
|
466
|
-
creator: text(data["creator"]),
|
|
467
|
-
characterVersion: text(data["character_version"]),
|
|
468
|
-
...book === void 0 ? {} : { book: {
|
|
469
|
-
name: text(book["name"]),
|
|
470
|
-
description: text(book["description"]),
|
|
471
|
-
entries
|
|
472
|
-
} },
|
|
473
|
-
ignored: {
|
|
474
|
-
scripts,
|
|
475
|
-
extensions: Object.keys(extensions).filter((key) => ![
|
|
476
|
-
"talkativeness",
|
|
477
|
-
"fav",
|
|
478
|
-
"world",
|
|
479
|
-
"depth_prompt"
|
|
480
|
-
].includes(key))
|
|
481
|
-
},
|
|
482
|
-
urls: urlsOf(data)
|
|
483
|
-
};
|
|
484
|
-
}
|
|
485
|
-
/** Whether a file looks like a PNG, so that its picture can be kept. */
|
|
486
|
-
const isPng = (file) => file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE);
|
|
487
|
-
//#endregion
|
|
488
328
|
//#region src/host/worlds/authoring-language.ts
|
|
489
329
|
/**
|
|
490
330
|
* The language the person was using when they last worked on a world with the authoring assistant. The assistant's instructions
|
|
@@ -648,6 +488,32 @@ async function startTranslation(deps, id, to, title, language) {
|
|
|
648
488
|
}
|
|
649
489
|
}
|
|
650
490
|
//#endregion
|
|
491
|
+
//#region src/host/import/upload-preset.ts
|
|
492
|
+
/**
|
|
493
|
+
* Keeps an uploaded narration preset in the world's import folder and has the world's authoring chat apply it, which asks the person before it changes a prompt.
|
|
494
|
+
* @throws {ImportCardError} when the file is not a preset. @throws {WorldNotFoundError} when the world does not exist.
|
|
495
|
+
*/
|
|
496
|
+
async function uploadPreset(deps, worldId, file, name, language) {
|
|
497
|
+
const world = await deps.worlds.find(worldId);
|
|
498
|
+
if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
|
|
499
|
+
const preset = readPreset(file, name);
|
|
500
|
+
await mkdir(join(world.directory, IMPORT_FOLDER), { recursive: true });
|
|
501
|
+
await writeFile(join(world.directory, IMPORT_FOLDER, PRESET_FILE), file);
|
|
502
|
+
const chatSessionId = await deps.authoring.ensure(world.summary.id, world.summary.name, `Authoring ${world.summary.name}`, language);
|
|
503
|
+
let failure;
|
|
504
|
+
try {
|
|
505
|
+
await deps.authoring.send(chatSessionId, presetMessage());
|
|
506
|
+
} catch (error) {
|
|
507
|
+
failure = error instanceof Error ? error.message : String(error);
|
|
508
|
+
}
|
|
509
|
+
return {
|
|
510
|
+
chatSessionId,
|
|
511
|
+
preset: preset.name,
|
|
512
|
+
started: failure === void 0,
|
|
513
|
+
...failure === void 0 ? {} : { failure }
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
//#endregion
|
|
651
517
|
//#region src/host/agent/authoring-sessions.ts
|
|
652
518
|
const AUTHORING_PROJECT_TITLE = "World Authoring";
|
|
653
519
|
const AUTHORING_AGENT_PRESET = "world-authoring";
|
|
@@ -702,6 +568,42 @@ var AuthoringSessions = class {
|
|
|
702
568
|
}
|
|
703
569
|
};
|
|
704
570
|
//#endregion
|
|
571
|
+
//#region src/host/agent/doctor-sessions.ts
|
|
572
|
+
const DOCTOR_PROJECT_TITLE = "Session Doctor";
|
|
573
|
+
const DOCTOR_AGENT_PRESET = "session-doctor";
|
|
574
|
+
/** Creates or reopens the chat in which a bystander reads one session's records and proposes fixes. */
|
|
575
|
+
var DoctorSessions = class {
|
|
576
|
+
services;
|
|
577
|
+
roleplayRoot;
|
|
578
|
+
prompts;
|
|
579
|
+
constructor(services, roleplayRoot, prompts) {
|
|
580
|
+
this.services = services;
|
|
581
|
+
this.roleplayRoot = roleplayRoot;
|
|
582
|
+
this.prompts = prompts;
|
|
583
|
+
}
|
|
584
|
+
async ensure(session, title, language) {
|
|
585
|
+
const services = this.services();
|
|
586
|
+
const projectPath = join(this.roleplayRoot(), "sessions");
|
|
587
|
+
const project = await services.registry.create(projectPath, DOCTOR_PROJECT_TITLE);
|
|
588
|
+
const sessionId = doctorChatSessionId(session.id);
|
|
589
|
+
if (!project.sessionIds.includes(sessionId) && !await isStored(services.persistence, sessionId)) {
|
|
590
|
+
if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of a session doctor chat");
|
|
591
|
+
await storeDoctorOpening(services.persistence, {
|
|
592
|
+
id: sessionId,
|
|
593
|
+
cwd: project.path,
|
|
594
|
+
agentPreset: DOCTOR_AGENT_PRESET
|
|
595
|
+
}, this.prompts.text("doctor/welcome", language, { session: session.name }));
|
|
596
|
+
}
|
|
597
|
+
return await ensureAgentChat(services, {
|
|
598
|
+
projectPath,
|
|
599
|
+
projectTitle: DOCTOR_PROJECT_TITLE,
|
|
600
|
+
sessionId,
|
|
601
|
+
agentPreset: DOCTOR_AGENT_PRESET,
|
|
602
|
+
title
|
|
603
|
+
}, project);
|
|
604
|
+
}
|
|
605
|
+
};
|
|
606
|
+
//#endregion
|
|
705
607
|
//#region src/host/orchestration/service.ts
|
|
706
608
|
/**
|
|
707
609
|
* The extension points of a roleplay turn. Another plugin changes how the turn
|
|
@@ -1095,6 +997,17 @@ async function addStarterWorld(catalog, folder, directory = starterDirectory())
|
|
|
1095
997
|
return added;
|
|
1096
998
|
}
|
|
1097
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
|
|
1098
1011
|
//#region src/host/http/respond.ts
|
|
1099
1012
|
function sendJson(res, status, payload) {
|
|
1100
1013
|
res.statusCode = status;
|
|
@@ -1910,6 +1823,21 @@ async function sendImage(res, image) {
|
|
|
1910
1823
|
res.setHeader("cache-control", "private, max-age=31536000, immutable");
|
|
1911
1824
|
await pipeline(createReadStream(image.file), res);
|
|
1912
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
|
+
}
|
|
1913
1841
|
/** The status an import failure is shown with: what is wrong with the card or the choices is the person's to fix. */
|
|
1914
1842
|
function importFailure(res, error) {
|
|
1915
1843
|
if (error instanceof ImportCardError) return sendError(res, 422, error.message);
|
|
@@ -1932,7 +1860,7 @@ function languageField(value) {
|
|
|
1932
1860
|
throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
|
|
1933
1861
|
}
|
|
1934
1862
|
}
|
|
1935
|
-
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 }) {
|
|
1936
1864
|
const routes = {
|
|
1937
1865
|
"/speech/capabilities": { GET: async (_req, res) => {
|
|
1938
1866
|
sendJson(res, 200, { streaming: speech.streaming() });
|
|
@@ -1973,6 +1901,81 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
|
|
|
1973
1901
|
}
|
|
1974
1902
|
}
|
|
1975
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
|
+
} },
|
|
1976
1979
|
"/worlds/starter": {
|
|
1977
1980
|
GET: async (_req, res) => {
|
|
1978
1981
|
sendJson(res, 200, await starter.list());
|
|
@@ -1997,6 +2000,15 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
|
|
|
1997
2000
|
return importFailure(res, error);
|
|
1998
2001
|
}
|
|
1999
2002
|
} },
|
|
2003
|
+
"/worlds/import/preset": { POST: async (req, res, url) => {
|
|
2004
|
+
const name = decodeURIComponent(String(req.headers["x-file-name"] ?? url.searchParams.get("name") ?? "preset"));
|
|
2005
|
+
try {
|
|
2006
|
+
sendJson(res, 200, await importer.uploadPreset(url.searchParams.get("id") ?? "", await readBinaryBody(req, importer.maxUploadBytes), name, languageField(url.searchParams.get("language") ?? void 0)));
|
|
2007
|
+
} catch (error) {
|
|
2008
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
2009
|
+
return importFailure(res, error);
|
|
2010
|
+
}
|
|
2011
|
+
} },
|
|
2000
2012
|
"/worlds/import": {
|
|
2001
2013
|
GET: async (_req, res, url) => {
|
|
2002
2014
|
try {
|
|
@@ -2212,6 +2224,93 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
|
|
|
2212
2224
|
}
|
|
2213
2225
|
}
|
|
2214
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
|
+
},
|
|
2215
2314
|
"/worlds/state/plots": { PUT: async (req, res, url) => {
|
|
2216
2315
|
try {
|
|
2217
2316
|
const body = await readJsonBody(req);
|
|
@@ -2453,6 +2552,72 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
|
|
|
2453
2552
|
return sendError(res, 404, error instanceof Error ? error.message : String(error));
|
|
2454
2553
|
}
|
|
2455
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
|
+
])),
|
|
2456
2621
|
"/worlds/characters": { GET: async (_req, res, url) => {
|
|
2457
2622
|
try {
|
|
2458
2623
|
sendJson(res, 200, await worldCharacters(url.searchParams.get("id") ?? ""));
|
|
@@ -2804,6 +2969,17 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
|
|
|
2804
2969
|
throw error;
|
|
2805
2970
|
}
|
|
2806
2971
|
} },
|
|
2972
|
+
"/sessions/doctor": { POST: async (req, res, url) => {
|
|
2973
|
+
const body = await readJsonBody(req);
|
|
2974
|
+
if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
|
|
2975
|
+
try {
|
|
2976
|
+
sendJson(res, 200, await sessions.doctor(url.searchParams.get("id") ?? "", body.title.trim(), languageField(body.language) ?? "en"));
|
|
2977
|
+
} catch (error) {
|
|
2978
|
+
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
2979
|
+
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
2980
|
+
throw error;
|
|
2981
|
+
}
|
|
2982
|
+
} },
|
|
2807
2983
|
"/sessions/reflect": { POST: async (_req, res, url) => {
|
|
2808
2984
|
try {
|
|
2809
2985
|
await sessions.reflect(url.searchParams.get("id") ?? "");
|
|
@@ -2926,6 +3102,7 @@ function registerApi(ctx, deps) {
|
|
|
2926
3102
|
async function deleteSession(deps, id) {
|
|
2927
3103
|
const directory = deps.sessionsDir();
|
|
2928
3104
|
if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
|
|
3105
|
+
await deps.purgeChat(doctorChatSessionId(id));
|
|
2929
3106
|
await deps.purgeChat(chatSessionId(id));
|
|
2930
3107
|
deps.state.deleteSession(directory, id);
|
|
2931
3108
|
}
|
|
@@ -3283,7 +3460,7 @@ function sessionOf(deps, id) {
|
|
|
3283
3460
|
return deps.state.openSession(directory, id);
|
|
3284
3461
|
}
|
|
3285
3462
|
const keyOf = (character) => character.sourceId ?? String(character.id);
|
|
3286
|
-
function worldOf(session, sessionsDir) {
|
|
3463
|
+
function worldOf$1(session, sessionsDir) {
|
|
3287
3464
|
const narrationVoice = session.metadata.getValue("roleplay.tts.narrationVoice");
|
|
3288
3465
|
const characters = session.characters.list().map((character) => {
|
|
3289
3466
|
const state = session.characterStates.get(character.id);
|
|
@@ -3347,6 +3524,7 @@ function worldOf(session, sessionsDir) {
|
|
|
3347
3524
|
key: location.sourceId ?? String(location.id),
|
|
3348
3525
|
name: location.name,
|
|
3349
3526
|
description: location.description,
|
|
3527
|
+
...imageOf(session, sessionsDir, "place", location),
|
|
3350
3528
|
...location.parentId === void 0 ? {} : { parent: {
|
|
3351
3529
|
key: session.locations.get(location.parentId)?.sourceId ?? String(location.parentId),
|
|
3352
3530
|
name: locationName(location.parentId)
|
|
@@ -3368,6 +3546,7 @@ function worldOf(session, sessionsDir) {
|
|
|
3368
3546
|
key: item.sourceId ?? String(item.id),
|
|
3369
3547
|
name: item.name,
|
|
3370
3548
|
description: item.description,
|
|
3549
|
+
...imageOf(session, sessionsDir, "thing", item),
|
|
3371
3550
|
quantity: item.quantity,
|
|
3372
3551
|
unique: item.unique,
|
|
3373
3552
|
quality: item.quality,
|
|
@@ -3570,7 +3749,7 @@ function editWorldLore(deps, id, key, edit) {
|
|
|
3570
3749
|
const entry = session.lore.list().find((candidate) => (candidate.sourceId ?? String(candidate.id)) === key);
|
|
3571
3750
|
if (entry === void 0) throw new InvalidEditProblems([`there is no lore "${key}"`]);
|
|
3572
3751
|
session.lore.update(entry.id, edit);
|
|
3573
|
-
return worldOf(session, deps.sessionsDir());
|
|
3752
|
+
return worldOf$1(session, deps.sessionsDir());
|
|
3574
3753
|
}
|
|
3575
3754
|
function editWorldPlots(deps, id, edit) {
|
|
3576
3755
|
const parsed = parsePlotsFile(JSON.stringify(edit.plots));
|
|
@@ -3598,13 +3777,13 @@ function editWorldPlots(deps, id, edit) {
|
|
|
3598
3777
|
});
|
|
3599
3778
|
}
|
|
3600
3779
|
session.metadata.setValue(PLOTS_METADATA_KEY, merged);
|
|
3601
|
-
return worldOf(session, deps.sessionsDir());
|
|
3780
|
+
return worldOf$1(session, deps.sessionsDir());
|
|
3602
3781
|
}
|
|
3603
3782
|
function editSessionNarrationVoice(deps, id, voice) {
|
|
3604
3783
|
const session = sessionOf(deps, id);
|
|
3605
3784
|
if (voice.trim() === "") session.metadata.deleteValue("roleplay.tts.narrationVoice");
|
|
3606
3785
|
else session.metadata.setValue("roleplay.tts.narrationVoice", voice.trim());
|
|
3607
|
-
return worldOf(session, deps.sessionsDir());
|
|
3786
|
+
return worldOf$1(session, deps.sessionsDir());
|
|
3608
3787
|
}
|
|
3609
3788
|
const relationKey = (...parts) => parts.map((part) => encodeURIComponent(part)).join(":");
|
|
3610
3789
|
const relationParts = (key) => key.split(":").map((part) => decodeURIComponent(part));
|
|
@@ -3613,7 +3792,7 @@ const relationParts = (key) => key.split(":").map((part) => decodeURIComponent(p
|
|
|
3613
3792
|
* @throws {SessionNotFoundError} when the id names no session.
|
|
3614
3793
|
*/
|
|
3615
3794
|
function readWorldState(deps, id) {
|
|
3616
|
-
return worldOf(sessionOf(deps, id), deps.sessionsDir());
|
|
3795
|
+
return worldOf$1(sessionOf(deps, id), deps.sessionsDir());
|
|
3617
3796
|
}
|
|
3618
3797
|
/**
|
|
3619
3798
|
* Change a character of a session, all of it or none of it, and say how the world stands after.
|
|
@@ -3657,7 +3836,7 @@ function editWorldCharacter(deps, id, key, edit) {
|
|
|
3657
3836
|
if (error instanceof Error && error.name === "InvalidValueError") throw new InvalidEditProblems([error.message]);
|
|
3658
3837
|
throw error;
|
|
3659
3838
|
}
|
|
3660
|
-
return worldOf(session, deps.sessionsDir());
|
|
3839
|
+
return worldOf$1(session, deps.sessionsDir());
|
|
3661
3840
|
}
|
|
3662
3841
|
function editWorldPlace(deps, id, key, edit) {
|
|
3663
3842
|
const session = sessionOf(deps, id);
|
|
@@ -3680,7 +3859,7 @@ function editWorldPlace(deps, id, key, edit) {
|
|
|
3680
3859
|
if (error instanceof Error && (error.name === "InvalidValueError" || error.name === "ConflictError")) throw new InvalidEditProblems([error.message]);
|
|
3681
3860
|
throw error;
|
|
3682
3861
|
}
|
|
3683
|
-
return worldOf(session, deps.sessionsDir());
|
|
3862
|
+
return worldOf$1(session, deps.sessionsDir());
|
|
3684
3863
|
}
|
|
3685
3864
|
function editWorldThing(deps, id, key, edit) {
|
|
3686
3865
|
const session = sessionOf(deps, id);
|
|
@@ -3704,7 +3883,7 @@ function editWorldThing(deps, id, key, edit) {
|
|
|
3704
3883
|
if (error instanceof Error && (error.name === "InvalidValueError" || error.name === "ConflictError")) throw new InvalidEditProblems([error.message]);
|
|
3705
3884
|
throw error;
|
|
3706
3885
|
}
|
|
3707
|
-
return worldOf(session, deps.sessionsDir());
|
|
3886
|
+
return worldOf$1(session, deps.sessionsDir());
|
|
3708
3887
|
}
|
|
3709
3888
|
function editWorldFaction(deps, id, key, edit) {
|
|
3710
3889
|
const session = sessionOf(deps, id);
|
|
@@ -3724,7 +3903,7 @@ function editWorldFaction(deps, id, key, edit) {
|
|
|
3724
3903
|
if (error instanceof Error && (error.name === "InvalidValueError" || error.name === "ConflictError")) throw new InvalidEditProblems([error.message]);
|
|
3725
3904
|
throw error;
|
|
3726
3905
|
}
|
|
3727
|
-
return worldOf(session, deps.sessionsDir());
|
|
3906
|
+
return worldOf$1(session, deps.sessionsDir());
|
|
3728
3907
|
}
|
|
3729
3908
|
function editWorldRelation(deps, id, edit) {
|
|
3730
3909
|
const session = sessionOf(deps, id);
|
|
@@ -3783,7 +3962,7 @@ function editWorldRelation(deps, id, edit) {
|
|
|
3783
3962
|
].includes(error.name)) throw new InvalidEditProblems([error.message]);
|
|
3784
3963
|
throw error;
|
|
3785
3964
|
}
|
|
3786
|
-
return worldOf(session, deps.sessionsDir());
|
|
3965
|
+
return worldOf$1(session, deps.sessionsDir());
|
|
3787
3966
|
}
|
|
3788
3967
|
const isNewRelation = (edit) => "create" in edit && edit.create === true;
|
|
3789
3968
|
function createSessionRelation(session, sessionsDir, edit) {
|
|
@@ -3835,13 +4014,79 @@ function createSessionRelation(session, sessionsDir, edit) {
|
|
|
3835
4014
|
].includes(error.name)) throw new InvalidEditProblems([error.message]);
|
|
3836
4015
|
throw error;
|
|
3837
4016
|
}
|
|
3838
|
-
return worldOf(session, sessionsDir);
|
|
4017
|
+
return worldOf$1(session, sessionsDir);
|
|
3839
4018
|
}
|
|
3840
4019
|
function characterOf(session, key) {
|
|
3841
4020
|
const character = session.characters.list().find((candidate) => keyOf(candidate) === key);
|
|
3842
4021
|
if (character === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
|
|
3843
4022
|
return character;
|
|
3844
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
|
+
}
|
|
3845
4090
|
/** Generate or replace a session character's stable reference portrait from its copied identity. */
|
|
3846
4091
|
async function generateSessionCharacterPortrait(deps, id, key, service) {
|
|
3847
4092
|
const session = sessionOf(deps, id);
|
|
@@ -3858,7 +4103,7 @@ async function generateSessionCharacterPortrait(deps, id, key, service) {
|
|
|
3858
4103
|
},
|
|
3859
4104
|
identity
|
|
3860
4105
|
});
|
|
3861
|
-
return worldOf(session, deps.sessionsDir());
|
|
4106
|
+
return worldOf$1(session, deps.sessionsDir());
|
|
3862
4107
|
}
|
|
3863
4108
|
/** The picture the player brought becomes the session character's portrait. */
|
|
3864
4109
|
async function uploadSessionCharacterPortrait(deps, id, key, png, originalName) {
|
|
@@ -3880,7 +4125,7 @@ async function uploadSessionCharacterPortrait(deps, id, key, png, originalName)
|
|
|
3880
4125
|
} catch (error) {
|
|
3881
4126
|
throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
|
|
3882
4127
|
}
|
|
3883
|
-
return worldOf(session, deps.sessionsDir());
|
|
4128
|
+
return worldOf$1(session, deps.sessionsDir());
|
|
3884
4129
|
}
|
|
3885
4130
|
/** Resolve a portrait through session state so request parameters cannot select arbitrary files. */
|
|
3886
4131
|
async function sessionCharacterPortraitFile(deps, id, key) {
|
|
@@ -4076,7 +4321,8 @@ function infoOf(document) {
|
|
|
4076
4321
|
tools: toolsOf(document["tools"]),
|
|
4077
4322
|
alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
|
|
4078
4323
|
title: textOf(entry["title"]),
|
|
4079
|
-
text: entry["text"]
|
|
4324
|
+
text: entry["text"],
|
|
4325
|
+
...textOf(entry["character"]) === "" ? {} : { character: textOf(entry["character"]) }
|
|
4080
4326
|
}] : []) : []
|
|
4081
4327
|
};
|
|
4082
4328
|
}
|
|
@@ -4133,7 +4379,8 @@ async function editWorldInfo(directory, edit) {
|
|
|
4133
4379
|
if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
|
|
4134
4380
|
else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
|
|
4135
4381
|
title: entry.title === "" ? entry.text.slice(0, 40) : entry.title,
|
|
4136
|
-
text: entry.text
|
|
4382
|
+
text: entry.text,
|
|
4383
|
+
...entry.character === void 0 || entry.character === "" ? {} : { character: entry.character }
|
|
4137
4384
|
}));
|
|
4138
4385
|
}
|
|
4139
4386
|
if (edit.tools !== void 0) {
|
|
@@ -4182,6 +4429,13 @@ async function startSession(deps, request) {
|
|
|
4182
4429
|
const player = characters.find((character) => character.id === playerId);
|
|
4183
4430
|
if (player === void 0) throw new InvalidStartError(request.playerAvatar === void 0 ? `"${world.summary.name}" has no character "${request.playerCharacterId}"` : `the avatar "${request.playerAvatar}" is not among the avatars brought along`);
|
|
4184
4431
|
if (player.role !== "playable") throw new InvalidStartError(`${player.name} cannot be played`);
|
|
4432
|
+
const openingProblems = (world.alternateOpenings ?? []).flatMap((entry, index) => entry.character === void 0 || authored.some((character) => character.id === entry.character && character.role === "playable") ? [] : [{
|
|
4433
|
+
path: `alternate_openings[${index}].character`,
|
|
4434
|
+
message: `"${entry.character}" is not a playable character of this world`
|
|
4435
|
+
}]);
|
|
4436
|
+
if (openingProblems.length > 0) throw new InvalidWorldError(`the alternate openings of "${world.summary.name}" have ${openingProblems.length} problem(s)`, openingProblems);
|
|
4437
|
+
const forCharacter = request.opening === void 0 ? void 0 : world.alternateOpenings[request.opening].character;
|
|
4438
|
+
if (forCharacter !== void 0 && forCharacter !== player.id) throw new InvalidStartError(`this opening is for ${authored.find((character) => character.id === forCharacter)?.name ?? forCharacter}, not for ${player.name}`);
|
|
4185
4439
|
const name = request.name?.trim() || world.summary.name;
|
|
4186
4440
|
if (name.length > 200) throw new InvalidStartError(`the name must be at most 200 characters`);
|
|
4187
4441
|
let settings = DEFAULT_SETTINGS;
|
|
@@ -4398,6 +4652,7 @@ function payloadOf(deps, id, settings) {
|
|
|
4398
4652
|
pendingRecords: deps.pendingRecords(id),
|
|
4399
4653
|
pendingConsolidation: deps.pendingConsolidation(id),
|
|
4400
4654
|
activity: deps.activity(id),
|
|
4655
|
+
usage: deps.usage(id),
|
|
4401
4656
|
interventions: deps.interventions(id),
|
|
4402
4657
|
vectors: deps.vectors(id),
|
|
4403
4658
|
reflection: deps.reflection(id),
|
|
@@ -4456,6 +4711,65 @@ function resetVectors(session) {
|
|
|
4456
4711
|
session.recallIndex.reset();
|
|
4457
4712
|
}
|
|
4458
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
|
|
4459
4773
|
//#region src/host/sessions/interventions.ts
|
|
4460
4774
|
/** What the story's triggers delivered lately and what became of each, oldest first. */
|
|
4461
4775
|
function readInterventions(session) {
|
|
@@ -4560,7 +4874,10 @@ async function worldCharacters(worlds, worldId) {
|
|
|
4560
4874
|
tier,
|
|
4561
4875
|
kind
|
|
4562
4876
|
})),
|
|
4563
|
-
openings: (world.alternateOpenings ?? []).map((opening) =>
|
|
4877
|
+
openings: (world.alternateOpenings ?? []).map((opening) => ({
|
|
4878
|
+
title: opening.title,
|
|
4879
|
+
...opening.character === void 0 ? {} : { character: opening.character }
|
|
4880
|
+
})),
|
|
4564
4881
|
startingTime: world.clock?.startingTime === void 0 ? "" : localInstant(world.clock.startingTime, world.clock.timeZone ?? "UTC"),
|
|
4565
4882
|
timeZone: world.clock?.timeZone ?? "",
|
|
4566
4883
|
problems
|
|
@@ -4863,6 +5180,796 @@ var WorldCatalog = class extends Service {
|
|
|
4863
5180
|
}
|
|
4864
5181
|
};
|
|
4865
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
|
|
4866
5973
|
//#region src/host/speech/service.ts
|
|
4867
5974
|
async function voicesOf(service) {
|
|
4868
5975
|
return await service.voices();
|
|
@@ -4934,6 +6041,12 @@ function mergeWav(buffers) {
|
|
|
4934
6041
|
const Config = z.object({
|
|
4935
6042
|
rootPath: z.string().default("~/dsh-roleplay").volatile(),
|
|
4936
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),
|
|
4937
6050
|
importMaxUploadBytes: z.number().min(1024).default(104857600),
|
|
4938
6051
|
importConcurrency: z.number().min(1).max(16).default(4),
|
|
4939
6052
|
importReasoning: z.string().default(""),
|
|
@@ -4971,6 +6084,7 @@ function apply(ctx, config) {
|
|
|
4971
6084
|
const languages = new AuthoringLanguages(ctx, () => join(root.path, "worlds"));
|
|
4972
6085
|
const agent = new AgentSessions(agentServicesOf(ctx), () => root.path);
|
|
4973
6086
|
const authoring = new AuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
|
|
6087
|
+
const doctors = new DoctorSessions(agentServicesOf(ctx), () => root.path, prompts);
|
|
4974
6088
|
const imports = new ImportStore(() => root.path);
|
|
4975
6089
|
new RoleplayImport(ctx, {
|
|
4976
6090
|
maxUploadBytes: config.importMaxUploadBytes,
|
|
@@ -4987,6 +6101,7 @@ function apply(ctx, config) {
|
|
|
4987
6101
|
vectors: (id) => vectorStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
|
|
4988
6102
|
reflection: (id) => reflectionStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id), ctx.roleplayOrchestration.reflecting(chatSessionId(id))),
|
|
4989
6103
|
activity: (id) => readActivity(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
|
|
6104
|
+
usage: (id) => readUsage(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
|
|
4990
6105
|
interventions: (id) => readInterventions(ctx.roleplayState.openSession(join(root.path, "sessions"), id))
|
|
4991
6106
|
};
|
|
4992
6107
|
const purgeChat = purgeOf(ctx, config.sessionStorePath);
|
|
@@ -4998,6 +6113,21 @@ function apply(ctx, config) {
|
|
|
4998
6113
|
avatars: () => avatarsWorld(root.path)
|
|
4999
6114
|
};
|
|
5000
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
|
+
}),
|
|
5001
6131
|
packs: new InterfaceService({
|
|
5002
6132
|
open: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
|
|
5003
6133
|
root: () => root.path,
|
|
@@ -5043,7 +6173,11 @@ function apply(ctx, config) {
|
|
|
5043
6173
|
authoring,
|
|
5044
6174
|
chatTitle: (name) => `Authoring ${name}`
|
|
5045
6175
|
}, id, choices, language),
|
|
5046
|
-
picture: (id) => imports.picture(id)
|
|
6176
|
+
picture: (id) => imports.picture(id),
|
|
6177
|
+
uploadPreset: (worldId, file, name, language) => uploadPreset({
|
|
6178
|
+
worlds,
|
|
6179
|
+
authoring
|
|
6180
|
+
}, worldId, file, name, language)
|
|
5047
6181
|
},
|
|
5048
6182
|
worldCharacters: (worldId) => worldCharacters(worlds, worldId),
|
|
5049
6183
|
avatars: {
|
|
@@ -5101,14 +6235,36 @@ function apply(ctx, config) {
|
|
|
5101
6235
|
editLore: async (worldId, key, edit) => await editWorldLore$1(await editableWorld(worlds, worldId, root.path), key, edit),
|
|
5102
6236
|
addLore: async (worldId, title) => (await addWorldLore(await editableWorld(worlds, worldId, root.path), title)).state,
|
|
5103
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),
|
|
5104
6245
|
editPlots: async (worldId, edit) => await editWorldPlots$1(await editableWorld(worlds, worldId, root.path), edit),
|
|
5105
6246
|
editRelation: async (worldId, edit) => await editWorldRelation$1(await editableWorld(worlds, worldId, root.path), edit),
|
|
5106
6247
|
editNarrationVoice: async (worldId, voice) => await editWorldNarrationVoice(await editableWorld(worlds, worldId, root.path), voice),
|
|
5107
6248
|
generatePortrait: async (worldId, key) => await generateWorldCharacterPortrait(await editableWorld(worlds, worldId, root.path), key, imageGenerationOf(ctx)),
|
|
5108
6249
|
portraitFile: async (worldId, key) => await worldCharacterPortraitFile(await editableWorld(worlds, worldId, root.path), key),
|
|
5109
|
-
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)
|
|
5110
6254
|
},
|
|
5111
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),
|
|
5112
6268
|
list: () => listSessions(deps),
|
|
5113
6269
|
start: (request) => startSession(deps, request),
|
|
5114
6270
|
open: (id) => openSession(deps, id),
|
|
@@ -5192,6 +6348,14 @@ function apply(ctx, config) {
|
|
|
5192
6348
|
if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
|
|
5193
6349
|
return readRunDetail(sessionFolder(sessions, id), run);
|
|
5194
6350
|
},
|
|
6351
|
+
doctor: async (id, title, language) => {
|
|
6352
|
+
const sessions = join(root.path, "sessions");
|
|
6353
|
+
if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
|
|
6354
|
+
return { chatSessionId: await doctors.ensure({
|
|
6355
|
+
id,
|
|
6356
|
+
name: ctx.roleplayState.openSession(sessions, id).metadata.get().name
|
|
6357
|
+
}, title, language) };
|
|
6358
|
+
},
|
|
5195
6359
|
reflect: async (id) => {
|
|
5196
6360
|
const sessions = join(root.path, "sessions");
|
|
5197
6361
|
if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
|