@dsh-agentic-roleplay/core 0.7.1 → 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.
Files changed (29) hide show
  1. package/README.md +1 -1
  2. package/lib/{authoring-tools-BKltdiea.js → authoring-tools-CIsWbq0B.js} +197 -20
  3. package/lib/authoring.js +410 -32
  4. package/lib/client.js +679 -347
  5. package/lib/client.js.map +1 -1
  6. package/lib/doctor.js +1 -1
  7. package/lib/{gallery-BxZGOgMb.js → gallery-DmBZ2L5l.js} +2 -2
  8. package/lib/{generator-BFmSYvR8.js → generator-BmdoTIL2.js} +2 -2
  9. package/lib/{hooks-HnqXO8mM.js → hooks-C8eELrni.js} +2 -2
  10. package/lib/images.js +4 -4
  11. package/lib/index.js +111 -566
  12. package/lib/{library-BGxPKs9a.js → library-lVNf9qG_.js} +37 -4
  13. package/lib/{lorebook-author-tools-BAnUyRtS.js → lorebook-author-tools-BDOs4i5C.js} +6 -6
  14. package/lib/lorebook-authoring.js +3 -3
  15. package/lib/orchestration.js +8 -8
  16. package/lib/{pack-jail-DLGguGS3.js → pack-jail-DeTscGT2.js} +1255 -12
  17. package/lib/{packs-jowC-MN_.js → packs-CY8ms8v_.js} +2 -2
  18. package/lib/{presenter-agent-DvZtnf0Q.js → presenter-agent-cFR4sos3.js} +4 -4
  19. package/lib/{preset-author-tools-C26kj6t5.js → preset-author-tools-2m4BLtws.js} +6 -6
  20. package/lib/preset-authoring.js +4 -4
  21. package/lib/{preset-CXbC0NeU.js → preset-n4-j6k4S.js} +2 -2
  22. package/lib/{reflection-CvOZGjmn.js → reflection-CJB5s0ip.js} +6 -6
  23. package/lib/{route-DRTJ_vcA.js → route-C6SHz9j2.js} +2 -2
  24. package/lib/{text-JbWfTHbr.js → text-Cwl5s0j0.js} +3 -1
  25. package/package.json +2 -2
  26. package/prompts/en/import/finish-ok.md +1 -1
  27. package/prompts/en/world/procedure.md +1 -1
  28. package/prompts/zh/import/finish-ok.md +1 -1
  29. package/prompts/zh/world/procedure.md +1 -1
package/lib/index.js CHANGED
@@ -1,26 +1,24 @@
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 { A as loadDice, At as InvalidEditProblems, Bt as pictureOf, C as populateRoutines, Ct as updateLorebookInfo, D as TRIGGERS_FILE_NAME, E as routineProblems, Ft as parseRelationEdit, G as partsOf, Gt as DICE_READINGS, H as loadCharacters, Ht as LORE_KINDS, I as loadLocations, It as parseThingEdit, J as loadVariables, Jt as authoringChatSessionId, K as withPlayer, Kt as DICE_RESULTS, Lt as IMPORT_COMMAND, M as CALENDAR_FILE_NAME, Mt as parseFactionEdit, N as loadCalendar, Nt as parseLoreEdit, P as parseCalendarFile, Pt as parsePlaceEdit, R as loadItems, Rt as ImportCardError, S as populateLore, St as reserveLorebook, T as populateVariables, Ut as LORE_SCOPES, V as CHARACTERS_DIR, Vt as readCard, Wt as DICE_COMPARISONS, X as variableProblems, Y as parseVariablesFile, _ as populateDice, _t as isLorebookName, at as IMPORT_FOLDER, b as populateKnowledge, bt as lorebookDirectory, ct as parseChoices, d as vetUrl, dt as parseWorldInfoEdit, f as loadValidatedWorld, ft as addLorebookEntries, g as populateClock, gt as entriesOf, h as populateCharacters, ht as deleteLorebookEntry, it as parseCharacterFile, j as parseDiceFile, jt as parseCharacterEdit, k as DICE_FILE_NAME, kt as subfolders, l as markReady, lt as WORLD_FILE_NAME, m as populateCalendar, mt as deleteLorebook, ot as ImportNotFoundError, p as knowsCharacter, pt as createLorebook, q as VARIABLES_FILE_NAME, qt as authoredWorldOf, rt as CHARACTER_FILE_NAME, st as ImportStore, t as AuthoringTools, u as guardedLookup, ut as parseWorldFile, v as populateFactions, vt as listLorebooks, w as populateTriggers, wt as writeLorebookEntry, x as populateLocations, y as populateItems, yt as loadLorebook, zt as isPng } from "./authoring-tools-BKltdiea.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-BAnUyRtS.js";
4
- import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-C26kj6t5.js";
5
- import { C as readWorldPrompt, S as listWorldPrompts, _ as savePresetFromWorld, d as isPresetName, f as listPresets, g as reservePreset, l as createPresetFromShipped, m as presetDirectory, p as loadPreset, s as PRESET_FILE, u as deletePreset, w as writeWorldPrompt, x as deleteWorldPrompt, y as updatePresetInfo } from "./route-DRTJ_vcA.js";
6
- import { c as copyPreset, d as switchPreset, f as readTimeline, h as defaultBoundaries, i as reflectionStatus, l as presetStatus, m as pathTo, o as TimelineError, p as writeTimeline, u as recordPreset } from "./reflection-CvOZGjmn.js";
7
- import { a as liveSettings, c as writeSettings, d as parseSettings, i as InvalidSettingsError, l as DEFAULT_SETTINGS, n as encodeOutput, o as readSettings, p as WORLD_RULES_KEY, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-DvFBqmqe.js";
8
- import { C as readNotes, G as formatIssue, H as plotReferenceProblems, K as errorMessage, M as plotProgressOf, N as populatePlots, O as zoneOf, Q as languageOf, S as notesOfSession, U as readDocument, V as parsePlotsFile, X as copyWorldPrompts, Y as PromptLibrary, _ as readRunDetail, at as InvalidWorldError, b as readWithdrawn, ct as SessionNotFoundError, g as readActivity, h as readDecisionStats, i as externalTools, it as InvalidStartError, j as PLOTS_METADATA_KEY, lt as WorldNotFoundError, m as readUsage, ot as ReflectionRefusedError, rt as AgentUnavailableError, st as SessionArchivedError, tt as shippedLanguages, w as observeAsPlayer, x as addToNote } from "./hooks-HnqXO8mM.js";
9
- import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-JbWfTHbr.js";
2
+ import { $ as parseCalendarFile, B as populateLocations, Bt as deleteLorebook, Dt as IMPORT_FOLDER, E as vetUrl, Et as parseCharacterFile, F as populateClock, Ft as WORLD_FILE_NAME, G as routineProblems, Gt as loadLorebook, H as populateRoutines, Ht as entriesOf, I as populateDice, It as parseWorldFile, J as DICE_FILE_NAME, Jt as reserveLorebook, K as TRIGGERS_FILE_NAME, Kt as lorebookDirectory, L as populateFactions, Lt as parseWorldInfoEdit, M as knowsCharacter, Mt as parseChoices, N as populateCalendar, Ot as ImportNotFoundError, P as populateCharacters, Q as loadCalendar, R as populateItems, Rt as addLorebookEntries, Tt as CHARACTER_FILE_NAME, U as populateTriggers, Ut as isLorebookName, V as populateLore, Vt as deleteLorebookEntry, W as populateVariables, Wt as listLorebooks, X as parseDiceFile, Xt as writeLorebookEntry, Y as loadDice, Yt as updateLorebookInfo, Z as CALENDAR_FILE_NAME, _ as readOrigin, _n as DICE_READINGS, _t as parseVariablesFile, an as parseLoreEdit, cn as parseThingEdit, dn as isPng, fn as pictureOf, g as localChanges, gn as DICE_COMPARISONS, gt as loadVariables, h as isUnchanged, hn as LORE_SCOPES, ht as VARIABLES_FILE_NAME, in as parseFactionEdit, j as loadValidatedWorld, kt as ImportStore, ln as IMPORT_COMMAND, m as hashWorld, mn as LORE_KINDS, mt as withPlayer, nn as InvalidEditProblems, on as parsePlaceEdit, ot as CHARACTERS_DIR, p as describeChanges, pn as readCard, pt as partsOf, rn as parseCharacterEdit, rt as loadItems, sn as parseRelationEdit, st as loadCharacters, t as AuthoringTools, tn as subfolders, tt as loadLocations, u as markReady, un as ImportCardError, v as writeOrigin, vn as DICE_RESULTS, vt as variableProblems, w as guardedLookup, y as CatalogueError, yn as authoredWorldOf, z as populateKnowledge, zt as createLorebook } from "./authoring-tools-CIsWbq0B.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-BDOs4i5C.js";
4
+ import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-2m4BLtws.js";
5
+ import { C as readWorldPrompt, S as listWorldPrompts, _ as savePresetFromWorld, d as isPresetName, f as listPresets, g as reservePreset, l as createPresetFromShipped, m as presetDirectory, p as loadPreset, s as PRESET_FILE, u as deletePreset, w as writeWorldPrompt, x as deleteWorldPrompt, y as updatePresetInfo } from "./route-C6SHz9j2.js";
6
+ import { c as copyPreset, d as switchPreset, f as readTimeline, h as defaultBoundaries, i as reflectionStatus, l as presetStatus, m as pathTo, o as TimelineError, p as writeTimeline, u as recordPreset } from "./reflection-CJB5s0ip.js";
7
+ import { a as liveSettings, c as writeSettings, d as parseSettings, i as InvalidSettingsError, l as DEFAULT_SETTINGS, o as readSettings, p as WORLD_RULES_KEY, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-DvFBqmqe.js";
8
+ import { C as readNotes, G as formatIssue, H as plotReferenceProblems, K as errorMessage, M as plotProgressOf, N as populatePlots, O as zoneOf, Q as languageOf, S as notesOfSession, U as readDocument, V as parsePlotsFile, X as copyWorldPrompts, Y as PromptLibrary, _ as readRunDetail, at as InvalidWorldError, b as readWithdrawn, ct as SessionNotFoundError, g as readActivity, h as readDecisionStats, i as externalTools, it as InvalidStartError, j as PLOTS_METADATA_KEY, lt as WorldNotFoundError, m as readUsage, ot as ReflectionRefusedError, rt as AgentUnavailableError, st as SessionArchivedError, tt as shippedLanguages, w as observeAsPlayer, x as addToNote } from "./hooks-C8eELrni.js";
9
+ import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-Cwl5s0j0.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-DeTscGT2.js";
10
11
  import { d as sharedSamplingOf, i as childSamplingOf, u as parseSampling } from "./child-CyCViUKa.js";
11
- import { S as uniqueKey, a as inheritImages, b as slug, c as referenceImagePath, l as sceneImagePath, t as addToLibrary } from "./library-BGxPKs9a.js";
12
- import { A as worldEntityImageFile, B as readWorldInfo, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as loadWorldParts, I as PRESET_FILE$1, L as presetMessage, O as uploadWorldEntityImage, S as generateWorldEntityImage, T as removeWorldTrigger, U as languageOfDocuments, V as translateMessage, W as readWorldDocuments, _ as editWorldPlots$1, a as deleteWorldPackFile, b as entityFolder, c as createAuthoredEntity, f as editWorldCharacter$1, g as editWorldPlace$1, h as editWorldNarrationVoice, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, m as editWorldLore$1, n as packFileProblem, p as editWorldFaction$1, t as MAX_PACK_TEXT, u as readAuthoredEntityDocument, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1, z as editWorldInfo } from "./pack-jail-DLGguGS3.js";
13
- import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-CXbC0NeU.js";
12
+ import { S as slug, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath, w as uniqueKey } from "./library-lVNf9qG_.js";
13
+ import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-n4-j6k4S.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-jowC-MN_.js";
16
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-BFmSYvR8.js";
17
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-BxZGOgMb.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-CY8ms8v_.js";
16
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-BmdoTIL2.js";
17
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-DmBZ2L5l.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
21
  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
22
  import { inflateRawSync } from "node:zlib";
25
23
  import { fileURLToPath } from "node:url";
26
24
  import { Service } from "@deepseek-ai/cordis";
@@ -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,65 +77,6 @@ var RoleplayImport = class extends Service {
456
77
  }
457
78
  };
458
79
  //#endregion
459
- //#region src/host/agent/authoring-sessions.ts
460
- const AUTHORING_PROJECT_TITLE = "World Authoring";
461
- const AUTHORING_AGENT_PRESET = "world-authoring";
462
- /** The title of a world's authoring chat, in the language of the person who opened it. */
463
- function authoringTitle(worldName, language) {
464
- return translator(languageOf$1(language))("Authoring {name}", { name: worldName });
465
- }
466
- /** Creates or reopens the dedicated authoring chat of an authored world, and speaks in it for the person when asked to. */
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);
515
- }
516
- };
517
- //#endregion
518
80
  //#region src/host/worlds/create-world.ts
519
81
  const FOLDER = /^[\p{L}\p{N}][\p{L}\p{N}._ -]{0,99}$/u;
520
82
  var WorldFolderExistsError = class extends Error {};
@@ -1601,17 +1163,6 @@ async function addStarterWorld(catalog, folder, directory = starterDirectory())
1601
1163
  return added;
1602
1164
  }
1603
1165
  //#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
1166
  //#region src/host/http/respond.ts
1616
1167
  function sendJson(res, status, payload) {
1617
1168
  res.statusCode = status;
@@ -3068,6 +2619,11 @@ function catalogueFailure(res, error) {
3068
2619
  });
3069
2620
  throw error;
3070
2621
  }
2622
+ /** The world a card is to update, when the request names one. */
2623
+ function updateField(body) {
2624
+ const value = typeof body === "object" && body !== null ? body.update : void 0;
2625
+ return typeof value === "string" && value.trim() !== "" ? value : void 0;
2626
+ }
3071
2627
  /** The status an import failure is shown with: what is wrong with the card or the choices is the person's to fix. */
3072
2628
  function importFailure(res, error) {
3073
2629
  if (error instanceof ImportCardError) return sendError(res, 422, error.message);
@@ -3090,7 +2646,7 @@ function languageField(value) {
3090
2646
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
3091
2647
  }
3092
2648
  }
3093
- function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, presets, lorebooks, sync, locked, anyLocked, connection, speech, externalTools }) {
2649
+ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, presets, lorebooks, sync, locked, anyLocked, connection, speech, externalTools, redundantLayers }) {
3094
2650
  const routes = {
3095
2651
  "/speech/capabilities": { GET: async (_req, res) => {
3096
2652
  sendJson(res, 200, { streaming: speech.streaming() });
@@ -3251,11 +2807,13 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
3251
2807
  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
2808
  try {
3253
2809
  const language = languageField(body.language);
2810
+ const update = updateField(body);
3254
2811
  sendJson(res, 201, await catalogue.convertStaged({
3255
2812
  source: body.source,
3256
2813
  versionId: body.versionId,
3257
2814
  id: body.id,
3258
2815
  choices: parseChoices(body.choices),
2816
+ ...update === void 0 ? {} : { update },
3259
2817
  ...language === void 0 ? {} : { language }
3260
2818
  }));
3261
2819
  } catch (error) {
@@ -3332,6 +2890,24 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
3332
2890
  return importFailure(res, error);
3333
2891
  }
3334
2892
  } },
2893
+ "/worlds/import/update": {
2894
+ GET: async (_req, res, url) => {
2895
+ try {
2896
+ sendJson(res, 200, await importer.updateStatus(url.searchParams.get("id") ?? ""));
2897
+ } catch (error) {
2898
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2899
+ throw error;
2900
+ }
2901
+ },
2902
+ DELETE: async (_req, res, url) => {
2903
+ try {
2904
+ sendJson(res, 200, await importer.revertUpdate(url.searchParams.get("id") ?? ""));
2905
+ } catch (error) {
2906
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2907
+ return importFailure(res, error);
2908
+ }
2909
+ }
2910
+ },
3335
2911
  "/worlds/import/preset": { POST: async (req, res, url) => {
3336
2912
  const name = decodeURIComponent(String(req.headers["x-file-name"] ?? url.searchParams.get("name") ?? "preset"));
3337
2913
  try {
@@ -3412,7 +2988,7 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
3412
2988
  "/worlds/import/start": { POST: async (req, res, url) => {
3413
2989
  try {
3414
2990
  const body = await readJsonBody(req);
3415
- sendJson(res, 200, await importer.start(url.searchParams.get("id") ?? "", parseChoices(body), languageField(body.language)));
2991
+ sendJson(res, 200, await importer.start(url.searchParams.get("id") ?? "", parseChoices(body), languageField(body.language), updateField(body)));
3416
2992
  } catch (error) {
3417
2993
  return importFailure(res, error);
3418
2994
  }
@@ -4162,6 +3738,9 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
4162
3738
  }
4163
3739
  await sendImage(res, image);
4164
3740
  } },
3741
+ "/setup": { GET: async (_req, res) => {
3742
+ sendJson(res, 200, { redundantLayers: redundantLayers?.() ?? [] });
3743
+ } },
4165
3744
  "/tools": { GET: async (_req, res) => {
4166
3745
  sendJson(res, 200, { tools: externalTools?.() ?? [] });
4167
3746
  } },
@@ -4651,6 +4230,35 @@ function purgeDepsOf(ctx, storePath) {
4651
4230
  }
4652
4231
  const purgeOf = (ctx, storePath) => (chat) => purgeChat(purgeDepsOf(ctx, storePath), chat);
4653
4232
  //#endregion
4233
+ //#region src/host/setup/rows.ts
4234
+ const ALL = ["@dsh-agentic-roleplay/all", "dsh-agentic-roleplay"];
4235
+ const SINGLE = [
4236
+ "@dsh-agentic-roleplay/core",
4237
+ "@dsh-agentic-roleplay/state",
4238
+ "dsh-agentic-roleplay-core",
4239
+ "dsh-roleplay-state"
4240
+ ];
4241
+ /** The bundle layers the profile has selected, in order; none when the profile cannot be read. */
4242
+ function selectedBundles(profileDir) {
4243
+ if (profileDir === void 0) return [];
4244
+ try {
4245
+ const bundles = JSON.parse(readFileSync(join(profileDir, "package.json"), "utf8")).dsh?.profile?.bundles;
4246
+ return Array.isArray(bundles) ? bundles.filter((name) => typeof name === "string") : [];
4247
+ } catch {
4248
+ return [];
4249
+ }
4250
+ }
4251
+ /**
4252
+ * The layers of single packages that are selected next to the `all` layer. Each of them inserts the same plugin row as `all`, so the profile then holds the row twice
4253
+ * and DSH, which writes a plugin's settings through its row, refuses every save of Settings → Role Play.
4254
+ */
4255
+ function redundantLayers(bundles) {
4256
+ return bundles.some((name) => ALL.includes(name)) ? bundles.filter((name) => SINGLE.includes(name)) : [];
4257
+ }
4258
+ function redundantLayersMessage(layers) {
4259
+ return `the profile selects ${layers.map((name) => `"${name}"`).join(", ")} next to the all bundle, which already inserts the same plugin rows, so DSH refuses to save the Role Play settings: deselect them (keep the packages installed) and restart`;
4260
+ }
4261
+ //#endregion
4654
4262
  //#region src/host/worlds/daily-life.ts
4655
4263
  /** The day each character lives, and the places its windows may name. */
4656
4264
  async function readRoutines(world) {
@@ -6644,90 +6252,6 @@ var WorldCatalog = class extends Service {
6644
6252
  }
6645
6253
  };
6646
6254
  //#endregion
6647
- //#region src/host/catalogue/origin.ts
6648
- const ORIGIN_FILE = ".catalogue.json";
6649
- const MAX_LISTED_CHANGES = 12;
6650
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6651
- /** The origin recorded in a world's folder, or nothing when it has none. @throws {CatalogueError} when the record is damaged. */
6652
- async function readOrigin(directory) {
6653
- let text;
6654
- try {
6655
- text = await readFile(join(directory, ORIGIN_FILE), "utf8");
6656
- } catch (error) {
6657
- if (error.code === "ENOENT") return void 0;
6658
- throw error;
6659
- }
6660
- const damaged = () => new CatalogueError(`${ORIGIN_FILE} in ${directory} is damaged`, "invalid");
6661
- let value;
6662
- try {
6663
- value = JSON.parse(text);
6664
- } catch {
6665
- throw damaged();
6666
- }
6667
- if (!isRecord(value)) throw damaged();
6668
- const { kind, root, resourceId, versionId, version, files } = value;
6669
- if (kind !== "release" && kind !== "card" || typeof root !== "string" || typeof resourceId !== "string" || typeof versionId !== "string" || typeof version !== "string") throw damaged();
6670
- if (kind === "card") return {
6671
- kind,
6672
- root,
6673
- resourceId,
6674
- versionId,
6675
- version
6676
- };
6677
- if (!isRecord(files) || !Object.values(files).every((hash) => typeof hash === "string")) throw damaged();
6678
- return {
6679
- kind,
6680
- root,
6681
- resourceId,
6682
- versionId,
6683
- version,
6684
- files
6685
- };
6686
- }
6687
- async function writeOrigin(directory, origin) {
6688
- const file = join(directory, ORIGIN_FILE);
6689
- const temporary = `${file}.${randomUUID()}.tmp`;
6690
- await writeFile(temporary, JSON.stringify(origin, null, 2));
6691
- await rename(temporary, file);
6692
- }
6693
- /** 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. */
6694
- async function hashWorld(directory) {
6695
- const hashes = {};
6696
- const walk = async (relative) => {
6697
- for (const entry of await readdir(join(directory, relative), { withFileTypes: true })) {
6698
- if (relative === "" && entry.name.startsWith(".")) continue;
6699
- const path = relative === "" ? entry.name : `${relative}/${entry.name}`;
6700
- if (entry.isDirectory()) await walk(path);
6701
- else if (entry.isFile()) hashes[path] = createHash("sha256").update(await readFile(join(directory, path))).digest("hex");
6702
- }
6703
- };
6704
- await walk("");
6705
- return hashes;
6706
- }
6707
- function compare(recorded, current) {
6708
- return {
6709
- changed: Object.keys(recorded).filter((path) => current[path] !== void 0 && current[path] !== recorded[path]),
6710
- added: Object.keys(current).filter((path) => recorded[path] === void 0),
6711
- removed: Object.keys(recorded).filter((path) => current[path] === void 0)
6712
- };
6713
- }
6714
- const isUnchanged = (changes) => changes.changed.length + changes.added.length + changes.removed.length === 0;
6715
- /** The differences as short lines for a person to read, capped. */
6716
- function describeChanges(changes) {
6717
- const lines = [
6718
- ...changes.changed.map((path) => `changed: ${path}`),
6719
- ...changes.added.map((path) => `added: ${path}`),
6720
- ...changes.removed.map((path) => `removed: ${path}`)
6721
- ];
6722
- return lines.length <= MAX_LISTED_CHANGES ? lines : [...lines.slice(0, MAX_LISTED_CHANGES), `and ${lines.length - MAX_LISTED_CHANGES} more`];
6723
- }
6724
- /** How a world's files compare with the release it came from: the differences, or `unverified` when no record of the release exists. */
6725
- async function localChanges(directory) {
6726
- const origin = await readOrigin(directory);
6727
- if (origin?.kind !== "release") return "unverified";
6728
- return compare(origin.files, await hashWorld(directory));
6729
- }
6730
- //#endregion
6731
6255
  //#region src/host/catalogue/zip.ts
6732
6256
  const END_SIGNATURE = 101010256;
6733
6257
  const CENTRAL_SIGNATURE = 33639248;
@@ -7346,11 +6870,11 @@ var Catalogue = class {
7346
6870
  const release = await this.download(this.deps.sources.get(request.source), request.versionId, CATALOGUE_CARD_TYPE, "a character card");
7347
6871
  return await this.deps.previewCard(release.body, `${release.versionId}${isPng(release.body) ? ".png" : ".json"}`);
7348
6872
  }
7349
- /** Makes the world of a card that `stageCard` offered, with what the person chose. Like `convert`, it never replaces a world. */
6873
+ /** 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. */
7350
6874
  async convertStaged(request) {
7351
6875
  const source = this.deps.sources.get(request.source);
7352
6876
  const release = await this.describe(source, request.versionId, CATALOGUE_CARD_TYPE, "a character card");
7353
- const converted = await this.deps.startCard(request.id, request.choices, request.language);
6877
+ const converted = await this.deps.startCard(request.id, request.choices, request.language, request.update);
7354
6878
  const record = await this.deps.worlds.find(converted.worldId);
7355
6879
  if (record === void 0) throw new CatalogueError("the world was made but cannot be found", "upstream");
7356
6880
  await writeOrigin(record.directory, {
@@ -8623,7 +8147,8 @@ const Config = z.object({
8623
8147
  importTemperature: z.number().min(0).max(2).default(.2).volatile(),
8624
8148
  importTimeoutMinutes: z.number().min(0).max(240).default(15).volatile(),
8625
8149
  importDecisions: z.union([z.const("llm"), z.const("decision")]).default("llm").volatile(),
8626
- importConfidence: z.number().min(0).max(1).default(.7).volatile()
8150
+ importConfidence: z.number().min(0).max(1).default(.7).volatile(),
8151
+ authoringApproval: z.union([z.const("ask"), z.const("auto")]).default("ask").volatile()
8627
8152
  });
8628
8153
  //#endregion
8629
8154
  //#region src/index.ts
@@ -8631,6 +8156,9 @@ const name = "@dsh-agentic-roleplay/core";
8631
8156
  /** Sessions are kept by the state plugin, which the bundle installs with this one. */
8632
8157
  const inject = ["roleplayState"];
8633
8158
  function apply(ctx, config) {
8159
+ const layers = () => redundantLayers(selectedBundles(ctx.get("profileContext")?.dir));
8160
+ const repeated = layers();
8161
+ if (repeated.length > 0) ctx.logger.error(redundantLayersMessage(repeated));
8634
8162
  ctx.inject(["aiProviders"], (scope) => {
8635
8163
  const providers = Reflect.get(scope, "aiProviders");
8636
8164
  scope.effect(() => providers.policy(({ options }) => {
@@ -8682,7 +8210,8 @@ function apply(ctx, config) {
8682
8210
  temperature: config.importTemperature.get(),
8683
8211
  timeoutMinutes: config.importTimeoutMinutes.get(),
8684
8212
  decisions: config.importDecisions.get() === "decision" ? "decision" : "llm",
8685
- confidence: config.importConfidence.get()
8213
+ confidence: config.importConfidence.get(),
8214
+ approval: config.authoringApproval.get() === "auto" ? "auto" : "ask"
8686
8215
  }));
8687
8216
  const settingsDeps = {
8688
8217
  sessionsDir: () => join(root.path, "sessions"),
@@ -8731,6 +8260,22 @@ function apply(ctx, config) {
8731
8260
  },
8732
8261
  playing: (id) => orchestration.playing(chatSessionId(id))
8733
8262
  });
8263
+ const withTargets = async (preview) => {
8264
+ const targets = await findTargets(worlds, preview.choices.name);
8265
+ return targets.length === 0 ? preview : {
8266
+ ...preview,
8267
+ targets
8268
+ };
8269
+ };
8270
+ const begin = async (id, choices, language, update) => update === void 0 ? await startImport({
8271
+ store: imports,
8272
+ worlds,
8273
+ authoring
8274
+ }, id, choices, language) : await startUpdate({
8275
+ store: imports,
8276
+ worlds,
8277
+ authoring
8278
+ }, id, choices, update, language);
8734
8279
  const catalogue = new Catalogue({
8735
8280
  sources: new Sources(() => config.catalogues.get(), () => ctx.get("credentials")),
8736
8281
  worlds,
@@ -8743,12 +8288,8 @@ function apply(ctx, config) {
8743
8288
  stage: (kind, file, name) => staging.stage(kind, file, name),
8744
8289
  importPreset: async (file, title, language) => await presetLibrary.importTitled(title, file, language),
8745
8290
  importLorebook: async (file, title, language) => await lorebookLibrary.importTitled(title, file, language),
8746
- previewCard: async (file, name) => await imports.create(readCard(file, name), isPng(file) ? pictureOf(file) : void 0),
8747
- startCard: async (id, choices, language) => await startImport({
8748
- store: imports,
8749
- worlds,
8750
- authoring
8751
- }, id, choices, language),
8291
+ previewCard: async (file, name) => await withTargets(await imports.create(readCard(file, name), isPng(file) ? pictureOf(file) : void 0)),
8292
+ startCard: begin,
8752
8293
  importCard: async (file, name, language) => {
8753
8294
  const preview = await imports.create(readCard(file, name), isPng(file) ? pictureOf(file) : void 0);
8754
8295
  return await startImport({
@@ -8821,17 +8362,20 @@ function apply(ctx, config) {
8821
8362
  },
8822
8363
  upload: async (file, name) => {
8823
8364
  const card = readCard(file, name);
8824
- return await imports.create(card, isPng(file) ? pictureOf(file) : void 0);
8365
+ return await withTargets(await imports.create(card, isPng(file) ? pictureOf(file) : void 0));
8825
8366
  },
8826
- read: (id) => imports.read(id),
8367
+ read: async (id) => await withTargets(await imports.read(id)),
8827
8368
  choose: (id, choices) => imports.choose(id, choices),
8828
8369
  discard: (id) => imports.discard(id),
8829
- start: (id, choices, language) => startImport({
8830
- store: imports,
8831
- worlds,
8832
- authoring
8833
- }, id, choices, language),
8370
+ start: begin,
8834
8371
  picture: (id) => imports.picture(id),
8372
+ updateStatus: async (worldId) => await updateStatus((await editableWorld(worlds, worldId, root.path)).directory),
8373
+ revertUpdate: async (worldId) => {
8374
+ const directory = (await editableWorld(worlds, worldId, root.path)).directory;
8375
+ const { keptIn } = await revertUpdate(directory);
8376
+ await worlds.list({ refresh: true });
8377
+ return { keptIn: relative(directory, keptIn) };
8378
+ },
8835
8379
  uploadPreset: (worldId, file, name, language) => uploadPreset({
8836
8380
  worlds,
8837
8381
  authoring
@@ -8868,6 +8412,7 @@ function apply(ctx, config) {
8868
8412
  return await addAvatarsToWorld(await avatarsWorld(root.path), world, keys, locations);
8869
8413
  }
8870
8414
  },
8415
+ redundantLayers: layers,
8871
8416
  externalTools: () => {
8872
8417
  const registry = ctx.get("tools");
8873
8418
  return registry === void 0 ? [] : externalTools(registry);