@dsh-agentic-roleplay/core 0.7.2 → 0.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/lib/{authoring-tools-q34iq3hW.js → authoring-tools-CIsWbq0B.js} +197 -20
- package/lib/authoring.js +251 -331
- package/lib/client.js +613 -331
- package/lib/client.js.map +1 -1
- package/lib/doctor.js +1 -1
- package/lib/{gallery-BxZGOgMb.js → gallery-DmBZ2L5l.js} +2 -2
- package/lib/{generator-BFmSYvR8.js → generator-BmdoTIL2.js} +2 -2
- package/lib/{hooks-HnqXO8mM.js → hooks-C8eELrni.js} +2 -2
- package/lib/images.js +4 -4
- package/lib/index.js +70 -563
- package/lib/{library-BGxPKs9a.js → library-lVNf9qG_.js} +37 -4
- package/lib/{lorebook-author-tools-D9RrMK5g.js → lorebook-author-tools-BDOs4i5C.js} +6 -6
- package/lib/lorebook-authoring.js +3 -3
- package/lib/orchestration.js +8 -8
- package/lib/{pack-jail-MPekqSuQ.js → pack-jail-DeTscGT2.js} +1255 -12
- package/lib/{packs-jowC-MN_.js → packs-CY8ms8v_.js} +2 -2
- package/lib/{presenter-agent-DvZtnf0Q.js → presenter-agent-cFR4sos3.js} +4 -4
- package/lib/{preset-author-tools-8kv1Glxe.js → preset-author-tools-2m4BLtws.js} +6 -6
- package/lib/preset-authoring.js +4 -4
- package/lib/{preset-VatN-845.js → preset-n4-j6k4S.js} +2 -2
- package/lib/{reflection-CvOZGjmn.js → reflection-CJB5s0ip.js} +6 -6
- package/lib/{route-DRTJ_vcA.js → route-C6SHz9j2.js} +2 -2
- package/lib/{text-JbWfTHbr.js → text-Cwl5s0j0.js} +3 -1
- package/package.json +2 -2
|
@@ -1,20 +1,1263 @@
|
|
|
1
|
-
import "./access-DtOxFKBK.js";
|
|
2
|
-
import { At as
|
|
3
|
-
import { w as writeWorldPrompt } from "./route-
|
|
4
|
-
import { f as parseSwitchboard } from "./narration-DvFBqmqe.js";
|
|
5
|
-
import { B as loadPlots, F as STORY_LANGUAGES, G as formatIssue, H as plotReferenceProblems, I as isStoryLanguage, J as PROMPTS_FOLDER, L as textLanguage, P as LANGUAGE_NAMES, V as parsePlotsFile, at as InvalidWorldError, tt as shippedLanguages, z as PLOTS_FILE_NAME } from "./hooks-
|
|
6
|
-
import { i as translator, r as languageOf } from "./text-
|
|
1
|
+
import { a as chatSessionId } from "./access-DtOxFKBK.js";
|
|
2
|
+
import { $t as LORE_FILE_NAME, A as writePortrait, At as PICTURE_FILE, B as populateLocations, C as fetchPictures, Ct as FACTION_FILE_NAME, D as alternateOpenings, Dt as IMPORT_FOLDER, Et as parseCharacterFile, Ft as WORLD_FILE_NAME, It as parseWorldFile, K as TRIGGERS_FILE_NAME, M as knowsCharacter, Nt as readImportFolder, O as cardCharacter, P as populateCharacters, Pt as writeChoices, Q as loadCalendar, Qt as loadLore, R as populateItems, S as candidateUrls, St as parseItemFile, T as mergeReports, Tt as CHARACTER_FILE_NAME, W as populateVariables, Zt as LORE_DIR, at as loadFactions, b as addressKey, bn as authoringChatSessionId, bt as parseLocationFile, c as importPhase, ct as extractStyleFrom, d as editsSince, en as parseLoreFile, et as LOCATIONS_DIR, f as writeSnapshot, ft as itemise, gt as loadVariables, i as contextOf, it as FACTIONS_DIR, j as loadValidatedWorld, jt as openingText, k as openingMessage, lt as sourcesFor, mt as withPlayer, nn as InvalidEditProblems, nt as ITEMS_DIR, ot as CHARACTERS_DIR, q as loadTriggers, rt as loadItems, s as worldOf, st as loadCharacters, tn as subfolders, tt as loadLocations, ut as findEntity, wt as parseFactionFile, x as addressesToFetch, xt as ITEM_FILE_NAME, yn as authoredWorldOf, yt as LOCATION_FILE_NAME } from "./authoring-tools-CIsWbq0B.js";
|
|
3
|
+
import { w as writeWorldPrompt } from "./route-C6SHz9j2.js";
|
|
4
|
+
import { f as parseSwitchboard, n as encodeOutput } from "./narration-DvFBqmqe.js";
|
|
5
|
+
import { B as loadPlots, F as STORY_LANGUAGES, G as formatIssue, H as plotReferenceProblems, I as isStoryLanguage, J as PROMPTS_FOLDER, L as textLanguage, P as LANGUAGE_NAMES, V as parsePlotsFile, at as InvalidWorldError, lt as WorldNotFoundError, rt as AgentUnavailableError, tt as shippedLanguages, z as PLOTS_FILE_NAME } from "./hooks-C8eELrni.js";
|
|
6
|
+
import { i as translator, r as languageOf } from "./text-Cwl5s0j0.js";
|
|
7
7
|
import { u as parseSampling } from "./child-CyCViUKa.js";
|
|
8
|
-
import {
|
|
9
|
-
import { n as readPreset } from "./preset-
|
|
10
|
-
import { _ as API_PREFIX, a as packIds, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId } from "./packs-
|
|
11
|
-
import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-
|
|
8
|
+
import { b as mapLimit, h as readImageFileMetadata, u as referenceImagePath, x as norm } from "./library-lVNf9qG_.js";
|
|
9
|
+
import { n as readPreset } from "./preset-n4-j6k4S.js";
|
|
10
|
+
import { _ as API_PREFIX, a as packIds, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId } from "./packs-CY8ms8v_.js";
|
|
11
|
+
import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-BmdoTIL2.js";
|
|
12
12
|
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
13
13
|
import { existsSync, lstatSync, statSync } from "node:fs";
|
|
14
14
|
import { randomUUID } from "node:crypto";
|
|
15
|
+
import { Session, SessionId } from "@deepseek-ai/dsh-session";
|
|
16
|
+
import { ToolCallId, createMessage, createSystemMessage, createToolResultMessage } from "@deepseek-ai/dsh-llm";
|
|
17
|
+
import { setApprovalPolicy } from "@deepseek-ai/dsh-user-approval";
|
|
15
18
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
16
19
|
import { chmod, cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
17
20
|
import { createSessionStore, readTriggerDefinition, triggerReferenceProblems, writeCalendar } from "@dsh-agentic-roleplay/state";
|
|
21
|
+
//#region src/host/agent/opening.ts
|
|
22
|
+
/** What the opening is reported to come from, where a chat shows the source of a message. */
|
|
23
|
+
const OPENING_SOURCE = {
|
|
24
|
+
provider: "roleplay",
|
|
25
|
+
model: "opening"
|
|
26
|
+
};
|
|
27
|
+
const AUTHORING_OPENING_SOURCE = {
|
|
28
|
+
provider: "world-authoring",
|
|
29
|
+
model: "opening"
|
|
30
|
+
};
|
|
31
|
+
const DOCTOR_OPENING_SOURCE = {
|
|
32
|
+
provider: "session-doctor",
|
|
33
|
+
model: "opening"
|
|
34
|
+
};
|
|
35
|
+
const NARRATE_TOOL = "narrate";
|
|
36
|
+
/**
|
|
37
|
+
* The first node of a conversation's surface is the system prompt, even an empty one: the log format refuses a system prompt that
|
|
38
|
+
* arrives after other nodes, which is what a chat that starts with an opening would otherwise get at its first real turn. The agent
|
|
39
|
+
* replaces this empty head with the real prompt then.
|
|
40
|
+
*/
|
|
41
|
+
function reservePromptHead(session, turn, step) {
|
|
42
|
+
session.append("system/message", {
|
|
43
|
+
turn,
|
|
44
|
+
step,
|
|
45
|
+
message: createSystemMessage("")
|
|
46
|
+
}, { surfaceOp: "append" });
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* One finished turn in which the output was delivered the way every turn delivers it (a `narrate` call and its result), so it renders
|
|
50
|
+
* 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.
|
|
51
|
+
*/
|
|
52
|
+
function appendNarratedTurn(session, turn, output, player) {
|
|
53
|
+
const step = 1;
|
|
54
|
+
const callId = ToolCallId(player === void 0 ? "opening-narrate" : `narrate-${turn}`);
|
|
55
|
+
const sent = output.segments.map((segment) => segment.type === "utterance" ? {
|
|
56
|
+
type: "utterance",
|
|
57
|
+
character: segment.character,
|
|
58
|
+
text: segment.text
|
|
59
|
+
} : {
|
|
60
|
+
type: "narration",
|
|
61
|
+
text: segment.text
|
|
62
|
+
});
|
|
63
|
+
const args = JSON.stringify({ segments: sent });
|
|
64
|
+
const started = session.append("turn/start", { turn });
|
|
65
|
+
session.append("step/start", {
|
|
66
|
+
turn,
|
|
67
|
+
step
|
|
68
|
+
});
|
|
69
|
+
let asked;
|
|
70
|
+
if (player === void 0) reservePromptHead(session, turn, step);
|
|
71
|
+
else asked = session.append("user/message", createMessage({
|
|
72
|
+
role: "user",
|
|
73
|
+
content: [{
|
|
74
|
+
type: "text",
|
|
75
|
+
text: player
|
|
76
|
+
}],
|
|
77
|
+
source: { kind: "user" }
|
|
78
|
+
}), { surfaceOp: "append" }).seq;
|
|
79
|
+
session.append("assistant/message", {
|
|
80
|
+
stream: [],
|
|
81
|
+
turn,
|
|
82
|
+
step,
|
|
83
|
+
message: createMessage({
|
|
84
|
+
role: "assistant",
|
|
85
|
+
content: [{
|
|
86
|
+
type: "tool-call",
|
|
87
|
+
id: callId,
|
|
88
|
+
name: NARRATE_TOOL,
|
|
89
|
+
arguments: args
|
|
90
|
+
}],
|
|
91
|
+
source: {
|
|
92
|
+
kind: "model",
|
|
93
|
+
...OPENING_SOURCE
|
|
94
|
+
}
|
|
95
|
+
})
|
|
96
|
+
}, { surfaceOp: "append" });
|
|
97
|
+
const call = session.append("tool/call", {
|
|
98
|
+
turn,
|
|
99
|
+
step,
|
|
100
|
+
callId,
|
|
101
|
+
name: NARRATE_TOOL,
|
|
102
|
+
arguments: args
|
|
103
|
+
});
|
|
104
|
+
session.append("tool/result", {
|
|
105
|
+
turn,
|
|
106
|
+
step,
|
|
107
|
+
message: createToolResultMessage({
|
|
108
|
+
callId,
|
|
109
|
+
content: [{
|
|
110
|
+
type: "text",
|
|
111
|
+
text: `The output has been delivered to the player. The turn ends here.\n${encodeOutput(output)}`
|
|
112
|
+
}],
|
|
113
|
+
isError: false
|
|
114
|
+
})
|
|
115
|
+
}, {
|
|
116
|
+
surfaceOp: "append",
|
|
117
|
+
sourceEventSeqs: [call.seq]
|
|
118
|
+
});
|
|
119
|
+
session.append("step/end", {
|
|
120
|
+
turn,
|
|
121
|
+
step
|
|
122
|
+
});
|
|
123
|
+
const ended = session.append("turn/end", {
|
|
124
|
+
turn,
|
|
125
|
+
reason: { kind: "completed" }
|
|
126
|
+
});
|
|
127
|
+
return {
|
|
128
|
+
startSeq: started.seq,
|
|
129
|
+
...asked === void 0 ? {} : { userSeq: asked },
|
|
130
|
+
endSeq: ended.seq
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
/** A turn in which nothing was said and nothing was delivered, to keep the log's turns consecutive. */
|
|
134
|
+
function appendEmptyTurn(session, turn) {
|
|
135
|
+
session.append("turn/start", { turn });
|
|
136
|
+
session.append("turn/end", {
|
|
137
|
+
turn,
|
|
138
|
+
reason: { kind: "completed" }
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* 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.
|
|
143
|
+
*/
|
|
144
|
+
function openingEvents(segments) {
|
|
145
|
+
const session = Session.create(SessionId("opening"));
|
|
146
|
+
appendNarratedTurn(session, 1, {
|
|
147
|
+
segments: [...segments],
|
|
148
|
+
repaired: false
|
|
149
|
+
});
|
|
150
|
+
return session.snapshotEvents();
|
|
151
|
+
}
|
|
152
|
+
/** A visible first turn makes a newly created authoring chat a full conversation immediately. */
|
|
153
|
+
function authoringOpeningEvents(welcome, source = AUTHORING_OPENING_SOURCE) {
|
|
154
|
+
const session = Session.create(SessionId("authoring-opening"));
|
|
155
|
+
setApprovalPolicy(session, "ask");
|
|
156
|
+
const turn = 1;
|
|
157
|
+
const step = 1;
|
|
158
|
+
session.append("turn/start", { turn });
|
|
159
|
+
session.append("step/start", {
|
|
160
|
+
turn,
|
|
161
|
+
step
|
|
162
|
+
});
|
|
163
|
+
reservePromptHead(session, turn, step);
|
|
164
|
+
session.append("assistant/message", {
|
|
165
|
+
stream: [],
|
|
166
|
+
turn,
|
|
167
|
+
step,
|
|
168
|
+
message: createMessage({
|
|
169
|
+
role: "assistant",
|
|
170
|
+
content: [{
|
|
171
|
+
type: "text",
|
|
172
|
+
text: welcome
|
|
173
|
+
}],
|
|
174
|
+
source: {
|
|
175
|
+
kind: "model",
|
|
176
|
+
...source
|
|
177
|
+
}
|
|
178
|
+
})
|
|
179
|
+
}, { surfaceOp: "append" });
|
|
180
|
+
session.append("step/end", {
|
|
181
|
+
turn,
|
|
182
|
+
step
|
|
183
|
+
});
|
|
184
|
+
session.append("turn/end", {
|
|
185
|
+
turn,
|
|
186
|
+
reason: { kind: "completed" }
|
|
187
|
+
});
|
|
188
|
+
return session.snapshotEvents();
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Store a chat that already holds its opening, before any agent exists for it.
|
|
192
|
+
* The agent loop reads its turn counter from the log when it is built, so the
|
|
193
|
+
* opening has to be in the stored log by then: the chat is then adopted by id.
|
|
194
|
+
*/
|
|
195
|
+
async function storeOpening(persistence, chat, segments, events = openingEvents(segments)) {
|
|
196
|
+
await storeInitialEvents(persistence, chat, events);
|
|
197
|
+
}
|
|
198
|
+
async function storeAuthoringOpening(persistence, chat, welcome) {
|
|
199
|
+
await storeInitialEvents(persistence, chat, authoringOpeningEvents(welcome));
|
|
200
|
+
}
|
|
201
|
+
async function storeDoctorOpening(persistence, chat, welcome) {
|
|
202
|
+
await storeInitialEvents(persistence, chat, authoringOpeningEvents(welcome, DOCTOR_OPENING_SOURCE));
|
|
203
|
+
}
|
|
204
|
+
async function storeInitialEvents(persistence, chat, events) {
|
|
205
|
+
const header = {
|
|
206
|
+
version: 4,
|
|
207
|
+
id: SessionId(chat.id),
|
|
208
|
+
createdAt: Date.now(),
|
|
209
|
+
cwd: chat.cwd,
|
|
210
|
+
isSeeded: false,
|
|
211
|
+
agentPreset: chat.agentPreset
|
|
212
|
+
};
|
|
213
|
+
const handle = await persistence.create(header);
|
|
214
|
+
try {
|
|
215
|
+
await handle.append(events);
|
|
216
|
+
await handle.flush();
|
|
217
|
+
} finally {
|
|
218
|
+
await handle.close();
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
//#endregion
|
|
222
|
+
//#region src/host/agent/agent-sessions.ts
|
|
223
|
+
/** Title of the DSH project that groups every roleplay chat. */
|
|
224
|
+
const PROJECT_TITLE = "Roleplay";
|
|
225
|
+
/** The agent preset roleplay chats run under; it is declared by the bundle. */
|
|
226
|
+
const AGENT_PRESET = "roleplay";
|
|
227
|
+
async function isStored(persistence, sessionId) {
|
|
228
|
+
return persistence?.stat !== void 0 && await persistence.stat(SessionId(sessionId)) !== void 0;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* 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
|
|
232
|
+
* 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
|
|
233
|
+
* attached to the project, and only a chat that does not exist is created.
|
|
234
|
+
*/
|
|
235
|
+
async function ensureAgentChat(services, request, knownProject) {
|
|
236
|
+
const project = knownProject ?? await services.registry.create(request.projectPath, request.projectTitle);
|
|
237
|
+
const existed = project.sessionIds.includes(request.sessionId);
|
|
238
|
+
if (!existed) {
|
|
239
|
+
if (await isStored(services.persistence, request.sessionId)) await project.attachSession(request.sessionId);
|
|
240
|
+
else {
|
|
241
|
+
const { sessionId } = await services.controller.create({
|
|
242
|
+
workspaceId: project.id,
|
|
243
|
+
sessionId: request.sessionId,
|
|
244
|
+
agentPreset: request.agentPreset
|
|
245
|
+
});
|
|
246
|
+
if (sessionId !== request.sessionId) throw new Error(`DSH made the chat "${sessionId}" instead of "${request.sessionId}", so the chat cannot be found again`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
if (!existed || request.renameExisting === true) await services.controller.rename({
|
|
250
|
+
sessionId: request.sessionId,
|
|
251
|
+
title: request.title
|
|
252
|
+
});
|
|
253
|
+
return request.sessionId;
|
|
254
|
+
}
|
|
255
|
+
/** Looks the services up on first use: profiles without the web app do not have them. */
|
|
256
|
+
function agentServicesOf(ctx) {
|
|
257
|
+
return () => {
|
|
258
|
+
const controller = ctx.get("sessionController");
|
|
259
|
+
const registry = ctx.get("workspaceRegistry");
|
|
260
|
+
if (controller === void 0 || registry === void 0) throw new AgentUnavailableError("this DSH profile has no session services, so a roleplay chat cannot be opened");
|
|
261
|
+
const persistence = ctx.get("sessionPersistence");
|
|
262
|
+
const agents = ctx.get("agents");
|
|
263
|
+
return {
|
|
264
|
+
controller,
|
|
265
|
+
registry,
|
|
266
|
+
...persistence === void 0 ? {} : { persistence },
|
|
267
|
+
...agents === void 0 ? {} : { unload: unloader(agents) }
|
|
268
|
+
};
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
/** DSH has no call to unload an agent; disposing its scope is what its own teardown (a closed log, a released registration) hangs from. */
|
|
272
|
+
function unloader(agents) {
|
|
273
|
+
return async (chat) => {
|
|
274
|
+
const live = agents.get(chat);
|
|
275
|
+
if (live === void 0) return;
|
|
276
|
+
await (live.scope.rawDispose ?? live.scope.dispose.bind(live.scope))();
|
|
277
|
+
for (let waited = 0; agents.get(chat) !== void 0; waited += 50) {
|
|
278
|
+
if (waited >= 5e3) throw new Error(`the chat ${chat} is still loaded and cannot be replaced`);
|
|
279
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Gives roleplay sessions a DSH chat. All chats share one project whose folder
|
|
285
|
+
* is the roleplay root, because DSH groups a session under a project only when
|
|
286
|
+
* the session's working folder is the project's folder.
|
|
287
|
+
*/
|
|
288
|
+
var AgentSessions = class {
|
|
289
|
+
services;
|
|
290
|
+
projectPath;
|
|
291
|
+
constructor(services, projectPath) {
|
|
292
|
+
this.services = services;
|
|
293
|
+
this.projectPath = projectPath;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Create the chat of a roleplay session unless it exists; returns its DSH session id.
|
|
297
|
+
* @param title - the name to give a chat that is new; one that exists keeps its own.
|
|
298
|
+
* @param opening - what a chat that is new opens with: narration and lines of its characters, shown before the player says anything.
|
|
299
|
+
* @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).
|
|
300
|
+
* @throws {AgentUnavailableError} when there is an opening and no way to store it.
|
|
301
|
+
*/
|
|
302
|
+
async ensure(sessionId, title, opening, events) {
|
|
303
|
+
const services = this.services();
|
|
304
|
+
const { registry, persistence } = services;
|
|
305
|
+
const project = await registry.create(this.projectPath(), PROJECT_TITLE);
|
|
306
|
+
const wanted = chatSessionId(sessionId);
|
|
307
|
+
const existed = project.sessionIds.includes(wanted);
|
|
308
|
+
const stored = opening !== void 0 && !existed && await isStored(persistence, wanted);
|
|
309
|
+
if (opening !== void 0 && !existed && !stored) {
|
|
310
|
+
if (persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store a chat with an opening message");
|
|
311
|
+
await services.unload?.(wanted);
|
|
312
|
+
await storeOpening(persistence, {
|
|
313
|
+
id: wanted,
|
|
314
|
+
cwd: project.path,
|
|
315
|
+
agentPreset: AGENT_PRESET
|
|
316
|
+
}, opening, events);
|
|
317
|
+
}
|
|
318
|
+
return await ensureAgentChat(services, {
|
|
319
|
+
projectPath: project.path,
|
|
320
|
+
projectTitle: PROJECT_TITLE,
|
|
321
|
+
sessionId: wanted,
|
|
322
|
+
agentPreset: AGENT_PRESET,
|
|
323
|
+
title
|
|
324
|
+
}, project);
|
|
325
|
+
}
|
|
326
|
+
/** Whether the chat of a session exists on this installation: in the project, or stored and waiting to be attached. */
|
|
327
|
+
async has(sessionId) {
|
|
328
|
+
const { registry, persistence } = this.services();
|
|
329
|
+
const project = await registry.create(this.projectPath(), PROJECT_TITLE);
|
|
330
|
+
const wanted = chatSessionId(sessionId);
|
|
331
|
+
return project.sessionIds.includes(wanted) || await isStored(persistence, wanted);
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* 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
|
|
335
|
+
* 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.
|
|
336
|
+
*/
|
|
337
|
+
async replace(sessionId, title, events, purge) {
|
|
338
|
+
const { controller, registry, persistence, unload } = this.services();
|
|
339
|
+
if (persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store a chat");
|
|
340
|
+
const project = await registry.create(this.projectPath(), PROJECT_TITLE);
|
|
341
|
+
const chat = chatSessionId(sessionId);
|
|
342
|
+
await unload?.(chat);
|
|
343
|
+
await purge(chat);
|
|
344
|
+
await storeInitialEvents(persistence, {
|
|
345
|
+
id: chat,
|
|
346
|
+
cwd: project.path,
|
|
347
|
+
agentPreset: AGENT_PRESET
|
|
348
|
+
}, events);
|
|
349
|
+
await controller.rename({
|
|
350
|
+
sessionId: chat,
|
|
351
|
+
title
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
/** 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`). */
|
|
355
|
+
async send(sessionId, text) {
|
|
356
|
+
await this.services().controller.prompt({
|
|
357
|
+
requestId: randomUUID(),
|
|
358
|
+
sessionId: chatSessionId(sessionId),
|
|
359
|
+
mode: "queue",
|
|
360
|
+
content: [{
|
|
361
|
+
type: "text",
|
|
362
|
+
text
|
|
363
|
+
}]
|
|
364
|
+
}, new AbortController().signal);
|
|
365
|
+
}
|
|
366
|
+
/** Give the chat of a session a new title. A chat that was never created has none to change. */
|
|
367
|
+
async rename(sessionId, title) {
|
|
368
|
+
const { controller, registry } = this.services();
|
|
369
|
+
const project = await registry.create(this.projectPath(), PROJECT_TITLE);
|
|
370
|
+
const chat = chatSessionId(sessionId);
|
|
371
|
+
if (project.sessionIds.includes(chat)) await controller.rename({
|
|
372
|
+
sessionId: chat,
|
|
373
|
+
title
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
/** Put the chat away: hidden and stopped, and kept; a chat that was never created is nothing to put away. */
|
|
377
|
+
async archive(sessionId) {
|
|
378
|
+
await this.retire(sessionId);
|
|
379
|
+
}
|
|
380
|
+
/** 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. */
|
|
381
|
+
async restore(sessionId) {
|
|
382
|
+
try {
|
|
383
|
+
await this.services().registry.unarchiveSession(chatSessionId(sessionId));
|
|
384
|
+
} catch (error) {
|
|
385
|
+
if (!(error instanceof Error && error.name === "WorkspaceUnknownSessionError")) throw error;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
/** Hide the chat and stop its work; a chat that was never created is nothing to retire. */
|
|
389
|
+
async retire(sessionId) {
|
|
390
|
+
try {
|
|
391
|
+
await this.services().registry.archiveSession(chatSessionId(sessionId), { stopActivity: true });
|
|
392
|
+
} catch (error) {
|
|
393
|
+
if (!(error instanceof Error && error.name === "WorkspaceUnknownSessionError")) throw error;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
//#endregion
|
|
398
|
+
//#region src/host/agent/authoring-sessions.ts
|
|
399
|
+
const AUTHORING_PROJECT_TITLE = "World Authoring";
|
|
400
|
+
const AUTHORING_AGENT_PRESET = "world-authoring";
|
|
401
|
+
/** The title of a world's authoring chat, in the language of the person who opened it. */
|
|
402
|
+
function authoringTitle(worldName, language) {
|
|
403
|
+
return translator(languageOf(language))("Authoring {name}", { name: worldName });
|
|
404
|
+
}
|
|
405
|
+
/** Creates or reopens the dedicated authoring chat of an authored world, and speaks in it for the person when asked to. */
|
|
406
|
+
var AuthoringSessions = class {
|
|
407
|
+
services;
|
|
408
|
+
roleplayRoot;
|
|
409
|
+
prompts;
|
|
410
|
+
languages;
|
|
411
|
+
constructor(services, roleplayRoot, prompts, languages) {
|
|
412
|
+
this.services = services;
|
|
413
|
+
this.roleplayRoot = roleplayRoot;
|
|
414
|
+
this.prompts = prompts;
|
|
415
|
+
this.languages = languages;
|
|
416
|
+
}
|
|
417
|
+
async ensure(worldId, worldName, title, language) {
|
|
418
|
+
const chatTitle = title ?? authoringTitle(worldName, language);
|
|
419
|
+
this.languages.set(worldId, language);
|
|
420
|
+
const services = this.services();
|
|
421
|
+
const projectPath = join(this.roleplayRoot(), "worlds");
|
|
422
|
+
const project = await services.registry.create(projectPath, AUTHORING_PROJECT_TITLE);
|
|
423
|
+
const sessionId = authoringChatSessionId(worldId);
|
|
424
|
+
const existed = project.sessionIds.includes(sessionId);
|
|
425
|
+
const stored = !existed && await isStored(services.persistence, sessionId);
|
|
426
|
+
if (!existed && !stored) {
|
|
427
|
+
if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of an authoring chat");
|
|
428
|
+
await storeAuthoringOpening(services.persistence, {
|
|
429
|
+
id: sessionId,
|
|
430
|
+
cwd: project.path,
|
|
431
|
+
agentPreset: AUTHORING_AGENT_PRESET
|
|
432
|
+
}, this.prompts.text("world/welcome", this.languages.get(worldId), { world: worldName }));
|
|
433
|
+
}
|
|
434
|
+
return await ensureAgentChat(services, {
|
|
435
|
+
projectPath,
|
|
436
|
+
projectTitle: AUTHORING_PROJECT_TITLE,
|
|
437
|
+
sessionId,
|
|
438
|
+
agentPreset: AUTHORING_AGENT_PRESET,
|
|
439
|
+
title: chatTitle,
|
|
440
|
+
renameExisting: true
|
|
441
|
+
}, project);
|
|
442
|
+
}
|
|
443
|
+
/** Sends a message into a chat as if the person had written it. */
|
|
444
|
+
async send(sessionId, text) {
|
|
445
|
+
await this.services().controller.prompt({
|
|
446
|
+
requestId: randomUUID(),
|
|
447
|
+
sessionId,
|
|
448
|
+
mode: "queue",
|
|
449
|
+
content: [{
|
|
450
|
+
type: "text",
|
|
451
|
+
text
|
|
452
|
+
}]
|
|
453
|
+
}, new AbortController().signal);
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
//#endregion
|
|
457
|
+
//#region src/host/import/card-tools.ts
|
|
458
|
+
/** The most of a piece one `card_read` returns; a long lorebook entry is read in turns. */
|
|
459
|
+
const READ_CHARS = 6e3;
|
|
460
|
+
const SNIPPET_CHARS = 240;
|
|
461
|
+
const DEFAULT_HITS = 8;
|
|
462
|
+
const MAX_HITS = 20;
|
|
463
|
+
const baseId = (id) => id.replace(/#\d+$/, "");
|
|
464
|
+
/** The folder inside `.import` where a newer version of the card waits to be applied to the world. */
|
|
465
|
+
const UPDATE_FOLDER = "update";
|
|
466
|
+
/** Everything the card holds, in the order the card has it. */
|
|
467
|
+
function cardPieces(card, choices) {
|
|
468
|
+
const read = new Set(itemise(card, choices).map((item) => baseId(item.id)));
|
|
469
|
+
const field = (id, label, text) => text.trim() === "" ? [] : [{
|
|
470
|
+
id,
|
|
471
|
+
label,
|
|
472
|
+
title: "",
|
|
473
|
+
keys: [],
|
|
474
|
+
text,
|
|
475
|
+
used: read.has(id)
|
|
476
|
+
}];
|
|
477
|
+
return [
|
|
478
|
+
...field("field:description", "description", card.description),
|
|
479
|
+
...field("field:personality", "personality", card.personality),
|
|
480
|
+
...field("field:scenario", "scenario", card.scenario),
|
|
481
|
+
...field("field:example", "example messages", card.messageExample),
|
|
482
|
+
...field("field:first-message", "first message", card.firstMessage),
|
|
483
|
+
...card.alternateGreetings.flatMap((text, index) => field(`field:greeting-${index + 1}`, `alternate greeting ${index + 1}`, text)),
|
|
484
|
+
...field("field:creator-notes", "creator's notes", card.creatorNotes),
|
|
485
|
+
...field("field:system-prompt", "system prompt", card.systemPrompt),
|
|
486
|
+
...field("field:post-history", "post-history instructions", card.postHistoryInstructions),
|
|
487
|
+
...(card.book?.entries ?? []).filter((entry) => entry.content.trim() !== "").map((entry) => ({
|
|
488
|
+
id: entry.id,
|
|
489
|
+
label: entry.title === "" ? entry.id : `entry “${entry.title}”`,
|
|
490
|
+
title: entry.title,
|
|
491
|
+
keys: entry.keys,
|
|
492
|
+
text: entry.content,
|
|
493
|
+
used: read.has(entry.id),
|
|
494
|
+
enabled: entry.enabled
|
|
495
|
+
}))
|
|
496
|
+
];
|
|
497
|
+
}
|
|
498
|
+
async function optional(file) {
|
|
499
|
+
try {
|
|
500
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
501
|
+
} catch (error) {
|
|
502
|
+
if (error.code === "ENOENT") return void 0;
|
|
503
|
+
throw error;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
/** The card kept in a world's import folder, and what the import made of it. The tools exist as long as the card does. */
|
|
507
|
+
async function readSource(directory, withRecords, version = "current") {
|
|
508
|
+
const folder = join(directory, IMPORT_FOLDER);
|
|
509
|
+
let read;
|
|
510
|
+
try {
|
|
511
|
+
read = await readImportFolder(version === "new" ? join(folder, UPDATE_FOLDER) : folder);
|
|
512
|
+
} catch (error) {
|
|
513
|
+
if (error.code === "ENOENT") throw new Error(version === "new" ? "no newer version of the card is waiting to update this world" : "this world has no source card: it was not imported from one, or its .import folder was removed");
|
|
514
|
+
throw error;
|
|
515
|
+
}
|
|
516
|
+
const records = withRecords && version === "current" ? {
|
|
517
|
+
classified: await optional(join(folder, "classification.json")),
|
|
518
|
+
roster: await optional(join(folder, "roster.json")),
|
|
519
|
+
report: await optional(join(folder, "report.json"))
|
|
520
|
+
} : {};
|
|
521
|
+
return {
|
|
522
|
+
card: read.card,
|
|
523
|
+
choices: read.choices,
|
|
524
|
+
pieces: cardPieces(read.card, read.choices),
|
|
525
|
+
records
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
const rolesOf = (classified, id) => {
|
|
529
|
+
if (classified === void 0) return [];
|
|
530
|
+
return [...new Set(Object.entries(classified).filter(([key]) => baseId(key) === id).flatMap(([, entry]) => entry.roles))];
|
|
531
|
+
};
|
|
532
|
+
function snippet(text, at, length) {
|
|
533
|
+
const start = Math.max(0, at - Math.floor((SNIPPET_CHARS - length) / 2));
|
|
534
|
+
const end = Math.min(text.length, start + SNIPPET_CHARS);
|
|
535
|
+
return `${start > 0 ? "…" : ""}${text.slice(start, end).replace(/\s+/g, " ")}${end < text.length ? "…" : ""}`;
|
|
536
|
+
}
|
|
537
|
+
function searchPieces(pieces, query, limit) {
|
|
538
|
+
const phrase = query.trim().toLowerCase();
|
|
539
|
+
if (phrase === "") return [];
|
|
540
|
+
const words = [...new Set(phrase.split(/[\s,;,、]+/).filter((word) => word.length >= (/^[\x00-\x7f]+$/.test(word) ? 3 : 2)))];
|
|
541
|
+
const count = (text, needle) => {
|
|
542
|
+
let n = 0;
|
|
543
|
+
let first = -1;
|
|
544
|
+
for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + needle.length)) {
|
|
545
|
+
n += 1;
|
|
546
|
+
if (first < 0) first = at;
|
|
547
|
+
}
|
|
548
|
+
return {
|
|
549
|
+
n,
|
|
550
|
+
first
|
|
551
|
+
};
|
|
552
|
+
};
|
|
553
|
+
const look = (text) => {
|
|
554
|
+
const lowered = text.toLowerCase();
|
|
555
|
+
const whole = count(lowered, phrase);
|
|
556
|
+
if (whole.n > 0) return {
|
|
557
|
+
matches: whole.n,
|
|
558
|
+
score: whole.n * 4 + 100,
|
|
559
|
+
at: whole.first,
|
|
560
|
+
length: phrase.length
|
|
561
|
+
};
|
|
562
|
+
const found = words.map((word) => ({
|
|
563
|
+
word,
|
|
564
|
+
...count(lowered, word)
|
|
565
|
+
})).filter((entry) => entry.n > 0);
|
|
566
|
+
if (found.length === 0) return void 0;
|
|
567
|
+
const best = found.reduce((a, b) => a.first <= b.first ? a : b, found[0]);
|
|
568
|
+
return {
|
|
569
|
+
matches: found.reduce((sum, entry) => sum + entry.n, 0),
|
|
570
|
+
score: found.length * 10 + found.reduce((sum, entry) => sum + entry.n, 0),
|
|
571
|
+
at: best.first,
|
|
572
|
+
length: best.word.length
|
|
573
|
+
};
|
|
574
|
+
};
|
|
575
|
+
return pieces.flatMap((piece) => {
|
|
576
|
+
const inText = look(piece.text);
|
|
577
|
+
if (inText !== void 0) return [{
|
|
578
|
+
piece,
|
|
579
|
+
in: "text",
|
|
580
|
+
matches: inText.matches,
|
|
581
|
+
score: inText.score,
|
|
582
|
+
snippet: snippet(piece.text, inText.at, inText.length)
|
|
583
|
+
}];
|
|
584
|
+
const head = [piece.title, ...piece.keys].filter((part) => part !== "").join(" · ");
|
|
585
|
+
const inHead = look(head);
|
|
586
|
+
return inHead === void 0 ? [] : [{
|
|
587
|
+
piece,
|
|
588
|
+
in: "title or keys",
|
|
589
|
+
matches: inHead.matches,
|
|
590
|
+
score: inHead.score - 50,
|
|
591
|
+
snippet: `${piece.title === "" ? "" : `title: ${piece.title}`}${piece.keys.length === 0 ? "" : `${piece.title === "" ? "" : "; "}keys: ${piece.keys.join(", ")}`}`
|
|
592
|
+
}];
|
|
593
|
+
}).sort((a, b) => b.score - a.score).slice(0, limit).map(({ piece, matches, in: where, snippet: text }) => ({
|
|
594
|
+
piece,
|
|
595
|
+
matches,
|
|
596
|
+
in: where,
|
|
597
|
+
snippet: text
|
|
598
|
+
}));
|
|
599
|
+
}
|
|
600
|
+
const versionParameter = {
|
|
601
|
+
type: "string",
|
|
602
|
+
enum: ["current", "new"],
|
|
603
|
+
description: "current (the default) is the card the world was made from; new is the newer version waiting to update it, when card_diff says there is one. Piece ids are those of that version."
|
|
604
|
+
};
|
|
605
|
+
const output = {
|
|
606
|
+
schema: { type: "json" },
|
|
607
|
+
render: (_args, value) => [{
|
|
608
|
+
type: "text",
|
|
609
|
+
text: JSON.stringify(value, null, 1)
|
|
610
|
+
}]
|
|
611
|
+
};
|
|
612
|
+
const json = (value) => JSON.parse(JSON.stringify(value));
|
|
613
|
+
const idOf = (exec) => {
|
|
614
|
+
const chat = exec.agent?.session.id;
|
|
615
|
+
const world = chat === void 0 ? void 0 : authoredWorldOf(chat);
|
|
616
|
+
if (world === void 0) throw new Error("this tool is available only in a world authoring chat");
|
|
617
|
+
return world;
|
|
618
|
+
};
|
|
619
|
+
/**
|
|
620
|
+
* Read-only tools over the card a world was imported from, which stays in the world's `.import` folder: they work while that folder holds the card and say so when it does not.
|
|
621
|
+
* `records` adds what the import made of the card (the role of each piece, who it was used for); it is off only when a test compares the agent with and without it.
|
|
622
|
+
*/
|
|
623
|
+
function cardTools(worlds, options = {}) {
|
|
624
|
+
const withRecords = options.records !== false;
|
|
625
|
+
const source = async (exec, version = "current") => {
|
|
626
|
+
const id = idOf(exec);
|
|
627
|
+
const record = await worlds.find(id);
|
|
628
|
+
if (record === void 0) throw new Error(`the authored world "${id}" no longer exists`);
|
|
629
|
+
return await readSource(record.directory, withRecords, version);
|
|
630
|
+
};
|
|
631
|
+
const versionOf = (value) => {
|
|
632
|
+
if (value === void 0 || value === "current") return "current";
|
|
633
|
+
if (value === "new") return "new";
|
|
634
|
+
throw new Error("version must be current or new");
|
|
635
|
+
};
|
|
636
|
+
const find = (pieces, id) => {
|
|
637
|
+
const found = pieces.find((piece) => piece.id === id);
|
|
638
|
+
if (found === void 0) throw new Error(`the card has no piece "${id}": use an id from card_overview or card_search`);
|
|
639
|
+
return found;
|
|
640
|
+
};
|
|
641
|
+
return [
|
|
642
|
+
defineTool({
|
|
643
|
+
name: "card_overview",
|
|
644
|
+
description: "The card this world was imported from, which is kept: its name, creator and tags, every piece of it (field, greeting or lorebook entry) with its size, and, from the import's own records, what each piece was taken to be and which characters, places and things were made from it. Start here when the person asks where something in the world came from.",
|
|
645
|
+
parameters: {},
|
|
646
|
+
output,
|
|
647
|
+
isConcurrencySafe: () => true,
|
|
648
|
+
async execute(_args, exec) {
|
|
649
|
+
const { card, choices, pieces, records } = await source(exec);
|
|
650
|
+
const madeFrom = entitiesByPiece({
|
|
651
|
+
card,
|
|
652
|
+
choices,
|
|
653
|
+
pieces,
|
|
654
|
+
records
|
|
655
|
+
});
|
|
656
|
+
const made = (id) => madeFrom.get(id) ?? [];
|
|
657
|
+
return json({
|
|
658
|
+
card: {
|
|
659
|
+
name: card.name,
|
|
660
|
+
creator: card.creator,
|
|
661
|
+
version: card.characterVersion,
|
|
662
|
+
tags: card.tags,
|
|
663
|
+
format: card.sourceSpec,
|
|
664
|
+
ignoredScripts: card.ignored.scripts
|
|
665
|
+
},
|
|
666
|
+
pieces: pieces.map((piece) => ({
|
|
667
|
+
id: piece.id,
|
|
668
|
+
label: piece.label,
|
|
669
|
+
characters: piece.text.length,
|
|
670
|
+
readByTheImport: piece.used,
|
|
671
|
+
...piece.enabled === void 0 ? {} : { switchedOnInCard: piece.enabled },
|
|
672
|
+
...withRecords ? {
|
|
673
|
+
takenToBe: rolesOf(records.classified, piece.id),
|
|
674
|
+
madeInto: made(piece.id)
|
|
675
|
+
} : {}
|
|
676
|
+
})),
|
|
677
|
+
...records.roster === void 0 ? {} : { imported: records.roster.map((entity) => ({
|
|
678
|
+
name: entity.name,
|
|
679
|
+
kind: entity.kind,
|
|
680
|
+
aliases: entity.aliases,
|
|
681
|
+
playedByThePlayer: entity.player
|
|
682
|
+
})) },
|
|
683
|
+
...records.report === void 0 ? {} : {
|
|
684
|
+
importNotes: records.report.notes,
|
|
685
|
+
leftOut: records.report.leftOut
|
|
686
|
+
},
|
|
687
|
+
note: "The import's records are its own judgement and can be wrong or incomplete; check them against the text of the piece with card_read."
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
}),
|
|
691
|
+
defineTool({
|
|
692
|
+
name: "card_search",
|
|
693
|
+
description: "Searches everything the card says (fields, greetings, lorebook entries and their keys) for a name or phrase and returns the pieces that contain it, best first, each with a short snippet and whether it was found in the text or only in the title or keys of an entry. A hit is a pointer, not evidence: read the piece with card_read before you answer from it.",
|
|
694
|
+
parameters: {
|
|
695
|
+
query: {
|
|
696
|
+
type: "string",
|
|
697
|
+
required: true,
|
|
698
|
+
description: "A name or phrase to look for, in the card's own language."
|
|
699
|
+
},
|
|
700
|
+
version: versionParameter,
|
|
701
|
+
limit: {
|
|
702
|
+
type: "number",
|
|
703
|
+
description: `How many pieces to return, at most ${MAX_HITS} (default ${DEFAULT_HITS}).`
|
|
704
|
+
}
|
|
705
|
+
},
|
|
706
|
+
output,
|
|
707
|
+
isConcurrencySafe: () => true,
|
|
708
|
+
async execute(args, exec) {
|
|
709
|
+
const { pieces } = await source(exec, versionOf(args.version));
|
|
710
|
+
const limit = Math.min(MAX_HITS, Math.max(1, Math.floor(typeof args.limit === "number" && Number.isFinite(args.limit) ? args.limit : DEFAULT_HITS)));
|
|
711
|
+
const hits = searchPieces(pieces, args.query, limit);
|
|
712
|
+
return json({
|
|
713
|
+
query: args.query,
|
|
714
|
+
found: hits.length,
|
|
715
|
+
hits: hits.map(({ piece, matches, in: where, snippet: text }) => ({
|
|
716
|
+
piece: piece.id,
|
|
717
|
+
label: piece.label,
|
|
718
|
+
matches,
|
|
719
|
+
foundIn: where,
|
|
720
|
+
snippet: text
|
|
721
|
+
}))
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
}),
|
|
725
|
+
defineTool({
|
|
726
|
+
name: "card_read",
|
|
727
|
+
description: `The text of one piece of the card, word for word as the card has it (the card's own placeholders such as {{user}} included). A long piece is read in turns of ${READ_CHARS} characters: when "next" is given, call again with that offset.`,
|
|
728
|
+
parameters: {
|
|
729
|
+
piece: {
|
|
730
|
+
type: "string",
|
|
731
|
+
required: true,
|
|
732
|
+
description: "A piece id from card_overview, card_search or card_diff, such as field:description or entry:3."
|
|
733
|
+
},
|
|
734
|
+
version: versionParameter,
|
|
735
|
+
offset: {
|
|
736
|
+
type: "number",
|
|
737
|
+
description: "Where to start reading, in characters (default 0)."
|
|
738
|
+
}
|
|
739
|
+
},
|
|
740
|
+
output,
|
|
741
|
+
isConcurrencySafe: () => true,
|
|
742
|
+
async execute(args, exec) {
|
|
743
|
+
const { pieces } = await source(exec, versionOf(args.version));
|
|
744
|
+
const piece = find(pieces, args.piece);
|
|
745
|
+
const from = Math.min(piece.text.length, Math.max(0, Math.floor(typeof args.offset === "number" && Number.isFinite(args.offset) ? args.offset : 0)));
|
|
746
|
+
const to = Math.min(piece.text.length, from + READ_CHARS);
|
|
747
|
+
return json({
|
|
748
|
+
piece: piece.id,
|
|
749
|
+
label: piece.label,
|
|
750
|
+
...piece.keys.length === 0 ? {} : { keys: piece.keys },
|
|
751
|
+
from,
|
|
752
|
+
to,
|
|
753
|
+
of: piece.text.length,
|
|
754
|
+
...to < piece.text.length ? { next: to } : {},
|
|
755
|
+
text: piece.text.slice(from, to)
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
}),
|
|
759
|
+
defineTool({
|
|
760
|
+
name: "card_origin",
|
|
761
|
+
description: "Where a character, place, organisation or thing of this world came from: the pieces of the card the import read to make it (the pieces about it first, then those that only mention it), with what each was taken to be. For a name the import did not make anything of, the pieces of the card that mention it. Then read the pieces with card_read to answer from their text.",
|
|
762
|
+
parameters: { name: {
|
|
763
|
+
type: "string",
|
|
764
|
+
required: true,
|
|
765
|
+
description: "The name or an alias, as the world or the card has it."
|
|
766
|
+
} },
|
|
767
|
+
output,
|
|
768
|
+
isConcurrencySafe: () => true,
|
|
769
|
+
async execute(args, exec) {
|
|
770
|
+
const { card, choices, pieces, records } = await source(exec);
|
|
771
|
+
const entity = records.roster === void 0 ? void 0 : findEntity(records.roster, args.name);
|
|
772
|
+
if (entity === void 0 || records.classified === void 0) return json({
|
|
773
|
+
name: args.name,
|
|
774
|
+
madeByTheImport: false,
|
|
775
|
+
mentions: searchPieces(pieces, args.name, DEFAULT_HITS).map(({ piece, in: where, snippet: text }) => ({
|
|
776
|
+
piece: piece.id,
|
|
777
|
+
label: piece.label,
|
|
778
|
+
foundIn: where,
|
|
779
|
+
snippet: text
|
|
780
|
+
}))
|
|
781
|
+
});
|
|
782
|
+
return json({
|
|
783
|
+
name: entity.name,
|
|
784
|
+
kind: entity.kind,
|
|
785
|
+
aliases: entity.aliases,
|
|
786
|
+
madeByTheImport: true,
|
|
787
|
+
usedPieces: originOf(card, choices, pieces, records, entity.name).map((entry) => ({
|
|
788
|
+
piece: entry.piece,
|
|
789
|
+
label: entry.label,
|
|
790
|
+
how: entry.how,
|
|
791
|
+
takenToBe: rolesOf(records.classified, entry.piece)
|
|
792
|
+
}))
|
|
793
|
+
});
|
|
794
|
+
}
|
|
795
|
+
})
|
|
796
|
+
];
|
|
797
|
+
}
|
|
798
|
+
/** For each piece of the card, the names of the characters, places and things the import made from it. */
|
|
799
|
+
function entitiesByPiece(source) {
|
|
800
|
+
const made = /* @__PURE__ */ new Map();
|
|
801
|
+
for (const entity of source.records.roster ?? []) for (const entry of originOf(source.card, source.choices, source.pieces, source.records, entity.name)) made.set(entry.piece, [...made.get(entry.piece) ?? [], entity.name]);
|
|
802
|
+
return made;
|
|
803
|
+
}
|
|
804
|
+
/** The pieces an entity was made from, as the build chose them: the ones the survey said are about it, then those that name it. */
|
|
805
|
+
function originOf(card, choices, pieces, records, name) {
|
|
806
|
+
if (records.roster === void 0 || records.classified === void 0) return [];
|
|
807
|
+
const entity = findEntity(records.roster, name);
|
|
808
|
+
if (entity === void 0) return [];
|
|
809
|
+
const names = [entity.name, ...entity.aliases].map(norm);
|
|
810
|
+
const items = itemise(card, choices);
|
|
811
|
+
const chosen = sourcesFor(entity, items, records.classified);
|
|
812
|
+
const about = (id) => (records.classified?.[id]?.targets ?? []).some((target) => target.kind === entity.kind && names.includes(norm(target.name)));
|
|
813
|
+
const seen = /* @__PURE__ */ new Set();
|
|
814
|
+
return chosen.flatMap((item) => {
|
|
815
|
+
const id = baseId(item.id);
|
|
816
|
+
const piece = pieces.find((entry) => entry.id === id);
|
|
817
|
+
if (piece === void 0 || seen.has(id)) return [];
|
|
818
|
+
seen.add(id);
|
|
819
|
+
return [{
|
|
820
|
+
piece: id,
|
|
821
|
+
label: piece.label,
|
|
822
|
+
how: about(item.id) ? "about it" : "mentions it"
|
|
823
|
+
}];
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
//#endregion
|
|
827
|
+
//#region src/host/import/card-diff.ts
|
|
828
|
+
const MAX_SEGMENTS = 1500;
|
|
829
|
+
const MAX_HUNK_CHARS = 700;
|
|
830
|
+
/** Entries that kept neither their title nor their keys count as the same one only when this much of their words is shared. */
|
|
831
|
+
const SAME_ENTRY = .5;
|
|
832
|
+
const normalised = (text) => text.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
|
|
833
|
+
const entryHead = (piece) => normalised([piece.title, ...piece.keys].join("|"));
|
|
834
|
+
const words = (text) => new Set(text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []);
|
|
835
|
+
function overlap$1(a, b) {
|
|
836
|
+
const first = words(a);
|
|
837
|
+
const second = words(b);
|
|
838
|
+
if (first.size === 0 && second.size === 0) return 1;
|
|
839
|
+
let shared = 0;
|
|
840
|
+
for (const word of first) if (second.has(word)) shared += 1;
|
|
841
|
+
return shared / (first.size + second.size - shared);
|
|
842
|
+
}
|
|
843
|
+
/**
|
|
844
|
+
* Which piece of the old card is which piece of the new one. Fields and greetings are the same by their id; lorebook entries are numbered by position, which an edit
|
|
845
|
+
* shifts, so they are found by what they are called and keyed on, then by their text, and only then by the number.
|
|
846
|
+
*/
|
|
847
|
+
function matchPieces(before, after) {
|
|
848
|
+
const pairs = [];
|
|
849
|
+
const left = new Map(before.map((piece) => [piece.id, piece]));
|
|
850
|
+
const right = new Map(after.map((piece) => [piece.id, piece]));
|
|
851
|
+
const pair = (a, b) => {
|
|
852
|
+
pairs.push({
|
|
853
|
+
before: a,
|
|
854
|
+
after: b
|
|
855
|
+
});
|
|
856
|
+
left.delete(a.id);
|
|
857
|
+
right.delete(b.id);
|
|
858
|
+
};
|
|
859
|
+
const isEntry = (piece) => piece.id.startsWith("entry:");
|
|
860
|
+
for (const piece of before) {
|
|
861
|
+
const other = right.get(piece.id);
|
|
862
|
+
if (!isEntry(piece) && other !== void 0) pair(piece, other);
|
|
863
|
+
}
|
|
864
|
+
const unmatched = (map) => [...map.values()].filter(isEntry);
|
|
865
|
+
for (const keyOf of [entryHead, (piece) => normalised(piece.text)]) {
|
|
866
|
+
const taken = /* @__PURE__ */ new Set();
|
|
867
|
+
for (const piece of unmatched(left)) {
|
|
868
|
+
const key = keyOf(piece);
|
|
869
|
+
if (key === "" || key === "|") continue;
|
|
870
|
+
const candidates = unmatched(right).filter((other) => !taken.has(other.id) && keyOf(other) === key);
|
|
871
|
+
const same = candidates.find((other) => other.id === piece.id) ?? candidates[0];
|
|
872
|
+
if (same !== void 0) {
|
|
873
|
+
taken.add(same.id);
|
|
874
|
+
pair(piece, same);
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
for (const piece of unmatched(left)) {
|
|
879
|
+
const other = right.get(piece.id);
|
|
880
|
+
if (other !== void 0 && overlap$1(piece.text, other.text) >= SAME_ENTRY) pair(piece, other);
|
|
881
|
+
}
|
|
882
|
+
const order = new Map(before.map((piece, index) => [piece.id, index]));
|
|
883
|
+
return {
|
|
884
|
+
pairs: pairs.sort((a, b) => (order.get(a.before.id) ?? 0) - (order.get(b.before.id) ?? 0)),
|
|
885
|
+
added: [...right.values()],
|
|
886
|
+
removed: [...left.values()]
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
/** The sentences and lines of a text, each with the whitespace that follows it, so that joining them gives the text back. */
|
|
890
|
+
function segments(text) {
|
|
891
|
+
const parts = [];
|
|
892
|
+
const endings = ".!?。!?\n";
|
|
893
|
+
let start = 0;
|
|
894
|
+
let at = 0;
|
|
895
|
+
while (at < text.length) {
|
|
896
|
+
if (!endings.includes(text[at])) {
|
|
897
|
+
at += 1;
|
|
898
|
+
continue;
|
|
899
|
+
}
|
|
900
|
+
while (at < text.length && endings.includes(text[at])) at += 1;
|
|
901
|
+
while (at < text.length && /\s/u.test(text[at])) at += 1;
|
|
902
|
+
parts.push(text.slice(start, at));
|
|
903
|
+
start = at;
|
|
904
|
+
}
|
|
905
|
+
if (start < text.length) parts.push(text.slice(start));
|
|
906
|
+
return parts;
|
|
907
|
+
}
|
|
908
|
+
const shorten = (text) => {
|
|
909
|
+
const clean = text.replace(/\s+/g, " ").trim();
|
|
910
|
+
return clean.length <= MAX_HUNK_CHARS ? clean : `${clean.slice(0, MAX_HUNK_CHARS)}…`;
|
|
911
|
+
};
|
|
912
|
+
/** Where two versions of a text differ, sentence by sentence; nothing when they are the same, and undefined when the texts are too long to compare (read both then). */
|
|
913
|
+
function diffText(before, after) {
|
|
914
|
+
if (before === after) return [];
|
|
915
|
+
const a = segments(before).map((part) => part.trim());
|
|
916
|
+
const b = segments(after).map((part) => part.trim());
|
|
917
|
+
if (a.length > MAX_SEGMENTS || b.length > MAX_SEGMENTS) return void 0;
|
|
918
|
+
const width = b.length + 1;
|
|
919
|
+
const table = new Uint16Array((a.length + 1) * width);
|
|
920
|
+
for (let i = a.length - 1; i >= 0; i -= 1) for (let j = b.length - 1; j >= 0; j -= 1) table[i * width + j] = a[i] === b[j] ? table[(i + 1) * width + j + 1] + 1 : Math.max(table[(i + 1) * width + j], table[i * width + j + 1]);
|
|
921
|
+
const hunks = [];
|
|
922
|
+
let i = 0;
|
|
923
|
+
let j = 0;
|
|
924
|
+
let last;
|
|
925
|
+
let removed = [];
|
|
926
|
+
let added = [];
|
|
927
|
+
let before_;
|
|
928
|
+
const close = () => {
|
|
929
|
+
if (removed.length + added.length === 0) return;
|
|
930
|
+
hunks.push({
|
|
931
|
+
...before_ === void 0 ? {} : { after: shorten(before_) },
|
|
932
|
+
removed: shorten(removed.join(" ")),
|
|
933
|
+
added: shorten(added.join(" "))
|
|
934
|
+
});
|
|
935
|
+
removed = [];
|
|
936
|
+
added = [];
|
|
937
|
+
};
|
|
938
|
+
while (i < a.length || j < b.length) {
|
|
939
|
+
if (i < a.length && j < b.length && a[i] === b[j]) {
|
|
940
|
+
close();
|
|
941
|
+
last = a[i];
|
|
942
|
+
before_ = last;
|
|
943
|
+
i += 1;
|
|
944
|
+
j += 1;
|
|
945
|
+
continue;
|
|
946
|
+
}
|
|
947
|
+
if (removed.length + added.length === 0) before_ = last;
|
|
948
|
+
if (j < b.length && (i === a.length || table[i * width + j + 1] >= table[(i + 1) * width + j])) {
|
|
949
|
+
added.push(b[j]);
|
|
950
|
+
j += 1;
|
|
951
|
+
} else {
|
|
952
|
+
removed.push(a[i]);
|
|
953
|
+
i += 1;
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
close();
|
|
957
|
+
return hunks;
|
|
958
|
+
}
|
|
959
|
+
/** What differs in what the card says about itself rather than in its pieces. */
|
|
960
|
+
function cardChanges(before, after) {
|
|
961
|
+
const lines = [];
|
|
962
|
+
const compare = (label, a, b) => {
|
|
963
|
+
if (a !== b) lines.push(`${label}: “${shorten(a)}” → “${shorten(b)}”`);
|
|
964
|
+
};
|
|
965
|
+
compare("name", before.name, after.name);
|
|
966
|
+
compare("creator", before.creator, after.creator);
|
|
967
|
+
compare("version", before.characterVersion, after.characterVersion);
|
|
968
|
+
compare("tags", before.tags.join(", "), after.tags.join(", "));
|
|
969
|
+
return lines;
|
|
970
|
+
}
|
|
971
|
+
/** What the newer card changes that the world keeps in its own file (the fields edit_world_info sets) rather than in a character, place, thing or entry. */
|
|
972
|
+
function worldFieldChanges(before, after) {
|
|
973
|
+
const changes = [];
|
|
974
|
+
const differ = (a, b) => a.trim() !== b.trim();
|
|
975
|
+
if (differ(before.card.description, after.card.description) || differ(before.card.scenario, after.card.scenario) || differ(before.card.creatorNotes, after.card.creatorNotes)) changes.push({
|
|
976
|
+
field: "description",
|
|
977
|
+
because: "the card's description, scenario or creator's notes changed, and the world's description summarises them"
|
|
978
|
+
});
|
|
979
|
+
if (before.card.tags.join("\n") !== after.card.tags.join("\n")) changes.push({
|
|
980
|
+
field: "tags",
|
|
981
|
+
because: `the card\'s tags are now: ${after.card.tags.join(", ") || "(none)"}; the world\'s tags follow them, and you add none of your own`
|
|
982
|
+
});
|
|
983
|
+
if (differ(before.card.creator, after.card.creator)) changes.push({
|
|
984
|
+
field: "authorName",
|
|
985
|
+
because: `the card\'s creator is now “${after.card.creator}”`
|
|
986
|
+
});
|
|
987
|
+
if (differ(openingText(before.card, before.choices.opening) ?? "", openingText(after.card, after.choices.opening) ?? "")) changes.push({
|
|
988
|
+
field: "opening",
|
|
989
|
+
because: "the greeting the world opens with changed; suggested is the new greeting as the import writes an opening (plain paragraphs, the card's markup removed, the player named by the world's player character where the card says {{user}})",
|
|
990
|
+
suggested: openingMessage(openingText(after.card, after.choices.opening) ?? "", after.card.name)
|
|
991
|
+
});
|
|
992
|
+
if (JSON.stringify(alternateOpenings(before.card, before.choices.opening)) !== JSON.stringify(alternateOpenings(after.card, after.choices.opening))) changes.push({
|
|
993
|
+
field: "alternateOpenings",
|
|
994
|
+
because: "the card's other greetings changed; suggested is the whole list as the import writes it",
|
|
995
|
+
suggested: alternateOpenings(after.card, after.choices.opening)
|
|
996
|
+
});
|
|
997
|
+
return changes;
|
|
998
|
+
}
|
|
999
|
+
//#endregion
|
|
1000
|
+
//#region src/host/import/update.ts
|
|
1001
|
+
const PREVIOUS_FOLDER = "previous";
|
|
1002
|
+
const CLASSIFICATION = "classification.json";
|
|
1003
|
+
const sameName = (a, b) => a.normalize("NFKC").trim().toLowerCase() === b.normalize("NFKC").trim().toLowerCase();
|
|
1004
|
+
const exists = (path) => stat(path).then(() => true, () => false);
|
|
1005
|
+
/** Whether a world holds the card it was made from and its import is over: the only kind of world a newer card can update. */
|
|
1006
|
+
async function importedFromCard(directory) {
|
|
1007
|
+
if (!await exists(join(directory, ".import", "card.json"))) return false;
|
|
1008
|
+
const phase = await importPhase(directory);
|
|
1009
|
+
return phase === void 0 || phase === "done";
|
|
1010
|
+
}
|
|
1011
|
+
/** What the editor of a world needs to know to offer a card update, or to undo the last one. */
|
|
1012
|
+
async function updateStatus(directory) {
|
|
1013
|
+
return {
|
|
1014
|
+
fromCard: await importedFromCard(directory),
|
|
1015
|
+
revertible: await canRevert(directory),
|
|
1016
|
+
waiting: await pendingUpdate(directory)
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
/** Whether a newer card is waiting to update the world. */
|
|
1020
|
+
const pendingUpdate = (directory) => exists(join(directory, IMPORT_FOLDER, UPDATE_FOLDER, "card.json"));
|
|
1021
|
+
/** How many worlds one upload offers to update: a person with more than this has other things to worry about. */
|
|
1022
|
+
const MAX_TARGETS = 50;
|
|
1023
|
+
/** The worlds made from a card whose import is over: what a newer card can update, the ones with the card's name first, and whether anyone has changed each since. */
|
|
1024
|
+
async function findTargets(worlds, name) {
|
|
1025
|
+
const targets = [];
|
|
1026
|
+
for (const summary of (await worlds.list()).worlds) {
|
|
1027
|
+
const record = await worlds.find(summary.id);
|
|
1028
|
+
if (record === void 0 || !await importedFromCard(record.directory)) continue;
|
|
1029
|
+
const edits = await editsSince(record.directory);
|
|
1030
|
+
targets.push({
|
|
1031
|
+
worldId: summary.id,
|
|
1032
|
+
name: summary.name,
|
|
1033
|
+
sameName: sameName(summary.name, name),
|
|
1034
|
+
edited: edits.edited,
|
|
1035
|
+
changes: edits.edited === "yes" ? edits.changes : []
|
|
1036
|
+
});
|
|
1037
|
+
}
|
|
1038
|
+
return targets.sort((a, b) => Number(b.sameName) - Number(a.sameName)).slice(0, MAX_TARGETS);
|
|
1039
|
+
}
|
|
1040
|
+
/** The message that sends the authoring chat to bring a world up to date with the newer card; it speaks the person's language, like the import command. */
|
|
1041
|
+
function updateMessage(language) {
|
|
1042
|
+
return translator(languageOf(language))("The character card this world was made from has a newer version, kept in this world's .import/update folder. Bring the world up to date with it. First call card_diff: it lists what changed between the two versions, which characters, places and things were made from each changed piece, and which files of the world have been edited since the import. Read the pieces you need with card_read (version current is the old card, version new is the new one). Then change only what the new card changed, with your editing tools, and keep what the person has edited since the import. What the card says about the world itself (its description, tags and opening) is changed with edit_world_info. Remove what only a dropped piece made unless the person edited it. Do not add what neither version of the card says. When the world matches the new card, call card_update_finish, then tell me briefly what you changed, what you left alone and why.");
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* Starts the update of a world from an uploaded card: the card waits in the world's import folder, the world's authoring chat is opened, and it is told to apply the difference.
|
|
1046
|
+
* @throws {WorldNotFoundError} when the world is gone. @throws {InvalidEditProblems} when the world was not made from a card, or the choices cannot be used.
|
|
1047
|
+
*/
|
|
1048
|
+
async function startUpdate(deps, id, choices, worldId, language) {
|
|
1049
|
+
const record = await deps.worlds.find(worldId);
|
|
1050
|
+
if (record === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
|
|
1051
|
+
if (!await importedFromCard(record.directory)) throw new InvalidEditProblems([`the world "${record.summary.name}" was not made from a card, or its import has not finished`]);
|
|
1052
|
+
await deps.store.choose(id, {
|
|
1053
|
+
...choices,
|
|
1054
|
+
name: record.summary.name
|
|
1055
|
+
});
|
|
1056
|
+
const waiting = join(record.directory, IMPORT_FOLDER, UPDATE_FOLDER);
|
|
1057
|
+
if (!await pendingUpdate(record.directory) || !await canRevert(record.directory)) await backUp(record.directory);
|
|
1058
|
+
await rm(waiting, {
|
|
1059
|
+
recursive: true,
|
|
1060
|
+
force: true
|
|
1061
|
+
});
|
|
1062
|
+
await deps.store.adopt(id, record.directory, join(IMPORT_FOLDER, UPDATE_FOLDER));
|
|
1063
|
+
const chatSessionId = await deps.authoring.ensure(record.summary.id, record.summary.name, authoringTitle(record.summary.name, language), language);
|
|
1064
|
+
let failure;
|
|
1065
|
+
try {
|
|
1066
|
+
await deps.authoring.send(chatSessionId, updateMessage(language));
|
|
1067
|
+
} catch (error) {
|
|
1068
|
+
failure = error instanceof Error ? error.message : String(error);
|
|
1069
|
+
}
|
|
1070
|
+
return {
|
|
1071
|
+
worldId: record.summary.id,
|
|
1072
|
+
chatSessionId,
|
|
1073
|
+
started: failure === void 0,
|
|
1074
|
+
...failure === void 0 ? {} : { failure }
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
const BACKUP_FOLDER = "before-update";
|
|
1078
|
+
const NOT_RECORDS = /* @__PURE__ */ new Set([
|
|
1079
|
+
UPDATE_FOLDER,
|
|
1080
|
+
PREVIOUS_FOLDER,
|
|
1081
|
+
BACKUP_FOLDER
|
|
1082
|
+
]);
|
|
1083
|
+
/** What an update may change of a world: its files. The pictures are made and fetched on their own, and a name that starts with a dot is the program's. */
|
|
1084
|
+
const isWorldFile = (name) => !name.startsWith(".") && name !== "images";
|
|
1085
|
+
/** Keeps the world as it is before an update changes it, so the update can be undone as a whole. */
|
|
1086
|
+
async function backUp(directory) {
|
|
1087
|
+
const target = join(directory, IMPORT_FOLDER, BACKUP_FOLDER);
|
|
1088
|
+
await rm(target, {
|
|
1089
|
+
recursive: true,
|
|
1090
|
+
force: true
|
|
1091
|
+
});
|
|
1092
|
+
await mkdir(join(target, "world"), { recursive: true });
|
|
1093
|
+
await mkdir(join(target, "import"), { recursive: true });
|
|
1094
|
+
for (const entry of await readdir(directory)) if (isWorldFile(entry)) await cp(join(directory, entry), join(target, "world", entry), { recursive: true });
|
|
1095
|
+
for (const entry of await readdir(join(directory, IMPORT_FOLDER))) if (!NOT_RECORDS.has(entry)) await cp(join(directory, IMPORT_FOLDER, entry), join(target, "import", entry), { recursive: true });
|
|
1096
|
+
}
|
|
1097
|
+
/** Whether the world was kept as it was before its last update, which is what undoing that update returns it to. */
|
|
1098
|
+
const canRevert = (directory) => exists(join(directory, IMPORT_FOLDER, BACKUP_FOLDER, "world"));
|
|
1099
|
+
/**
|
|
1100
|
+
* Returns the world to what it was before its last card update, the import's records included. What the world holds now is moved to `.trash` rather than deleted,
|
|
1101
|
+
* so edits made after the update can still be found. Pictures are not part of it.
|
|
1102
|
+
* @throws {InvalidEditProblems} when there is no update to undo.
|
|
1103
|
+
*/
|
|
1104
|
+
async function revertUpdate(directory) {
|
|
1105
|
+
if (!await canRevert(directory)) throw new InvalidEditProblems(["there is no card update to undo in this world"]);
|
|
1106
|
+
const backup = join(directory, IMPORT_FOLDER, BACKUP_FOLDER);
|
|
1107
|
+
const keptIn = join(directory, ".trash", `update-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`);
|
|
1108
|
+
await mkdir(keptIn, { recursive: true });
|
|
1109
|
+
for (const entry of await readdir(directory)) if (isWorldFile(entry)) await rename(join(directory, entry), join(keptIn, entry));
|
|
1110
|
+
for (const entry of await readdir(join(backup, "world"))) await cp(join(backup, "world", entry), join(directory, entry), { recursive: true });
|
|
1111
|
+
const folder = join(directory, IMPORT_FOLDER);
|
|
1112
|
+
for (const entry of await readdir(folder)) if (!NOT_RECORDS.has(entry)) await rm(join(folder, entry), {
|
|
1113
|
+
recursive: true,
|
|
1114
|
+
force: true
|
|
1115
|
+
});
|
|
1116
|
+
for (const entry of await readdir(join(backup, "import"))) await cp(join(backup, "import", entry), join(folder, entry), { recursive: true });
|
|
1117
|
+
await rm(join(folder, UPDATE_FOLDER), {
|
|
1118
|
+
recursive: true,
|
|
1119
|
+
force: true
|
|
1120
|
+
});
|
|
1121
|
+
await rm(join(folder, PREVIOUS_FOLDER), {
|
|
1122
|
+
recursive: true,
|
|
1123
|
+
force: true
|
|
1124
|
+
});
|
|
1125
|
+
await rm(backup, {
|
|
1126
|
+
recursive: true,
|
|
1127
|
+
force: true
|
|
1128
|
+
});
|
|
1129
|
+
return { keptIn };
|
|
1130
|
+
}
|
|
1131
|
+
/**
|
|
1132
|
+
* The newer card becomes the card the world was made from: the old one is kept in `.import/previous`, the import's record of which piece is what follows the pieces that
|
|
1133
|
+
* stayed, and what the world holds now is what a later edit is measured against.
|
|
1134
|
+
* @throws {Error} when no newer card is waiting.
|
|
1135
|
+
*/
|
|
1136
|
+
async function finishUpdate(directory, options = {}) {
|
|
1137
|
+
const folder = join(directory, IMPORT_FOLDER);
|
|
1138
|
+
const waiting = join(folder, UPDATE_FOLDER);
|
|
1139
|
+
let next;
|
|
1140
|
+
try {
|
|
1141
|
+
next = await readImportFolder(waiting);
|
|
1142
|
+
} catch (error) {
|
|
1143
|
+
if (error.code === "ENOENT") throw new Error("no newer version of the card is waiting to update this world");
|
|
1144
|
+
throw error;
|
|
1145
|
+
}
|
|
1146
|
+
const current = await readImportFolder(folder);
|
|
1147
|
+
const oldPicture = current.hasPicture ? await readFile(join(folder, PICTURE_FILE)) : void 0;
|
|
1148
|
+
const newPicture = next.hasPicture ? await readFile(join(waiting, PICTURE_FILE)) : void 0;
|
|
1149
|
+
const forgotten = await followPieces(folder, current.card, current.choices, next.card, next.choices);
|
|
1150
|
+
const previous = join(folder, PREVIOUS_FOLDER);
|
|
1151
|
+
await rm(previous, {
|
|
1152
|
+
recursive: true,
|
|
1153
|
+
force: true
|
|
1154
|
+
});
|
|
1155
|
+
await mkdir(previous, { recursive: true });
|
|
1156
|
+
for (const file of [
|
|
1157
|
+
"card.json",
|
|
1158
|
+
"choices.json",
|
|
1159
|
+
PICTURE_FILE
|
|
1160
|
+
]) await cp(join(folder, file), join(previous, file)).catch((error) => {
|
|
1161
|
+
if (error.code !== "ENOENT") throw error;
|
|
1162
|
+
});
|
|
1163
|
+
await writeFile(join(folder, "card.json"), JSON.stringify(next.card));
|
|
1164
|
+
await writeChoices(folder, next.choices);
|
|
1165
|
+
if (next.hasPicture) await cp(join(waiting, PICTURE_FILE), join(folder, PICTURE_FILE));
|
|
1166
|
+
else await rm(join(folder, PICTURE_FILE), { force: true });
|
|
1167
|
+
await rm(waiting, {
|
|
1168
|
+
recursive: true,
|
|
1169
|
+
force: true
|
|
1170
|
+
});
|
|
1171
|
+
const pictures = await updatePictures(directory, current.card.urls ?? [], next.card.urls ?? [], options);
|
|
1172
|
+
const portrait = newPicture === void 0 ? "none" : oldPicture !== void 0 && oldPicture.equals(newPicture) ? "kept" : await refreshPortrait(directory, newPicture, next.card.name);
|
|
1173
|
+
await writeSnapshot(directory);
|
|
1174
|
+
return {
|
|
1175
|
+
forgotten,
|
|
1176
|
+
pictures,
|
|
1177
|
+
aboutTheWorld: worldFieldChanges(current, next).map((change) => `${change.field}: ${change.because}`),
|
|
1178
|
+
portrait
|
|
1179
|
+
};
|
|
1180
|
+
}
|
|
1181
|
+
/** Fetches what the newer card points to that the world does not have yet, keeps the record of the fetches, and says which fetched pictures the card no longer points to. */
|
|
1182
|
+
async function updatePictures(directory, earlier, later, options) {
|
|
1183
|
+
const file = join(directory, IMPORT_FOLDER, "pictures.json");
|
|
1184
|
+
const record = await readFile(file, "utf8").then((text) => JSON.parse(text), () => void 0);
|
|
1185
|
+
const ask = addressesToFetch(earlier, later, record);
|
|
1186
|
+
const report = ask.length === 0 ? void 0 : await (options.fetcher ?? fetchPictures)(directory, ask, options.signal === void 0 ? {} : { signal: options.signal }).catch(() => ({
|
|
1187
|
+
found: 0,
|
|
1188
|
+
added: [],
|
|
1189
|
+
skipped: []
|
|
1190
|
+
}));
|
|
1191
|
+
if (report !== void 0 && (record !== void 0 || report.found > 0)) await writeFile(file, JSON.stringify(mergeReports(record, report, candidateUrls(later).candidates.length)));
|
|
1192
|
+
const merged = report === void 0 ? record : mergeReports(record, report, 0);
|
|
1193
|
+
const pointedTo = new Set(later.map(addressKey));
|
|
1194
|
+
const stillWanted = new Set([...merged?.added ?? [], ...(merged?.skipped ?? []).flatMap((entry) => entry.of === void 0 ? [] : [{
|
|
1195
|
+
url: entry.url,
|
|
1196
|
+
path: entry.of
|
|
1197
|
+
}])].filter((entry) => pointedTo.has(addressKey(entry.url))).map((entry) => entry.path));
|
|
1198
|
+
const dropped = [];
|
|
1199
|
+
for (const entry of record?.added ?? []) if (!stillWanted.has(entry.path) && !dropped.includes(entry.path) && await exists(join(directory, "images", entry.path))) dropped.push(entry.path);
|
|
1200
|
+
return {
|
|
1201
|
+
found: report?.found ?? 0,
|
|
1202
|
+
added: report?.added.length ?? 0,
|
|
1203
|
+
droppedFromTheCard: dropped
|
|
1204
|
+
};
|
|
1205
|
+
}
|
|
1206
|
+
/** Carries the import's record of what each piece was over to the new card's piece ids; the pieces the new card dropped are forgotten. */
|
|
1207
|
+
async function followPieces(folder, before, beforeChoices, after, afterChoices) {
|
|
1208
|
+
const file = join(folder, CLASSIFICATION);
|
|
1209
|
+
let classified;
|
|
1210
|
+
try {
|
|
1211
|
+
classified = JSON.parse(await readFile(file, "utf8"));
|
|
1212
|
+
} catch (error) {
|
|
1213
|
+
if (error.code === "ENOENT") return 0;
|
|
1214
|
+
throw error;
|
|
1215
|
+
}
|
|
1216
|
+
const match = matchPieces(cardPieces(before, beforeChoices), cardPieces(after, afterChoices));
|
|
1217
|
+
const renamed = new Map(match.pairs.map((pair) => [pair.before.id, pair.after.id]));
|
|
1218
|
+
const dropped = new Set(match.removed.map((piece) => piece.id));
|
|
1219
|
+
const followed = {};
|
|
1220
|
+
let forgotten = 0;
|
|
1221
|
+
for (const [key, value] of Object.entries(classified)) {
|
|
1222
|
+
const base = baseId(key);
|
|
1223
|
+
if (dropped.has(base)) {
|
|
1224
|
+
forgotten += 1;
|
|
1225
|
+
continue;
|
|
1226
|
+
}
|
|
1227
|
+
followed[`${renamed.get(base) ?? base}${key.slice(base.length)}`] = value;
|
|
1228
|
+
}
|
|
1229
|
+
const temporary = `${file}.tmp`;
|
|
1230
|
+
await writeFile(temporary, JSON.stringify(followed));
|
|
1231
|
+
await rename(temporary, file);
|
|
1232
|
+
return forgotten;
|
|
1233
|
+
}
|
|
1234
|
+
/** Replaces the portrait that came with the card by the new card's picture, unless the person has put another there; a card portrait the world never got is made now. */
|
|
1235
|
+
async function refreshPortrait(directory, picture, cardName) {
|
|
1236
|
+
const characters = join(directory, CHARACTERS_DIR);
|
|
1237
|
+
const documents = [];
|
|
1238
|
+
for (const entry of await readdir(characters).catch(() => [])) {
|
|
1239
|
+
const document = await readFile(join(characters, entry, CHARACTER_FILE_NAME), "utf8").then((text) => JSON.parse(text), () => void 0);
|
|
1240
|
+
if (document !== void 0) documents.push({
|
|
1241
|
+
...document,
|
|
1242
|
+
id: document["id"] ?? entry
|
|
1243
|
+
});
|
|
1244
|
+
}
|
|
1245
|
+
for (const document of documents) {
|
|
1246
|
+
const file = referenceImagePath(directory, {
|
|
1247
|
+
kind: "character",
|
|
1248
|
+
localId: String(document["id"])
|
|
1249
|
+
});
|
|
1250
|
+
const made = await readImageFileMetadata(file);
|
|
1251
|
+
if (made?.origin === "uploaded" && made.originalName === "picture.png") return await writePortrait(directory, picture, [document], String(document["name"])) ? "replaced" : "kept";
|
|
1252
|
+
}
|
|
1253
|
+
const character = cardCharacter(documents, cardName);
|
|
1254
|
+
if (character === void 0 || await exists(referenceImagePath(directory, {
|
|
1255
|
+
kind: "character",
|
|
1256
|
+
localId: String(character["id"])
|
|
1257
|
+
}))) return "kept";
|
|
1258
|
+
return await writePortrait(directory, picture, documents, cardName) ? "replaced" : "kept";
|
|
1259
|
+
}
|
|
1260
|
+
//#endregion
|
|
18
1261
|
//#region src/host/translate/terms.ts
|
|
19
1262
|
const STOP = /* @__PURE__ */ new Set([
|
|
20
1263
|
"the",
|
|
@@ -2139,6 +3382,6 @@ function registerPackJail(ctx, deps) {
|
|
|
2139
3382
|
ctx.on("tools/pre-execute", (exec, next) => packJail(exec, next, deps), { prepend: true });
|
|
2140
3383
|
}
|
|
2141
3384
|
//#endregion
|
|
2142
|
-
export { worldEntityImageFile as A, readWorldInfo as B, readWorldEditor as C, uploadWorldCharacterPortrait as D, replaceFile$1 as E, loadWorldParts as F, translateTools as H, PRESET_FILE as I, presetMessage as L, deleteTriggerDocument as M, readTriggerDocuments as N, uploadWorldEntityImage as O, writeTriggerDocument as P, presetTools as R, generateWorldEntityImage as S, removeWorldTrigger as T, languageOfDocuments as U, translateMessage as V, readWorldDocuments as W, editWorldPlots as _, deleteWorldPackFile as a, entityFolder as b, createAuthoredEntity as c, replaceAuthoredEntity as d, editWorldCharacter as f, editWorldPlace as g, editWorldNarrationVoice as h, checkWorldPack as i, writeWorldTrigger as j, worldCharacterPortraitFile as k, deleteAuthoredEntity as l, editWorldLore as m, packFileProblem as n, listWorldPacks as o, editWorldFaction as p, registerPackJail as r, AUTHORED_ENTITY_KINDS as s, MAX_PACK_TEXT as t, readAuthoredEntityDocument as u, editWorldRelation as v, readWorldTrigger as w, generateWorldCharacterPortrait as x, editWorldThing as y, editWorldInfo as z };
|
|
3385
|
+
export { matchPieces as $, worldEntityImageFile as A, readWorldInfo as B, readWorldEditor as C, uploadWorldCharacterPortrait as D, replaceFile$1 as E, loadWorldParts as F, findTargets as G, translateTools as H, PRESET_FILE as I, revertUpdate as J, finishUpdate as K, presetMessage as L, deleteTriggerDocument as M, readTriggerDocuments as N, uploadWorldEntityImage as O, writeTriggerDocument as P, diffText as Q, presetTools as R, generateWorldEntityImage as S, removeWorldTrigger as T, languageOfDocuments as U, translateMessage as V, readWorldDocuments as W, updateStatus as X, startUpdate as Y, cardChanges as Z, editWorldPlots as _, deleteWorldPackFile as a, authoringTitle as at, entityFolder as b, createAuthoredEntity as c, ensureAgentChat as ct, replaceAuthoredEntity as d, appendNarratedTurn as dt, worldFieldChanges as et, editWorldCharacter as f, storeAuthoringOpening as ft, editWorldPlace as g, editWorldNarrationVoice as h, checkWorldPack as i, AuthoringSessions as it, writeWorldTrigger as j, worldCharacterPortraitFile as k, deleteAuthoredEntity as l, isStored as lt, editWorldLore as m, packFileProblem as n, entitiesByPiece as nt, listWorldPacks as o, AgentSessions as ot, editWorldFaction as p, storeDoctorOpening as pt, pendingUpdate as q, registerPackJail as r, readSource as rt, AUTHORED_ENTITY_KINDS as s, agentServicesOf as st, MAX_PACK_TEXT as t, cardTools as tt, readAuthoredEntityDocument as u, appendEmptyTurn as ut, editWorldRelation as v, readWorldTrigger as w, generateWorldCharacterPortrait as x, editWorldThing as y, editWorldInfo as z };
|
|
2143
3386
|
|
|
2144
|
-
//# sourceMappingURL=pack-jail-
|
|
3387
|
+
//# sourceMappingURL=pack-jail-DeTscGT2.js.map
|