@dsh-agentic-roleplay/core 0.7.2 → 0.8.1
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/README.md +1 -1
- package/lib/authoring-tools-DNnx0Nts.js +3574 -0
- package/lib/authoring.js +295 -333
- package/lib/{child-CyCViUKa.js → child-D6mpkkCE.js} +130 -6
- package/lib/client.js +931 -415
- package/lib/client.js.map +1 -1
- package/lib/compaction.js +2 -2
- package/lib/doctor.js +2 -2
- package/lib/{gallery-BxZGOgMb.js → gallery-D9nG3C78.js} +2 -2
- package/lib/{generator-BFmSYvR8.js → generator-r1Czm7oi.js} +2 -2
- package/lib/helper.js +1 -1
- package/lib/{hooks-HnqXO8mM.js → hooks-BQCzgggH.js} +92 -8
- package/lib/images.js +4 -4
- package/lib/index.js +1326 -1638
- package/lib/{library-BGxPKs9a.js → library-zI-2tG7h.js} +59 -9
- package/lib/{lorebook-author-tools-D9RrMK5g.js → lorebook-author-tools-ywaYicwd.js} +7 -7
- package/lib/lorebook-authoring.js +4 -4
- package/lib/{narration-DvFBqmqe.js → narration-CnBlVure.js} +52 -8
- package/lib/orchestration.js +95 -18
- package/lib/{pack-jail-MPekqSuQ.js → pack-jail-5EJ-WYyW.js} +1274 -69
- package/lib/{packs-jowC-MN_.js → packs-Cv8hanXJ.js} +2 -2
- package/lib/{presenter-agent-DvZtnf0Q.js → presenter-agent-BSaMSd3G.js} +6 -6
- package/lib/{preset-VatN-845.js → preset-CWI3-0r1.js} +4 -3
- package/lib/{preset-author-tools-8kv1Glxe.js → preset-author-tools-BrJYa2cr.js} +7 -7
- package/lib/preset-authoring.js +5 -5
- package/lib/presets-MwOSMMyu.js +3998 -0
- package/lib/{reflection-CvOZGjmn.js → reflection-zSaMsjKj.js} +127 -127
- package/lib/{text-JbWfTHbr.js → text-BzudpQLS.js} +11 -1
- package/lib/{turn-guard-BvCs1VxB.js → turn-guard-Cv8pfHEA.js} +6 -2
- package/package.json +2 -2
- package/prompts/en/import/casting.md +14 -0
- package/prompts/en/import/classifier.md +9 -0
- package/prompts/en/import/finish-draft.md +1 -0
- package/prompts/en/import/generator.md +8 -0
- package/prompts/en/import/notice-repair.md +4 -0
- package/prompts/en/import/repair-again.md +3 -0
- package/prompts/en/import/roster.md +1 -0
- package/prompts/en/import/variables.md +1 -0
- package/prompts/en/roleplay/game-master.md +3 -0
- package/prompts/en/roleplay/standing.md +1 -0
- package/prompts/en/world/author.md +1 -1
- package/prompts/zh/import/casting.md +14 -0
- package/prompts/zh/import/classifier.md +9 -0
- package/prompts/zh/import/finish-draft.md +1 -0
- package/prompts/zh/import/generator.md +8 -0
- package/prompts/zh/import/notice-repair.md +4 -0
- package/prompts/zh/import/repair-again.md +3 -0
- package/prompts/zh/import/roster.md +1 -0
- package/prompts/zh/import/variables.md +1 -0
- package/prompts/zh/roleplay/game-master.md +3 -0
- package/prompts/zh/roleplay/standing.md +1 -0
- package/prompts/zh/world/author.md +1 -1
- package/lib/authoring-tools-q34iq3hW.js +0 -6140
- package/lib/route-DRTJ_vcA.js +0 -518
package/lib/index.js
CHANGED
|
@@ -1,30 +1,28 @@
|
|
|
1
1
|
import { a as chatSessionId, i as VARIABLE_VISIBILITIES, n as VARIABLE_KINDS, o as roleplaySessionOf, r as VARIABLE_SUBJECTS } from "./access-DtOxFKBK.js";
|
|
2
|
-
import { $ as
|
|
3
|
-
import { a as lorebookImportMessage, c as readLorebook, d as lorebookOfChat, l as selectEntries, s as previewLorebook, t as LOREBOOK_UPLOAD, u as lorebookChatSessionId } from "./lorebook-author-tools-
|
|
4
|
-
import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-
|
|
5
|
-
import {
|
|
6
|
-
import { c as
|
|
7
|
-
import { a as liveSettings, c as writeSettings, d as
|
|
8
|
-
import {
|
|
9
|
-
import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-
|
|
2
|
+
import { $ as knowsCharacter, At as loadCharacters, B as deleteLorebook, Bt as authoredWorldOf, Ct as DICE_FILE_NAME, D as guardedLookup, Dt as loadCalendar, Et as CALENDAR_FILE_NAME, F as WORLD_FILE_NAME, Ft as pictureOf, G as loadLorebook, H as entriesOf, I as parseWorldFile, It as readCard, J as reserveLorebook, K as lorebookDirectory, L as parseWorldInfoEdit, Lt as DICE_COMPARISONS, Mt as knownOutputCeiling, Nt as ImportCardError, Ot as parseCalendarFile, Pt as isPng, Q as loadValidatedWorld, R as addLorebookEntries, Rt as DICE_READINGS, S as CatalogueError, Tt as parseDiceFile, U as isLorebookName, V as deleteLorebookEntry, W as listLorebooks, X as writeLorebookEntry, Y as updateLorebookInfo, Z as checkWorld, _ as hashWorld, at as populateItems, b as readOrigin, bt as loadItems, c as importPhase, ct as populateLore, d as markReady, dt as populateVariables, et as populateCalendar, f as settleDraft, ft as routineProblems, g as describeChanges, it as populateFactions, jt as subfolders, k as vetUrl, kt as CHARACTERS_DIR, lt as populateRoutines, nt as populateClock, ot as populateKnowledge, pt as TRIGGERS_FILE_NAME, rt as populateDice, st as populateLocations, t as AuthoringTools, tt as populateCharacters, u as keepDraft, ut as populateTriggers, v as isUnchanged, vt as loadLocations, wt as loadDice, x as writeOrigin, y as localChanges, z as createLorebook, zt as DICE_RESULTS } from "./authoring-tools-DNnx0Nts.js";
|
|
3
|
+
import { a as lorebookImportMessage, c as readLorebook, d as lorebookOfChat, l as selectEntries, s as previewLorebook, t as LOREBOOK_UPLOAD, u as lorebookChatSessionId } from "./lorebook-author-tools-ywaYicwd.js";
|
|
4
|
+
import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-BrJYa2cr.js";
|
|
5
|
+
import { B as readWorldPrompt, Ct as parseLoreEdit, Dt as LORE_KINDS, Et as parseThingEdit, G as withPlayer, J as ImportStore, K as IMPORT_FOLDER, Ot as LORE_SCOPES, R as deleteWorldPrompt, St as parseFactionEdit, Tt as parseRelationEdit, V as writeWorldPrompt, W as partsOf, Z as parseChoices, _t as parseCharacterFile, a as isPresetName, at as variableProblems, bt as InvalidEditProblems, c as presetDirectory, d as savePresetFromWorld, et as IMPORT_COMMAND, gt as CHARACTER_FILE_NAME, i as deletePreset, it as parseVariablesFile, nt as VARIABLES_FILE_NAME, o as listPresets, p as updatePresetInfo, q as ImportNotFoundError, r as createPresetFromShipped, rt as loadVariables, s as loadPreset, t as PRESET_FILE, u as reservePreset, wt as parsePlaceEdit, xt as parseCharacterEdit, z as listWorldPrompts } from "./presets-MwOSMMyu.js";
|
|
6
|
+
import { c as readTimeline, d as copyPreset, f as presetStatus, h as defaultBoundaries, i as reflectionStatus, l as writeTimeline, m as switchPreset, o as TimelineError, p as recordPreset, u as pathTo } from "./reflection-zSaMsjKj.js";
|
|
7
|
+
import { a as liveSettings, c as writeSettings, d as DEFAULT_SETTINGS, f as SETTINGS_SPEC, h as WORLD_RULES_KEY, i as InvalidSettingsError, l as atomicWrite, o as readSettings, p as parseSettings, s as useChildReasoning } from "./narration-CnBlVure.js";
|
|
8
|
+
import { $ as copyWorldPrompts, C as notesOfSession, H as parsePlotsFile, J as formatIssue, K as readDocument, M as PLOTS_METADATA_KEY, N as plotProgressOf, P as populatePlots, Q as PromptLibrary, S as addToNote, T as observeAsPlayer, U as plotReferenceProblems, W as COMMANDS_KEY, Y as errorMessage, _ as readActivity, ct as InvalidStartError, dt as SessionArchivedError, ft as SessionNotFoundError, g as readDecisionStats, h as readUsage, i as externalTools, it as shippedLanguages, k as zoneOf, lt as InvalidWorldError, pt as WorldNotFoundError, st as AgentUnavailableError, tt as languageOf, ut as ReflectionRefusedError, v as readRunDetail, w as readNotes, x as readWithdrawn } from "./hooks-BQCzgggH.js";
|
|
9
|
+
import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-BzudpQLS.js";
|
|
10
|
+
import { A as worldEntityImageFile, B as readWorldInfo, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as loadWorldParts, G as findTargets, I as PRESET_FILE$1, J as revertUpdate, L as presetMessage, O as uploadWorldEntityImage, S as generateWorldEntityImage, T as removeWorldTrigger, U as languageOfDocuments, V as translateMessage, W as readWorldDocuments, X as updateStatus, Y as startUpdate, _ as editWorldPlots$1, a as deleteWorldPackFile, at as authoringTitle, b as entityFolder, c as createAuthoredEntity, ct as ensureAgentChat, dt as appendNarratedTurn, f as editWorldCharacter$1, ft as storeAuthoringOpening, g as editWorldPlace$1, h as editWorldNarrationVoice, it as AuthoringSessions, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, lt as isStored, m as editWorldLore$1, n as packFileProblem, ot as AgentSessions, p as editWorldFaction$1, pt as storeDoctorOpening, st as agentServicesOf, t as MAX_PACK_TEXT, u as readAuthoredEntityDocument, ut as appendEmptyTurn, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1, z as editWorldInfo } from "./pack-jail-5EJ-WYyW.js";
|
|
11
|
+
import { d as sharedSamplingOf, i as childSamplingOf, u as parseSampling } from "./child-D6mpkkCE.js";
|
|
12
|
+
import { S as slug, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath, w as uniqueKey } from "./library-zI-2tG7h.js";
|
|
13
|
+
import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-CWI3-0r1.js";
|
|
14
14
|
import { t as doctorChatSessionId } from "./doctor-chat-ByDfCMeo.js";
|
|
15
|
-
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-
|
|
16
|
-
import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-
|
|
17
|
-
import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-
|
|
15
|
+
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-Cv8hanXJ.js";
|
|
16
|
+
import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-r1Czm7oi.js";
|
|
17
|
+
import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-D9nG3C78.js";
|
|
18
18
|
import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
|
|
19
19
|
import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
20
20
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
21
|
+
import { copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
21
22
|
import { Session, SessionId } from "@deepseek-ai/dsh-session";
|
|
22
|
-
import { ToolCallId, createMessage, createSystemMessage, createToolResultMessage } from "@deepseek-ai/dsh-llm";
|
|
23
|
-
import { setApprovalPolicy } from "@deepseek-ai/dsh-user-approval";
|
|
24
23
|
import { inflateRawSync } from "node:zlib";
|
|
25
24
|
import { fileURLToPath } from "node:url";
|
|
26
25
|
import { Service } from "@deepseek-ai/cordis";
|
|
27
|
-
import { chmod, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
28
26
|
import { addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
|
|
29
27
|
import { request } from "node:http";
|
|
30
28
|
import { request as request$1 } from "node:https";
|
|
@@ -32,383 +30,6 @@ import { pipeline } from "node:stream/promises";
|
|
|
32
30
|
import { homedir } from "node:os";
|
|
33
31
|
import { spawn } from "node:child_process";
|
|
34
32
|
import z from "@deepseek-ai/schemastery";
|
|
35
|
-
//#region src/host/agent/opening.ts
|
|
36
|
-
/** What the opening is reported to come from, where a chat shows the source of a message. */
|
|
37
|
-
const OPENING_SOURCE = {
|
|
38
|
-
provider: "roleplay",
|
|
39
|
-
model: "opening"
|
|
40
|
-
};
|
|
41
|
-
const AUTHORING_OPENING_SOURCE = {
|
|
42
|
-
provider: "world-authoring",
|
|
43
|
-
model: "opening"
|
|
44
|
-
};
|
|
45
|
-
const DOCTOR_OPENING_SOURCE = {
|
|
46
|
-
provider: "session-doctor",
|
|
47
|
-
model: "opening"
|
|
48
|
-
};
|
|
49
|
-
const NARRATE_TOOL = "narrate";
|
|
50
|
-
/**
|
|
51
|
-
* The first node of a conversation's surface is the system prompt, even an empty one: the log format refuses a system prompt that
|
|
52
|
-
* arrives after other nodes, which is what a chat that starts with an opening would otherwise get at its first real turn. The agent
|
|
53
|
-
* replaces this empty head with the real prompt then.
|
|
54
|
-
*/
|
|
55
|
-
function reservePromptHead(session, turn, step) {
|
|
56
|
-
session.append("system/message", {
|
|
57
|
-
turn,
|
|
58
|
-
step,
|
|
59
|
-
message: createSystemMessage("")
|
|
60
|
-
}, { surfaceOp: "append" });
|
|
61
|
-
}
|
|
62
|
-
/**
|
|
63
|
-
* One finished turn in which the output was delivered the way every turn delivers it (a `narrate` call and its result), so it renders
|
|
64
|
-
* the same and the model reads a history that looks like the one it will write. A turn with a player starts with the player's message.
|
|
65
|
-
*/
|
|
66
|
-
function appendNarratedTurn(session, turn, output, player) {
|
|
67
|
-
const step = 1;
|
|
68
|
-
const callId = ToolCallId(player === void 0 ? "opening-narrate" : `narrate-${turn}`);
|
|
69
|
-
const sent = output.segments.map((segment) => segment.type === "utterance" ? {
|
|
70
|
-
type: "utterance",
|
|
71
|
-
character: segment.character,
|
|
72
|
-
text: segment.text
|
|
73
|
-
} : {
|
|
74
|
-
type: "narration",
|
|
75
|
-
text: segment.text
|
|
76
|
-
});
|
|
77
|
-
const args = JSON.stringify({ segments: sent });
|
|
78
|
-
const started = session.append("turn/start", { turn });
|
|
79
|
-
session.append("step/start", {
|
|
80
|
-
turn,
|
|
81
|
-
step
|
|
82
|
-
});
|
|
83
|
-
let asked;
|
|
84
|
-
if (player === void 0) reservePromptHead(session, turn, step);
|
|
85
|
-
else asked = session.append("user/message", createMessage({
|
|
86
|
-
role: "user",
|
|
87
|
-
content: [{
|
|
88
|
-
type: "text",
|
|
89
|
-
text: player
|
|
90
|
-
}],
|
|
91
|
-
source: { kind: "user" }
|
|
92
|
-
}), { surfaceOp: "append" }).seq;
|
|
93
|
-
session.append("assistant/message", {
|
|
94
|
-
stream: [],
|
|
95
|
-
turn,
|
|
96
|
-
step,
|
|
97
|
-
message: createMessage({
|
|
98
|
-
role: "assistant",
|
|
99
|
-
content: [{
|
|
100
|
-
type: "tool-call",
|
|
101
|
-
id: callId,
|
|
102
|
-
name: NARRATE_TOOL,
|
|
103
|
-
arguments: args
|
|
104
|
-
}],
|
|
105
|
-
source: {
|
|
106
|
-
kind: "model",
|
|
107
|
-
...OPENING_SOURCE
|
|
108
|
-
}
|
|
109
|
-
})
|
|
110
|
-
}, { surfaceOp: "append" });
|
|
111
|
-
const call = session.append("tool/call", {
|
|
112
|
-
turn,
|
|
113
|
-
step,
|
|
114
|
-
callId,
|
|
115
|
-
name: NARRATE_TOOL,
|
|
116
|
-
arguments: args
|
|
117
|
-
});
|
|
118
|
-
session.append("tool/result", {
|
|
119
|
-
turn,
|
|
120
|
-
step,
|
|
121
|
-
message: createToolResultMessage({
|
|
122
|
-
callId,
|
|
123
|
-
content: [{
|
|
124
|
-
type: "text",
|
|
125
|
-
text: `The output has been delivered to the player. The turn ends here.\n${encodeOutput(output)}`
|
|
126
|
-
}],
|
|
127
|
-
isError: false
|
|
128
|
-
})
|
|
129
|
-
}, {
|
|
130
|
-
surfaceOp: "append",
|
|
131
|
-
sourceEventSeqs: [call.seq]
|
|
132
|
-
});
|
|
133
|
-
session.append("step/end", {
|
|
134
|
-
turn,
|
|
135
|
-
step
|
|
136
|
-
});
|
|
137
|
-
const ended = session.append("turn/end", {
|
|
138
|
-
turn,
|
|
139
|
-
reason: { kind: "completed" }
|
|
140
|
-
});
|
|
141
|
-
return {
|
|
142
|
-
startSeq: started.seq,
|
|
143
|
-
...asked === void 0 ? {} : { userSeq: asked },
|
|
144
|
-
endSeq: ended.seq
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
|
-
/** A turn in which nothing was said and nothing was delivered, to keep the log's turns consecutive. */
|
|
148
|
-
function appendEmptyTurn(session, turn) {
|
|
149
|
-
session.append("turn/start", { turn });
|
|
150
|
-
session.append("turn/end", {
|
|
151
|
-
turn,
|
|
152
|
-
reason: { kind: "completed" }
|
|
153
|
-
});
|
|
154
|
-
}
|
|
155
|
-
/**
|
|
156
|
-
* The log of a chat that opens with a story: a finished first turn. The player's message starts the second turn. Nothing is asked of a model.
|
|
157
|
-
*/
|
|
158
|
-
function openingEvents(segments) {
|
|
159
|
-
const session = Session.create(SessionId("opening"));
|
|
160
|
-
appendNarratedTurn(session, 1, {
|
|
161
|
-
segments: [...segments],
|
|
162
|
-
repaired: false
|
|
163
|
-
});
|
|
164
|
-
return session.snapshotEvents();
|
|
165
|
-
}
|
|
166
|
-
/** A visible first turn makes a newly created authoring chat a full conversation immediately. */
|
|
167
|
-
function authoringOpeningEvents(welcome, source = AUTHORING_OPENING_SOURCE) {
|
|
168
|
-
const session = Session.create(SessionId("authoring-opening"));
|
|
169
|
-
setApprovalPolicy(session, "ask");
|
|
170
|
-
const turn = 1;
|
|
171
|
-
const step = 1;
|
|
172
|
-
session.append("turn/start", { turn });
|
|
173
|
-
session.append("step/start", {
|
|
174
|
-
turn,
|
|
175
|
-
step
|
|
176
|
-
});
|
|
177
|
-
reservePromptHead(session, turn, step);
|
|
178
|
-
session.append("assistant/message", {
|
|
179
|
-
stream: [],
|
|
180
|
-
turn,
|
|
181
|
-
step,
|
|
182
|
-
message: createMessage({
|
|
183
|
-
role: "assistant",
|
|
184
|
-
content: [{
|
|
185
|
-
type: "text",
|
|
186
|
-
text: welcome
|
|
187
|
-
}],
|
|
188
|
-
source: {
|
|
189
|
-
kind: "model",
|
|
190
|
-
...source
|
|
191
|
-
}
|
|
192
|
-
})
|
|
193
|
-
}, { surfaceOp: "append" });
|
|
194
|
-
session.append("step/end", {
|
|
195
|
-
turn,
|
|
196
|
-
step
|
|
197
|
-
});
|
|
198
|
-
session.append("turn/end", {
|
|
199
|
-
turn,
|
|
200
|
-
reason: { kind: "completed" }
|
|
201
|
-
});
|
|
202
|
-
return session.snapshotEvents();
|
|
203
|
-
}
|
|
204
|
-
/**
|
|
205
|
-
* Store a chat that already holds its opening, before any agent exists for it.
|
|
206
|
-
* The agent loop reads its turn counter from the log when it is built, so the
|
|
207
|
-
* opening has to be in the stored log by then: the chat is then adopted by id.
|
|
208
|
-
*/
|
|
209
|
-
async function storeOpening(persistence, chat, segments, events = openingEvents(segments)) {
|
|
210
|
-
await storeInitialEvents(persistence, chat, events);
|
|
211
|
-
}
|
|
212
|
-
async function storeAuthoringOpening(persistence, chat, welcome) {
|
|
213
|
-
await storeInitialEvents(persistence, chat, authoringOpeningEvents(welcome));
|
|
214
|
-
}
|
|
215
|
-
async function storeDoctorOpening(persistence, chat, welcome) {
|
|
216
|
-
await storeInitialEvents(persistence, chat, authoringOpeningEvents(welcome, DOCTOR_OPENING_SOURCE));
|
|
217
|
-
}
|
|
218
|
-
async function storeInitialEvents(persistence, chat, events) {
|
|
219
|
-
const header = {
|
|
220
|
-
version: 4,
|
|
221
|
-
id: SessionId(chat.id),
|
|
222
|
-
createdAt: Date.now(),
|
|
223
|
-
cwd: chat.cwd,
|
|
224
|
-
isSeeded: false,
|
|
225
|
-
agentPreset: chat.agentPreset
|
|
226
|
-
};
|
|
227
|
-
const handle = await persistence.create(header);
|
|
228
|
-
try {
|
|
229
|
-
await handle.append(events);
|
|
230
|
-
await handle.flush();
|
|
231
|
-
} finally {
|
|
232
|
-
await handle.close();
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
//#endregion
|
|
236
|
-
//#region src/host/agent/agent-sessions.ts
|
|
237
|
-
/** Title of the DSH project that groups every roleplay chat. */
|
|
238
|
-
const PROJECT_TITLE = "Roleplay";
|
|
239
|
-
/** The agent preset roleplay chats run under; it is declared by the bundle. */
|
|
240
|
-
const AGENT_PRESET = "roleplay";
|
|
241
|
-
async function isStored(persistence, sessionId) {
|
|
242
|
-
return persistence?.stat !== void 0 && await persistence.stat(SessionId(sessionId)) !== void 0;
|
|
243
|
-
}
|
|
244
|
-
/**
|
|
245
|
-
* Make sure one named preset chat belongs to its project, and only name it on first creation. DSH's `create` reuses a stored chat only while
|
|
246
|
-
* it has no turn and mints another id otherwise, so a chat that exists is never created again: one that is stored (it holds an opening) is
|
|
247
|
-
* attached to the project, and only a chat that does not exist is created.
|
|
248
|
-
*/
|
|
249
|
-
async function ensureAgentChat(services, request, knownProject) {
|
|
250
|
-
const project = knownProject ?? await services.registry.create(request.projectPath, request.projectTitle);
|
|
251
|
-
const existed = project.sessionIds.includes(request.sessionId);
|
|
252
|
-
if (!existed) {
|
|
253
|
-
if (await isStored(services.persistence, request.sessionId)) await project.attachSession(request.sessionId);
|
|
254
|
-
else {
|
|
255
|
-
const { sessionId } = await services.controller.create({
|
|
256
|
-
workspaceId: project.id,
|
|
257
|
-
sessionId: request.sessionId,
|
|
258
|
-
agentPreset: request.agentPreset
|
|
259
|
-
});
|
|
260
|
-
if (sessionId !== request.sessionId) throw new Error(`DSH made the chat "${sessionId}" instead of "${request.sessionId}", so the chat cannot be found again`);
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
if (!existed || request.renameExisting === true) await services.controller.rename({
|
|
264
|
-
sessionId: request.sessionId,
|
|
265
|
-
title: request.title
|
|
266
|
-
});
|
|
267
|
-
return request.sessionId;
|
|
268
|
-
}
|
|
269
|
-
/** Looks the services up on first use: profiles without the web app do not have them. */
|
|
270
|
-
function agentServicesOf(ctx) {
|
|
271
|
-
return () => {
|
|
272
|
-
const controller = ctx.get("sessionController");
|
|
273
|
-
const registry = ctx.get("workspaceRegistry");
|
|
274
|
-
if (controller === void 0 || registry === void 0) throw new AgentUnavailableError("this DSH profile has no session services, so a roleplay chat cannot be opened");
|
|
275
|
-
const persistence = ctx.get("sessionPersistence");
|
|
276
|
-
const agents = ctx.get("agents");
|
|
277
|
-
return {
|
|
278
|
-
controller,
|
|
279
|
-
registry,
|
|
280
|
-
...persistence === void 0 ? {} : { persistence },
|
|
281
|
-
...agents === void 0 ? {} : { unload: unloader(agents) }
|
|
282
|
-
};
|
|
283
|
-
};
|
|
284
|
-
}
|
|
285
|
-
/** DSH has no call to unload an agent; disposing its scope is what its own teardown (a closed log, a released registration) hangs from. */
|
|
286
|
-
function unloader(agents) {
|
|
287
|
-
return async (chat) => {
|
|
288
|
-
const live = agents.get(chat);
|
|
289
|
-
if (live === void 0) return;
|
|
290
|
-
await (live.scope.rawDispose ?? live.scope.dispose.bind(live.scope))();
|
|
291
|
-
for (let waited = 0; agents.get(chat) !== void 0; waited += 50) {
|
|
292
|
-
if (waited >= 5e3) throw new Error(`the chat ${chat} is still loaded and cannot be replaced`);
|
|
293
|
-
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
294
|
-
}
|
|
295
|
-
};
|
|
296
|
-
}
|
|
297
|
-
/**
|
|
298
|
-
* Gives roleplay sessions a DSH chat. All chats share one project whose folder
|
|
299
|
-
* is the roleplay root, because DSH groups a session under a project only when
|
|
300
|
-
* the session's working folder is the project's folder.
|
|
301
|
-
*/
|
|
302
|
-
var AgentSessions = class {
|
|
303
|
-
services;
|
|
304
|
-
projectPath;
|
|
305
|
-
constructor(services, projectPath) {
|
|
306
|
-
this.services = services;
|
|
307
|
-
this.projectPath = projectPath;
|
|
308
|
-
}
|
|
309
|
-
/**
|
|
310
|
-
* Create the chat of a roleplay session unless it exists; returns its DSH session id.
|
|
311
|
-
* @param title - the name to give a chat that is new; one that exists keeps its own.
|
|
312
|
-
* @param opening - what a chat that is new opens with: narration and lines of its characters, shown before the player says anything.
|
|
313
|
-
* @param events - the whole log a chat that is new starts from, when it is made again from a session that was played (the opening is its first turn).
|
|
314
|
-
* @throws {AgentUnavailableError} when there is an opening and no way to store it.
|
|
315
|
-
*/
|
|
316
|
-
async ensure(sessionId, title, opening, events) {
|
|
317
|
-
const services = this.services();
|
|
318
|
-
const { registry, persistence } = services;
|
|
319
|
-
const project = await registry.create(this.projectPath(), PROJECT_TITLE);
|
|
320
|
-
const wanted = chatSessionId(sessionId);
|
|
321
|
-
const existed = project.sessionIds.includes(wanted);
|
|
322
|
-
const stored = opening !== void 0 && !existed && await isStored(persistence, wanted);
|
|
323
|
-
if (opening !== void 0 && !existed && !stored) {
|
|
324
|
-
if (persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store a chat with an opening message");
|
|
325
|
-
await services.unload?.(wanted);
|
|
326
|
-
await storeOpening(persistence, {
|
|
327
|
-
id: wanted,
|
|
328
|
-
cwd: project.path,
|
|
329
|
-
agentPreset: AGENT_PRESET
|
|
330
|
-
}, opening, events);
|
|
331
|
-
}
|
|
332
|
-
return await ensureAgentChat(services, {
|
|
333
|
-
projectPath: project.path,
|
|
334
|
-
projectTitle: PROJECT_TITLE,
|
|
335
|
-
sessionId: wanted,
|
|
336
|
-
agentPreset: AGENT_PRESET,
|
|
337
|
-
title
|
|
338
|
-
}, project);
|
|
339
|
-
}
|
|
340
|
-
/** Whether the chat of a session exists on this installation: in the project, or stored and waiting to be attached. */
|
|
341
|
-
async has(sessionId) {
|
|
342
|
-
const { registry, persistence } = this.services();
|
|
343
|
-
const project = await registry.create(this.projectPath(), PROJECT_TITLE);
|
|
344
|
-
const wanted = chatSessionId(sessionId);
|
|
345
|
-
return project.sessionIds.includes(wanted) || await isStored(persistence, wanted);
|
|
346
|
-
}
|
|
347
|
-
/**
|
|
348
|
-
* Put a log made again in the place of the chat's own, for a session whose folder came from another installation after the chat was
|
|
349
|
-
* made. The old log is deleted first, and with it the chat's title, which is given again; DSH keeps the chat in its project, so the same id is stored again and `ensure` is not needed.
|
|
350
|
-
*/
|
|
351
|
-
async replace(sessionId, title, events, purge) {
|
|
352
|
-
const { controller, registry, persistence, unload } = this.services();
|
|
353
|
-
if (persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store a chat");
|
|
354
|
-
const project = await registry.create(this.projectPath(), PROJECT_TITLE);
|
|
355
|
-
const chat = chatSessionId(sessionId);
|
|
356
|
-
await unload?.(chat);
|
|
357
|
-
await purge(chat);
|
|
358
|
-
await storeInitialEvents(persistence, {
|
|
359
|
-
id: chat,
|
|
360
|
-
cwd: project.path,
|
|
361
|
-
agentPreset: AGENT_PRESET
|
|
362
|
-
}, events);
|
|
363
|
-
await controller.rename({
|
|
364
|
-
sessionId: chat,
|
|
365
|
-
title
|
|
366
|
-
});
|
|
367
|
-
}
|
|
368
|
-
/** Says something in the chat of a session as the player would; it is queued behind what the chat is doing. The chat must exist (`ensure`). */
|
|
369
|
-
async send(sessionId, text) {
|
|
370
|
-
await this.services().controller.prompt({
|
|
371
|
-
requestId: randomUUID(),
|
|
372
|
-
sessionId: chatSessionId(sessionId),
|
|
373
|
-
mode: "queue",
|
|
374
|
-
content: [{
|
|
375
|
-
type: "text",
|
|
376
|
-
text
|
|
377
|
-
}]
|
|
378
|
-
}, new AbortController().signal);
|
|
379
|
-
}
|
|
380
|
-
/** Give the chat of a session a new title. A chat that was never created has none to change. */
|
|
381
|
-
async rename(sessionId, title) {
|
|
382
|
-
const { controller, registry } = this.services();
|
|
383
|
-
const project = await registry.create(this.projectPath(), PROJECT_TITLE);
|
|
384
|
-
const chat = chatSessionId(sessionId);
|
|
385
|
-
if (project.sessionIds.includes(chat)) await controller.rename({
|
|
386
|
-
sessionId: chat,
|
|
387
|
-
title
|
|
388
|
-
});
|
|
389
|
-
}
|
|
390
|
-
/** Put the chat away: hidden and stopped, and kept; a chat that was never created is nothing to put away. */
|
|
391
|
-
async archive(sessionId) {
|
|
392
|
-
await this.retire(sessionId);
|
|
393
|
-
}
|
|
394
|
-
/** Show a chat that was put away again. A chat that does not exist (it is made when the session is opened) is nothing to bring back. */
|
|
395
|
-
async restore(sessionId) {
|
|
396
|
-
try {
|
|
397
|
-
await this.services().registry.unarchiveSession(chatSessionId(sessionId));
|
|
398
|
-
} catch (error) {
|
|
399
|
-
if (!(error instanceof Error && error.name === "WorkspaceUnknownSessionError")) throw error;
|
|
400
|
-
}
|
|
401
|
-
}
|
|
402
|
-
/** Hide the chat and stop its work; a chat that was never created is nothing to retire. */
|
|
403
|
-
async retire(sessionId) {
|
|
404
|
-
try {
|
|
405
|
-
await this.services().registry.archiveSession(chatSessionId(sessionId), { stopActivity: true });
|
|
406
|
-
} catch (error) {
|
|
407
|
-
if (!(error instanceof Error && error.name === "WorkspaceUnknownSessionError")) throw error;
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
};
|
|
411
|
-
//#endregion
|
|
412
33
|
//#region src/host/worlds/authoring-language.ts
|
|
413
34
|
/**
|
|
414
35
|
* The language the person was using when they last worked on a world with the authoring assistant. The assistant's instructions
|
|
@@ -456,64 +77,16 @@ var RoleplayImport = class extends Service {
|
|
|
456
77
|
}
|
|
457
78
|
};
|
|
458
79
|
//#endregion
|
|
459
|
-
//#region src/host/
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
var AuthoringSessions = class {
|
|
468
|
-
services;
|
|
469
|
-
roleplayRoot;
|
|
470
|
-
prompts;
|
|
471
|
-
languages;
|
|
472
|
-
constructor(services, roleplayRoot, prompts, languages) {
|
|
473
|
-
this.services = services;
|
|
474
|
-
this.roleplayRoot = roleplayRoot;
|
|
475
|
-
this.prompts = prompts;
|
|
476
|
-
this.languages = languages;
|
|
477
|
-
}
|
|
478
|
-
async ensure(worldId, worldName, title, language) {
|
|
479
|
-
const chatTitle = title ?? authoringTitle(worldName, language);
|
|
480
|
-
this.languages.set(worldId, language);
|
|
481
|
-
const services = this.services();
|
|
482
|
-
const projectPath = join(this.roleplayRoot(), "worlds");
|
|
483
|
-
const project = await services.registry.create(projectPath, AUTHORING_PROJECT_TITLE);
|
|
484
|
-
const sessionId = authoringChatSessionId(worldId);
|
|
485
|
-
const existed = project.sessionIds.includes(sessionId);
|
|
486
|
-
const stored = !existed && await isStored(services.persistence, sessionId);
|
|
487
|
-
if (!existed && !stored) {
|
|
488
|
-
if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of an authoring chat");
|
|
489
|
-
await storeAuthoringOpening(services.persistence, {
|
|
490
|
-
id: sessionId,
|
|
491
|
-
cwd: project.path,
|
|
492
|
-
agentPreset: AUTHORING_AGENT_PRESET
|
|
493
|
-
}, this.prompts.text("world/welcome", this.languages.get(worldId), { world: worldName }));
|
|
494
|
-
}
|
|
495
|
-
return await ensureAgentChat(services, {
|
|
496
|
-
projectPath,
|
|
497
|
-
projectTitle: AUTHORING_PROJECT_TITLE,
|
|
498
|
-
sessionId,
|
|
499
|
-
agentPreset: AUTHORING_AGENT_PRESET,
|
|
500
|
-
title: chatTitle,
|
|
501
|
-
renameExisting: true
|
|
502
|
-
}, project);
|
|
503
|
-
}
|
|
504
|
-
/** Sends a message into a chat as if the person had written it. */
|
|
505
|
-
async send(sessionId, text) {
|
|
506
|
-
await this.services().controller.prompt({
|
|
507
|
-
requestId: randomUUID(),
|
|
508
|
-
sessionId,
|
|
509
|
-
mode: "queue",
|
|
510
|
-
content: [{
|
|
511
|
-
type: "text",
|
|
512
|
-
text
|
|
513
|
-
}]
|
|
514
|
-
}, new AbortController().signal);
|
|
80
|
+
//#region src/host/worlds/draft.ts
|
|
81
|
+
/** Whether the world is an import that was written but would not start yet: its import state (kept in the world's `.import` folder) says it is being repaired. */
|
|
82
|
+
async function isDraftWorld(directory) {
|
|
83
|
+
try {
|
|
84
|
+
return JSON.parse(await readFile(join(directory, ".import", "state.json"), "utf8")).phase === "repair";
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (error.code === "ENOENT") return false;
|
|
87
|
+
throw error;
|
|
515
88
|
}
|
|
516
|
-
}
|
|
89
|
+
}
|
|
517
90
|
//#endregion
|
|
518
91
|
//#region src/host/worlds/create-world.ts
|
|
519
92
|
const FOLDER = /^[\p{L}\p{N}][\p{L}\p{N}._ -]{0,99}$/u;
|
|
@@ -573,6 +146,30 @@ function importMessage(language) {
|
|
|
573
146
|
return `${IMPORT_COMMAND} ${IMPORT_FOLDER}/card.json ${tr("Import this card into this newly created world.")}`;
|
|
574
147
|
}
|
|
575
148
|
/**
|
|
149
|
+
* Has the chat of a world whose import stopped before it was done carry on from the step it reached (the import hooks tell the chat which step that is). An import is lost
|
|
150
|
+
* to a server restart, a refused finish or a chat that ended early; the card and what was extracted stay in the world's import folder.
|
|
151
|
+
* @throws {WorldNotFoundError} when the world is gone. @throws {InvalidEditProblems} when no import is waiting in it.
|
|
152
|
+
*/
|
|
153
|
+
async function resumeImport(deps, worldId, language) {
|
|
154
|
+
const record = await deps.worlds.find(worldId);
|
|
155
|
+
if (record === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
|
|
156
|
+
const phase = await importPhase(record.directory);
|
|
157
|
+
if (phase === void 0 || phase === "done") throw new InvalidEditProblems(["no import is waiting in this world"]);
|
|
158
|
+
const chatSessionId = await deps.authoring.ensure(record.summary.id, record.summary.name, authoringTitle(record.summary.name, language), language);
|
|
159
|
+
let failure;
|
|
160
|
+
try {
|
|
161
|
+
await deps.authoring.send(chatSessionId, importMessage(language));
|
|
162
|
+
} catch (error) {
|
|
163
|
+
failure = error instanceof Error ? error.message : String(error);
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
worldId: record.summary.id,
|
|
167
|
+
chatSessionId,
|
|
168
|
+
started: failure === void 0,
|
|
169
|
+
...failure === void 0 ? {} : { failure }
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
576
173
|
* Turns an uploaded card into a new empty world with its authoring chat, and has the chat start importing it on the person's behalf.
|
|
577
174
|
* @throws {InvalidEditProblems} when the choices cannot be used. @throws {ImportNotFoundError} when the upload is gone.
|
|
578
175
|
*/
|
|
@@ -610,6 +207,56 @@ async function startImport(deps, id, choices, language) {
|
|
|
610
207
|
};
|
|
611
208
|
}
|
|
612
209
|
//#endregion
|
|
210
|
+
//#region src/host/import/draft.ts
|
|
211
|
+
async function draftOf(worlds, worldId) {
|
|
212
|
+
const record = await worlds.find(worldId);
|
|
213
|
+
if (record === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
|
|
214
|
+
return record;
|
|
215
|
+
}
|
|
216
|
+
async function draftStatus(worlds, worldId) {
|
|
217
|
+
const record = await draftOf(worlds, worldId);
|
|
218
|
+
if (!await isDraftWorld(record.directory)) return { draft: false };
|
|
219
|
+
if (await settleDraft(record.directory)) {
|
|
220
|
+
await worlds.list({ refresh: true });
|
|
221
|
+
return { draft: false };
|
|
222
|
+
}
|
|
223
|
+
return {
|
|
224
|
+
draft: true,
|
|
225
|
+
check: await checkWorld({
|
|
226
|
+
directory: record.directory,
|
|
227
|
+
summary: record.summary,
|
|
228
|
+
...record.variables === void 0 ? {} : { variables: record.variables }
|
|
229
|
+
})
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* What the person decides about a draft: have the assistant try again (with the card at hand), keep it as it is (an ordinary world that cannot be played until it is mended),
|
|
234
|
+
* or discard it (the folder goes to the root's trash, where it can still be found).
|
|
235
|
+
* @throws {InvalidEditProblems} when the world is not a draft.
|
|
236
|
+
*/
|
|
237
|
+
async function actOnDraft(deps, worldId, action, language) {
|
|
238
|
+
const record = await draftOf(deps.worlds, worldId);
|
|
239
|
+
if (!await isDraftWorld(record.directory)) throw new InvalidEditProblems(["this world is not a draft"]);
|
|
240
|
+
if (action === "ask") return {
|
|
241
|
+
action,
|
|
242
|
+
started: await resumeImport(deps, worldId, language)
|
|
243
|
+
};
|
|
244
|
+
if (action === "keep") {
|
|
245
|
+
await keepDraft(record.directory);
|
|
246
|
+
await deps.worlds.list({ refresh: true });
|
|
247
|
+
return { action };
|
|
248
|
+
}
|
|
249
|
+
const trash = join(deps.root(), ".trash", "worlds");
|
|
250
|
+
await mkdir(trash, { recursive: true });
|
|
251
|
+
const destination = join(trash, `${basename(record.directory)}-${Date.now()}`);
|
|
252
|
+
await rename(record.directory, destination);
|
|
253
|
+
await deps.worlds.list({ refresh: true });
|
|
254
|
+
return {
|
|
255
|
+
action,
|
|
256
|
+
keptIn: relative(deps.root(), destination)
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
//#endregion
|
|
613
260
|
//#region src/host/translate/service.ts
|
|
614
261
|
async function recordOf(worlds, id) {
|
|
615
262
|
const record = await worlds.find(id);
|
|
@@ -1246,642 +893,493 @@ var RoleplayOrchestration = class extends Service {
|
|
|
1246
893
|
}
|
|
1247
894
|
};
|
|
1248
895
|
//#endregion
|
|
1249
|
-
//#region src/
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
"
|
|
1253
|
-
"
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
/**
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
896
|
+
//#region src/host/http/respond.ts
|
|
897
|
+
function sendJson(res, status, payload) {
|
|
898
|
+
res.statusCode = status;
|
|
899
|
+
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
900
|
+
res.setHeader("cache-control", "no-store");
|
|
901
|
+
res.end(JSON.stringify(payload));
|
|
902
|
+
}
|
|
903
|
+
function sendError(res, status, message) {
|
|
904
|
+
sendJson(res, status, { message });
|
|
905
|
+
}
|
|
906
|
+
/** A failure with the status the client should see. */
|
|
907
|
+
var HttpError = class extends Error {
|
|
908
|
+
status;
|
|
909
|
+
constructor(status, message) {
|
|
910
|
+
super(message);
|
|
911
|
+
this.status = status;
|
|
912
|
+
}
|
|
913
|
+
};
|
|
914
|
+
//#endregion
|
|
915
|
+
//#region src/host/presets/service.ts
|
|
916
|
+
/** The story's prompts cannot change right now. */
|
|
917
|
+
var PresetBusyError = class extends Error {};
|
|
918
|
+
/** The preset library and the presets of stories. Refusals are plain `Error`s with the reason; unknown stories and worlds are not-found errors. */
|
|
919
|
+
var Presets = class {
|
|
920
|
+
deps;
|
|
921
|
+
constructor(deps) {
|
|
922
|
+
this.deps = deps;
|
|
923
|
+
}
|
|
924
|
+
get maxUploadBytes() {
|
|
925
|
+
return this.deps.maxUploadBytes;
|
|
926
|
+
}
|
|
927
|
+
list() {
|
|
928
|
+
return listPresets(this.deps.root()).map((entry) => entry.summary);
|
|
929
|
+
}
|
|
930
|
+
/** A preset with the text of each prompt it carries, keyed `<language>/<id>`. */
|
|
931
|
+
read(name) {
|
|
932
|
+
const loaded = loadPreset(this.deps.root(), name);
|
|
933
|
+
return {
|
|
934
|
+
summary: loaded.summary,
|
|
935
|
+
prompts: Object.fromEntries([...loaded.files].map(([path, text]) => [path.slice(0, -3), text]))
|
|
1281
936
|
};
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
}
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
937
|
+
}
|
|
938
|
+
async saveFromWorld(request) {
|
|
939
|
+
const directory = await this.deps.worldDirectory(request.fromWorld);
|
|
940
|
+
if (directory === void 0) throw new WorldNotFoundError(`there is no world with id "${request.fromWorld}"`);
|
|
941
|
+
return (await savePresetFromWorld(this.deps.root(), directory, request)).summary;
|
|
942
|
+
}
|
|
943
|
+
/** Makes a preset from a world's own prose prompts, or from the shipped ones as a starting point when no world is given. */
|
|
944
|
+
async create(request) {
|
|
945
|
+
if (request.fromWorld !== void 0) return await this.saveFromWorld({
|
|
946
|
+
...request,
|
|
947
|
+
fromWorld: request.fromWorld
|
|
948
|
+
});
|
|
949
|
+
return (await createPresetFromShipped(this.deps.root(), request)).summary;
|
|
950
|
+
}
|
|
951
|
+
async updateInfo(name, change) {
|
|
952
|
+
return (await updatePresetInfo(this.deps.root(), name, change)).summary;
|
|
953
|
+
}
|
|
954
|
+
/** Writes the person's own text of a prompt; `undefined` takes the preset's version out. */
|
|
955
|
+
async writePrompt(name, language, id, text) {
|
|
956
|
+
const directory = this.existing(name);
|
|
957
|
+
if (!id.startsWith("roleplay/")) throw new Error(`"${id}" is not a prompt of the story`);
|
|
958
|
+
if (text === void 0) await deleteWorldPrompt(directory, language, id);
|
|
959
|
+
else await writeWorldPrompt(directory, language, id, text);
|
|
960
|
+
return loadPreset(this.deps.root(), name).summary;
|
|
961
|
+
}
|
|
962
|
+
/** The prompts holding the rules of the game that the preset does not carry yet, which it may take over from the shipped ones. */
|
|
963
|
+
rulesPrompts(name, language) {
|
|
964
|
+
return listWorldPrompts(this.existing(name), language).filter((entry) => entry.kind === "rules" && !entry.carried).map((entry) => entry.id);
|
|
965
|
+
}
|
|
966
|
+
/** The text of a prompt as a story with this preset gets it: the preset's own, else the shipped one. */
|
|
967
|
+
promptText(name, language, id) {
|
|
968
|
+
return readWorldPrompt(this.existing(name), language, id).text;
|
|
969
|
+
}
|
|
970
|
+
existing(name) {
|
|
971
|
+
const directory = presetDirectory(this.deps.root(), name);
|
|
972
|
+
if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
|
|
973
|
+
return directory;
|
|
974
|
+
}
|
|
975
|
+
/** Like `importFile`, under a name made from the title that is not yet taken. */
|
|
976
|
+
async importTitled(title, file, language) {
|
|
977
|
+
return await this.importFile(this.freeName(title), file, language, title.trim() === "" ? void 0 : title.trim().slice(0, 300));
|
|
978
|
+
}
|
|
979
|
+
freeName(title) {
|
|
980
|
+
const base = trimCharacters(title.normalize("NFKD").replace(/[^A-Za-z0-9_-]+/g, "-"), "-_").slice(0, 56) || "preset";
|
|
981
|
+
const taken = new Set(listPresets(this.deps.root()).map((entry) => entry.summary.name));
|
|
982
|
+
let name = base;
|
|
983
|
+
for (let index = 2; taken.has(name); index += 1) name = `${base}-${index}`;
|
|
984
|
+
return name;
|
|
985
|
+
}
|
|
986
|
+
/**
|
|
987
|
+
* Imports the chosen prompts of a staged preset as they are, with no assistant: a new library preset is made and holds them as its narration style in every language the program ships, and nothing else happens.
|
|
988
|
+
* @throws {ImportNotFoundError} when the file is no longer staged. @throws {ImportCardError} when the choice cannot be used.
|
|
989
|
+
*/
|
|
990
|
+
async importVerbatim(request) {
|
|
991
|
+
const { file, name: fileName } = this.deps.staging.choose("preset", request);
|
|
992
|
+
const made = verbatimStyle(file, fileName);
|
|
993
|
+
const title = request.title ?? made.name;
|
|
994
|
+
const name = request.name ?? this.freeName(title);
|
|
995
|
+
if (!isPresetName(name)) throw new Error(`"${name}" is not a usable preset name (letters, digits, "-" and "_", up to 64)`);
|
|
996
|
+
const root = this.deps.root();
|
|
997
|
+
const directory = await reservePreset(root, name, title, made.sampling);
|
|
998
|
+
try {
|
|
999
|
+
for (const language of shippedLanguages()) await writeWorldPrompt(directory, language, "roleplay/style", made.text);
|
|
1000
|
+
} catch (error) {
|
|
1001
|
+
await deletePreset(root, name);
|
|
1002
|
+
throw error;
|
|
1003
|
+
}
|
|
1004
|
+
this.deps.staging.discard(request.id);
|
|
1005
|
+
return { name };
|
|
1006
|
+
}
|
|
1007
|
+
/** Opens the authoring chat of a preset. */
|
|
1008
|
+
async author(name, language) {
|
|
1009
|
+
const loaded = loadPreset(this.deps.root(), name);
|
|
1010
|
+
return { chatSessionId: await this.deps.authoring.ensure(name, loaded.summary.title, language) };
|
|
1011
|
+
}
|
|
1012
|
+
/** Keeps an uploaded SillyTavern preset in a new library preset and has its authoring chat turn it into prompts. @throws {ImportCardError} when the file is not a preset. */
|
|
1013
|
+
async importFile(name, file, language, title) {
|
|
1014
|
+
const uploaded = readPreset(file, name);
|
|
1015
|
+
const root = this.deps.root();
|
|
1016
|
+
const directory = await reservePreset(root, name, title ?? uploaded.name, uploaded.sampling);
|
|
1017
|
+
try {
|
|
1018
|
+
await mkdir(join(directory, IMPORT_FOLDER), { recursive: true });
|
|
1019
|
+
await writeFile(join(directory, IMPORT_FOLDER, PRESET_FILE), file);
|
|
1020
|
+
} catch (error) {
|
|
1021
|
+
await deletePreset(root, name);
|
|
1022
|
+
throw error;
|
|
1023
|
+
}
|
|
1024
|
+
const chatSessionId = await this.deps.authoring.ensure(name, title ?? uploaded.name, language);
|
|
1025
|
+
let failure;
|
|
1026
|
+
try {
|
|
1027
|
+
await this.deps.authoring.send(chatSessionId, this.deps.importMessage(language));
|
|
1028
|
+
} catch (problem) {
|
|
1029
|
+
failure = problem instanceof Error ? problem.message : String(problem);
|
|
1030
|
+
}
|
|
1301
1031
|
return {
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
...entry["reading"] === void 0 ? {} : { reading: entry["reading"] },
|
|
1307
|
-
...typeof hit === "number" ? { hit } : {},
|
|
1308
|
-
...entry["compare"] === void 0 ? {} : { compare: entry["compare"] },
|
|
1309
|
-
...text(entry["modifier"]) === "" ? {} : { modifier: text(entry["modifier"]) },
|
|
1310
|
-
bands: (bands ?? []).map((band, bandIndex) => {
|
|
1311
|
-
const where = `${at}.bands[${bandIndex}]`;
|
|
1312
|
-
if (!isObject$1(band)) {
|
|
1313
|
-
problems.push(`${where} must be an object`);
|
|
1314
|
-
return {
|
|
1315
|
-
label: "",
|
|
1316
|
-
result: "failed"
|
|
1317
|
-
};
|
|
1318
|
-
}
|
|
1319
|
-
for (const key of Object.keys(band)) if (!BAND_FIELDS.includes(key)) problems.push(`${where}.${key} is not a field of a band`);
|
|
1320
|
-
for (const key of ["min", "max"]) if (band[key] !== void 0 && (typeof band[key] !== "number" || !Number.isFinite(band[key]))) problems.push(`${where}.${key} must be a number`);
|
|
1321
|
-
if (typeof band["label"] !== "string") problems.push(`${where}.label must be text`);
|
|
1322
|
-
if (!DICE_RESULTS.includes(band["result"])) problems.push(`${where}.result must be one of: ${DICE_RESULTS.join(", ")}`);
|
|
1323
|
-
const min = band["min"];
|
|
1324
|
-
const max = band["max"];
|
|
1325
|
-
return {
|
|
1326
|
-
label: text(band["label"]),
|
|
1327
|
-
result: band["result"],
|
|
1328
|
-
...typeof min === "number" ? { min } : {},
|
|
1329
|
-
...typeof max === "number" ? { max } : {},
|
|
1330
|
-
...band["critical"] === true ? { critical: true } : {}
|
|
1331
|
-
};
|
|
1332
|
-
})
|
|
1032
|
+
name,
|
|
1033
|
+
chatSessionId,
|
|
1034
|
+
started: failure === void 0,
|
|
1035
|
+
...failure === void 0 ? {} : { failure }
|
|
1333
1036
|
};
|
|
1334
|
-
}
|
|
1335
|
-
|
|
1336
|
-
|
|
1037
|
+
}
|
|
1038
|
+
/** Imports a staged preset with only the prompts the person chose; a name is the library name they gave it, else one is made from the title. @throws {ImportNotFoundError} when the file is no longer staged. */
|
|
1039
|
+
async importStaged(request) {
|
|
1040
|
+
const { file, name: fileName } = this.deps.staging.choose("preset", request);
|
|
1041
|
+
const opened = request.name === void 0 ? await this.importTitled(request.title ?? readPreset(file, fileName).name, file, request.language) : await this.importFile(request.name, file, request.language, request.title);
|
|
1042
|
+
this.deps.staging.discard(request.id);
|
|
1043
|
+
return opened;
|
|
1044
|
+
}
|
|
1045
|
+
async remove(name) {
|
|
1046
|
+
await deletePreset(this.deps.root(), name);
|
|
1047
|
+
}
|
|
1048
|
+
status(session) {
|
|
1049
|
+
return presetStatus(this.deps.root(), this.folder(session));
|
|
1050
|
+
}
|
|
1051
|
+
/** Puts the named preset into a story, or takes the story's preset out when no name is given. */
|
|
1052
|
+
apply(session, name) {
|
|
1053
|
+
const folder = this.folder(session);
|
|
1054
|
+
if (this.deps.playing(session)) throw new PresetBusyError("a turn is being played; change the preset when it is over");
|
|
1055
|
+
return { files: switchPreset(this.deps.root(), folder, name) };
|
|
1056
|
+
}
|
|
1057
|
+
folder(id) {
|
|
1058
|
+
const sessions = `${this.deps.root()}/sessions`;
|
|
1059
|
+
if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
|
|
1060
|
+
return sessionFolder(sessions, id);
|
|
1061
|
+
}
|
|
1062
|
+
};
|
|
1063
|
+
//#endregion
|
|
1064
|
+
//#region src/host/http/body.ts
|
|
1065
|
+
/** Request bodies here are small JSON objects; anything larger is not one. */
|
|
1066
|
+
const MAX_BODY_BYTES = 16384;
|
|
1067
|
+
/** Read a request body that must be a JSON object. */
|
|
1068
|
+
async function readJsonBody(req) {
|
|
1069
|
+
if (String(req.headers["content-type"] ?? "").split(";", 1)[0]?.trim().toLowerCase() !== "application/json") throw new HttpError(415, "content-type must be application/json");
|
|
1070
|
+
const chunks = [];
|
|
1071
|
+
let size = 0;
|
|
1072
|
+
for await (const chunk of req) {
|
|
1073
|
+
size += chunk.length;
|
|
1074
|
+
if (size > MAX_BODY_BYTES) throw new HttpError(413, "request body is too large");
|
|
1075
|
+
chunks.push(chunk);
|
|
1076
|
+
}
|
|
1077
|
+
let body;
|
|
1078
|
+
try {
|
|
1079
|
+
body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
1080
|
+
} catch {
|
|
1081
|
+
throw new HttpError(400, "request body is not valid JSON");
|
|
1082
|
+
}
|
|
1083
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) throw new HttpError(400, "request body must be a JSON object");
|
|
1084
|
+
return body;
|
|
1085
|
+
}
|
|
1086
|
+
/** Reads a request body of any kind up to `limit` bytes; a larger one is refused as soon as it is known to be, without being read. */
|
|
1087
|
+
async function readBinaryBody(req, limit) {
|
|
1088
|
+
const declared = Number(req.headers["content-length"]);
|
|
1089
|
+
if (Number.isFinite(declared) && declared > limit) throw new HttpError(413, `the upload is larger than ${Math.round(limit / 1024 / 1024)} MB`);
|
|
1090
|
+
const chunks = [];
|
|
1091
|
+
let size = 0;
|
|
1092
|
+
for await (const chunk of req) {
|
|
1093
|
+
size += chunk.length;
|
|
1094
|
+
if (size > limit) throw new HttpError(413, `the upload is larger than ${Math.round(limit / 1024 / 1024)} MB`);
|
|
1095
|
+
chunks.push(chunk);
|
|
1096
|
+
}
|
|
1097
|
+
if (size === 0) throw new HttpError(400, "the upload is empty");
|
|
1098
|
+
return Buffer.concat(chunks);
|
|
1337
1099
|
}
|
|
1338
1100
|
//#endregion
|
|
1339
|
-
//#region src/
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
"position",
|
|
1350
|
-
"interruptible"
|
|
1351
|
-
];
|
|
1352
|
-
/**
|
|
1353
|
-
* The windows of a day as the browser sends them.
|
|
1354
|
-
* @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the times and places are acceptable is checked when the file is read back.
|
|
1355
|
-
*/
|
|
1356
|
-
function parseRoutineEdit(value) {
|
|
1101
|
+
//#region src/host/presets/routes.ts
|
|
1102
|
+
/** Not found is 404 and a request the library refuses is 422 with its reason; anything else is a fault. */
|
|
1103
|
+
function failure$2(res, error) {
|
|
1104
|
+
if (error instanceof ImportNotFoundError) return sendError(res, 404, error.message);
|
|
1105
|
+
if (error instanceof SessionNotFoundError || error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
1106
|
+
if (error instanceof PresetBusyError) return sendError(res, 409, error.message);
|
|
1107
|
+
if (error instanceof Error) return sendError(res, 422, error.message);
|
|
1108
|
+
throw error;
|
|
1109
|
+
}
|
|
1110
|
+
function samplingOf(value) {
|
|
1357
1111
|
const problems = [];
|
|
1358
|
-
const
|
|
1359
|
-
|
|
1360
|
-
const windows = list.map((entry, index) => {
|
|
1361
|
-
const at = `windows[${index}]`;
|
|
1362
|
-
if (!isObject(entry)) {
|
|
1363
|
-
problems.push(`${at} must be an object`);
|
|
1364
|
-
return {
|
|
1365
|
-
days: [],
|
|
1366
|
-
from: "",
|
|
1367
|
-
to: "",
|
|
1368
|
-
activity: "",
|
|
1369
|
-
interruptible: true
|
|
1370
|
-
};
|
|
1371
|
-
}
|
|
1372
|
-
for (const key of Object.keys(entry)) if (!ROUTINE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a window`);
|
|
1373
|
-
for (const key of [
|
|
1374
|
-
"from",
|
|
1375
|
-
"to",
|
|
1376
|
-
"activity"
|
|
1377
|
-
]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
1378
|
-
for (const key of [
|
|
1379
|
-
"location",
|
|
1380
|
-
"feature",
|
|
1381
|
-
"position"
|
|
1382
|
-
]) if (entry[key] !== void 0 && typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
1383
|
-
if (entry["days"] !== void 0 && !(Array.isArray(entry["days"]) && entry["days"].every((day) => typeof day === "string"))) problems.push(`${at}.days must be a list of days`);
|
|
1384
|
-
if (entry["interruptible"] !== void 0 && typeof entry["interruptible"] !== "boolean") problems.push(`${at}.interruptible must be true or false`);
|
|
1385
|
-
const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
|
|
1386
|
-
return {
|
|
1387
|
-
days: Array.isArray(entry["days"]) ? entry["days"].map((day) => day.trim().toLowerCase()).filter((day) => day !== "") : [],
|
|
1388
|
-
...Array.isArray(entry["on"]) && entry["on"].length > 0 ? { on: entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") } : {},
|
|
1389
|
-
from: text("from"),
|
|
1390
|
-
to: text("to"),
|
|
1391
|
-
activity: text("activity"),
|
|
1392
|
-
...text("location") === "" ? {} : { location: text("location") },
|
|
1393
|
-
...text("feature") === "" ? {} : { feature: text("feature") },
|
|
1394
|
-
...text("position") === "" ? {} : { position: text("position") },
|
|
1395
|
-
interruptible: entry["interruptible"] !== false
|
|
1396
|
-
};
|
|
1397
|
-
});
|
|
1398
|
-
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
1399
|
-
return windows;
|
|
1112
|
+
const sampling = parseSampling(value, "sampling", problems);
|
|
1113
|
+
return problems.length === 0 ? sampling : problems.join("; ");
|
|
1400
1114
|
}
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
problems.push(`${at} must be an object`);
|
|
1430
|
-
return [];
|
|
1431
|
-
}
|
|
1432
|
-
for (const key of Object.keys(entry)) if (!VARIABLE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a variable`);
|
|
1433
|
-
const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
|
|
1434
|
-
const number = (key) => {
|
|
1435
|
-
if (entry[key] === void 0 || entry[key] === null || entry[key] === "") return void 0;
|
|
1436
|
-
if (typeof entry[key] !== "number" || !Number.isFinite(entry[key])) {
|
|
1437
|
-
problems.push(`${at}.${key} must be a number`);
|
|
1438
|
-
return;
|
|
1115
|
+
function presetRoutes(api) {
|
|
1116
|
+
return {
|
|
1117
|
+
"/presets": {
|
|
1118
|
+
GET: async (_req, res) => {
|
|
1119
|
+
try {
|
|
1120
|
+
sendJson(res, 200, api.list());
|
|
1121
|
+
} catch (error) {
|
|
1122
|
+
failure$2(res, error);
|
|
1123
|
+
}
|
|
1124
|
+
},
|
|
1125
|
+
POST: async (req, res) => {
|
|
1126
|
+
const { name, title, description, sampling, fromWorld } = await readJsonBody(req);
|
|
1127
|
+
if (typeof name !== "string" || name === "") return sendError(res, 400, "\"name\" is required");
|
|
1128
|
+
if (fromWorld !== void 0 && (typeof fromWorld !== "string" || fromWorld === "")) return sendError(res, 400, "\"fromWorld\" must be a world id, or left out to start from the shipped prompts");
|
|
1129
|
+
if (title !== void 0 && typeof title !== "string" || description !== void 0 && typeof description !== "string") return sendError(res, 400, "\"title\" and \"description\" must be text");
|
|
1130
|
+
const given = samplingOf(sampling);
|
|
1131
|
+
if (typeof given === "string") return sendError(res, 400, given);
|
|
1132
|
+
try {
|
|
1133
|
+
sendJson(res, 201, await api.create({
|
|
1134
|
+
name,
|
|
1135
|
+
...fromWorld === void 0 ? {} : { fromWorld },
|
|
1136
|
+
...title === void 0 ? {} : { title },
|
|
1137
|
+
...description === void 0 ? {} : { description },
|
|
1138
|
+
sampling: given
|
|
1139
|
+
}));
|
|
1140
|
+
} catch (error) {
|
|
1141
|
+
failure$2(res, error);
|
|
1142
|
+
}
|
|
1439
1143
|
}
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1144
|
+
},
|
|
1145
|
+
"/presets/item": {
|
|
1146
|
+
GET: async (_req, res, url) => {
|
|
1147
|
+
try {
|
|
1148
|
+
sendJson(res, 200, api.read(url.searchParams.get("name") ?? ""));
|
|
1149
|
+
} catch (error) {
|
|
1150
|
+
failure$2(res, error);
|
|
1151
|
+
}
|
|
1152
|
+
},
|
|
1153
|
+
PUT: async (req, res, url) => {
|
|
1154
|
+
const { title, description, sampling } = await readJsonBody(req);
|
|
1155
|
+
if (title !== void 0 && typeof title !== "string" || description !== void 0 && typeof description !== "string") return sendError(res, 400, "\"title\" and \"description\" must be text");
|
|
1156
|
+
const given = sampling === void 0 ? void 0 : samplingOf(sampling);
|
|
1157
|
+
if (typeof given === "string") return sendError(res, 400, given);
|
|
1158
|
+
try {
|
|
1159
|
+
sendJson(res, 200, await api.updateInfo(url.searchParams.get("name") ?? "", {
|
|
1160
|
+
...title === void 0 ? {} : { title },
|
|
1161
|
+
...description === void 0 ? {} : { description },
|
|
1162
|
+
...given === void 0 ? {} : { sampling: given }
|
|
1163
|
+
}));
|
|
1164
|
+
} catch (error) {
|
|
1165
|
+
failure$2(res, error);
|
|
1166
|
+
}
|
|
1167
|
+
},
|
|
1168
|
+
DELETE: async (_req, res, url) => {
|
|
1169
|
+
try {
|
|
1170
|
+
await api.remove(url.searchParams.get("name") ?? "");
|
|
1171
|
+
res.statusCode = 204;
|
|
1172
|
+
res.end();
|
|
1173
|
+
} catch (error) {
|
|
1174
|
+
failure$2(res, error);
|
|
1175
|
+
}
|
|
1447
1176
|
}
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
return [];
|
|
1177
|
+
},
|
|
1178
|
+
"/presets/prompts": { GET: async (_req, res, url) => {
|
|
1179
|
+
try {
|
|
1180
|
+
sendJson(res, 200, api.rulesPrompts(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? "")));
|
|
1181
|
+
} catch (error) {
|
|
1182
|
+
failure$2(res, error);
|
|
1455
1183
|
}
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
};
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
}
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
if (typeof document.id !== "string" || typeof document.name !== "string") throw new Error(`the starter world "${entry.name}" has no id or name`);
|
|
1556
|
-
found.push({
|
|
1557
|
-
folder: entry.name,
|
|
1558
|
-
id: document.id,
|
|
1559
|
-
name: document.name,
|
|
1560
|
-
description: typeof document.description === "string" ? document.description : "",
|
|
1561
|
-
tags: Array.isArray(document.metadata?.tags) ? document.metadata.tags.filter((tag) => typeof tag === "string") : []
|
|
1562
|
-
});
|
|
1563
|
-
}
|
|
1564
|
-
return found.sort((a, b) => a.folder.localeCompare(b.folder));
|
|
1565
|
-
}
|
|
1566
|
-
/** The worlds the package ships, each with whether the person's worlds have it already. */
|
|
1567
|
-
async function listStarterWorlds(catalog, directory = starterDirectory()) {
|
|
1568
|
-
const known = await catalog.list();
|
|
1569
|
-
return (await shipped(directory)).map(({ id, ...world }) => ({
|
|
1570
|
-
...world,
|
|
1571
|
-
installed: known.worlds.some((existing) => existing.id === id) || existsSync(join(catalog.directory, world.folder))
|
|
1572
|
-
}));
|
|
1573
|
-
}
|
|
1574
|
-
/**
|
|
1575
|
-
* Copies a shipped world into the person's worlds, as a world of their own to play and edit, and makes the catalogue see it. Nothing is overwritten.
|
|
1576
|
-
* @throws {UnknownStarterError} when the package ships no such world.
|
|
1577
|
-
* @throws {WorldFolderExistsError} when the person already has that folder or a world with the same id.
|
|
1578
|
-
*/
|
|
1579
|
-
async function addStarterWorld(catalog, folder, directory = starterDirectory()) {
|
|
1580
|
-
const world = (await shipped(directory)).find((candidate) => candidate.folder === folder);
|
|
1581
|
-
if (world === void 0) throw new UnknownStarterError(`there is no starter world "${folder}"`);
|
|
1582
|
-
if ((await catalog.list({ refresh: true })).worlds.some((existing) => existing.id === world.id)) throw new WorldFolderExistsError(`you already have "${world.name}"`);
|
|
1583
|
-
const target = join(catalog.directory, world.folder);
|
|
1584
|
-
if (existsSync(target)) throw new WorldFolderExistsError(`a world folder named "${world.folder}" already exists`);
|
|
1585
|
-
await mkdir(catalog.directory, { recursive: true });
|
|
1586
|
-
try {
|
|
1587
|
-
await cp(join(directory, world.folder), target, {
|
|
1588
|
-
recursive: true,
|
|
1589
|
-
errorOnExist: true,
|
|
1590
|
-
force: false
|
|
1591
|
-
});
|
|
1592
|
-
} catch (error) {
|
|
1593
|
-
await rm(target, {
|
|
1594
|
-
recursive: true,
|
|
1595
|
-
force: true
|
|
1596
|
-
});
|
|
1597
|
-
throw error;
|
|
1598
|
-
}
|
|
1599
|
-
const added = (await catalog.list({ refresh: true })).worlds.find((candidate) => candidate.id === world.id);
|
|
1600
|
-
if (added === void 0) throw new Error(`added "${world.name}" but it was not found when the catalogue refreshed`);
|
|
1601
|
-
return added;
|
|
1602
|
-
}
|
|
1603
|
-
//#endregion
|
|
1604
|
-
//#region src/host/catalogue/errors.ts
|
|
1605
|
-
var CatalogueError = class extends Error {
|
|
1606
|
-
failure;
|
|
1607
|
-
detail;
|
|
1608
|
-
constructor(message, failure, detail) {
|
|
1609
|
-
super(message);
|
|
1610
|
-
this.failure = failure;
|
|
1611
|
-
this.detail = detail;
|
|
1612
|
-
}
|
|
1613
|
-
};
|
|
1614
|
-
//#endregion
|
|
1615
|
-
//#region src/host/http/respond.ts
|
|
1616
|
-
function sendJson(res, status, payload) {
|
|
1617
|
-
res.statusCode = status;
|
|
1618
|
-
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
1619
|
-
res.setHeader("cache-control", "no-store");
|
|
1620
|
-
res.end(JSON.stringify(payload));
|
|
1621
|
-
}
|
|
1622
|
-
function sendError(res, status, message) {
|
|
1623
|
-
sendJson(res, status, { message });
|
|
1184
|
+
} },
|
|
1185
|
+
"/presets/prompt": {
|
|
1186
|
+
GET: async (_req, res, url) => {
|
|
1187
|
+
try {
|
|
1188
|
+
sendJson(res, 200, { text: api.promptText(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? ""), url.searchParams.get("id") ?? "") });
|
|
1189
|
+
} catch (error) {
|
|
1190
|
+
failure$2(res, error);
|
|
1191
|
+
}
|
|
1192
|
+
},
|
|
1193
|
+
PUT: async (req, res, url) => {
|
|
1194
|
+
const { text } = await readJsonBody(req);
|
|
1195
|
+
if (typeof text !== "string" || text.trim() === "") return sendError(res, 400, "\"text\" is required");
|
|
1196
|
+
try {
|
|
1197
|
+
sendJson(res, 200, await api.writePrompt(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? ""), url.searchParams.get("id") ?? "", text));
|
|
1198
|
+
} catch (error) {
|
|
1199
|
+
failure$2(res, error);
|
|
1200
|
+
}
|
|
1201
|
+
},
|
|
1202
|
+
DELETE: async (_req, res, url) => {
|
|
1203
|
+
try {
|
|
1204
|
+
sendJson(res, 200, await api.writePrompt(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? ""), url.searchParams.get("id") ?? "", void 0));
|
|
1205
|
+
} catch (error) {
|
|
1206
|
+
failure$2(res, error);
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
},
|
|
1210
|
+
"/presets/authoring": { POST: async (req, res, url) => {
|
|
1211
|
+
const { language } = await readJsonBody(req);
|
|
1212
|
+
if (language !== void 0 && typeof language !== "string") return sendError(res, 400, "\"language\" must be text");
|
|
1213
|
+
try {
|
|
1214
|
+
sendJson(res, 200, await api.author(url.searchParams.get("name") ?? "", language === void 0 ? void 0 : languageOf(language)));
|
|
1215
|
+
} catch (error) {
|
|
1216
|
+
failure$2(res, error);
|
|
1217
|
+
}
|
|
1218
|
+
} },
|
|
1219
|
+
"/presets/import/verbatim": { POST: async (req, res) => {
|
|
1220
|
+
const body = await readJsonBody(req);
|
|
1221
|
+
const choice = parseSelectionChoice(body);
|
|
1222
|
+
if (typeof choice === "string") return sendError(res, 400, choice);
|
|
1223
|
+
const { name, title } = body;
|
|
1224
|
+
for (const [field, value] of [["name", name], ["title", title]]) if (value !== void 0 && typeof value !== "string") return sendError(res, 400, `"${field}" must be text`);
|
|
1225
|
+
try {
|
|
1226
|
+
sendJson(res, 200, await api.importVerbatim({
|
|
1227
|
+
...choice,
|
|
1228
|
+
...name === void 0 ? {} : { name },
|
|
1229
|
+
...title === void 0 ? {} : { title }
|
|
1230
|
+
}));
|
|
1231
|
+
} catch (error) {
|
|
1232
|
+
failure$2(res, error);
|
|
1233
|
+
}
|
|
1234
|
+
} },
|
|
1235
|
+
"/presets/import/staged": { POST: async (req, res) => {
|
|
1236
|
+
const body = await readJsonBody(req);
|
|
1237
|
+
const choice = parseSelectionChoice(body);
|
|
1238
|
+
if (typeof choice === "string") return sendError(res, 400, choice);
|
|
1239
|
+
const { name, title, language } = body;
|
|
1240
|
+
for (const [field, value] of [
|
|
1241
|
+
["name", name],
|
|
1242
|
+
["title", title],
|
|
1243
|
+
["language", language]
|
|
1244
|
+
]) if (value !== void 0 && typeof value !== "string") return sendError(res, 400, `"${field}" must be text`);
|
|
1245
|
+
try {
|
|
1246
|
+
sendJson(res, 200, await api.importStaged({
|
|
1247
|
+
...choice,
|
|
1248
|
+
...name === void 0 ? {} : { name },
|
|
1249
|
+
...title === void 0 ? {} : { title },
|
|
1250
|
+
...language === void 0 ? {} : { language: languageOf(language) }
|
|
1251
|
+
}));
|
|
1252
|
+
} catch (error) {
|
|
1253
|
+
failure$2(res, error);
|
|
1254
|
+
}
|
|
1255
|
+
} },
|
|
1256
|
+
"/presets/import": { POST: async (req, res, url) => {
|
|
1257
|
+
const language = url.searchParams.get("language");
|
|
1258
|
+
try {
|
|
1259
|
+
sendJson(res, 200, await api.importFile(url.searchParams.get("name") ?? "", await readBinaryBody(req, api.maxUploadBytes), language === null ? void 0 : languageOf(language)));
|
|
1260
|
+
} catch (error) {
|
|
1261
|
+
failure$2(res, error);
|
|
1262
|
+
}
|
|
1263
|
+
} },
|
|
1264
|
+
"/sessions/preset": {
|
|
1265
|
+
GET: async (_req, res, url) => {
|
|
1266
|
+
try {
|
|
1267
|
+
sendJson(res, 200, api.status(url.searchParams.get("id") ?? ""));
|
|
1268
|
+
} catch (error) {
|
|
1269
|
+
failure$2(res, error);
|
|
1270
|
+
}
|
|
1271
|
+
},
|
|
1272
|
+
POST: async (req, res, url) => {
|
|
1273
|
+
const { name } = await readJsonBody(req);
|
|
1274
|
+
if (name !== void 0 && name !== null && (typeof name !== "string" || name === "")) return sendError(res, 400, "\"name\" must be a preset name, or left out to take the preset out");
|
|
1275
|
+
try {
|
|
1276
|
+
sendJson(res, 200, api.apply(url.searchParams.get("id") ?? "", typeof name === "string" ? name : void 0));
|
|
1277
|
+
} catch (error) {
|
|
1278
|
+
failure$2(res, error);
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
};
|
|
1624
1283
|
}
|
|
1625
|
-
/** A failure with the status the client should see. */
|
|
1626
|
-
var HttpError = class extends Error {
|
|
1627
|
-
status;
|
|
1628
|
-
constructor(status, message) {
|
|
1629
|
-
super(message);
|
|
1630
|
-
this.status = status;
|
|
1631
|
-
}
|
|
1632
|
-
};
|
|
1633
1284
|
//#endregion
|
|
1634
|
-
//#region src/host/
|
|
1635
|
-
/**
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
if (
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
for await (const chunk of req) {
|
|
1643
|
-
size += chunk.length;
|
|
1644
|
-
if (size > MAX_BODY_BYTES) throw new HttpError(413, "request body is too large");
|
|
1645
|
-
chunks.push(chunk);
|
|
1646
|
-
}
|
|
1647
|
-
let body;
|
|
1648
|
-
try {
|
|
1649
|
-
body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
1650
|
-
} catch {
|
|
1651
|
-
throw new HttpError(400, "request body is not valid JSON");
|
|
1652
|
-
}
|
|
1653
|
-
if (typeof body !== "object" || body === null || Array.isArray(body)) throw new HttpError(400, "request body must be a JSON object");
|
|
1654
|
-
return body;
|
|
1285
|
+
//#region src/host/lorebooks/routes.ts
|
|
1286
|
+
/** Not found is 404, a story in the middle of a turn 409, and a request the library refuses 422 with its reason; anything else is a fault. */
|
|
1287
|
+
function failure$1(res, error) {
|
|
1288
|
+
if (error instanceof ImportNotFoundError) return sendError(res, 404, error.message);
|
|
1289
|
+
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
1290
|
+
if (error instanceof LorebookBusyError) return sendError(res, 409, error.message);
|
|
1291
|
+
if (error instanceof Error) return sendError(res, 422, error.message);
|
|
1292
|
+
throw error;
|
|
1655
1293
|
}
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1294
|
+
const texts = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
1295
|
+
/** Reads the body of an entry, or says what is wrong with it. */
|
|
1296
|
+
function entryOf(id, body) {
|
|
1297
|
+
const { title, kind, scope, knownBy, summary, body: text, related } = body;
|
|
1298
|
+
if (typeof title !== "string") return "\"title\" must be text";
|
|
1299
|
+
if (typeof kind !== "string" || !LORE_KINDS.includes(kind)) return `"kind" must be one of ${LORE_KINDS.join(", ")}`;
|
|
1300
|
+
if (typeof scope !== "string" || !LORE_SCOPES.includes(scope)) return `"scope" must be one of ${LORE_SCOPES.join(", ")}`;
|
|
1301
|
+
if (knownBy !== void 0 && !texts(knownBy)) return "\"knownBy\" must be a list of text";
|
|
1302
|
+
if (related !== void 0 && !texts(related)) return "\"related\" must be a list of text";
|
|
1303
|
+
if (summary !== void 0 && typeof summary !== "string" || text !== void 0 && typeof text !== "string") return "\"summary\" and \"body\" must be text";
|
|
1304
|
+
return {
|
|
1305
|
+
id,
|
|
1306
|
+
title,
|
|
1307
|
+
kind,
|
|
1308
|
+
scope,
|
|
1309
|
+
knownBy: knownBy?.map((entry) => entry.trim()).filter((entry) => entry !== "") ?? [],
|
|
1310
|
+
summary: summary ?? "",
|
|
1311
|
+
body: text ?? "",
|
|
1312
|
+
related: related ?? []
|
|
1313
|
+
};
|
|
1669
1314
|
}
|
|
1670
|
-
|
|
1671
|
-
//#region src/host/presets/service.ts
|
|
1672
|
-
/** The story's prompts cannot change right now. */
|
|
1673
|
-
var PresetBusyError = class extends Error {};
|
|
1674
|
-
/** The preset library and the presets of stories. Refusals are plain `Error`s with the reason; unknown stories and worlds are not-found errors. */
|
|
1675
|
-
var Presets = class {
|
|
1676
|
-
deps;
|
|
1677
|
-
constructor(deps) {
|
|
1678
|
-
this.deps = deps;
|
|
1679
|
-
}
|
|
1680
|
-
get maxUploadBytes() {
|
|
1681
|
-
return this.deps.maxUploadBytes;
|
|
1682
|
-
}
|
|
1683
|
-
list() {
|
|
1684
|
-
return listPresets(this.deps.root()).map((entry) => entry.summary);
|
|
1685
|
-
}
|
|
1686
|
-
/** A preset with the text of each prompt it carries, keyed `<language>/<id>`. */
|
|
1687
|
-
read(name) {
|
|
1688
|
-
const loaded = loadPreset(this.deps.root(), name);
|
|
1689
|
-
return {
|
|
1690
|
-
summary: loaded.summary,
|
|
1691
|
-
prompts: Object.fromEntries([...loaded.files].map(([path, text]) => [path.slice(0, -3), text]))
|
|
1692
|
-
};
|
|
1693
|
-
}
|
|
1694
|
-
async saveFromWorld(request) {
|
|
1695
|
-
const directory = await this.deps.worldDirectory(request.fromWorld);
|
|
1696
|
-
if (directory === void 0) throw new WorldNotFoundError(`there is no world with id "${request.fromWorld}"`);
|
|
1697
|
-
return (await savePresetFromWorld(this.deps.root(), directory, request)).summary;
|
|
1698
|
-
}
|
|
1699
|
-
/** Makes a preset from a world's own prose prompts, or from the shipped ones as a starting point when no world is given. */
|
|
1700
|
-
async create(request) {
|
|
1701
|
-
if (request.fromWorld !== void 0) return await this.saveFromWorld({
|
|
1702
|
-
...request,
|
|
1703
|
-
fromWorld: request.fromWorld
|
|
1704
|
-
});
|
|
1705
|
-
return (await createPresetFromShipped(this.deps.root(), request)).summary;
|
|
1706
|
-
}
|
|
1707
|
-
async updateInfo(name, change) {
|
|
1708
|
-
return (await updatePresetInfo(this.deps.root(), name, change)).summary;
|
|
1709
|
-
}
|
|
1710
|
-
/** Writes the person's own text of a prompt; `undefined` takes the preset's version out. */
|
|
1711
|
-
async writePrompt(name, language, id, text) {
|
|
1712
|
-
const directory = this.existing(name);
|
|
1713
|
-
if (!id.startsWith("roleplay/")) throw new Error(`"${id}" is not a prompt of the story`);
|
|
1714
|
-
if (text === void 0) await deleteWorldPrompt(directory, language, id);
|
|
1715
|
-
else await writeWorldPrompt(directory, language, id, text);
|
|
1716
|
-
return loadPreset(this.deps.root(), name).summary;
|
|
1717
|
-
}
|
|
1718
|
-
/** The prompts holding the rules of the game that the preset does not carry yet, which it may take over from the shipped ones. */
|
|
1719
|
-
rulesPrompts(name, language) {
|
|
1720
|
-
return listWorldPrompts(this.existing(name), language).filter((entry) => entry.kind === "rules" && !entry.carried).map((entry) => entry.id);
|
|
1721
|
-
}
|
|
1722
|
-
/** The text of a prompt as a story with this preset gets it: the preset's own, else the shipped one. */
|
|
1723
|
-
promptText(name, language, id) {
|
|
1724
|
-
return readWorldPrompt(this.existing(name), language, id).text;
|
|
1725
|
-
}
|
|
1726
|
-
existing(name) {
|
|
1727
|
-
const directory = presetDirectory(this.deps.root(), name);
|
|
1728
|
-
if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
|
|
1729
|
-
return directory;
|
|
1730
|
-
}
|
|
1731
|
-
/** Like `importFile`, under a name made from the title that is not yet taken. */
|
|
1732
|
-
async importTitled(title, file, language) {
|
|
1733
|
-
return await this.importFile(this.freeName(title), file, language, title.trim() === "" ? void 0 : title.trim().slice(0, 300));
|
|
1734
|
-
}
|
|
1735
|
-
freeName(title) {
|
|
1736
|
-
const base = trimCharacters(title.normalize("NFKD").replace(/[^A-Za-z0-9_-]+/g, "-"), "-_").slice(0, 56) || "preset";
|
|
1737
|
-
const taken = new Set(listPresets(this.deps.root()).map((entry) => entry.summary.name));
|
|
1738
|
-
let name = base;
|
|
1739
|
-
for (let index = 2; taken.has(name); index += 1) name = `${base}-${index}`;
|
|
1740
|
-
return name;
|
|
1741
|
-
}
|
|
1742
|
-
/**
|
|
1743
|
-
* Imports the chosen prompts of a staged preset as they are, with no assistant: a new library preset is made and holds them as its narration style in every language the program ships, and nothing else happens.
|
|
1744
|
-
* @throws {ImportNotFoundError} when the file is no longer staged. @throws {ImportCardError} when the choice cannot be used.
|
|
1745
|
-
*/
|
|
1746
|
-
async importVerbatim(request) {
|
|
1747
|
-
const { file, name: fileName } = this.deps.staging.choose("preset", request);
|
|
1748
|
-
const made = verbatimStyle(file, fileName);
|
|
1749
|
-
const title = request.title ?? made.name;
|
|
1750
|
-
const name = request.name ?? this.freeName(title);
|
|
1751
|
-
if (!isPresetName(name)) throw new Error(`"${name}" is not a usable preset name (letters, digits, "-" and "_", up to 64)`);
|
|
1752
|
-
const root = this.deps.root();
|
|
1753
|
-
const directory = await reservePreset(root, name, title, made.sampling);
|
|
1754
|
-
try {
|
|
1755
|
-
for (const language of shippedLanguages()) await writeWorldPrompt(directory, language, "roleplay/style", made.text);
|
|
1756
|
-
} catch (error) {
|
|
1757
|
-
await deletePreset(root, name);
|
|
1758
|
-
throw error;
|
|
1759
|
-
}
|
|
1760
|
-
this.deps.staging.discard(request.id);
|
|
1761
|
-
return { name };
|
|
1762
|
-
}
|
|
1763
|
-
/** Opens the authoring chat of a preset. */
|
|
1764
|
-
async author(name, language) {
|
|
1765
|
-
const loaded = loadPreset(this.deps.root(), name);
|
|
1766
|
-
return { chatSessionId: await this.deps.authoring.ensure(name, loaded.summary.title, language) };
|
|
1767
|
-
}
|
|
1768
|
-
/** Keeps an uploaded SillyTavern preset in a new library preset and has its authoring chat turn it into prompts. @throws {ImportCardError} when the file is not a preset. */
|
|
1769
|
-
async importFile(name, file, language, title) {
|
|
1770
|
-
const uploaded = readPreset(file, name);
|
|
1771
|
-
const root = this.deps.root();
|
|
1772
|
-
const directory = await reservePreset(root, name, title ?? uploaded.name, uploaded.sampling);
|
|
1773
|
-
try {
|
|
1774
|
-
await mkdir(join(directory, IMPORT_FOLDER), { recursive: true });
|
|
1775
|
-
await writeFile(join(directory, IMPORT_FOLDER, PRESET_FILE), file);
|
|
1776
|
-
} catch (error) {
|
|
1777
|
-
await deletePreset(root, name);
|
|
1778
|
-
throw error;
|
|
1779
|
-
}
|
|
1780
|
-
const chatSessionId = await this.deps.authoring.ensure(name, title ?? uploaded.name, language);
|
|
1781
|
-
let failure;
|
|
1782
|
-
try {
|
|
1783
|
-
await this.deps.authoring.send(chatSessionId, this.deps.importMessage(language));
|
|
1784
|
-
} catch (problem) {
|
|
1785
|
-
failure = problem instanceof Error ? problem.message : String(problem);
|
|
1786
|
-
}
|
|
1787
|
-
return {
|
|
1788
|
-
name,
|
|
1789
|
-
chatSessionId,
|
|
1790
|
-
started: failure === void 0,
|
|
1791
|
-
...failure === void 0 ? {} : { failure }
|
|
1792
|
-
};
|
|
1793
|
-
}
|
|
1794
|
-
/** Imports a staged preset with only the prompts the person chose; a name is the library name they gave it, else one is made from the title. @throws {ImportNotFoundError} when the file is no longer staged. */
|
|
1795
|
-
async importStaged(request) {
|
|
1796
|
-
const { file, name: fileName } = this.deps.staging.choose("preset", request);
|
|
1797
|
-
const opened = request.name === void 0 ? await this.importTitled(request.title ?? readPreset(file, fileName).name, file, request.language) : await this.importFile(request.name, file, request.language, request.title);
|
|
1798
|
-
this.deps.staging.discard(request.id);
|
|
1799
|
-
return opened;
|
|
1800
|
-
}
|
|
1801
|
-
async remove(name) {
|
|
1802
|
-
await deletePreset(this.deps.root(), name);
|
|
1803
|
-
}
|
|
1804
|
-
status(session) {
|
|
1805
|
-
return presetStatus(this.deps.root(), this.folder(session));
|
|
1806
|
-
}
|
|
1807
|
-
/** Puts the named preset into a story, or takes the story's preset out when no name is given. */
|
|
1808
|
-
apply(session, name) {
|
|
1809
|
-
const folder = this.folder(session);
|
|
1810
|
-
if (this.deps.playing(session)) throw new PresetBusyError("a turn is being played; change the preset when it is over");
|
|
1811
|
-
return { files: switchPreset(this.deps.root(), folder, name) };
|
|
1812
|
-
}
|
|
1813
|
-
folder(id) {
|
|
1814
|
-
const sessions = `${this.deps.root()}/sessions`;
|
|
1815
|
-
if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
|
|
1816
|
-
return sessionFolder(sessions, id);
|
|
1817
|
-
}
|
|
1818
|
-
};
|
|
1819
|
-
//#endregion
|
|
1820
|
-
//#region src/host/presets/routes.ts
|
|
1821
|
-
/** Not found is 404 and a request the library refuses is 422 with its reason; anything else is a fault. */
|
|
1822
|
-
function failure$2(res, error) {
|
|
1823
|
-
if (error instanceof ImportNotFoundError) return sendError(res, 404, error.message);
|
|
1824
|
-
if (error instanceof SessionNotFoundError || error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
1825
|
-
if (error instanceof PresetBusyError) return sendError(res, 409, error.message);
|
|
1826
|
-
if (error instanceof Error) return sendError(res, 422, error.message);
|
|
1827
|
-
throw error;
|
|
1828
|
-
}
|
|
1829
|
-
function samplingOf(value) {
|
|
1830
|
-
const problems = [];
|
|
1831
|
-
const sampling = parseSampling(value, "sampling", problems);
|
|
1832
|
-
return problems.length === 0 ? sampling : problems.join("; ");
|
|
1833
|
-
}
|
|
1834
|
-
function presetRoutes(api) {
|
|
1315
|
+
function lorebookRoutes(api) {
|
|
1835
1316
|
return {
|
|
1836
|
-
"/
|
|
1317
|
+
"/sessions/lorebooks": {
|
|
1318
|
+
GET: async (_req, res, url) => {
|
|
1319
|
+
try {
|
|
1320
|
+
sendJson(res, 200, await api.status(url.searchParams.get("id") ?? ""));
|
|
1321
|
+
} catch (error) {
|
|
1322
|
+
failure$1(res, error);
|
|
1323
|
+
}
|
|
1324
|
+
},
|
|
1325
|
+
POST: async (req, res, url) => {
|
|
1326
|
+
const { name } = await readJsonBody(req);
|
|
1327
|
+
if (typeof name !== "string" || name === "") return sendError(res, 400, "\"name\" is required");
|
|
1328
|
+
try {
|
|
1329
|
+
sendJson(res, 200, await api.addToStory(url.searchParams.get("id") ?? "", name));
|
|
1330
|
+
} catch (error) {
|
|
1331
|
+
failure$1(res, error);
|
|
1332
|
+
}
|
|
1333
|
+
},
|
|
1334
|
+
DELETE: async (_req, res, url) => {
|
|
1335
|
+
try {
|
|
1336
|
+
sendJson(res, 200, api.removeFromStory(url.searchParams.get("id") ?? "", url.searchParams.get("name") ?? ""));
|
|
1337
|
+
} catch (error) {
|
|
1338
|
+
failure$1(res, error);
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
},
|
|
1342
|
+
"/lorebooks": {
|
|
1837
1343
|
GET: async (_req, res) => {
|
|
1838
1344
|
try {
|
|
1839
|
-
sendJson(res, 200, api.list());
|
|
1345
|
+
sendJson(res, 200, await api.list());
|
|
1840
1346
|
} catch (error) {
|
|
1841
|
-
failure$
|
|
1347
|
+
failure$1(res, error);
|
|
1842
1348
|
}
|
|
1843
1349
|
},
|
|
1844
1350
|
POST: async (req, res) => {
|
|
1845
|
-
const { name, title, description
|
|
1351
|
+
const { name, title, description } = await readJsonBody(req);
|
|
1846
1352
|
if (typeof name !== "string" || name === "") return sendError(res, 400, "\"name\" is required");
|
|
1847
|
-
if (fromWorld !== void 0 && (typeof fromWorld !== "string" || fromWorld === "")) return sendError(res, 400, "\"fromWorld\" must be a world id, or left out to start from the shipped prompts");
|
|
1848
1353
|
if (title !== void 0 && typeof title !== "string" || description !== void 0 && typeof description !== "string") return sendError(res, 400, "\"title\" and \"description\" must be text");
|
|
1849
|
-
const given = samplingOf(sampling);
|
|
1850
|
-
if (typeof given === "string") return sendError(res, 400, given);
|
|
1851
1354
|
try {
|
|
1852
1355
|
sendJson(res, 201, await api.create({
|
|
1853
1356
|
name,
|
|
1854
|
-
...fromWorld === void 0 ? {} : { fromWorld },
|
|
1855
1357
|
...title === void 0 ? {} : { title },
|
|
1856
|
-
...description === void 0 ? {} : { description }
|
|
1857
|
-
sampling: given
|
|
1358
|
+
...description === void 0 ? {} : { description }
|
|
1858
1359
|
}));
|
|
1859
1360
|
} catch (error) {
|
|
1860
|
-
failure$
|
|
1361
|
+
failure$1(res, error);
|
|
1861
1362
|
}
|
|
1862
1363
|
}
|
|
1863
1364
|
},
|
|
1864
|
-
"/
|
|
1365
|
+
"/lorebooks/item": {
|
|
1865
1366
|
GET: async (_req, res, url) => {
|
|
1866
1367
|
try {
|
|
1867
|
-
sendJson(res, 200, api.read(url.searchParams.get("name") ?? ""));
|
|
1368
|
+
sendJson(res, 200, await api.read(url.searchParams.get("name") ?? ""));
|
|
1868
1369
|
} catch (error) {
|
|
1869
|
-
failure$
|
|
1370
|
+
failure$1(res, error);
|
|
1870
1371
|
}
|
|
1871
1372
|
},
|
|
1872
1373
|
PUT: async (req, res, url) => {
|
|
1873
|
-
const { title, description
|
|
1374
|
+
const { title, description } = await readJsonBody(req);
|
|
1874
1375
|
if (title !== void 0 && typeof title !== "string" || description !== void 0 && typeof description !== "string") return sendError(res, 400, "\"title\" and \"description\" must be text");
|
|
1875
|
-
const given = sampling === void 0 ? void 0 : samplingOf(sampling);
|
|
1876
|
-
if (typeof given === "string") return sendError(res, 400, given);
|
|
1877
1376
|
try {
|
|
1878
1377
|
sendJson(res, 200, await api.updateInfo(url.searchParams.get("name") ?? "", {
|
|
1879
1378
|
...title === void 0 ? {} : { title },
|
|
1880
|
-
...description === void 0 ? {} : { description }
|
|
1881
|
-
...given === void 0 ? {} : { sampling: given }
|
|
1379
|
+
...description === void 0 ? {} : { description }
|
|
1882
1380
|
}));
|
|
1883
1381
|
} catch (error) {
|
|
1884
|
-
failure$
|
|
1382
|
+
failure$1(res, error);
|
|
1885
1383
|
}
|
|
1886
1384
|
},
|
|
1887
1385
|
DELETE: async (_req, res, url) => {
|
|
@@ -1890,68 +1388,56 @@ function presetRoutes(api) {
|
|
|
1890
1388
|
res.statusCode = 204;
|
|
1891
1389
|
res.end();
|
|
1892
1390
|
} catch (error) {
|
|
1893
|
-
failure$
|
|
1391
|
+
failure$1(res, error);
|
|
1894
1392
|
}
|
|
1895
1393
|
}
|
|
1896
1394
|
},
|
|
1897
|
-
"/
|
|
1898
|
-
try {
|
|
1899
|
-
sendJson(res, 200, api.rulesPrompts(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? "")));
|
|
1900
|
-
} catch (error) {
|
|
1901
|
-
failure$2(res, error);
|
|
1902
|
-
}
|
|
1903
|
-
} },
|
|
1904
|
-
"/presets/prompt": {
|
|
1905
|
-
GET: async (_req, res, url) => {
|
|
1906
|
-
try {
|
|
1907
|
-
sendJson(res, 200, { text: api.promptText(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? ""), url.searchParams.get("id") ?? "") });
|
|
1908
|
-
} catch (error) {
|
|
1909
|
-
failure$2(res, error);
|
|
1910
|
-
}
|
|
1911
|
-
},
|
|
1395
|
+
"/lorebooks/entry": {
|
|
1912
1396
|
PUT: async (req, res, url) => {
|
|
1913
|
-
const
|
|
1914
|
-
if (typeof
|
|
1397
|
+
const entry = entryOf(url.searchParams.get("id") ?? "", await readJsonBody(req));
|
|
1398
|
+
if (typeof entry === "string") return sendError(res, 400, entry);
|
|
1915
1399
|
try {
|
|
1916
|
-
sendJson(res, 200, await api.
|
|
1400
|
+
sendJson(res, 200, await api.writeEntry(url.searchParams.get("name") ?? "", entry));
|
|
1917
1401
|
} catch (error) {
|
|
1918
|
-
failure$
|
|
1402
|
+
failure$1(res, error);
|
|
1919
1403
|
}
|
|
1920
1404
|
},
|
|
1921
1405
|
DELETE: async (_req, res, url) => {
|
|
1922
1406
|
try {
|
|
1923
|
-
sendJson(res, 200, await api.
|
|
1407
|
+
sendJson(res, 200, await api.removeEntry(url.searchParams.get("name") ?? "", url.searchParams.get("id") ?? ""));
|
|
1924
1408
|
} catch (error) {
|
|
1925
|
-
failure$
|
|
1409
|
+
failure$1(res, error);
|
|
1926
1410
|
}
|
|
1927
1411
|
}
|
|
1928
1412
|
},
|
|
1929
|
-
"/
|
|
1413
|
+
"/lorebooks/authoring": { POST: async (req, res, url) => {
|
|
1930
1414
|
const { language } = await readJsonBody(req);
|
|
1931
1415
|
if (language !== void 0 && typeof language !== "string") return sendError(res, 400, "\"language\" must be text");
|
|
1932
1416
|
try {
|
|
1933
1417
|
sendJson(res, 200, await api.author(url.searchParams.get("name") ?? "", language === void 0 ? void 0 : languageOf(language)));
|
|
1934
1418
|
} catch (error) {
|
|
1935
|
-
failure$
|
|
1419
|
+
failure$1(res, error);
|
|
1936
1420
|
}
|
|
1937
1421
|
} },
|
|
1938
|
-
"/
|
|
1422
|
+
"/lorebooks/import/verbatim": { POST: async (req, res) => {
|
|
1939
1423
|
const body = await readJsonBody(req);
|
|
1940
1424
|
const choice = parseSelectionChoice(body);
|
|
1941
1425
|
if (typeof choice === "string") return sendError(res, 400, choice);
|
|
1942
|
-
const { name, title } = body;
|
|
1426
|
+
const { name, title, knownBy } = body;
|
|
1943
1427
|
for (const [field, value] of [["name", name], ["title", title]]) if (value !== void 0 && typeof value !== "string") return sendError(res, 400, `"${field}" must be text`);
|
|
1428
|
+
if (knownBy !== "everyone" && knownBy !== "master") return sendError(res, 400, "\"knownBy\" must be everyone or master");
|
|
1944
1429
|
try {
|
|
1945
1430
|
sendJson(res, 200, await api.importVerbatim({
|
|
1946
1431
|
...choice,
|
|
1432
|
+
knownBy,
|
|
1947
1433
|
...name === void 0 ? {} : { name },
|
|
1948
1434
|
...title === void 0 ? {} : { title }
|
|
1949
1435
|
}));
|
|
1950
1436
|
} catch (error) {
|
|
1951
|
-
failure$
|
|
1437
|
+
failure$1(res, error);
|
|
1952
1438
|
}
|
|
1953
1439
|
} },
|
|
1954
|
-
"/
|
|
1440
|
+
"/lorebooks/import/staged": { POST: async (req, res) => {
|
|
1955
1441
|
const body = await readJsonBody(req);
|
|
1956
1442
|
const choice = parseSelectionChoice(body);
|
|
1957
1443
|
if (typeof choice === "string") return sendError(res, 400, choice);
|
|
@@ -1969,239 +1455,20 @@ function presetRoutes(api) {
|
|
|
1969
1455
|
...language === void 0 ? {} : { language: languageOf(language) }
|
|
1970
1456
|
}));
|
|
1971
1457
|
} catch (error) {
|
|
1972
|
-
failure$
|
|
1458
|
+
failure$1(res, error);
|
|
1973
1459
|
}
|
|
1974
1460
|
} },
|
|
1975
|
-
"/
|
|
1461
|
+
"/lorebooks/import": { POST: async (req, res, url) => {
|
|
1976
1462
|
const language = url.searchParams.get("language");
|
|
1977
1463
|
try {
|
|
1978
1464
|
sendJson(res, 200, await api.importFile(url.searchParams.get("name") ?? "", await readBinaryBody(req, api.maxUploadBytes), language === null ? void 0 : languageOf(language)));
|
|
1979
1465
|
} catch (error) {
|
|
1980
|
-
failure$
|
|
1981
|
-
}
|
|
1982
|
-
} },
|
|
1983
|
-
"/sessions/preset": {
|
|
1984
|
-
GET: async (_req, res, url) => {
|
|
1985
|
-
try {
|
|
1986
|
-
sendJson(res, 200, api.status(url.searchParams.get("id") ?? ""));
|
|
1987
|
-
} catch (error) {
|
|
1988
|
-
failure$2(res, error);
|
|
1989
|
-
}
|
|
1990
|
-
},
|
|
1991
|
-
POST: async (req, res, url) => {
|
|
1992
|
-
const { name } = await readJsonBody(req);
|
|
1993
|
-
if (name !== void 0 && name !== null && (typeof name !== "string" || name === "")) return sendError(res, 400, "\"name\" must be a preset name, or left out to take the preset out");
|
|
1994
|
-
try {
|
|
1995
|
-
sendJson(res, 200, api.apply(url.searchParams.get("id") ?? "", typeof name === "string" ? name : void 0));
|
|
1996
|
-
} catch (error) {
|
|
1997
|
-
failure$2(res, error);
|
|
1998
|
-
}
|
|
1466
|
+
failure$1(res, error);
|
|
1999
1467
|
}
|
|
2000
|
-
}
|
|
1468
|
+
} }
|
|
2001
1469
|
};
|
|
2002
1470
|
}
|
|
2003
1471
|
//#endregion
|
|
2004
|
-
//#region src/host/lorebooks/routes.ts
|
|
2005
|
-
/** Not found is 404, a story in the middle of a turn 409, and a request the library refuses 422 with its reason; anything else is a fault. */
|
|
2006
|
-
function failure$1(res, error) {
|
|
2007
|
-
if (error instanceof ImportNotFoundError) return sendError(res, 404, error.message);
|
|
2008
|
-
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
2009
|
-
if (error instanceof LorebookBusyError) return sendError(res, 409, error.message);
|
|
2010
|
-
if (error instanceof Error) return sendError(res, 422, error.message);
|
|
2011
|
-
throw error;
|
|
2012
|
-
}
|
|
2013
|
-
const texts = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
2014
|
-
/** Reads the body of an entry, or says what is wrong with it. */
|
|
2015
|
-
function entryOf(id, body) {
|
|
2016
|
-
const { title, kind, scope, knownBy, summary, body: text, related } = body;
|
|
2017
|
-
if (typeof title !== "string") return "\"title\" must be text";
|
|
2018
|
-
if (typeof kind !== "string" || !LORE_KINDS.includes(kind)) return `"kind" must be one of ${LORE_KINDS.join(", ")}`;
|
|
2019
|
-
if (typeof scope !== "string" || !LORE_SCOPES.includes(scope)) return `"scope" must be one of ${LORE_SCOPES.join(", ")}`;
|
|
2020
|
-
if (knownBy !== void 0 && !texts(knownBy)) return "\"knownBy\" must be a list of text";
|
|
2021
|
-
if (related !== void 0 && !texts(related)) return "\"related\" must be a list of text";
|
|
2022
|
-
if (summary !== void 0 && typeof summary !== "string" || text !== void 0 && typeof text !== "string") return "\"summary\" and \"body\" must be text";
|
|
2023
|
-
return {
|
|
2024
|
-
id,
|
|
2025
|
-
title,
|
|
2026
|
-
kind,
|
|
2027
|
-
scope,
|
|
2028
|
-
knownBy: knownBy?.map((entry) => entry.trim()).filter((entry) => entry !== "") ?? [],
|
|
2029
|
-
summary: summary ?? "",
|
|
2030
|
-
body: text ?? "",
|
|
2031
|
-
related: related ?? []
|
|
2032
|
-
};
|
|
2033
|
-
}
|
|
2034
|
-
function lorebookRoutes(api) {
|
|
2035
|
-
return {
|
|
2036
|
-
"/sessions/lorebooks": {
|
|
2037
|
-
GET: async (_req, res, url) => {
|
|
2038
|
-
try {
|
|
2039
|
-
sendJson(res, 200, await api.status(url.searchParams.get("id") ?? ""));
|
|
2040
|
-
} catch (error) {
|
|
2041
|
-
failure$1(res, error);
|
|
2042
|
-
}
|
|
2043
|
-
},
|
|
2044
|
-
POST: async (req, res, url) => {
|
|
2045
|
-
const { name } = await readJsonBody(req);
|
|
2046
|
-
if (typeof name !== "string" || name === "") return sendError(res, 400, "\"name\" is required");
|
|
2047
|
-
try {
|
|
2048
|
-
sendJson(res, 200, await api.addToStory(url.searchParams.get("id") ?? "", name));
|
|
2049
|
-
} catch (error) {
|
|
2050
|
-
failure$1(res, error);
|
|
2051
|
-
}
|
|
2052
|
-
},
|
|
2053
|
-
DELETE: async (_req, res, url) => {
|
|
2054
|
-
try {
|
|
2055
|
-
sendJson(res, 200, api.removeFromStory(url.searchParams.get("id") ?? "", url.searchParams.get("name") ?? ""));
|
|
2056
|
-
} catch (error) {
|
|
2057
|
-
failure$1(res, error);
|
|
2058
|
-
}
|
|
2059
|
-
}
|
|
2060
|
-
},
|
|
2061
|
-
"/lorebooks": {
|
|
2062
|
-
GET: async (_req, res) => {
|
|
2063
|
-
try {
|
|
2064
|
-
sendJson(res, 200, await api.list());
|
|
2065
|
-
} catch (error) {
|
|
2066
|
-
failure$1(res, error);
|
|
2067
|
-
}
|
|
2068
|
-
},
|
|
2069
|
-
POST: async (req, res) => {
|
|
2070
|
-
const { name, title, description } = await readJsonBody(req);
|
|
2071
|
-
if (typeof name !== "string" || name === "") return sendError(res, 400, "\"name\" is required");
|
|
2072
|
-
if (title !== void 0 && typeof title !== "string" || description !== void 0 && typeof description !== "string") return sendError(res, 400, "\"title\" and \"description\" must be text");
|
|
2073
|
-
try {
|
|
2074
|
-
sendJson(res, 201, await api.create({
|
|
2075
|
-
name,
|
|
2076
|
-
...title === void 0 ? {} : { title },
|
|
2077
|
-
...description === void 0 ? {} : { description }
|
|
2078
|
-
}));
|
|
2079
|
-
} catch (error) {
|
|
2080
|
-
failure$1(res, error);
|
|
2081
|
-
}
|
|
2082
|
-
}
|
|
2083
|
-
},
|
|
2084
|
-
"/lorebooks/item": {
|
|
2085
|
-
GET: async (_req, res, url) => {
|
|
2086
|
-
try {
|
|
2087
|
-
sendJson(res, 200, await api.read(url.searchParams.get("name") ?? ""));
|
|
2088
|
-
} catch (error) {
|
|
2089
|
-
failure$1(res, error);
|
|
2090
|
-
}
|
|
2091
|
-
},
|
|
2092
|
-
PUT: async (req, res, url) => {
|
|
2093
|
-
const { title, description } = await readJsonBody(req);
|
|
2094
|
-
if (title !== void 0 && typeof title !== "string" || description !== void 0 && typeof description !== "string") return sendError(res, 400, "\"title\" and \"description\" must be text");
|
|
2095
|
-
try {
|
|
2096
|
-
sendJson(res, 200, await api.updateInfo(url.searchParams.get("name") ?? "", {
|
|
2097
|
-
...title === void 0 ? {} : { title },
|
|
2098
|
-
...description === void 0 ? {} : { description }
|
|
2099
|
-
}));
|
|
2100
|
-
} catch (error) {
|
|
2101
|
-
failure$1(res, error);
|
|
2102
|
-
}
|
|
2103
|
-
},
|
|
2104
|
-
DELETE: async (_req, res, url) => {
|
|
2105
|
-
try {
|
|
2106
|
-
await api.remove(url.searchParams.get("name") ?? "");
|
|
2107
|
-
res.statusCode = 204;
|
|
2108
|
-
res.end();
|
|
2109
|
-
} catch (error) {
|
|
2110
|
-
failure$1(res, error);
|
|
2111
|
-
}
|
|
2112
|
-
}
|
|
2113
|
-
},
|
|
2114
|
-
"/lorebooks/entry": {
|
|
2115
|
-
PUT: async (req, res, url) => {
|
|
2116
|
-
const entry = entryOf(url.searchParams.get("id") ?? "", await readJsonBody(req));
|
|
2117
|
-
if (typeof entry === "string") return sendError(res, 400, entry);
|
|
2118
|
-
try {
|
|
2119
|
-
sendJson(res, 200, await api.writeEntry(url.searchParams.get("name") ?? "", entry));
|
|
2120
|
-
} catch (error) {
|
|
2121
|
-
failure$1(res, error);
|
|
2122
|
-
}
|
|
2123
|
-
},
|
|
2124
|
-
DELETE: async (_req, res, url) => {
|
|
2125
|
-
try {
|
|
2126
|
-
sendJson(res, 200, await api.removeEntry(url.searchParams.get("name") ?? "", url.searchParams.get("id") ?? ""));
|
|
2127
|
-
} catch (error) {
|
|
2128
|
-
failure$1(res, error);
|
|
2129
|
-
}
|
|
2130
|
-
}
|
|
2131
|
-
},
|
|
2132
|
-
"/lorebooks/authoring": { POST: async (req, res, url) => {
|
|
2133
|
-
const { language } = await readJsonBody(req);
|
|
2134
|
-
if (language !== void 0 && typeof language !== "string") return sendError(res, 400, "\"language\" must be text");
|
|
2135
|
-
try {
|
|
2136
|
-
sendJson(res, 200, await api.author(url.searchParams.get("name") ?? "", language === void 0 ? void 0 : languageOf(language)));
|
|
2137
|
-
} catch (error) {
|
|
2138
|
-
failure$1(res, error);
|
|
2139
|
-
}
|
|
2140
|
-
} },
|
|
2141
|
-
"/lorebooks/import/verbatim": { POST: async (req, res) => {
|
|
2142
|
-
const body = await readJsonBody(req);
|
|
2143
|
-
const choice = parseSelectionChoice(body);
|
|
2144
|
-
if (typeof choice === "string") return sendError(res, 400, choice);
|
|
2145
|
-
const { name, title, knownBy } = body;
|
|
2146
|
-
for (const [field, value] of [["name", name], ["title", title]]) if (value !== void 0 && typeof value !== "string") return sendError(res, 400, `"${field}" must be text`);
|
|
2147
|
-
if (knownBy !== "everyone" && knownBy !== "master") return sendError(res, 400, "\"knownBy\" must be everyone or master");
|
|
2148
|
-
try {
|
|
2149
|
-
sendJson(res, 200, await api.importVerbatim({
|
|
2150
|
-
...choice,
|
|
2151
|
-
knownBy,
|
|
2152
|
-
...name === void 0 ? {} : { name },
|
|
2153
|
-
...title === void 0 ? {} : { title }
|
|
2154
|
-
}));
|
|
2155
|
-
} catch (error) {
|
|
2156
|
-
failure$1(res, error);
|
|
2157
|
-
}
|
|
2158
|
-
} },
|
|
2159
|
-
"/lorebooks/import/staged": { POST: async (req, res) => {
|
|
2160
|
-
const body = await readJsonBody(req);
|
|
2161
|
-
const choice = parseSelectionChoice(body);
|
|
2162
|
-
if (typeof choice === "string") return sendError(res, 400, choice);
|
|
2163
|
-
const { name, title, language } = body;
|
|
2164
|
-
for (const [field, value] of [
|
|
2165
|
-
["name", name],
|
|
2166
|
-
["title", title],
|
|
2167
|
-
["language", language]
|
|
2168
|
-
]) if (value !== void 0 && typeof value !== "string") return sendError(res, 400, `"${field}" must be text`);
|
|
2169
|
-
try {
|
|
2170
|
-
sendJson(res, 200, await api.importStaged({
|
|
2171
|
-
...choice,
|
|
2172
|
-
...name === void 0 ? {} : { name },
|
|
2173
|
-
...title === void 0 ? {} : { title },
|
|
2174
|
-
...language === void 0 ? {} : { language: languageOf(language) }
|
|
2175
|
-
}));
|
|
2176
|
-
} catch (error) {
|
|
2177
|
-
failure$1(res, error);
|
|
2178
|
-
}
|
|
2179
|
-
} },
|
|
2180
|
-
"/lorebooks/import": { POST: async (req, res, url) => {
|
|
2181
|
-
const language = url.searchParams.get("language");
|
|
2182
|
-
try {
|
|
2183
|
-
sendJson(res, 200, await api.importFile(url.searchParams.get("name") ?? "", await readBinaryBody(req, api.maxUploadBytes), language === null ? void 0 : languageOf(language)));
|
|
2184
|
-
} catch (error) {
|
|
2185
|
-
failure$1(res, error);
|
|
2186
|
-
}
|
|
2187
|
-
} }
|
|
2188
|
-
};
|
|
2189
|
-
}
|
|
2190
|
-
//#endregion
|
|
2191
|
-
//#region src/host/sync/errors.ts
|
|
2192
|
-
/** A run, or a choice, cannot be made now. */
|
|
2193
|
-
var SyncRefusedError = class extends Error {};
|
|
2194
|
-
/** rclone could not be started or reported a failure. */
|
|
2195
|
-
var RcloneError = class extends Error {
|
|
2196
|
-
code;
|
|
2197
|
-
constructor(message, code) {
|
|
2198
|
-
super(message);
|
|
2199
|
-
this.code = code;
|
|
2200
|
-
}
|
|
2201
|
-
};
|
|
2202
|
-
/** The unit is being synced: nothing may write to it or read from it until the run is over. */
|
|
2203
|
-
var UnitLockedError = class extends Error {};
|
|
2204
|
-
//#endregion
|
|
2205
1472
|
//#region src/shared/catalogue.ts
|
|
2206
1473
|
/** What a credential reference is: letters, digits and `_`, not starting with a digit (DSH's grammar). */
|
|
2207
1474
|
const CREDENTIAL_REF = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
@@ -2218,6 +1485,20 @@ const CATALOGUE_PRESET_TYPE = "sillytavern/preset";
|
|
|
2218
1485
|
const CATALOGUE_LOREBOOK_TYPE = "sillytavern/lorebook";
|
|
2219
1486
|
const CATALOGUE_WORLD_TYPE = "dsh-agentic-roleplay/world";
|
|
2220
1487
|
//#endregion
|
|
1488
|
+
//#region src/host/sync/errors.ts
|
|
1489
|
+
/** A run, or a choice, cannot be made now. */
|
|
1490
|
+
var SyncRefusedError = class extends Error {};
|
|
1491
|
+
/** rclone could not be started or reported a failure. */
|
|
1492
|
+
var RcloneError = class extends Error {
|
|
1493
|
+
code;
|
|
1494
|
+
constructor(message, code) {
|
|
1495
|
+
super(message);
|
|
1496
|
+
this.code = code;
|
|
1497
|
+
}
|
|
1498
|
+
};
|
|
1499
|
+
/** The unit is being synced: nothing may write to it or read from it until the run is over. */
|
|
1500
|
+
var UnitLockedError = class extends Error {};
|
|
1501
|
+
//#endregion
|
|
2221
1502
|
//#region src/host/sync/routes.ts
|
|
2222
1503
|
function failure(res, error) {
|
|
2223
1504
|
if (error instanceof UnitLockedError) return sendError(res, 423, error.message);
|
|
@@ -3024,25 +2305,115 @@ async function sendPackFile(api, path, res) {
|
|
|
3024
2305
|
await pipeline(createReadStream(file.file), res);
|
|
3025
2306
|
}
|
|
3026
2307
|
//#endregion
|
|
3027
|
-
//#region src/host/http/
|
|
3028
|
-
/** The
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
|
|
2308
|
+
//#region src/host/http/routes/speech.ts
|
|
2309
|
+
/** The routes of the API for speech. */
|
|
2310
|
+
function speechRoutes({ speech }) {
|
|
2311
|
+
return {
|
|
2312
|
+
"/speech/capabilities": { GET: async (_req, res) => {
|
|
2313
|
+
sendJson(res, 200, { streaming: speech.streaming() });
|
|
2314
|
+
} },
|
|
2315
|
+
"/speech/voices": { GET: async (_req, res) => {
|
|
2316
|
+
sendJson(res, 200, await speech.voices());
|
|
2317
|
+
} },
|
|
2318
|
+
"/speech/synthesize": { POST: async (req, res) => {
|
|
2319
|
+
const body = await readJsonBody(req);
|
|
2320
|
+
if (!Array.isArray(body.parts)) return sendError(res, 400, "parts must be a list");
|
|
2321
|
+
const parts = body.parts.filter((part) => typeof part === "object" && part !== null && typeof part.text === "string");
|
|
2322
|
+
if (parts.length !== body.parts.length) return sendError(res, 400, "each speech part needs text");
|
|
2323
|
+
const audio = await speech.speak(parts);
|
|
2324
|
+
res.statusCode = 200;
|
|
2325
|
+
res.setHeader("content-type", audio.mediaType);
|
|
2326
|
+
res.setHeader("content-length", audio.bytes.length);
|
|
2327
|
+
res.end(audio.bytes);
|
|
2328
|
+
} }
|
|
2329
|
+
};
|
|
2330
|
+
}
|
|
2331
|
+
//#endregion
|
|
2332
|
+
//#region src/host/worlds/starter.ts
|
|
2333
|
+
const STARTER_FOLDER = "starter-worlds";
|
|
2334
|
+
/** Names a starter world that the package does not ship. */
|
|
2335
|
+
var UnknownStarterError = class extends Error {};
|
|
2336
|
+
/** The folder of the worlds that ship with the package, found from this module so that it works from source and from the build. */
|
|
2337
|
+
function starterDirectory(from = dirname(fileURLToPath(import.meta.url))) {
|
|
2338
|
+
for (let directory = from;; directory = dirname(directory)) {
|
|
2339
|
+
const candidate = join(directory, STARTER_FOLDER);
|
|
2340
|
+
if (existsSync(join(directory, "package.json")) && existsSync(candidate)) return candidate;
|
|
2341
|
+
if (dirname(directory) === directory) throw new Error("the starter worlds shipped with the package were not found");
|
|
3044
2342
|
}
|
|
3045
|
-
|
|
2343
|
+
}
|
|
2344
|
+
async function shipped(directory) {
|
|
2345
|
+
const found = [];
|
|
2346
|
+
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
2347
|
+
if (!entry.isDirectory()) continue;
|
|
2348
|
+
const document = JSON.parse(await readFile(join(directory, entry.name, WORLD_FILE_NAME), "utf8"));
|
|
2349
|
+
if (typeof document.id !== "string" || typeof document.name !== "string") throw new Error(`the starter world "${entry.name}" has no id or name`);
|
|
2350
|
+
found.push({
|
|
2351
|
+
folder: entry.name,
|
|
2352
|
+
id: document.id,
|
|
2353
|
+
name: document.name,
|
|
2354
|
+
description: typeof document.description === "string" ? document.description : "",
|
|
2355
|
+
tags: Array.isArray(document.metadata?.tags) ? document.metadata.tags.filter((tag) => typeof tag === "string") : []
|
|
2356
|
+
});
|
|
2357
|
+
}
|
|
2358
|
+
return found.sort((a, b) => a.folder.localeCompare(b.folder));
|
|
2359
|
+
}
|
|
2360
|
+
/** The worlds the package ships, each with whether the person's worlds have it already. */
|
|
2361
|
+
async function listStarterWorlds(catalog, directory = starterDirectory()) {
|
|
2362
|
+
const known = await catalog.list();
|
|
2363
|
+
return (await shipped(directory)).map(({ id, ...world }) => ({
|
|
2364
|
+
...world,
|
|
2365
|
+
installed: known.worlds.some((existing) => existing.id === id) || existsSync(join(catalog.directory, world.folder))
|
|
2366
|
+
}));
|
|
2367
|
+
}
|
|
2368
|
+
/**
|
|
2369
|
+
* Copies a shipped world into the person's worlds, as a world of their own to play and edit, and makes the catalogue see it. Nothing is overwritten.
|
|
2370
|
+
* @throws {UnknownStarterError} when the package ships no such world.
|
|
2371
|
+
* @throws {WorldFolderExistsError} when the person already has that folder or a world with the same id.
|
|
2372
|
+
*/
|
|
2373
|
+
async function addStarterWorld(catalog, folder, directory = starterDirectory()) {
|
|
2374
|
+
const world = (await shipped(directory)).find((candidate) => candidate.folder === folder);
|
|
2375
|
+
if (world === void 0) throw new UnknownStarterError(`there is no starter world "${folder}"`);
|
|
2376
|
+
if ((await catalog.list({ refresh: true })).worlds.some((existing) => existing.id === world.id)) throw new WorldFolderExistsError(`you already have "${world.name}"`);
|
|
2377
|
+
const target = join(catalog.directory, world.folder);
|
|
2378
|
+
if (existsSync(target)) throw new WorldFolderExistsError(`a world folder named "${world.folder}" already exists`);
|
|
2379
|
+
await mkdir(catalog.directory, { recursive: true });
|
|
2380
|
+
try {
|
|
2381
|
+
await cp(join(directory, world.folder), target, {
|
|
2382
|
+
recursive: true,
|
|
2383
|
+
errorOnExist: true,
|
|
2384
|
+
force: false
|
|
2385
|
+
});
|
|
2386
|
+
} catch (error) {
|
|
2387
|
+
await rm(target, {
|
|
2388
|
+
recursive: true,
|
|
2389
|
+
force: true
|
|
2390
|
+
});
|
|
2391
|
+
throw error;
|
|
2392
|
+
}
|
|
2393
|
+
const added = (await catalog.list({ refresh: true })).worlds.find((candidate) => candidate.id === world.id);
|
|
2394
|
+
if (added === void 0) throw new Error(`added "${world.name}" but it was not found when the catalogue refreshed`);
|
|
2395
|
+
return added;
|
|
2396
|
+
}
|
|
2397
|
+
//#endregion
|
|
2398
|
+
//#region src/host/http/routes/shared.ts
|
|
2399
|
+
/** The largest picture that can be added to a gallery. */
|
|
2400
|
+
const MAX_UPLOAD_BYTES = 20971520;
|
|
2401
|
+
/** The changes to a picture's metadata a body asks for, or what is wrong with it. */
|
|
2402
|
+
function imageUpdateOf(body) {
|
|
2403
|
+
const update = {};
|
|
2404
|
+
if (body["reusable"] !== void 0) {
|
|
2405
|
+
if (typeof body["reusable"] !== "boolean") return "reusable must be true or false";
|
|
2406
|
+
update.reusable = body["reusable"];
|
|
2407
|
+
}
|
|
2408
|
+
if (body["description"] !== void 0) {
|
|
2409
|
+
if (typeof body["description"] !== "string") return "description must be text";
|
|
2410
|
+
update.description = body["description"].trim();
|
|
2411
|
+
}
|
|
2412
|
+
if (body["tags"] !== void 0) {
|
|
2413
|
+
if (!Array.isArray(body["tags"]) || !body["tags"].every((tag) => typeof tag === "string")) return "tags must be a list of text";
|
|
2414
|
+
update.tags = body["tags"].map((tag) => tag.trim()).filter((tag) => tag !== "");
|
|
2415
|
+
}
|
|
2416
|
+
return update;
|
|
3046
2417
|
}
|
|
3047
2418
|
async function sendImage(res, image) {
|
|
3048
2419
|
res.statusCode = 200;
|
|
@@ -3068,6 +2439,11 @@ function catalogueFailure(res, error) {
|
|
|
3068
2439
|
});
|
|
3069
2440
|
throw error;
|
|
3070
2441
|
}
|
|
2442
|
+
/** The world a card is to update, when the request names one. */
|
|
2443
|
+
function updateField(body) {
|
|
2444
|
+
const value = typeof body === "object" && body !== null ? body.update : void 0;
|
|
2445
|
+
return typeof value === "string" && value.trim() !== "" ? value : void 0;
|
|
2446
|
+
}
|
|
3071
2447
|
/** The status an import failure is shown with: what is wrong with the card or the choices is the person's to fix. */
|
|
3072
2448
|
function importFailure(res, error) {
|
|
3073
2449
|
if (error instanceof ImportCardError) return sendError(res, 422, error.message);
|
|
@@ -3079,7 +2455,6 @@ function importFailure(res, error) {
|
|
|
3079
2455
|
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
3080
2456
|
throw error;
|
|
3081
2457
|
}
|
|
3082
|
-
/** Build the request handler mounted at `/${API_PREFIX}`. */
|
|
3083
2458
|
/** The language a client says it is using, or nothing when it says none. */
|
|
3084
2459
|
function languageField(value) {
|
|
3085
2460
|
if (value === void 0) return void 0;
|
|
@@ -3090,25 +2465,11 @@ function languageField(value) {
|
|
|
3090
2465
|
throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
|
|
3091
2466
|
}
|
|
3092
2467
|
}
|
|
3093
|
-
|
|
3094
|
-
|
|
3095
|
-
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
"/speech/voices": { GET: async (_req, res) => {
|
|
3099
|
-
sendJson(res, 200, await speech.voices());
|
|
3100
|
-
} },
|
|
3101
|
-
"/speech/synthesize": { POST: async (req, res) => {
|
|
3102
|
-
const body = await readJsonBody(req);
|
|
3103
|
-
if (!Array.isArray(body.parts)) return sendError(res, 400, "parts must be a list");
|
|
3104
|
-
const parts = body.parts.filter((part) => typeof part === "object" && part !== null && typeof part.text === "string");
|
|
3105
|
-
if (parts.length !== body.parts.length) return sendError(res, 400, "each speech part needs text");
|
|
3106
|
-
const audio = await speech.speak(parts);
|
|
3107
|
-
res.statusCode = 200;
|
|
3108
|
-
res.setHeader("content-type", audio.mediaType);
|
|
3109
|
-
res.setHeader("content-length", audio.bytes.length);
|
|
3110
|
-
res.end(audio.bytes);
|
|
3111
|
-
} },
|
|
2468
|
+
//#endregion
|
|
2469
|
+
//#region src/host/http/routes/worlds.ts
|
|
2470
|
+
/** The routes of the API for worlds. */
|
|
2471
|
+
function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, avatars }) {
|
|
2472
|
+
return {
|
|
3112
2473
|
"/worlds": {
|
|
3113
2474
|
GET: async (_req, res) => {
|
|
3114
2475
|
sendJson(res, 200, await worlds.list());
|
|
@@ -3133,6 +2494,126 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
|
|
|
3133
2494
|
}
|
|
3134
2495
|
}
|
|
3135
2496
|
},
|
|
2497
|
+
"/worlds/starter": {
|
|
2498
|
+
GET: async (_req, res) => {
|
|
2499
|
+
sendJson(res, 200, await starter.list());
|
|
2500
|
+
},
|
|
2501
|
+
POST: async (req, res) => {
|
|
2502
|
+
const body = await readJsonBody(req);
|
|
2503
|
+
if (typeof body.folder !== "string") return sendError(res, 400, "folder must be text");
|
|
2504
|
+
try {
|
|
2505
|
+
sendJson(res, 201, await starter.add(body.folder));
|
|
2506
|
+
} catch (error) {
|
|
2507
|
+
if (error instanceof UnknownStarterError) return sendError(res, 404, error.message);
|
|
2508
|
+
if (error instanceof WorldFolderExistsError) return sendError(res, 409, error.message);
|
|
2509
|
+
throw error;
|
|
2510
|
+
}
|
|
2511
|
+
}
|
|
2512
|
+
},
|
|
2513
|
+
"/worlds/refresh": { POST: async (_req, res) => {
|
|
2514
|
+
sendJson(res, 200, await worlds.list({ refresh: true }));
|
|
2515
|
+
} },
|
|
2516
|
+
"/worlds/authoring": { POST: async (req, res, url) => {
|
|
2517
|
+
const body = await readJsonBody(req);
|
|
2518
|
+
if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
|
|
2519
|
+
try {
|
|
2520
|
+
sendJson(res, 200, await authorWorld(url.searchParams.get("id") ?? "", body.title.trim(), languageField(body.language)));
|
|
2521
|
+
} catch (error) {
|
|
2522
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
2523
|
+
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
2524
|
+
throw error;
|
|
2525
|
+
}
|
|
2526
|
+
} },
|
|
2527
|
+
"/worlds/language": { GET: async (_req, res, url) => {
|
|
2528
|
+
try {
|
|
2529
|
+
sendJson(res, 200, { language: await translation.language(url.searchParams.get("id") ?? "") ?? null });
|
|
2530
|
+
} catch (error) {
|
|
2531
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
2532
|
+
throw error;
|
|
2533
|
+
}
|
|
2534
|
+
} },
|
|
2535
|
+
"/worlds/translate": { POST: async (req, res, url) => {
|
|
2536
|
+
const body = await readJsonBody(req);
|
|
2537
|
+
if (body.to !== "en" && body.to !== "zh") return sendError(res, 400, "to must be \"en\" or \"zh\"");
|
|
2538
|
+
if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
|
|
2539
|
+
try {
|
|
2540
|
+
sendJson(res, 200, await translation.start(url.searchParams.get("id") ?? "", body.to, body.title.trim(), languageField(body.language) ?? "en"));
|
|
2541
|
+
} catch (error) {
|
|
2542
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
2543
|
+
if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
|
|
2544
|
+
message: error.message,
|
|
2545
|
+
problems: error.problems
|
|
2546
|
+
});
|
|
2547
|
+
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
2548
|
+
throw error;
|
|
2549
|
+
}
|
|
2550
|
+
} },
|
|
2551
|
+
"/avatars": {
|
|
2552
|
+
POST: async (req, res) => {
|
|
2553
|
+
const body = await readJsonBody(req);
|
|
2554
|
+
if (typeof body.name !== "string" || body.name.trim() === "") return sendError(res, 400, "name must be text");
|
|
2555
|
+
try {
|
|
2556
|
+
sendJson(res, 201, { key: await avatars.create(body.name) });
|
|
2557
|
+
} catch (error) {
|
|
2558
|
+
if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
|
|
2559
|
+
message: error.message,
|
|
2560
|
+
problems: error.problems
|
|
2561
|
+
});
|
|
2562
|
+
throw error;
|
|
2563
|
+
}
|
|
2564
|
+
},
|
|
2565
|
+
DELETE: async (_req, res, url) => {
|
|
2566
|
+
try {
|
|
2567
|
+
await avatars.remove(url.searchParams.get("key") ?? "");
|
|
2568
|
+
sendJson(res, 200, { deleted: true });
|
|
2569
|
+
} catch (error) {
|
|
2570
|
+
if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
|
|
2571
|
+
message: error.message,
|
|
2572
|
+
problems: error.problems
|
|
2573
|
+
});
|
|
2574
|
+
throw error;
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
2577
|
+
},
|
|
2578
|
+
"/worlds/avatars": { POST: async (req, res, url) => {
|
|
2579
|
+
const body = await readJsonBody(req);
|
|
2580
|
+
if (!Array.isArray(body.avatars) || body.avatars.length === 0 || !body.avatars.every((key) => typeof key === "string")) return sendError(res, 400, "avatars must be a list of keys");
|
|
2581
|
+
try {
|
|
2582
|
+
sendJson(res, 200, { added: await avatars.addToWorld(url.searchParams.get("id") ?? "", body.avatars) });
|
|
2583
|
+
} catch (error) {
|
|
2584
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
2585
|
+
if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
|
|
2586
|
+
message: error.message,
|
|
2587
|
+
problems: error.problems
|
|
2588
|
+
});
|
|
2589
|
+
throw error;
|
|
2590
|
+
}
|
|
2591
|
+
} },
|
|
2592
|
+
"/worlds/characters": { GET: async (_req, res, url) => {
|
|
2593
|
+
try {
|
|
2594
|
+
sendJson(res, 200, await worldCharacters(url.searchParams.get("id") ?? ""));
|
|
2595
|
+
} catch (error) {
|
|
2596
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
2597
|
+
throw error;
|
|
2598
|
+
}
|
|
2599
|
+
} },
|
|
2600
|
+
"/worlds/cover": { GET: async (_req, res, url) => {
|
|
2601
|
+
const cover = await worlds.cover(url.searchParams.get("id") ?? "");
|
|
2602
|
+
if (cover === void 0) return sendError(res, 404, "no cover");
|
|
2603
|
+
res.statusCode = 200;
|
|
2604
|
+
res.setHeader("content-type", cover.contentType);
|
|
2605
|
+
res.setHeader("content-length", cover.size);
|
|
2606
|
+
res.setHeader("x-content-type-options", "nosniff");
|
|
2607
|
+
res.setHeader("cache-control", cover.version === url.searchParams.get("v") ? "private, max-age=31536000, immutable" : "no-cache");
|
|
2608
|
+
await pipeline(createReadStream(cover.file), res);
|
|
2609
|
+
} }
|
|
2610
|
+
};
|
|
2611
|
+
}
|
|
2612
|
+
//#endregion
|
|
2613
|
+
//#region src/host/http/routes/catalogue.ts
|
|
2614
|
+
/** The routes of the API for catalogue. */
|
|
2615
|
+
function catalogueRoutes({ catalogue }) {
|
|
2616
|
+
return {
|
|
3136
2617
|
"/catalogue/sources": { GET: async (_req, res) => {
|
|
3137
2618
|
try {
|
|
3138
2619
|
sendJson(res, 200, await catalogue.sources());
|
|
@@ -3251,11 +2732,13 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
|
|
|
3251
2732
|
if (typeof body.source !== "string" || typeof body.versionId !== "string" || typeof body.id !== "string") return sendError(res, 400, "source, versionId and id must be text");
|
|
3252
2733
|
try {
|
|
3253
2734
|
const language = languageField(body.language);
|
|
2735
|
+
const update = updateField(body);
|
|
3254
2736
|
sendJson(res, 201, await catalogue.convertStaged({
|
|
3255
2737
|
source: body.source,
|
|
3256
2738
|
versionId: body.versionId,
|
|
3257
2739
|
id: body.id,
|
|
3258
2740
|
choices: parseChoices(body.choices),
|
|
2741
|
+
...update === void 0 ? {} : { update },
|
|
3259
2742
|
...language === void 0 ? {} : { language }
|
|
3260
2743
|
}));
|
|
3261
2744
|
} catch (error) {
|
|
@@ -3307,23 +2790,14 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
|
|
|
3307
2790
|
} catch (error) {
|
|
3308
2791
|
return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
|
|
3309
2792
|
}
|
|
3310
|
-
} }
|
|
3311
|
-
|
|
3312
|
-
|
|
3313
|
-
|
|
3314
|
-
|
|
3315
|
-
|
|
3316
|
-
|
|
3317
|
-
|
|
3318
|
-
try {
|
|
3319
|
-
sendJson(res, 201, await starter.add(body.folder));
|
|
3320
|
-
} catch (error) {
|
|
3321
|
-
if (error instanceof UnknownStarterError) return sendError(res, 404, error.message);
|
|
3322
|
-
if (error instanceof WorldFolderExistsError) return sendError(res, 409, error.message);
|
|
3323
|
-
throw error;
|
|
3324
|
-
}
|
|
3325
|
-
}
|
|
3326
|
-
},
|
|
2793
|
+
} }
|
|
2794
|
+
};
|
|
2795
|
+
}
|
|
2796
|
+
//#endregion
|
|
2797
|
+
//#region src/host/http/routes/imports.ts
|
|
2798
|
+
/** The routes of the API for imports. */
|
|
2799
|
+
function importsRoutes({ importer }) {
|
|
2800
|
+
return {
|
|
3327
2801
|
"/worlds/import/card": { POST: async (req, res, url) => {
|
|
3328
2802
|
const name = decodeURIComponent(String(req.headers["x-file-name"] ?? url.searchParams.get("name") ?? "card"));
|
|
3329
2803
|
try {
|
|
@@ -3332,6 +2806,24 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
|
|
|
3332
2806
|
return importFailure(res, error);
|
|
3333
2807
|
}
|
|
3334
2808
|
} },
|
|
2809
|
+
"/worlds/import/update": {
|
|
2810
|
+
GET: async (_req, res, url) => {
|
|
2811
|
+
try {
|
|
2812
|
+
sendJson(res, 200, await importer.updateStatus(url.searchParams.get("id") ?? ""));
|
|
2813
|
+
} catch (error) {
|
|
2814
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
2815
|
+
throw error;
|
|
2816
|
+
}
|
|
2817
|
+
},
|
|
2818
|
+
DELETE: async (_req, res, url) => {
|
|
2819
|
+
try {
|
|
2820
|
+
sendJson(res, 200, await importer.revertUpdate(url.searchParams.get("id") ?? ""));
|
|
2821
|
+
} catch (error) {
|
|
2822
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
2823
|
+
return importFailure(res, error);
|
|
2824
|
+
}
|
|
2825
|
+
}
|
|
2826
|
+
},
|
|
3335
2827
|
"/worlds/import/preset": { POST: async (req, res, url) => {
|
|
3336
2828
|
const name = decodeURIComponent(String(req.headers["x-file-name"] ?? url.searchParams.get("name") ?? "preset"));
|
|
3337
2829
|
try {
|
|
@@ -3412,97 +2904,340 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
|
|
|
3412
2904
|
"/worlds/import/start": { POST: async (req, res, url) => {
|
|
3413
2905
|
try {
|
|
3414
2906
|
const body = await readJsonBody(req);
|
|
3415
|
-
sendJson(res, 200, await importer.start(url.searchParams.get("id") ?? "", parseChoices(body), languageField(body.language)));
|
|
2907
|
+
sendJson(res, 200, await importer.start(url.searchParams.get("id") ?? "", parseChoices(body), languageField(body.language), updateField(body)));
|
|
3416
2908
|
} catch (error) {
|
|
3417
2909
|
return importFailure(res, error);
|
|
3418
2910
|
}
|
|
3419
2911
|
} },
|
|
3420
|
-
"/worlds/import/
|
|
3421
|
-
|
|
3422
|
-
await sendImage(res, await importer.picture(url.searchParams.get("id") ?? ""));
|
|
3423
|
-
} catch (error) {
|
|
3424
|
-
return sendError(res, 404, error instanceof Error ? error.message : String(error));
|
|
3425
|
-
}
|
|
3426
|
-
} },
|
|
3427
|
-
"/worlds/refresh": { POST: async (_req, res) => {
|
|
3428
|
-
sendJson(res, 200, await worlds.list({ refresh: true }));
|
|
3429
|
-
} },
|
|
3430
|
-
"/worlds/authoring": { POST: async (req, res, url) => {
|
|
3431
|
-
const body = await readJsonBody(req);
|
|
3432
|
-
if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
|
|
3433
|
-
try {
|
|
3434
|
-
sendJson(res, 200, await authorWorld(url.searchParams.get("id") ?? "", body.title.trim(), languageField(body.language)));
|
|
3435
|
-
} catch (error) {
|
|
3436
|
-
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
3437
|
-
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
3438
|
-
throw error;
|
|
3439
|
-
}
|
|
3440
|
-
} },
|
|
3441
|
-
"/worlds/language": { GET: async (_req, res, url) => {
|
|
3442
|
-
try {
|
|
3443
|
-
sendJson(res, 200, { language: await translation.language(url.searchParams.get("id") ?? "") ?? null });
|
|
3444
|
-
} catch (error) {
|
|
3445
|
-
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
3446
|
-
throw error;
|
|
3447
|
-
}
|
|
3448
|
-
} },
|
|
3449
|
-
"/worlds/translate": { POST: async (req, res, url) => {
|
|
3450
|
-
const body = await readJsonBody(req);
|
|
3451
|
-
if (body.to !== "en" && body.to !== "zh") return sendError(res, 400, "to must be \"en\" or \"zh\"");
|
|
3452
|
-
if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
|
|
3453
|
-
try {
|
|
3454
|
-
sendJson(res, 200, await translation.start(url.searchParams.get("id") ?? "", body.to, body.title.trim(), languageField(body.language) ?? "en"));
|
|
3455
|
-
} catch (error) {
|
|
3456
|
-
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
3457
|
-
if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
|
|
3458
|
-
message: error.message,
|
|
3459
|
-
problems: error.problems
|
|
3460
|
-
});
|
|
3461
|
-
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
3462
|
-
throw error;
|
|
3463
|
-
}
|
|
3464
|
-
} },
|
|
3465
|
-
"/avatars": {
|
|
3466
|
-
POST: async (req, res) => {
|
|
3467
|
-
const body = await readJsonBody(req);
|
|
3468
|
-
if (typeof body.name !== "string" || body.name.trim() === "") return sendError(res, 400, "name must be text");
|
|
2912
|
+
"/worlds/import/draft": {
|
|
2913
|
+
GET: async (_req, res, url) => {
|
|
3469
2914
|
try {
|
|
3470
|
-
sendJson(res,
|
|
2915
|
+
sendJson(res, 200, await importer.draftStatus(url.searchParams.get("id") ?? ""));
|
|
3471
2916
|
} catch (error) {
|
|
3472
|
-
|
|
3473
|
-
message: error.message,
|
|
3474
|
-
problems: error.problems
|
|
3475
|
-
});
|
|
3476
|
-
throw error;
|
|
2917
|
+
return importFailure(res, error);
|
|
3477
2918
|
}
|
|
3478
2919
|
},
|
|
3479
|
-
|
|
2920
|
+
POST: async (req, res, url) => {
|
|
3480
2921
|
try {
|
|
3481
|
-
await
|
|
3482
|
-
|
|
2922
|
+
const body = await readJsonBody(req);
|
|
2923
|
+
if (body.action !== "ask" && body.action !== "keep" && body.action !== "discard") return sendError(res, 400, "\"action\" must be ask, keep or discard");
|
|
2924
|
+
sendJson(res, 200, await importer.actOnDraft(url.searchParams.get("id") ?? "", body.action, languageField(body.language)));
|
|
3483
2925
|
} catch (error) {
|
|
3484
|
-
|
|
3485
|
-
message: error.message,
|
|
3486
|
-
problems: error.problems
|
|
3487
|
-
});
|
|
3488
|
-
throw error;
|
|
2926
|
+
return importFailure(res, error);
|
|
3489
2927
|
}
|
|
3490
2928
|
}
|
|
3491
2929
|
},
|
|
3492
|
-
"/worlds/
|
|
3493
|
-
const body = await readJsonBody(req);
|
|
3494
|
-
if (!Array.isArray(body.avatars) || body.avatars.length === 0 || !body.avatars.every((key) => typeof key === "string")) return sendError(res, 400, "avatars must be a list of keys");
|
|
2930
|
+
"/worlds/import/resume": { POST: async (req, res, url) => {
|
|
3495
2931
|
try {
|
|
3496
|
-
|
|
2932
|
+
const body = await readJsonBody(req);
|
|
2933
|
+
sendJson(res, 200, await importer.resume(url.searchParams.get("id") ?? "", languageField(body.language)));
|
|
3497
2934
|
} catch (error) {
|
|
3498
|
-
|
|
3499
|
-
if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
|
|
3500
|
-
message: error.message,
|
|
3501
|
-
problems: error.problems
|
|
3502
|
-
});
|
|
3503
|
-
throw error;
|
|
2935
|
+
return importFailure(res, error);
|
|
3504
2936
|
}
|
|
3505
2937
|
} },
|
|
2938
|
+
"/worlds/import/picture": { GET: async (_req, res, url) => {
|
|
2939
|
+
try {
|
|
2940
|
+
await sendImage(res, await importer.picture(url.searchParams.get("id") ?? ""));
|
|
2941
|
+
} catch (error) {
|
|
2942
|
+
return sendError(res, 404, error instanceof Error ? error.message : String(error));
|
|
2943
|
+
}
|
|
2944
|
+
} }
|
|
2945
|
+
};
|
|
2946
|
+
}
|
|
2947
|
+
//#endregion
|
|
2948
|
+
//#region src/shared/world-dice.ts
|
|
2949
|
+
const isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2950
|
+
const CHECK_FIELDS = [
|
|
2951
|
+
"key",
|
|
2952
|
+
"name",
|
|
2953
|
+
"use",
|
|
2954
|
+
"dice",
|
|
2955
|
+
"reading",
|
|
2956
|
+
"hit",
|
|
2957
|
+
"compare",
|
|
2958
|
+
"modifier",
|
|
2959
|
+
"bands"
|
|
2960
|
+
];
|
|
2961
|
+
const BAND_FIELDS = [
|
|
2962
|
+
"min",
|
|
2963
|
+
"max",
|
|
2964
|
+
"label",
|
|
2965
|
+
"result",
|
|
2966
|
+
"critical"
|
|
2967
|
+
];
|
|
2968
|
+
/** Reads a body that came from the browser: the shape of every field is checked here, and what the checks mean when the world is validated. */
|
|
2969
|
+
function parseDiceEdit(value) {
|
|
2970
|
+
const problems = [];
|
|
2971
|
+
if (!isObject$1(value) || !Array.isArray(value["checks"])) throw new InvalidEditProblems(["the dice must be { checks: [...] }"]);
|
|
2972
|
+
const checks = value["checks"].map((entry, index) => {
|
|
2973
|
+
const at = `checks[${index}]`;
|
|
2974
|
+
const empty = {
|
|
2975
|
+
key: "",
|
|
2976
|
+
name: "",
|
|
2977
|
+
use: "",
|
|
2978
|
+
dice: "",
|
|
2979
|
+
bands: []
|
|
2980
|
+
};
|
|
2981
|
+
if (!isObject$1(entry)) {
|
|
2982
|
+
problems.push(`${at} must be an object`);
|
|
2983
|
+
return empty;
|
|
2984
|
+
}
|
|
2985
|
+
for (const key of Object.keys(entry)) if (!CHECK_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a check`);
|
|
2986
|
+
for (const key of [
|
|
2987
|
+
"key",
|
|
2988
|
+
"name",
|
|
2989
|
+
"use",
|
|
2990
|
+
"dice"
|
|
2991
|
+
]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
2992
|
+
if (entry["reading"] !== void 0 && !DICE_READINGS.includes(entry["reading"])) problems.push(`${at}.reading must be one of: ${DICE_READINGS.join(", ")}`);
|
|
2993
|
+
if (entry["compare"] !== void 0 && !DICE_COMPARISONS.includes(entry["compare"])) problems.push(`${at}.compare must be one of: ${DICE_COMPARISONS.join(", ")}`);
|
|
2994
|
+
if (entry["hit"] !== void 0 && (typeof entry["hit"] !== "number" || !Number.isInteger(entry["hit"]))) problems.push(`${at}.hit must be a whole number`);
|
|
2995
|
+
if (entry["modifier"] !== void 0 && typeof entry["modifier"] !== "string") problems.push(`${at}.modifier must be text`);
|
|
2996
|
+
const bands = Array.isArray(entry["bands"]) ? entry["bands"] : void 0;
|
|
2997
|
+
if (bands === void 0) problems.push(`${at}.bands must be a list`);
|
|
2998
|
+
const text = (field) => typeof field === "string" ? field.trim() : "";
|
|
2999
|
+
const hit = entry["hit"];
|
|
3000
|
+
return {
|
|
3001
|
+
key: text(entry["key"]),
|
|
3002
|
+
name: text(entry["name"]),
|
|
3003
|
+
use: text(entry["use"]),
|
|
3004
|
+
dice: text(entry["dice"]),
|
|
3005
|
+
...entry["reading"] === void 0 ? {} : { reading: entry["reading"] },
|
|
3006
|
+
...typeof hit === "number" ? { hit } : {},
|
|
3007
|
+
...entry["compare"] === void 0 ? {} : { compare: entry["compare"] },
|
|
3008
|
+
...text(entry["modifier"]) === "" ? {} : { modifier: text(entry["modifier"]) },
|
|
3009
|
+
bands: (bands ?? []).map((band, bandIndex) => {
|
|
3010
|
+
const where = `${at}.bands[${bandIndex}]`;
|
|
3011
|
+
if (!isObject$1(band)) {
|
|
3012
|
+
problems.push(`${where} must be an object`);
|
|
3013
|
+
return {
|
|
3014
|
+
label: "",
|
|
3015
|
+
result: "failed"
|
|
3016
|
+
};
|
|
3017
|
+
}
|
|
3018
|
+
for (const key of Object.keys(band)) if (!BAND_FIELDS.includes(key)) problems.push(`${where}.${key} is not a field of a band`);
|
|
3019
|
+
for (const key of ["min", "max"]) if (band[key] !== void 0 && (typeof band[key] !== "number" || !Number.isFinite(band[key]))) problems.push(`${where}.${key} must be a number`);
|
|
3020
|
+
if (typeof band["label"] !== "string") problems.push(`${where}.label must be text`);
|
|
3021
|
+
if (!DICE_RESULTS.includes(band["result"])) problems.push(`${where}.result must be one of: ${DICE_RESULTS.join(", ")}`);
|
|
3022
|
+
const min = band["min"];
|
|
3023
|
+
const max = band["max"];
|
|
3024
|
+
return {
|
|
3025
|
+
label: text(band["label"]),
|
|
3026
|
+
result: band["result"],
|
|
3027
|
+
...typeof min === "number" ? { min } : {},
|
|
3028
|
+
...typeof max === "number" ? { max } : {},
|
|
3029
|
+
...band["critical"] === true ? { critical: true } : {}
|
|
3030
|
+
};
|
|
3031
|
+
})
|
|
3032
|
+
};
|
|
3033
|
+
});
|
|
3034
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
3035
|
+
return { checks };
|
|
3036
|
+
}
|
|
3037
|
+
//#endregion
|
|
3038
|
+
//#region src/shared/world-daily.ts
|
|
3039
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3040
|
+
const ROUTINE_FIELDS = [
|
|
3041
|
+
"days",
|
|
3042
|
+
"on",
|
|
3043
|
+
"from",
|
|
3044
|
+
"to",
|
|
3045
|
+
"activity",
|
|
3046
|
+
"location",
|
|
3047
|
+
"feature",
|
|
3048
|
+
"position",
|
|
3049
|
+
"interruptible"
|
|
3050
|
+
];
|
|
3051
|
+
/**
|
|
3052
|
+
* The windows of a day as the browser sends them.
|
|
3053
|
+
* @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the times and places are acceptable is checked when the file is read back.
|
|
3054
|
+
*/
|
|
3055
|
+
function parseRoutineEdit(value) {
|
|
3056
|
+
const problems = [];
|
|
3057
|
+
const list = isObject(value) && Array.isArray(value["windows"]) ? value["windows"] : void 0;
|
|
3058
|
+
if (list === void 0) throw new InvalidEditProblems(["the day must be { windows: [...] }"]);
|
|
3059
|
+
const windows = list.map((entry, index) => {
|
|
3060
|
+
const at = `windows[${index}]`;
|
|
3061
|
+
if (!isObject(entry)) {
|
|
3062
|
+
problems.push(`${at} must be an object`);
|
|
3063
|
+
return {
|
|
3064
|
+
days: [],
|
|
3065
|
+
from: "",
|
|
3066
|
+
to: "",
|
|
3067
|
+
activity: "",
|
|
3068
|
+
interruptible: true
|
|
3069
|
+
};
|
|
3070
|
+
}
|
|
3071
|
+
for (const key of Object.keys(entry)) if (!ROUTINE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a window`);
|
|
3072
|
+
for (const key of [
|
|
3073
|
+
"from",
|
|
3074
|
+
"to",
|
|
3075
|
+
"activity"
|
|
3076
|
+
]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
3077
|
+
for (const key of [
|
|
3078
|
+
"location",
|
|
3079
|
+
"feature",
|
|
3080
|
+
"position"
|
|
3081
|
+
]) if (entry[key] !== void 0 && typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
3082
|
+
if (entry["days"] !== void 0 && !(Array.isArray(entry["days"]) && entry["days"].every((day) => typeof day === "string"))) problems.push(`${at}.days must be a list of days`);
|
|
3083
|
+
if (entry["interruptible"] !== void 0 && typeof entry["interruptible"] !== "boolean") problems.push(`${at}.interruptible must be true or false`);
|
|
3084
|
+
const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
|
|
3085
|
+
return {
|
|
3086
|
+
days: Array.isArray(entry["days"]) ? entry["days"].map((day) => day.trim().toLowerCase()).filter((day) => day !== "") : [],
|
|
3087
|
+
...Array.isArray(entry["on"]) && entry["on"].length > 0 ? { on: entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") } : {},
|
|
3088
|
+
from: text("from"),
|
|
3089
|
+
to: text("to"),
|
|
3090
|
+
activity: text("activity"),
|
|
3091
|
+
...text("location") === "" ? {} : { location: text("location") },
|
|
3092
|
+
...text("feature") === "" ? {} : { feature: text("feature") },
|
|
3093
|
+
...text("position") === "" ? {} : { position: text("position") },
|
|
3094
|
+
interruptible: entry["interruptible"] !== false
|
|
3095
|
+
};
|
|
3096
|
+
});
|
|
3097
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
3098
|
+
return windows;
|
|
3099
|
+
}
|
|
3100
|
+
const VARIABLE_FIELDS = [
|
|
3101
|
+
"key",
|
|
3102
|
+
"name",
|
|
3103
|
+
"kind",
|
|
3104
|
+
"subject",
|
|
3105
|
+
"visibility",
|
|
3106
|
+
"description",
|
|
3107
|
+
"min",
|
|
3108
|
+
"max",
|
|
3109
|
+
"integer",
|
|
3110
|
+
"baseline",
|
|
3111
|
+
"always",
|
|
3112
|
+
"default",
|
|
3113
|
+
"only",
|
|
3114
|
+
"options",
|
|
3115
|
+
"bands"
|
|
3116
|
+
];
|
|
3117
|
+
/**
|
|
3118
|
+
* The declarations as the browser sends them, with empty fields left out. Whether they are acceptable together is checked against the world's files.
|
|
3119
|
+
* @throws {InvalidEditProblems} naming every field that has the wrong shape.
|
|
3120
|
+
*/
|
|
3121
|
+
function parseVariablesEdit(value) {
|
|
3122
|
+
const problems = [];
|
|
3123
|
+
const list = isObject(value) && Array.isArray(value["variables"]) ? value["variables"] : void 0;
|
|
3124
|
+
if (list === void 0) throw new InvalidEditProblems(["the variables must be { variables: [...] }"]);
|
|
3125
|
+
const declarations = list.flatMap((entry, index) => {
|
|
3126
|
+
const at = `variables[${index}]`;
|
|
3127
|
+
if (!isObject(entry)) {
|
|
3128
|
+
problems.push(`${at} must be an object`);
|
|
3129
|
+
return [];
|
|
3130
|
+
}
|
|
3131
|
+
for (const key of Object.keys(entry)) if (!VARIABLE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a variable`);
|
|
3132
|
+
const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
|
|
3133
|
+
const number = (key) => {
|
|
3134
|
+
if (entry[key] === void 0 || entry[key] === null || entry[key] === "") return void 0;
|
|
3135
|
+
if (typeof entry[key] !== "number" || !Number.isFinite(entry[key])) {
|
|
3136
|
+
problems.push(`${at}.${key} must be a number`);
|
|
3137
|
+
return;
|
|
3138
|
+
}
|
|
3139
|
+
return entry[key];
|
|
3140
|
+
};
|
|
3141
|
+
const flag = (key) => {
|
|
3142
|
+
if (entry[key] === void 0) return void 0;
|
|
3143
|
+
if (typeof entry[key] !== "boolean") {
|
|
3144
|
+
problems.push(`${at}.${key} must be true or false`);
|
|
3145
|
+
return;
|
|
3146
|
+
}
|
|
3147
|
+
return entry[key];
|
|
3148
|
+
};
|
|
3149
|
+
const strings = (key) => {
|
|
3150
|
+
if (entry[key] === void 0) return [];
|
|
3151
|
+
if (!(Array.isArray(entry[key]) && entry[key].every((item) => typeof item === "string"))) {
|
|
3152
|
+
problems.push(`${at}.${key} must be a list of text`);
|
|
3153
|
+
return [];
|
|
3154
|
+
}
|
|
3155
|
+
return entry[key].map((item) => item.trim()).filter((item) => item !== "");
|
|
3156
|
+
};
|
|
3157
|
+
const bands = Array.isArray(entry["bands"]) ? entry["bands"].flatMap((band) => isObject(band) && typeof band["up_to"] === "number" && typeof band["label"] === "string" && band["label"].trim() !== "" ? [{
|
|
3158
|
+
up_to: band["up_to"],
|
|
3159
|
+
label: band["label"].trim()
|
|
3160
|
+
}] : (problems.push(`${at}.bands needs { up_to, label } entries`), [])) : [];
|
|
3161
|
+
const rawDefault = entry["default"];
|
|
3162
|
+
if (rawDefault !== void 0 && rawDefault !== null && rawDefault !== "" && typeof rawDefault !== "number" && typeof rawDefault !== "boolean" && typeof rawDefault !== "string") problems.push(`${at}.default must be a number, true or false, or text`);
|
|
3163
|
+
for (const [key, allowed] of [
|
|
3164
|
+
["kind", VARIABLE_KINDS],
|
|
3165
|
+
["subject", VARIABLE_SUBJECTS],
|
|
3166
|
+
["visibility", VARIABLE_VISIBILITIES]
|
|
3167
|
+
]) if (!allowed.includes(text(key))) problems.push(`${at}.${key} must be one of: ${allowed.join(", ")}`);
|
|
3168
|
+
const [min, max] = [number("min"), number("max")];
|
|
3169
|
+
const [integer, baseline, always] = [
|
|
3170
|
+
flag("integer"),
|
|
3171
|
+
flag("baseline"),
|
|
3172
|
+
flag("always")
|
|
3173
|
+
];
|
|
3174
|
+
const only = strings("only");
|
|
3175
|
+
const options = strings("options");
|
|
3176
|
+
return [{
|
|
3177
|
+
key: text("key"),
|
|
3178
|
+
name: text("name"),
|
|
3179
|
+
kind: text("kind"),
|
|
3180
|
+
subject: text("subject"),
|
|
3181
|
+
visibility: text("visibility"),
|
|
3182
|
+
...text("description") === "" ? {} : { description: text("description") },
|
|
3183
|
+
...min === void 0 ? {} : { min },
|
|
3184
|
+
...max === void 0 ? {} : { max },
|
|
3185
|
+
...integer === true ? { integer } : {},
|
|
3186
|
+
...baseline === true ? { baseline } : {},
|
|
3187
|
+
...always === true ? { always } : {},
|
|
3188
|
+
...rawDefault === void 0 || rawDefault === null || rawDefault === "" ? {} : { default: rawDefault },
|
|
3189
|
+
...only.length === 0 ? {} : { only },
|
|
3190
|
+
...options.length === 0 ? {} : { options },
|
|
3191
|
+
...bands.length === 0 ? {} : { bands }
|
|
3192
|
+
}];
|
|
3193
|
+
});
|
|
3194
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
3195
|
+
return declarations;
|
|
3196
|
+
}
|
|
3197
|
+
/**
|
|
3198
|
+
* The calendar as the browser sends it.
|
|
3199
|
+
* @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the days and ids are acceptable is checked as the file is read.
|
|
3200
|
+
*/
|
|
3201
|
+
function parseCalendarEdit(value) {
|
|
3202
|
+
const problems = [];
|
|
3203
|
+
if (!isObject(value)) throw new InvalidEditProblems(["the calendar must be { hemisphere, holidays: [...] }"]);
|
|
3204
|
+
if (value["hemisphere"] !== "north" && value["hemisphere"] !== "south") problems.push("hemisphere must be \"north\" or \"south\"");
|
|
3205
|
+
const list = Array.isArray(value["holidays"]) ? value["holidays"] : void 0;
|
|
3206
|
+
if (list === void 0) problems.push("holidays must be a list");
|
|
3207
|
+
const holidays = (list ?? []).map((entry, index) => {
|
|
3208
|
+
const at = `holidays[${index}]`;
|
|
3209
|
+
if (!isObject(entry)) {
|
|
3210
|
+
problems.push(`${at} must be an object`);
|
|
3211
|
+
return {
|
|
3212
|
+
id: "",
|
|
3213
|
+
name: "",
|
|
3214
|
+
on: []
|
|
3215
|
+
};
|
|
3216
|
+
}
|
|
3217
|
+
for (const key of Object.keys(entry)) if (![
|
|
3218
|
+
"id",
|
|
3219
|
+
"name",
|
|
3220
|
+
"on"
|
|
3221
|
+
].includes(key)) problems.push(`${at}.${key} is not a field of a holiday`);
|
|
3222
|
+
for (const key of ["id", "name"]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
3223
|
+
if (!(Array.isArray(entry["on"]) && entry["on"].every((day) => typeof day === "string"))) problems.push(`${at}.on must be a list of days`);
|
|
3224
|
+
return {
|
|
3225
|
+
id: typeof entry["id"] === "string" ? entry["id"].trim() : "",
|
|
3226
|
+
name: typeof entry["name"] === "string" ? entry["name"].trim() : "",
|
|
3227
|
+
on: Array.isArray(entry["on"]) ? entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") : []
|
|
3228
|
+
};
|
|
3229
|
+
});
|
|
3230
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
3231
|
+
return {
|
|
3232
|
+
hemisphere: value["hemisphere"],
|
|
3233
|
+
holidays
|
|
3234
|
+
};
|
|
3235
|
+
}
|
|
3236
|
+
//#endregion
|
|
3237
|
+
//#region src/host/http/routes/worldFiles.ts
|
|
3238
|
+
/** The routes of the API for worldFiles. */
|
|
3239
|
+
function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
|
|
3240
|
+
return {
|
|
3506
3241
|
"/worlds/state": { GET: async (_req, res, url) => {
|
|
3507
3242
|
try {
|
|
3508
3243
|
sendJson(res, 200, await worldEditor.read(url.searchParams.get("id") ?? ""));
|
|
@@ -3992,15 +3727,14 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
|
|
|
3992
3727
|
return sendError(res, 404, error instanceof Error ? error.message : String(error));
|
|
3993
3728
|
}
|
|
3994
3729
|
} }]
|
|
3995
|
-
]))
|
|
3996
|
-
|
|
3997
|
-
|
|
3998
|
-
|
|
3999
|
-
|
|
4000
|
-
|
|
4001
|
-
|
|
4002
|
-
|
|
4003
|
-
} },
|
|
3730
|
+
]))
|
|
3731
|
+
};
|
|
3732
|
+
}
|
|
3733
|
+
//#endregion
|
|
3734
|
+
//#region src/host/http/routes/sessions.ts
|
|
3735
|
+
/** The routes of the API for sessions. */
|
|
3736
|
+
function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
|
|
3737
|
+
return {
|
|
4004
3738
|
"/sessions": {
|
|
4005
3739
|
GET: async (_req, res) => {
|
|
4006
3740
|
sendJson(res, 200, sessions.list());
|
|
@@ -4217,6 +3951,83 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
|
|
|
4217
3951
|
res.statusCode = 204;
|
|
4218
3952
|
res.end();
|
|
4219
3953
|
} },
|
|
3954
|
+
"/sessions/activity/run": { GET: async (_req, res, url) => {
|
|
3955
|
+
try {
|
|
3956
|
+
const detail = sessions.activityRun(url.searchParams.get("id") ?? "", url.searchParams.get("run") ?? "");
|
|
3957
|
+
if (detail === void 0) return sendError(res, 404, "this run was not kept, or has been dropped to make room");
|
|
3958
|
+
sendJson(res, 200, detail);
|
|
3959
|
+
} catch (error) {
|
|
3960
|
+
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
3961
|
+
if (error instanceof RangeError) return sendError(res, 400, error.message);
|
|
3962
|
+
throw error;
|
|
3963
|
+
}
|
|
3964
|
+
} },
|
|
3965
|
+
"/sessions/doctor": { POST: async (req, res, url) => {
|
|
3966
|
+
const body = await readJsonBody(req);
|
|
3967
|
+
if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
|
|
3968
|
+
try {
|
|
3969
|
+
sendJson(res, 200, await sessions.doctor(url.searchParams.get("id") ?? "", body.title.trim(), languageField(body.language) ?? "en"));
|
|
3970
|
+
} catch (error) {
|
|
3971
|
+
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
3972
|
+
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
3973
|
+
throw error;
|
|
3974
|
+
}
|
|
3975
|
+
} },
|
|
3976
|
+
"/sessions/reflect": { POST: async (_req, res, url) => {
|
|
3977
|
+
try {
|
|
3978
|
+
await sessions.reflect(url.searchParams.get("id") ?? "");
|
|
3979
|
+
} catch (error) {
|
|
3980
|
+
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
3981
|
+
if (error instanceof ReflectionRefusedError) return sendError(res, 409, error.message);
|
|
3982
|
+
throw error;
|
|
3983
|
+
}
|
|
3984
|
+
res.statusCode = 202;
|
|
3985
|
+
res.end();
|
|
3986
|
+
} },
|
|
3987
|
+
"/sessions/vectors/reset": { POST: async (_req, res, url) => {
|
|
3988
|
+
try {
|
|
3989
|
+
sessions.resetVectors(url.searchParams.get("id") ?? "");
|
|
3990
|
+
} catch (error) {
|
|
3991
|
+
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
3992
|
+
throw error;
|
|
3993
|
+
}
|
|
3994
|
+
res.statusCode = 204;
|
|
3995
|
+
res.end();
|
|
3996
|
+
} },
|
|
3997
|
+
"/sessions/rename": { POST: async (req, res, url) => {
|
|
3998
|
+
const body = await readJsonBody(req);
|
|
3999
|
+
const name = typeof body === "object" && body !== null ? body.name : void 0;
|
|
4000
|
+
if (typeof name !== "string") return sendError(res, 400, "the request needs a \"name\"");
|
|
4001
|
+
try {
|
|
4002
|
+
await sessions.rename(url.searchParams.get("id") ?? "", name);
|
|
4003
|
+
} catch (error) {
|
|
4004
|
+
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
4005
|
+
if (error instanceof InvalidStartError) return sendError(res, 422, error.message);
|
|
4006
|
+
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
4007
|
+
throw error;
|
|
4008
|
+
}
|
|
4009
|
+
res.statusCode = 204;
|
|
4010
|
+
res.end();
|
|
4011
|
+
} },
|
|
4012
|
+
"/sessions/item": { DELETE: async (_req, res, url) => {
|
|
4013
|
+
try {
|
|
4014
|
+
await sessions.delete(url.searchParams.get("id") ?? "", url.searchParams.get("everywhere") === "true");
|
|
4015
|
+
} catch (error) {
|
|
4016
|
+
if (error instanceof SyncRefusedError || error instanceof RcloneError) return failure(res, error);
|
|
4017
|
+
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
4018
|
+
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
4019
|
+
throw error;
|
|
4020
|
+
}
|
|
4021
|
+
res.statusCode = 204;
|
|
4022
|
+
res.end();
|
|
4023
|
+
} }
|
|
4024
|
+
};
|
|
4025
|
+
}
|
|
4026
|
+
//#endregion
|
|
4027
|
+
//#region src/host/http/routes/sessionWorld.ts
|
|
4028
|
+
/** The routes of the API for sessionWorld. */
|
|
4029
|
+
function sessionWorldRoutes({ sessions }) {
|
|
4030
|
+
return {
|
|
4220
4031
|
"/sessions/world": { GET: async (_req, res, url) => {
|
|
4221
4032
|
try {
|
|
4222
4033
|
sendJson(res, 200, sessions.world(url.searchParams.get("id") ?? ""));
|
|
@@ -4347,91 +4158,26 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
|
|
|
4347
4158
|
} catch (error) {
|
|
4348
4159
|
return sendError(res, 404, error instanceof Error ? error.message : String(error));
|
|
4349
4160
|
}
|
|
4350
|
-
} }
|
|
4351
|
-
|
|
4352
|
-
|
|
4353
|
-
|
|
4354
|
-
|
|
4355
|
-
|
|
4356
|
-
|
|
4357
|
-
|
|
4358
|
-
|
|
4359
|
-
|
|
4360
|
-
|
|
4361
|
-
|
|
4362
|
-
|
|
4363
|
-
|
|
4364
|
-
|
|
4365
|
-
|
|
4366
|
-
sendJson(res, 200, await sessions.doctor(url.searchParams.get("id") ?? "", body.title.trim(), languageField(body.language) ?? "en"));
|
|
4367
|
-
} catch (error) {
|
|
4368
|
-
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
4369
|
-
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
4370
|
-
throw error;
|
|
4371
|
-
}
|
|
4372
|
-
} },
|
|
4373
|
-
"/sessions/reflect": { POST: async (_req, res, url) => {
|
|
4374
|
-
try {
|
|
4375
|
-
await sessions.reflect(url.searchParams.get("id") ?? "");
|
|
4376
|
-
} catch (error) {
|
|
4377
|
-
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
4378
|
-
if (error instanceof ReflectionRefusedError) return sendError(res, 409, error.message);
|
|
4379
|
-
throw error;
|
|
4380
|
-
}
|
|
4381
|
-
res.statusCode = 202;
|
|
4382
|
-
res.end();
|
|
4383
|
-
} },
|
|
4384
|
-
"/sessions/vectors/reset": { POST: async (_req, res, url) => {
|
|
4385
|
-
try {
|
|
4386
|
-
sessions.resetVectors(url.searchParams.get("id") ?? "");
|
|
4387
|
-
} catch (error) {
|
|
4388
|
-
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
4389
|
-
throw error;
|
|
4390
|
-
}
|
|
4391
|
-
res.statusCode = 204;
|
|
4392
|
-
res.end();
|
|
4393
|
-
} },
|
|
4394
|
-
"/sessions/rename": { POST: async (req, res, url) => {
|
|
4395
|
-
const body = await readJsonBody(req);
|
|
4396
|
-
const name = typeof body === "object" && body !== null ? body.name : void 0;
|
|
4397
|
-
if (typeof name !== "string") return sendError(res, 400, "the request needs a \"name\"");
|
|
4398
|
-
try {
|
|
4399
|
-
await sessions.rename(url.searchParams.get("id") ?? "", name);
|
|
4400
|
-
} catch (error) {
|
|
4401
|
-
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
4402
|
-
if (error instanceof InvalidStartError) return sendError(res, 422, error.message);
|
|
4403
|
-
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
4404
|
-
throw error;
|
|
4405
|
-
}
|
|
4406
|
-
res.statusCode = 204;
|
|
4407
|
-
res.end();
|
|
4408
|
-
} },
|
|
4409
|
-
"/sessions/item": { DELETE: async (_req, res, url) => {
|
|
4410
|
-
try {
|
|
4411
|
-
await sessions.delete(url.searchParams.get("id") ?? "", url.searchParams.get("everywhere") === "true");
|
|
4412
|
-
} catch (error) {
|
|
4413
|
-
if (error instanceof SyncRefusedError || error instanceof RcloneError) return failure(res, error);
|
|
4414
|
-
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
4415
|
-
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
4416
|
-
throw error;
|
|
4417
|
-
}
|
|
4418
|
-
res.statusCode = 204;
|
|
4419
|
-
res.end();
|
|
4420
|
-
} },
|
|
4161
|
+
} }
|
|
4162
|
+
};
|
|
4163
|
+
}
|
|
4164
|
+
//#endregion
|
|
4165
|
+
//#region src/host/http/api.ts
|
|
4166
|
+
/** Build the request handler mounted at `/${API_PREFIX}`. */
|
|
4167
|
+
function createApiHandler(deps) {
|
|
4168
|
+
const { packs, presets, lorebooks, sync, locked, anyLocked, connection } = deps;
|
|
4169
|
+
const routes = {
|
|
4170
|
+
...speechRoutes(deps),
|
|
4171
|
+
...worldsRoutes(deps),
|
|
4172
|
+
...catalogueRoutes(deps),
|
|
4173
|
+
...importsRoutes(deps),
|
|
4174
|
+
...worldFilesRoutes(deps),
|
|
4175
|
+
...sessionsRoutes(deps),
|
|
4176
|
+
...sessionWorldRoutes(deps),
|
|
4421
4177
|
...interfaceRoutes(packs),
|
|
4422
4178
|
...presetRoutes(presets),
|
|
4423
4179
|
...lorebookRoutes(lorebooks),
|
|
4424
|
-
...syncRoutes(sync)
|
|
4425
|
-
"/worlds/cover": { GET: async (_req, res, url) => {
|
|
4426
|
-
const cover = await worlds.cover(url.searchParams.get("id") ?? "");
|
|
4427
|
-
if (cover === void 0) return sendError(res, 404, "no cover");
|
|
4428
|
-
res.statusCode = 200;
|
|
4429
|
-
res.setHeader("content-type", cover.contentType);
|
|
4430
|
-
res.setHeader("content-length", cover.size);
|
|
4431
|
-
res.setHeader("x-content-type-options", "nosniff");
|
|
4432
|
-
res.setHeader("cache-control", cover.version === url.searchParams.get("v") ? "private, max-age=31536000, immutable" : "no-cache");
|
|
4433
|
-
await pipeline(createReadStream(cover.file), res);
|
|
4434
|
-
} }
|
|
4180
|
+
...syncRoutes(sync)
|
|
4435
4181
|
};
|
|
4436
4182
|
return async (req, res) => {
|
|
4437
4183
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
@@ -5807,7 +5553,7 @@ function worldFindings(session) {
|
|
|
5807
5553
|
async function startSession(deps, request) {
|
|
5808
5554
|
const world = await deps.worlds.find(request.worldId);
|
|
5809
5555
|
if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${request.worldId}"`);
|
|
5810
|
-
const { characters: authored, factions, locations, items, slots, authoredLore, declared, scripted, authoredPlots, calendar, checks } = await loadValidatedWorld(world);
|
|
5556
|
+
const { characters: authored, factions, locations, items, slots, authoredLore, declared, scripted, authoredPlots, calendar, checks, commands } = await loadValidatedWorld(world);
|
|
5811
5557
|
if (request.opening !== void 0 && (!Number.isInteger(request.opening) || request.opening < 0 || request.opening >= (world.alternateOpenings?.length ?? 0))) throw new InvalidStartError(`the world has no alternate opening ${String(request.opening)}`);
|
|
5812
5558
|
const opening = request.opening === void 0 ? openingOf(world, authored) : [{
|
|
5813
5559
|
type: "narration",
|
|
@@ -5922,6 +5668,7 @@ async function startSession(deps, request) {
|
|
|
5922
5668
|
populateTriggers(session, scripted.triggers);
|
|
5923
5669
|
populatePlots(session.metadata, authoredPlots.plots);
|
|
5924
5670
|
populateClock(session, settings.clock, startsAt === void 0 ? void 0 : { startingTime: startsAt }, (deps.now ?? Date.now)());
|
|
5671
|
+
if (commands.length > 0) session.metadata.setValue(COMMANDS_KEY, commands.map((command) => ({ ...command })));
|
|
5925
5672
|
if (world.rules !== void 0) session.metadata.setValue(WORLD_RULES_KEY, world.rules);
|
|
5926
5673
|
if (world.narrationVoice !== void 0) session.metadata.setValue("roleplay.tts.narrationVoice", world.narrationVoice);
|
|
5927
5674
|
});
|
|
@@ -6201,15 +5948,7 @@ async function readWorldPackFile(directory, pack, path) {
|
|
|
6201
5948
|
async function writeWorldPackFile(directory, pack, path, text) {
|
|
6202
5949
|
if (Buffer.byteLength(text) > 204800) throw new InvalidEditProblems([`a file holds at most ${MAX_PACK_TEXT / 1024} KB of text`]);
|
|
6203
5950
|
const file = placeOf(directory, pack, path, "write", text);
|
|
6204
|
-
await
|
|
6205
|
-
const temporary = join(dirname(file), `.${process.pid}.${randomUUID()}.tmp`);
|
|
6206
|
-
try {
|
|
6207
|
-
await writeFile(temporary, text);
|
|
6208
|
-
await rename(temporary, file);
|
|
6209
|
-
} catch (error) {
|
|
6210
|
-
await rm(temporary, { force: true });
|
|
6211
|
-
throw error;
|
|
6212
|
-
}
|
|
5951
|
+
await atomicWrite(file, text, { createDirectory: true });
|
|
6213
5952
|
return problemsOf(directory, pack);
|
|
6214
5953
|
}
|
|
6215
5954
|
/** 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. */
|
|
@@ -6441,16 +6180,7 @@ function withWorldId(text, id) {
|
|
|
6441
6180
|
*/
|
|
6442
6181
|
async function assignWorldId(file) {
|
|
6443
6182
|
const id = randomUUID();
|
|
6444
|
-
|
|
6445
|
-
try {
|
|
6446
|
-
const { mode } = await stat(file);
|
|
6447
|
-
await writeFile(temporary, withWorldId(await readFile(file, "utf8"), id), { mode });
|
|
6448
|
-
await chmod(temporary, mode);
|
|
6449
|
-
await rename(temporary, file);
|
|
6450
|
-
} catch (error) {
|
|
6451
|
-
await rm(temporary, { force: true });
|
|
6452
|
-
throw error;
|
|
6453
|
-
}
|
|
6183
|
+
await atomicWrite(file, withWorldId(await readFile(file, "utf8"), id));
|
|
6454
6184
|
return id;
|
|
6455
6185
|
}
|
|
6456
6186
|
//#endregion
|
|
@@ -6537,7 +6267,8 @@ async function loadWorld(folder, dir, file, problems) {
|
|
|
6537
6267
|
description: world.description,
|
|
6538
6268
|
tags: world.tags,
|
|
6539
6269
|
...world.author === void 0 ? {} : { author: world.author },
|
|
6540
|
-
...world.version === void 0 ? {} : { version: world.version }
|
|
6270
|
+
...world.version === void 0 ? {} : { version: world.version },
|
|
6271
|
+
...await isDraftWorld(dir) ? { draft: true } : {}
|
|
6541
6272
|
},
|
|
6542
6273
|
...world.opening === void 0 ? {} : { opening: world.opening },
|
|
6543
6274
|
...world.clock === void 0 ? {} : { clock: world.clock },
|
|
@@ -6676,90 +6407,6 @@ var WorldCatalog = class extends Service {
|
|
|
6676
6407
|
}
|
|
6677
6408
|
};
|
|
6678
6409
|
//#endregion
|
|
6679
|
-
//#region src/host/catalogue/origin.ts
|
|
6680
|
-
const ORIGIN_FILE = ".catalogue.json";
|
|
6681
|
-
const MAX_LISTED_CHANGES = 12;
|
|
6682
|
-
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
6683
|
-
/** The origin recorded in a world's folder, or nothing when it has none. @throws {CatalogueError} when the record is damaged. */
|
|
6684
|
-
async function readOrigin(directory) {
|
|
6685
|
-
let text;
|
|
6686
|
-
try {
|
|
6687
|
-
text = await readFile(join(directory, ORIGIN_FILE), "utf8");
|
|
6688
|
-
} catch (error) {
|
|
6689
|
-
if (error.code === "ENOENT") return void 0;
|
|
6690
|
-
throw error;
|
|
6691
|
-
}
|
|
6692
|
-
const damaged = () => new CatalogueError(`${ORIGIN_FILE} in ${directory} is damaged`, "invalid");
|
|
6693
|
-
let value;
|
|
6694
|
-
try {
|
|
6695
|
-
value = JSON.parse(text);
|
|
6696
|
-
} catch {
|
|
6697
|
-
throw damaged();
|
|
6698
|
-
}
|
|
6699
|
-
if (!isRecord(value)) throw damaged();
|
|
6700
|
-
const { kind, root, resourceId, versionId, version, files } = value;
|
|
6701
|
-
if (kind !== "release" && kind !== "card" || typeof root !== "string" || typeof resourceId !== "string" || typeof versionId !== "string" || typeof version !== "string") throw damaged();
|
|
6702
|
-
if (kind === "card") return {
|
|
6703
|
-
kind,
|
|
6704
|
-
root,
|
|
6705
|
-
resourceId,
|
|
6706
|
-
versionId,
|
|
6707
|
-
version
|
|
6708
|
-
};
|
|
6709
|
-
if (!isRecord(files) || !Object.values(files).every((hash) => typeof hash === "string")) throw damaged();
|
|
6710
|
-
return {
|
|
6711
|
-
kind,
|
|
6712
|
-
root,
|
|
6713
|
-
resourceId,
|
|
6714
|
-
versionId,
|
|
6715
|
-
version,
|
|
6716
|
-
files
|
|
6717
|
-
};
|
|
6718
|
-
}
|
|
6719
|
-
async function writeOrigin(directory, origin) {
|
|
6720
|
-
const file = join(directory, ORIGIN_FILE);
|
|
6721
|
-
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
6722
|
-
await writeFile(temporary, JSON.stringify(origin, null, 2));
|
|
6723
|
-
await rename(temporary, file);
|
|
6724
|
-
}
|
|
6725
|
-
/** 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. */
|
|
6726
|
-
async function hashWorld(directory) {
|
|
6727
|
-
const hashes = {};
|
|
6728
|
-
const walk = async (relative) => {
|
|
6729
|
-
for (const entry of await readdir(join(directory, relative), { withFileTypes: true })) {
|
|
6730
|
-
if (relative === "" && entry.name.startsWith(".")) continue;
|
|
6731
|
-
const path = relative === "" ? entry.name : `${relative}/${entry.name}`;
|
|
6732
|
-
if (entry.isDirectory()) await walk(path);
|
|
6733
|
-
else if (entry.isFile()) hashes[path] = createHash("sha256").update(await readFile(join(directory, path))).digest("hex");
|
|
6734
|
-
}
|
|
6735
|
-
};
|
|
6736
|
-
await walk("");
|
|
6737
|
-
return hashes;
|
|
6738
|
-
}
|
|
6739
|
-
function compare(recorded, current) {
|
|
6740
|
-
return {
|
|
6741
|
-
changed: Object.keys(recorded).filter((path) => current[path] !== void 0 && current[path] !== recorded[path]),
|
|
6742
|
-
added: Object.keys(current).filter((path) => recorded[path] === void 0),
|
|
6743
|
-
removed: Object.keys(recorded).filter((path) => current[path] === void 0)
|
|
6744
|
-
};
|
|
6745
|
-
}
|
|
6746
|
-
const isUnchanged = (changes) => changes.changed.length + changes.added.length + changes.removed.length === 0;
|
|
6747
|
-
/** The differences as short lines for a person to read, capped. */
|
|
6748
|
-
function describeChanges(changes) {
|
|
6749
|
-
const lines = [
|
|
6750
|
-
...changes.changed.map((path) => `changed: ${path}`),
|
|
6751
|
-
...changes.added.map((path) => `added: ${path}`),
|
|
6752
|
-
...changes.removed.map((path) => `removed: ${path}`)
|
|
6753
|
-
];
|
|
6754
|
-
return lines.length <= MAX_LISTED_CHANGES ? lines : [...lines.slice(0, MAX_LISTED_CHANGES), `and ${lines.length - MAX_LISTED_CHANGES} more`];
|
|
6755
|
-
}
|
|
6756
|
-
/** How a world's files compare with the release it came from: the differences, or `unverified` when no record of the release exists. */
|
|
6757
|
-
async function localChanges(directory) {
|
|
6758
|
-
const origin = await readOrigin(directory);
|
|
6759
|
-
if (origin?.kind !== "release") return "unverified";
|
|
6760
|
-
return compare(origin.files, await hashWorld(directory));
|
|
6761
|
-
}
|
|
6762
|
-
//#endregion
|
|
6763
6410
|
//#region src/host/catalogue/zip.ts
|
|
6764
6411
|
const END_SIGNATURE = 101010256;
|
|
6765
6412
|
const CENTRAL_SIGNATURE = 33639248;
|
|
@@ -7378,11 +7025,11 @@ var Catalogue = class {
|
|
|
7378
7025
|
const release = await this.download(this.deps.sources.get(request.source), request.versionId, CATALOGUE_CARD_TYPE, "a character card");
|
|
7379
7026
|
return await this.deps.previewCard(release.body, `${release.versionId}${isPng(release.body) ? ".png" : ".json"}`);
|
|
7380
7027
|
}
|
|
7381
|
-
/** Makes the world of a card that `stageCard` offered, with what the person chose. Like `convert`, it never replaces a world. */
|
|
7028
|
+
/** Makes the world of a card that `stageCard` offered, with what the person chose, or has the authoring chat bring the world named in `update` up to date with it. Like `convert`, it never replaces a world's files by itself. */
|
|
7382
7029
|
async convertStaged(request) {
|
|
7383
7030
|
const source = this.deps.sources.get(request.source);
|
|
7384
7031
|
const release = await this.describe(source, request.versionId, CATALOGUE_CARD_TYPE, "a character card");
|
|
7385
|
-
const converted = await this.deps.startCard(request.id, request.choices, request.language);
|
|
7032
|
+
const converted = await this.deps.startCard(request.id, request.choices, request.language, request.update);
|
|
7386
7033
|
const record = await this.deps.worlds.find(converted.worldId);
|
|
7387
7034
|
if (record === void 0) throw new CatalogueError("the world was made but cannot be found", "upstream");
|
|
7388
7035
|
await writeOrigin(record.directory, {
|
|
@@ -7740,11 +7387,23 @@ function spawnRclone(setup) {
|
|
|
7740
7387
|
child.stdin.end(options.input ?? "");
|
|
7741
7388
|
}) };
|
|
7742
7389
|
}
|
|
7743
|
-
|
|
7390
|
+
const CHANGED_IN_TRANSIT = /corrupted on transfer: sizes? differ/;
|
|
7391
|
+
/** The files rclone named as arriving a different size than the server listed, up to a few. */
|
|
7392
|
+
function changedFiles(lines) {
|
|
7393
|
+
const names = lines.flatMap((line) => {
|
|
7394
|
+
const found = /^ERROR\s*: (.+?): .*corrupted on transfer/.exec(line);
|
|
7395
|
+
return found === null ? [] : [found[1]];
|
|
7396
|
+
});
|
|
7397
|
+
return [...new Set(names)].slice(0, 3);
|
|
7398
|
+
}
|
|
7399
|
+
/** What rclone said went wrong: its last error line, without the time and the colours, cut short. A file that arrives a different size than the server listed says what usually causes it. */
|
|
7744
7400
|
function why(result) {
|
|
7745
7401
|
const lines = (result.stderr || result.stdout).split("\n").map((line) => line.replace(/\u001b\[[0-9;]*m/g, "").replace(/^\d{4}\/\d\d\/\d\d \d\d:\d\d:\d\d /, "").trim()).filter((line) => line !== "");
|
|
7746
7402
|
const line = lines.findLast((entry) => /^(ERROR|NOTICE: Failed|CRITICAL)/.test(entry)) ?? lines.at(-1) ?? `rclone stopped with code ${result.code}`;
|
|
7747
|
-
|
|
7403
|
+
const shown = line.length > 300 ? `${line.slice(0, 300)}…` : line;
|
|
7404
|
+
if (!CHANGED_IN_TRANSIT.test(line)) return shown;
|
|
7405
|
+
const files = changedFiles(lines);
|
|
7406
|
+
return `${shown} — something between this device and the server changes files on the way${files.length === 0 ? "" : ` (${files.join(", ")})`}; a proxy or CDN that adds content to HTML pages is the usual cause: turn off its response rewriting for the server, or reach the server directly`;
|
|
7748
7407
|
}
|
|
7749
7408
|
//#endregion
|
|
7750
7409
|
//#region src/host/sync/state.ts
|
|
@@ -8651,7 +8310,9 @@ const Config = z.object({
|
|
|
8651
8310
|
importReasoning: z.string().default("").volatile(),
|
|
8652
8311
|
childReasoning: z.string().default("").volatile(),
|
|
8653
8312
|
importModel: z.string().default("").volatile(),
|
|
8654
|
-
|
|
8313
|
+
importStructuredOutput: z.union(["tool", "schema"]).default("tool").volatile(),
|
|
8314
|
+
importMaxTokens: z.number().min(0).max(1e6).default(0).volatile(),
|
|
8315
|
+
importVariablesPerRequest: z.number().min(5).max(500).default(25).volatile(),
|
|
8655
8316
|
importTemperature: z.number().min(0).max(2).default(.2).volatile(),
|
|
8656
8317
|
importTimeoutMinutes: z.number().min(0).max(240).default(15).volatile(),
|
|
8657
8318
|
importDecisions: z.union([z.const("llm"), z.const("decision")]).default("llm").volatile(),
|
|
@@ -8675,7 +8336,7 @@ function apply(ctx, config) {
|
|
|
8675
8336
|
const helper = childSamplingOf(id);
|
|
8676
8337
|
if (helper !== void 0) return helper;
|
|
8677
8338
|
if (authoredWorldOf(id) !== void 0 || presetOfChat(id) !== void 0 || lorebookOfChat(id) !== void 0) return {
|
|
8678
|
-
maxTokens: config.importMaxTokens.get(),
|
|
8339
|
+
maxTokens: knownOutputCeiling(config.importMaxTokens.get()),
|
|
8679
8340
|
priority: "foreground"
|
|
8680
8341
|
};
|
|
8681
8342
|
const session = roleplaySessionOf(id);
|
|
@@ -8715,6 +8376,8 @@ function apply(ctx, config) {
|
|
|
8715
8376
|
reasoning: config.importReasoning.get() || config.childReasoning.get(),
|
|
8716
8377
|
model: config.importModel.get(),
|
|
8717
8378
|
maxTokens: config.importMaxTokens.get(),
|
|
8379
|
+
variablesPerRequest: config.importVariablesPerRequest.get(),
|
|
8380
|
+
structured: config.importStructuredOutput.get(),
|
|
8718
8381
|
temperature: config.importTemperature.get(),
|
|
8719
8382
|
timeoutMinutes: config.importTimeoutMinutes.get(),
|
|
8720
8383
|
decisions: config.importDecisions.get() === "decision" ? "decision" : "llm",
|
|
@@ -8768,6 +8431,22 @@ function apply(ctx, config) {
|
|
|
8768
8431
|
},
|
|
8769
8432
|
playing: (id) => orchestration.playing(chatSessionId(id))
|
|
8770
8433
|
});
|
|
8434
|
+
const withTargets = async (preview) => {
|
|
8435
|
+
const targets = await findTargets(worlds, preview.choices.name);
|
|
8436
|
+
return targets.length === 0 ? preview : {
|
|
8437
|
+
...preview,
|
|
8438
|
+
targets
|
|
8439
|
+
};
|
|
8440
|
+
};
|
|
8441
|
+
const begin = async (id, choices, language, update) => update === void 0 ? await startImport({
|
|
8442
|
+
store: imports,
|
|
8443
|
+
worlds,
|
|
8444
|
+
authoring
|
|
8445
|
+
}, id, choices, language) : await startUpdate({
|
|
8446
|
+
store: imports,
|
|
8447
|
+
worlds,
|
|
8448
|
+
authoring
|
|
8449
|
+
}, id, choices, update, language);
|
|
8771
8450
|
const catalogue = new Catalogue({
|
|
8772
8451
|
sources: new Sources(() => config.catalogues.get(), () => ctx.get("credentials")),
|
|
8773
8452
|
worlds,
|
|
@@ -8780,12 +8459,8 @@ function apply(ctx, config) {
|
|
|
8780
8459
|
stage: (kind, file, name) => staging.stage(kind, file, name),
|
|
8781
8460
|
importPreset: async (file, title, language) => await presetLibrary.importTitled(title, file, language),
|
|
8782
8461
|
importLorebook: async (file, title, language) => await lorebookLibrary.importTitled(title, file, language),
|
|
8783
|
-
previewCard: async (file, name) => await imports.create(readCard(file, name), isPng(file) ? pictureOf(file) : void 0),
|
|
8784
|
-
startCard:
|
|
8785
|
-
store: imports,
|
|
8786
|
-
worlds,
|
|
8787
|
-
authoring
|
|
8788
|
-
}, id, choices, language),
|
|
8462
|
+
previewCard: async (file, name) => await withTargets(await imports.create(readCard(file, name), isPng(file) ? pictureOf(file) : void 0)),
|
|
8463
|
+
startCard: begin,
|
|
8789
8464
|
importCard: async (file, name, language) => {
|
|
8790
8465
|
const preview = await imports.create(readCard(file, name), isPng(file) ? pictureOf(file) : void 0);
|
|
8791
8466
|
return await startImport({
|
|
@@ -8858,17 +8533,30 @@ function apply(ctx, config) {
|
|
|
8858
8533
|
},
|
|
8859
8534
|
upload: async (file, name) => {
|
|
8860
8535
|
const card = readCard(file, name);
|
|
8861
|
-
return await imports.create(card, isPng(file) ? pictureOf(file) : void 0);
|
|
8536
|
+
return await withTargets(await imports.create(card, isPng(file) ? pictureOf(file) : void 0));
|
|
8862
8537
|
},
|
|
8863
|
-
read: (id) => imports.read(id),
|
|
8538
|
+
read: async (id) => await withTargets(await imports.read(id)),
|
|
8864
8539
|
choose: (id, choices) => imports.choose(id, choices),
|
|
8865
8540
|
discard: (id) => imports.discard(id),
|
|
8866
|
-
start:
|
|
8867
|
-
|
|
8541
|
+
start: begin,
|
|
8542
|
+
picture: (id) => imports.picture(id),
|
|
8543
|
+
resume: (worldId, language) => resumeImport({
|
|
8868
8544
|
worlds,
|
|
8869
8545
|
authoring
|
|
8870
|
-
},
|
|
8871
|
-
|
|
8546
|
+
}, worldId, language),
|
|
8547
|
+
draftStatus: (worldId) => draftStatus(worlds, worldId),
|
|
8548
|
+
actOnDraft: (worldId, action, language) => actOnDraft({
|
|
8549
|
+
worlds,
|
|
8550
|
+
authoring,
|
|
8551
|
+
root: () => root.path
|
|
8552
|
+
}, worldId, action, language),
|
|
8553
|
+
updateStatus: async (worldId) => await updateStatus((await editableWorld(worlds, worldId, root.path)).directory),
|
|
8554
|
+
revertUpdate: async (worldId) => {
|
|
8555
|
+
const directory = (await editableWorld(worlds, worldId, root.path)).directory;
|
|
8556
|
+
const { keptIn } = await revertUpdate(directory);
|
|
8557
|
+
await worlds.list({ refresh: true });
|
|
8558
|
+
return { keptIn: relative(directory, keptIn) };
|
|
8559
|
+
},
|
|
8872
8560
|
uploadPreset: (worldId, file, name, language) => uploadPreset({
|
|
8873
8561
|
worlds,
|
|
8874
8562
|
authoring
|