@dsh-agentic-roleplay/core 0.12.7 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/{authoring-tools-Bi9YQ9QH.js → authoring-tools-CKV1UnN7.js} +1089 -129
- package/lib/authoring.js +130 -37
- package/lib/client.js +1251 -662
- package/lib/client.js.map +1 -1
- package/lib/doctor.js +1 -1
- package/lib/{gallery-BT5lf-T5.js → gallery-CT5uj50b.js} +2 -2
- package/lib/{hooks-DR-HqE50.js → hooks-CnxV2uEh.js} +43 -16
- package/lib/images.js +3 -3
- package/lib/index.js +336 -15
- package/lib/{interpreter-BYNrjYZo.js → interpreter-Cz5qsuXk.js} +3 -3
- package/lib/{lorebook-author-tools-BI-r8fEt.js → lorebook-author-tools-p3Nfpuxh.js} +6 -6
- package/lib/lorebook-authoring.js +5 -5
- package/lib/orchestration.js +15 -10
- package/lib/{pack-jail-Y1XPbqHw.js → pack-jail-KyZen_gy.js} +9 -9
- package/lib/{packs-DD-v-Epl.js → packs-DU171pDX.js} +2 -2
- package/lib/{presenter-agent-00sOVGI9.js → presenter-agent-CwDg0WE8.js} +2 -2
- package/lib/{preset-Bnx3jhUv.js → preset-BO8iWQ-n.js} +3 -3
- package/lib/{preset-author-tools-DYrBcieA.js → preset-author-tools-C83shASm.js} +6 -6
- package/lib/preset-authoring.js +5 -5
- package/lib/{reflection-DqxoV9xE.js → reflection-CXS87Di3.js} +6 -6
- package/lib/{serial-CS46qAvI.js → serial-xcAG57p_.js} +148 -38
- package/lib/{text-B-HsLdb-.js → text-KnqhN_Zv.js} +4 -1
- package/lib/{turn-guard-bZkxzRXJ.js → turn-guard-CfsGepCg.js} +2 -2
- package/package.json +2 -2
- package/prompts/en/import/next-stage-go.md +1 -0
- package/prompts/en/import/next-stage-paused.md +1 -0
- package/prompts/en/import/next-survey-paused.md +1 -0
- package/prompts/en/import/notice-staged.md +5 -0
- package/prompts/en/import/pause-stages.md +1 -0
- package/prompts/en/import/pause-survey.md +1 -0
- package/prompts/en/world/procedure.md +3 -0
- package/prompts/zh/import/next-stage-go.md +1 -0
- package/prompts/zh/import/next-stage-paused.md +1 -0
- package/prompts/zh/import/next-survey-paused.md +1 -0
- package/prompts/zh/import/notice-staged.md +5 -0
- package/prompts/zh/import/pause-stages.md +1 -0
- package/prompts/zh/import/pause-survey.md +1 -0
- package/prompts/zh/world/procedure.md +3 -0
package/lib/doctor.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { n as silenceRuntimeContext, t as silenceHarnessDevContext } from "./dev-context-Cgv_wZbG.js";
|
|
2
2
|
import { A as chatSessionId } from "./child-Bfj7-Iuo.js";
|
|
3
3
|
import { n as doctorSessionOf } from "./doctor-chat-hL1a61hp.js";
|
|
4
|
-
import { s as externalTools, t as externalToolLimit } from "./hooks-
|
|
4
|
+
import { s as externalTools, t as externalToolLimit } from "./hooks-CnxV2uEh.js";
|
|
5
5
|
import { o as liveSettings } from "./narration-CUZIXzab.js";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { createTools, isSessionId, sessionDatabase, sessionFolder } from "@dsh-agentic-roleplay/state";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as atomicWrite } from "./access-5vtPAT3O.js";
|
|
2
|
-
import { i as translator, n as withoutExtension, r as languageOf, t as trimCharacters } from "./text-
|
|
2
|
+
import { i as translator, n as withoutExtension, r as languageOf, t as trimCharacters } from "./text-KnqhN_Zv.js";
|
|
3
3
|
import { dirname, extname, join, sep } from "node:path";
|
|
4
4
|
import { existsSync } from "node:fs";
|
|
5
5
|
import { createHash } from "node:crypto";
|
|
@@ -579,4 +579,4 @@ async function updateImage(sessionFolder, path, update) {
|
|
|
579
579
|
}
|
|
580
580
|
export { mapLimit as C, uniqueKey as D, trOf as E, NoEmbeddingService as S, slug as T, MEDIA_TYPES as _, updateImage as a, readPngMetadata as b, imageExtensionOf as c, inheritImages as d, nextSceneSerial as f, writeImage as g, sceneImagePath as h, listGallery as i, libraryHashes as l, referenceImagePath as m, describeGalleryImage as n, addToLibrary as o, readImageMetadata as p, galleryFile as r, addToLibraryOnce as s, addCardLink as t, entityImageDirectory as u, readImageFileMetadata as v, norm as w, withPngMetadata as x, writeImageFileMetadata as y };
|
|
581
581
|
|
|
582
|
-
//# sourceMappingURL=gallery-
|
|
582
|
+
//# sourceMappingURL=gallery-CT5uj50b.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { C as addTokens, D as finishOf, E as cutOff, O as estimateAnswer, S as NO_TOKENS, a as childTrace, b as estimateTokens, f as tracerOf, j as roleplaySessionOf, l as runChild, n as childModel, r as childSampling, u as TurnTraces, v as requestsOf, x as tokensOf, y as blockText } from "./child-Bfj7-Iuo.js";
|
|
2
2
|
import { g as DECISION_SITES, h as rulesOf, m as WORLD_RULES_KEY, n as encodeOutput, o as liveSettings, r as encodePreview, v as emptyStats } from "./narration-CUZIXzab.js";
|
|
3
3
|
import { t as promptFor } from "./access-5vtPAT3O.js";
|
|
4
|
-
import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-
|
|
4
|
+
import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-KnqhN_Zv.js";
|
|
5
5
|
import { n as storyRoots } from "./service-mRKwpWjX.js";
|
|
6
6
|
import { dirname, join } from "node:path";
|
|
7
7
|
import { DAY, ENGAGEMENT_GRACE, ITEM_ACTIONS, MINUTE, SECOND, addLocalDays, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, clockTime, createCharacterTools, createDiceTools, createTools, dayPart, describeDuration, describeInstant, describeValue, holidaysOn, inAudience, isSessionId, itemKey, localTime, locationKey, mentioned, nextOccurrence, nextTimeOfDay, occurrenceAt, overlap, parseInstant, planItemChange, planVariableChange, readCalendar, rollPlain, seasonOf, sessionDatabase, sessionFolder, shownVariables, tokens } from "@dsh-agentic-roleplay/state";
|
|
@@ -469,10 +469,6 @@ function inheritPrompts(from, to) {
|
|
|
469
469
|
function shippedLanguages(shipped = shippedPromptsDirectory()) {
|
|
470
470
|
return readdirSync(shipped, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
|
|
471
471
|
}
|
|
472
|
-
// src/host/errors.ts
|
|
473
|
-
function errorMessage(error) {
|
|
474
|
-
return error instanceof Error ? error.message : String(error);
|
|
475
|
-
}
|
|
476
472
|
// src/host/validation.ts
|
|
477
473
|
function formatIssue({ path, message }) {
|
|
478
474
|
return path === "" ? message : `${path}: ${message}`;
|
|
@@ -640,6 +636,10 @@ var Reader = class Reader {
|
|
|
640
636
|
return this.path === "" ? key : key === "" ? this.path : `${this.path}.${key}`;
|
|
641
637
|
}
|
|
642
638
|
};
|
|
639
|
+
// src/host/errors.ts
|
|
640
|
+
function errorMessage(error) {
|
|
641
|
+
return error instanceof Error ? error.message : String(error);
|
|
642
|
+
}
|
|
643
643
|
// src/host/read-document.ts
|
|
644
644
|
/** Authored documents are short; a larger file is not one. */
|
|
645
645
|
const MAX_DOCUMENT_BYTES = 1048576;
|
|
@@ -4563,32 +4563,59 @@ function worldCommands(intents, defined) {
|
|
|
4563
4563
|
}
|
|
4564
4564
|
// src/host/agents/repeat-guard.ts
|
|
4565
4565
|
/**
|
|
4566
|
-
* Keeps an agent that is stuck from
|
|
4567
|
-
*
|
|
4566
|
+
* Keeps an agent that is stuck from going on (found live: an assistant made one create-and-list pair 47 times in a review, a game master repeated one refused round resolution,
|
|
4567
|
+
* a review read entry 132, 133 ... 4000 of a card that has fewer):
|
|
4568
|
+
* - past `limit` identical calls in one turn the call is refused with a word that sends it on;
|
|
4569
|
+
* - past `FAILING_RUN` failures of one tool in a row, with whatever arguments, the tool is refused for the rest of the turn;
|
|
4570
|
+
* - when the model goes on regardless the turn is ended.
|
|
4571
|
+
* The counts start over at the first step of every turn.
|
|
4568
4572
|
* @param languageOf the language of the chat the call belongs to, or nothing when the guard does not apply to it.
|
|
4569
4573
|
*/
|
|
4570
4574
|
function guardRepeatedCalls(ctx, languageOf, limit) {
|
|
4571
|
-
const
|
|
4575
|
+
const chats = /* @__PURE__ */ new Map();
|
|
4572
4576
|
ctx.on("agent/pre-step", async (payload, next) => {
|
|
4573
|
-
if (payload.step === 1)
|
|
4577
|
+
if (payload.step === 1) chats.delete(payload.agent.session.id);
|
|
4574
4578
|
return await next();
|
|
4575
4579
|
});
|
|
4576
4580
|
ctx.on("tools/pre-execute", async (exec, next) => {
|
|
4577
4581
|
const chat = exec.agent?.session.id;
|
|
4578
4582
|
const language = chat === void 0 || exec.agent?.session.header.origin === "subagent" ? void 0 : languageOf(exec);
|
|
4579
4583
|
if (chat === void 0 || language === void 0) return await next();
|
|
4584
|
+
const state = chats.get(chat) ?? {
|
|
4585
|
+
calls: /* @__PURE__ */ new Map(),
|
|
4586
|
+
failures: /* @__PURE__ */ new Map(),
|
|
4587
|
+
refused: 0
|
|
4588
|
+
};
|
|
4589
|
+
chats.set(chat, state);
|
|
4590
|
+
const tr = translator(languageOf$1(language));
|
|
4591
|
+
const failing = state.failures.get(exec.name) ?? 0;
|
|
4592
|
+
if (failing >= 6) {
|
|
4593
|
+
state.refused += 1;
|
|
4594
|
+
if (state.refused > 5) exec.agent?.cancel({ kind: "user" }, { keepInbox: true });
|
|
4595
|
+
return {
|
|
4596
|
+
kind: "deny",
|
|
4597
|
+
reason: tr("`{tool}` failed {count} times in a row in this turn, with different arguments each time, so guessing more will not work. Do not call it again this turn: use another tool to find what you need (a search or an overview), or finish and say what is left.", {
|
|
4598
|
+
tool: exec.name,
|
|
4599
|
+
count: failing
|
|
4600
|
+
})
|
|
4601
|
+
};
|
|
4602
|
+
}
|
|
4580
4603
|
const signature = `${exec.name}:${JSON.stringify(exec.arguments)}`;
|
|
4581
|
-
const
|
|
4582
|
-
calls.set(
|
|
4583
|
-
const count = (seen.get(signature) ?? 0) + 1;
|
|
4584
|
-
seen.set(signature, count);
|
|
4604
|
+
const count = (state.calls.get(signature) ?? 0) + 1;
|
|
4605
|
+
state.calls.set(signature, count);
|
|
4585
4606
|
if (count <= limit) return await next();
|
|
4586
4607
|
if (count > limit + 5) exec.agent?.cancel({ kind: "user" }, { keepInbox: true });
|
|
4587
4608
|
return {
|
|
4588
4609
|
kind: "deny",
|
|
4589
|
-
reason:
|
|
4610
|
+
reason: tr("This exact call was already made {count} times in this turn with the same result. Do not repeat it: go on with the next step, or finish and say what is left.", { count: count - 1 })
|
|
4590
4611
|
};
|
|
4591
4612
|
}, { prepend: true });
|
|
4613
|
+
ctx.on("tools/result", (exec, result) => {
|
|
4614
|
+
const state = exec.agent === void 0 ? void 0 : chats.get(exec.agent.session.id);
|
|
4615
|
+
if (state === void 0) return;
|
|
4616
|
+
const failures = result.isError ? (state.failures.get(exec.name) ?? 0) + 1 : 0;
|
|
4617
|
+
state.failures.set(exec.name, failures);
|
|
4618
|
+
});
|
|
4592
4619
|
}
|
|
4593
4620
|
// src/host/orchestration/runaway.ts
|
|
4594
4621
|
/** The levels of thinking that mean none, as models name them. */
|
|
@@ -5049,6 +5076,6 @@ function installHooks(ctx, deps) {
|
|
|
5049
5076
|
};
|
|
5050
5077
|
});
|
|
5051
5078
|
}
|
|
5052
|
-
export { copyWorldPrompts as $, plotProgressOf as A, parsePlotsFile as B, readNotes as C, referent as D, sameWords as E, textLanguage as F, readDocument as G, COMMANDS_KEY as H, wrongLanguage as I,
|
|
5079
|
+
export { copyWorldPrompts as $, plotProgressOf as A, parsePlotsFile as B, readNotes as C, referent as D, sameWords as E, textLanguage as F, readDocument as G, COMMANDS_KEY as H, wrongLanguage as I, formatIssue as J, errorMessage as K, readUsage as L, LANGUAGE_NAMES as M, STORY_LANGUAGES as N, RESULTS as O, isStoryLanguage as P, PromptLibrary as Q, PLOTS_FILE_NAME as R, notesOfSession as S, defaultBoundaries as T, commandFlagKey as U, plotReferenceProblems as V, commandsOf as W, LANGUAGE_TAG as X, LANGUAGE_FOLDER as Y, PROMPTS_FOLDER as Z, readTraces as _, ClockError as _t, MAX_OOC_ANSWER as a, shippedPromptsDirectory as at, readWithdrawn as b, AUTHORING_NEEDS as bt, externalWithheld as c, InvalidStartError as ct, record as d, SessionArchivedError as dt, inheritPrompts as et, toolEnabled as f, SessionNotFoundError as ft, readRunDetail as g, runCommandLine as gt, readActivity as h, registerCommands as ht, characterRunner as i, shippedLanguages as it, populatePlots as j, PLOTS_METADATA_KEY as k, PREVIEW_TOOL as l, InvalidWorldError as lt, readDecisionStats as m, CommandRefusedError as mt, installHooks as n, listFiles as nt, externalGiven as o, shippedText as ot, storesOf as p, WorldNotFoundError as pt, Reader as q, guardRepeatedCalls as r, promptProblem as rt, externalTools as s, AgentUnavailableError as st, externalToolLimit as t, languageOf as tt, createTools$1 as u, ReflectionRefusedError as ut, readVerdicts as v, describeWhen as vt, observeAsPlayer as w, addToNote as x, COMPARISONS as xt, writeVerdicts as y, zoneOf as yt, loadPlots as z };
|
|
5053
5080
|
|
|
5054
|
-
//# sourceMappingURL=hooks-
|
|
5081
|
+
//# sourceMappingURL=hooks-CnxV2uEh.js.map
|
package/lib/images.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as runImagePresenter } from "./presenter-agent-
|
|
2
|
-
import { a as searchImages, c as presentedFor, d as referencePrompt, f as transientPrompt, l as generateReferenceImage, n as interpretImage, o as tokensOf, r as imageTools, s as present, u as generateTransientImage } from "./interpreter-
|
|
3
|
-
import { a as updateImage, b as readPngMetadata, d as inheritImages, f as nextSceneSerial, h as sceneImagePath, i as listGallery, m as referenceImagePath, o as addToLibrary, p as readImageMetadata, u as entityImageDirectory, x as withPngMetadata } from "./gallery-
|
|
1
|
+
import { t as runImagePresenter } from "./presenter-agent-CwDg0WE8.js";
|
|
2
|
+
import { a as searchImages, c as presentedFor, d as referencePrompt, f as transientPrompt, l as generateReferenceImage, n as interpretImage, o as tokensOf, r as imageTools, s as present, u as generateTransientImage } from "./interpreter-Cz5qsuXk.js";
|
|
3
|
+
import { a as updateImage, b as readPngMetadata, d as inheritImages, f as nextSceneSerial, h as sceneImagePath, i as listGallery, m as referenceImagePath, o as addToLibrary, p as readImageMetadata, u as entityImageDirectory, x as withPngMetadata } from "./gallery-CT5uj50b.js";
|
|
4
4
|
export { addToLibrary, entityImageDirectory, generateReferenceImage, generateTransientImage, imageTools, inheritImages, interpretImage, listGallery, nextSceneSerial, present, presentedFor, readImageMetadata, readPngMetadata, referenceImagePath, referencePrompt, runImagePresenter, sceneImagePath, searchImages, tokensOf, transientPrompt, updateImage, withPngMetadata };
|
package/lib/index.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import { A as chatSessionId, _ as RECOVERY_SHRINK, g as RECOVERY_FLOOR, h as sharedSamplingOf, i as childSamplingOf, j as roleplaySessionOf, m as parseSampling, r as childSampling, s as isUnfinishedCall, w as totalTokens } from "./child-Bfj7-Iuo.js";
|
|
2
|
-
import { $ as checkWorld, $t as authoredWorldOf, A as loadWorldParts, B as localChanges, Gt as ImportCardError, H as writeOrigin, J as guardedLookup, Jt as pictureOf, Kt as cardFormat, L as describeChanges, O as editWorldInfo, Ot as CHARACTERS_DIR, R as hashWorld, U as CatalogueError, V as readOrigin, X as vetUrl, Yt as readCard, _ as structureImport, _t as loadLocations, a as beginImport, at as populateClock, c as importTextFor, ct as populateItems, d as knownOutputCeiling, dt as populateLore, en as authoringChatSessionId, et as loadValidatedWorld, f as importPhase, ft as populateRoutines, g as settleDraft, h as markReady, i as ImportState, it as populateCharacters, k as readWorldInfo, kt as loadCharacters, lt as populateKnowledge, m as keepDraft, mt as populateVariables, nt as knowsCharacter, ot as populateDice, pt as populateTriggers, qt as isPng, rt as populateCalendar, st as populateFactions, t as AuthoringTools, ut as populateLocations, x as runChecks, z as isUnchanged } from "./authoring-tools-
|
|
3
|
-
import { a as lorebookImportMessage, c as readLorebook, d as lorebookOfChat, l as selectEntries, s as previewLorebook, t as LOREBOOK_UPLOAD, u as lorebookChatSessionId } from "./lorebook-author-tools-
|
|
4
|
-
import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-
|
|
5
|
-
import { $ as copyWorldPrompts, A as plotProgressOf, B as parsePlotsFile, C as readNotes, G as readDocument, H as COMMANDS_KEY, J as errorMessage, L as readUsage, Q as PromptLibrary, S as notesOfSession, T as defaultBoundaries, V as plotReferenceProblems, Y as LANGUAGE_FOLDER, Z as PROMPTS_FOLDER, _ as readTraces, b as readWithdrawn, ct as InvalidStartError, dt as SessionArchivedError, ft as SessionNotFoundError, g as readRunDetail, h as readActivity, it as shippedLanguages, j as populatePlots, k as PLOTS_METADATA_KEY, lt as InvalidWorldError, m as readDecisionStats, mt as CommandRefusedError, nt as listFiles, pt as WorldNotFoundError,
|
|
2
|
+
import { $ as checkWorld, $t as authoredWorldOf, A as loadWorldParts, B as localChanges, Gt as ImportCardError, H as writeOrigin, J as guardedLookup, Jt as pictureOf, Kt as cardFormat, L as describeChanges, O as editWorldInfo, Ot as CHARACTERS_DIR, R as hashWorld, U as CatalogueError, V as readOrigin, X as vetUrl, Yt as readCard, _ as structureImport, _t as loadLocations, a as beginImport, at as populateClock, c as importTextFor, ct as populateItems, d as knownOutputCeiling, dt as populateLore, en as authoringChatSessionId, et as loadValidatedWorld, f as importPhase, ft as populateRoutines, g as settleDraft, h as markReady, i as ImportState, it as populateCharacters, k as readWorldInfo, kt as loadCharacters, lt as populateKnowledge, m as keepDraft, mt as populateVariables, nt as knowsCharacter, ot as populateDice, pt as populateTriggers, qt as isPng, rt as populateCalendar, st as populateFactions, t as AuthoringTools, ut as populateLocations, x as runChecks, z as isUnchanged } from "./authoring-tools-CKV1UnN7.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-p3Nfpuxh.js";
|
|
4
|
+
import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-C83shASm.js";
|
|
5
|
+
import { $ as copyWorldPrompts, A as plotProgressOf, B as parsePlotsFile, C as readNotes, G as readDocument, H as COMMANDS_KEY, J as formatIssue, K as errorMessage, L as readUsage, Q as PromptLibrary, S as notesOfSession, T as defaultBoundaries, V as plotReferenceProblems, Y as LANGUAGE_FOLDER, Z as PROMPTS_FOLDER, _ as readTraces, b as readWithdrawn, ct as InvalidStartError, dt as SessionArchivedError, ft as SessionNotFoundError, g as readRunDetail, h as readActivity, it as shippedLanguages, j as populatePlots, k as PLOTS_METADATA_KEY, lt as InvalidWorldError, m as readDecisionStats, mt as CommandRefusedError, nt as listFiles, pt as WorldNotFoundError, rt as promptProblem, s as externalTools, st as AgentUnavailableError, tt as languageOf, ut as ReflectionRefusedError, w as observeAsPlayer, x as addToNote, yt as zoneOf } from "./hooks-CnxV2uEh.js";
|
|
6
6
|
import { a as InvalidSettingsError, c as useChildReasoning, d as SETTINGS_SPEC, f as parseSettings, l as writeSettings, m as WORLD_RULES_KEY, o as liveSettings, s as readSettings, u as DEFAULT_SETTINGS } from "./narration-CUZIXzab.js";
|
|
7
|
-
import {
|
|
8
|
-
import { $ as languageOfDocuments, A as generateWorldCharacterPortrait, C as editWorldFaction$1, D as editWorldPlots$1, E as editWorldPlace$1, F as uploadWorldCharacterPortrait, G as parseVariablesEdit, I as uploadWorldEntityImage, J as PRESET_FILE$1, K as parseDiceEdit, L as worldCharacterPortraitFile, M as readWorldEditor, N as readWorldTrigger, O as editWorldRelation$1, P as removeWorldTrigger, R as worldEntityImageFile, S as editWorldCharacter$1, T as editWorldNarrationVoice, U as parseCalendarEdit, W as parseRoutineEdit, Y as presetMessage, Z as translateMessage, _ as readCalendarDocument, a as deleteWorldPackFile, at as startUpdate, b as readRoutines, c as createAuthoredEntity, ct as authoringTitle, dt as agentServicesOf, et as readWorldDocuments, f as editCalendar, ft as DOCTOR_OPENING_SOURCE, g as editVariables, h as editRoutine, it as revertUpdate, j as generateWorldEntityImage, k as editWorldThing$1, l as deleteAuthoredEntity, lt as ensureAuthoringChat, m as editDice, mt as appendNarratedTurn, n as packFileProblem, ot as updateStatus, p as editCommands, pt as appendEmptyTurn, q as parseCommandsEdit, st as AuthoringSessions, t as MAX_PACK_TEXT, tt as findTargets, u as readAuthoredEntityDocument, ut as AgentSessions, v as readCommandsDocument, w as editWorldLore$1, x as readVariables, y as readDiceDocument, z as writeWorldTrigger } from "./pack-jail-
|
|
7
|
+
import { $ as createPresetFromShipped, At as subfolders, Bt as parseChoices, Ct as lorebookDirectory, Dt as writeLorebookEntry, Et as updateLorebookInfo, Ft as IMPORT_FOLDER, Gt as parseFactionEdit, H as parseWorldFile, It as ImportNotFoundError, J as combineAnswers, Jt as parseRelationEdit, Kt as parseLoreEdit, Lt as ImportStore, Nt as partsOf, Pt as withPlayer, St as loadLorebook, Tt as reserveLorebook, Ut as InvalidEditProblems, V as WORLD_FILE_NAME, Vt as readImportFolder, W as parseWorldInfoEdit, Wt as parseCharacterEdit, Y as questionView, Yt as parseThingEdit, Z as PRESET_FILE, _t as deleteLorebook, bn as LORE_KINDS, bt as isLorebookName, dt as deleteWorldPrompt, et as deletePreset, ft as listWorldPrompts, gt as createLorebook, ht as addLorebookEntries, it as presetDirectory, lt as updatePresetInfo, mt as writeWorldPrompt, nn as sourceSummary, nt as listPresets, ot as reservePreset, pt as readWorldPrompt, qt as parsePlaceEdit, rt as loadPreset, st as savePresetFromWorld, tt as isPresetName, vn as parseCharacterFile, vt as deleteLorebookEntry, xn as LORE_SCOPES, xt as listLorebooks, yn as guarded, yt as entriesOf } from "./serial-xcAG57p_.js";
|
|
8
|
+
import { $ as languageOfDocuments, A as generateWorldCharacterPortrait, C as editWorldFaction$1, D as editWorldPlots$1, E as editWorldPlace$1, F as uploadWorldCharacterPortrait, G as parseVariablesEdit, I as uploadWorldEntityImage, J as PRESET_FILE$1, K as parseDiceEdit, L as worldCharacterPortraitFile, M as readWorldEditor, N as readWorldTrigger, O as editWorldRelation$1, P as removeWorldTrigger, R as worldEntityImageFile, S as editWorldCharacter$1, T as editWorldNarrationVoice, U as parseCalendarEdit, W as parseRoutineEdit, Y as presetMessage, Z as translateMessage, _ as readCalendarDocument, a as deleteWorldPackFile, at as startUpdate, b as readRoutines, c as createAuthoredEntity, ct as authoringTitle, dt as agentServicesOf, et as readWorldDocuments, f as editCalendar, ft as DOCTOR_OPENING_SOURCE, g as editVariables, h as editRoutine, it as revertUpdate, j as generateWorldEntityImage, k as editWorldThing$1, l as deleteAuthoredEntity, lt as ensureAuthoringChat, m as editDice, mt as appendNarratedTurn, n as packFileProblem, ot as updateStatus, p as editCommands, pt as appendEmptyTurn, q as parseCommandsEdit, st as AuthoringSessions, t as MAX_PACK_TEXT, tt as findTargets, u as readAuthoredEntityDocument, ut as AgentSessions, v as readCommandsDocument, w as editWorldLore$1, x as readVariables, y as readDiceDocument, z as writeWorldTrigger } from "./pack-jail-KyZen_gy.js";
|
|
9
9
|
import { i as atomicWriteSync, n as atomicWrite, r as atomicWriteJson } from "./access-5vtPAT3O.js";
|
|
10
|
-
import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-
|
|
11
|
-
import { _ as pathTo, c as BranchError, d as recordPreset, f as switchPreset, g as childrenOf, h as START_SNAPSHOT, i as reflectionStatus, l as copyPreset, m as writeTimeline, o as TimelineError, p as readTimeline, u as presetStatus, v as snapshotOf } from "./reflection-
|
|
12
|
-
import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-
|
|
13
|
-
import { D as uniqueKey, T as slug, a as updateImage, d as inheritImages, h as sceneImagePath, i as listGallery, m as referenceImagePath, o as addToLibrary, r as galleryFile } from "./gallery-
|
|
10
|
+
import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-KnqhN_Zv.js";
|
|
11
|
+
import { _ as pathTo, c as BranchError, d as recordPreset, f as switchPreset, g as childrenOf, h as START_SNAPSHOT, i as reflectionStatus, l as copyPreset, m as writeTimeline, o as TimelineError, p as readTimeline, u as presetStatus, v as snapshotOf } from "./reflection-CXS87Di3.js";
|
|
12
|
+
import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-BO8iWQ-n.js";
|
|
13
|
+
import { D as uniqueKey, T as slug, a as updateImage, d as inheritImages, h as sceneImagePath, i as listGallery, m as referenceImagePath, o as addToLibrary, r as galleryFile } from "./gallery-CT5uj50b.js";
|
|
14
14
|
import { o as FOLDER_ACCESS, r as InvalidFoldersError, t as StoryFoldersService } from "./service-mRKwpWjX.js";
|
|
15
15
|
import { t as doctorChatSessionId } from "./doctor-chat-hL1a61hp.js";
|
|
16
|
-
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-
|
|
17
|
-
import { l as generateReferenceImage, n as interpretImage, p as uploadReferenceImage } from "./interpreter-
|
|
16
|
+
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-DU171pDX.js";
|
|
17
|
+
import { l as generateReferenceImage, n as interpretImage, p as uploadReferenceImage } from "./interpreter-Cz5qsuXk.js";
|
|
18
18
|
import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
|
|
19
19
|
import { SESSION_DATABASE_FILE, addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, openSessionStore, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
|
|
20
20
|
import { copyFileSync, cpSync, createReadStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
@@ -224,7 +224,7 @@ var PromptEditError = class extends Error {};
|
|
|
224
224
|
const normal = (text) => text.replace(/\r\n/g, "\n").trimEnd();
|
|
225
225
|
const VARIABLE = /\$\{([A-Za-z]+)\}/g;
|
|
226
226
|
const variablesOf = (text) => [...new Set([...text.matchAll(VARIABLE)].map((match) => match[1]))];
|
|
227
|
-
const ID$
|
|
227
|
+
const ID$2 = /^[a-z0-9-]+(\/[a-z0-9-]+)*$/;
|
|
228
228
|
/**
|
|
229
229
|
* The prompts of the roleplay root, for the person to look at and edit: what each file says, whether it differs from the shipped text, the shipped text itself
|
|
230
230
|
* to compare with, and replacing a file by it. Nothing is replaced by itself and no record is kept of what was shipped when, so a different file may be an edit or a
|
|
@@ -279,7 +279,7 @@ var PromptManager = class {
|
|
|
279
279
|
};
|
|
280
280
|
}
|
|
281
281
|
shipped(id, language) {
|
|
282
|
-
const file = ID$
|
|
282
|
+
const file = ID$2.test(id) ? join(this.library.shipped, language, `${id}.md`) : void 0;
|
|
283
283
|
if (file === void 0 || !LANGUAGE_FOLDER.test(language) || !existsSync(file)) throw new PromptEditError(`there is no shipped prompt "${id}" in "${language}"`);
|
|
284
284
|
return readFileSync(file, "utf8");
|
|
285
285
|
}
|
|
@@ -329,6 +329,280 @@ var AuthoringLanguages = class extends Service {
|
|
|
329
329
|
return join(this.worldsDirectory(), ".authoring", `${encodeURIComponent(worldId)}.json`);
|
|
330
330
|
}
|
|
331
331
|
};
|
|
332
|
+
// src/host/worlds/checkpoints.ts
|
|
333
|
+
const CHECKPOINTS_FOLDER = ".checkpoints";
|
|
334
|
+
const FILES = "files";
|
|
335
|
+
const INFO = "checkpoint.json";
|
|
336
|
+
const RESTORED = "restored.json";
|
|
337
|
+
const ID$1 = /^\d{8}T\d{9}Z-[0-9a-f]{4}$/;
|
|
338
|
+
/** Not versioned: the pictures. Every dot entry at the top (the import's records, the checks, the trash, the checkpoints) is left out too. */
|
|
339
|
+
const LEFT_OUT$1 = /* @__PURE__ */ new Set(["images", "media"]);
|
|
340
|
+
/** A world larger than this (text and packs, not pictures) is not copied: a checkpoint is a safety net for authored text, not a backup of a library. */
|
|
341
|
+
const CHECKPOINT_MAX_BYTES = 67108864;
|
|
342
|
+
/** The longest file the agent may read back from a checkpoint in one call. */
|
|
343
|
+
const CHECKPOINT_READ_CHARS = 2e4;
|
|
344
|
+
var CheckpointError = class extends Error {};
|
|
345
|
+
var CheckpointNotFoundError = class extends CheckpointError {};
|
|
346
|
+
const checkpointsOf = (world) => join(world, CHECKPOINTS_FOLDER);
|
|
347
|
+
const folderOf$3 = (world, id) => join(checkpointsOf(world), id);
|
|
348
|
+
function validId(id) {
|
|
349
|
+
if (!ID$1.test(id)) throw new CheckpointNotFoundError(`there is no checkpoint "${id}"`);
|
|
350
|
+
return id;
|
|
351
|
+
}
|
|
352
|
+
const stamp$1 = () => (/* @__PURE__ */ new Date()).toISOString().replace(/[-:.]/g, "");
|
|
353
|
+
const leftOut = (top) => top.startsWith(".") || LEFT_OUT$1.has(top);
|
|
354
|
+
/** The world's files that a checkpoint keeps, by path with the hash of their content. Links are skipped. */
|
|
355
|
+
async function scan(world, dir = "", top = true) {
|
|
356
|
+
const manifest = {};
|
|
357
|
+
let bytes = 0;
|
|
358
|
+
for (const entry of await readdir(join(world, dir), { withFileTypes: true })) {
|
|
359
|
+
if (top && leftOut(entry.name)) continue;
|
|
360
|
+
const path = dir === "" ? entry.name : `${dir}/${entry.name}`;
|
|
361
|
+
if (entry.isDirectory()) {
|
|
362
|
+
const inner = await scan(world, path, false);
|
|
363
|
+
Object.assign(manifest, inner.manifest);
|
|
364
|
+
bytes += inner.bytes;
|
|
365
|
+
} else if (entry.isFile()) {
|
|
366
|
+
const data = await readFile(join(world, path));
|
|
367
|
+
manifest[path] = createHash("sha256").update(data).digest("hex");
|
|
368
|
+
bytes += data.length;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return {
|
|
372
|
+
manifest,
|
|
373
|
+
bytes
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
const same = (a, b) => {
|
|
377
|
+
const keys = Object.keys(a);
|
|
378
|
+
return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key]);
|
|
379
|
+
};
|
|
380
|
+
async function readStored(world, id) {
|
|
381
|
+
try {
|
|
382
|
+
return JSON.parse(await readFile(join(folderOf$3(world, validId(id)), INFO), "utf8"));
|
|
383
|
+
} catch (error) {
|
|
384
|
+
if (error.code === "ENOENT") throw new CheckpointNotFoundError(`there is no checkpoint "${id}"`);
|
|
385
|
+
throw error;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
const infoOf = ({ manifest: _manifest, ...info }) => info;
|
|
389
|
+
/** The checkpoints of a world, newest first. A folder that was cut short (no record) is not one. */
|
|
390
|
+
async function listCheckpoints(world) {
|
|
391
|
+
let names;
|
|
392
|
+
try {
|
|
393
|
+
names = await readdir(checkpointsOf(world));
|
|
394
|
+
} catch (error) {
|
|
395
|
+
if (error.code === "ENOENT") return [];
|
|
396
|
+
throw error;
|
|
397
|
+
}
|
|
398
|
+
const found = [];
|
|
399
|
+
for (const name of names.filter((each) => ID$1.test(each))) try {
|
|
400
|
+
found.push(infoOf(await readStored(world, name)));
|
|
401
|
+
} catch (error) {
|
|
402
|
+
if (!(error instanceof CheckpointNotFoundError)) throw error;
|
|
403
|
+
}
|
|
404
|
+
return found.sort((a, b) => a.id < b.id ? 1 : -1);
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Copies the world's files into `<world>/.checkpoints/<id>/`. A world that is the same as its newest checkpoint is not copied again, except on request. Older checkpoints beyond `keep` are removed.
|
|
408
|
+
* @returns the checkpoint, and whether it was made now.
|
|
409
|
+
*/
|
|
410
|
+
async function makeCheckpoint(world, request) {
|
|
411
|
+
const { manifest, bytes } = await scan(world);
|
|
412
|
+
if (bytes > 67108864) throw new CheckpointError(`the world's files are ${Math.round(bytes / 1024 / 1024)} MB, more than the ${CHECKPOINT_MAX_BYTES / 1024 / 1024} MB a checkpoint keeps`);
|
|
413
|
+
const latest = (await listCheckpoints(world))[0];
|
|
414
|
+
if (latest !== void 0 && request.reason !== "manual" && same((await readStored(world, latest.id)).manifest, manifest)) return {
|
|
415
|
+
checkpoint: latest,
|
|
416
|
+
made: false
|
|
417
|
+
};
|
|
418
|
+
const id = `${stamp$1()}-${randomBytes(2).toString("hex")}`;
|
|
419
|
+
const target = folderOf$3(world, id);
|
|
420
|
+
try {
|
|
421
|
+
for (const path of Object.keys(manifest)) {
|
|
422
|
+
const to = join(target, FILES, path);
|
|
423
|
+
await mkdir(dirname(to), { recursive: true });
|
|
424
|
+
await copyFile(join(world, path), to);
|
|
425
|
+
}
|
|
426
|
+
const info = {
|
|
427
|
+
id,
|
|
428
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
429
|
+
label: request.label.slice(0, 200),
|
|
430
|
+
reason: request.reason,
|
|
431
|
+
...request.chat === void 0 ? {} : { chat: request.chat },
|
|
432
|
+
...request.turn === void 0 ? {} : { turn: request.turn },
|
|
433
|
+
files: Object.keys(manifest).length,
|
|
434
|
+
bytes,
|
|
435
|
+
manifest
|
|
436
|
+
};
|
|
437
|
+
await mkdir(target, { recursive: true });
|
|
438
|
+
await atomicWriteJson(join(target, INFO), info);
|
|
439
|
+
await prune(world, request.keep);
|
|
440
|
+
return {
|
|
441
|
+
checkpoint: infoOf(info),
|
|
442
|
+
made: true
|
|
443
|
+
};
|
|
444
|
+
} catch (error) {
|
|
445
|
+
await rm(target, {
|
|
446
|
+
recursive: true,
|
|
447
|
+
force: true
|
|
448
|
+
});
|
|
449
|
+
throw error;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
async function prune(world, keep) {
|
|
453
|
+
const all = await listCheckpoints(world);
|
|
454
|
+
for (const old of all.slice(Math.max(1, keep))) await rm(folderOf$3(world, old.id), {
|
|
455
|
+
recursive: true,
|
|
456
|
+
force: true
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
/** What differs between the world as it is and a checkpoint. */
|
|
460
|
+
async function diffCheckpoint(world, id) {
|
|
461
|
+
const stored = await readStored(world, id);
|
|
462
|
+
const { manifest } = await scan(world);
|
|
463
|
+
return {
|
|
464
|
+
changed: Object.keys(manifest).filter((path) => stored.manifest[path] !== void 0 && stored.manifest[path] !== manifest[path]).sort((a, b) => a.localeCompare(b)),
|
|
465
|
+
added: Object.keys(manifest).filter((path) => stored.manifest[path] === void 0).sort((a, b) => a.localeCompare(b)),
|
|
466
|
+
removed: Object.keys(stored.manifest).filter((path) => manifest[path] === void 0).sort((a, b) => a.localeCompare(b))
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
/** One file as the checkpoint has it. The path is one the checkpoint holds, never a way out of it. */
|
|
470
|
+
async function readCheckpointFile(world, id, path) {
|
|
471
|
+
const stored = await readStored(world, id);
|
|
472
|
+
const clean = normalize(path).split(sep).join("/");
|
|
473
|
+
if (clean.startsWith("..") || clean.startsWith("/") || stored.manifest[clean] === void 0) throw new CheckpointNotFoundError(`checkpoint ${id} has no file "${path}"`);
|
|
474
|
+
const text = await readFile(join(folderOf$3(world, id), FILES, clean), "utf8");
|
|
475
|
+
return {
|
|
476
|
+
path: clean,
|
|
477
|
+
text: text.slice(0, CHECKPOINT_READ_CHARS),
|
|
478
|
+
of: text.length,
|
|
479
|
+
truncated: text.length > CHECKPOINT_READ_CHARS
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
/** Puts the world's files back as a checkpoint has them. What is there now is first kept as a checkpoint of its own and moved to the trash, so a restore can be undone. */
|
|
483
|
+
async function restoreCheckpoint(world, id, keep) {
|
|
484
|
+
const stored = await readStored(world, id);
|
|
485
|
+
for (const path of Object.keys(stored.manifest)) await stat(join(folderOf$3(world, id), FILES, path)).catch(() => {
|
|
486
|
+
throw new CheckpointError(`checkpoint ${id} is incomplete: ${path} is missing`);
|
|
487
|
+
});
|
|
488
|
+
const before = (await makeCheckpoint(world, {
|
|
489
|
+
label: `Before restoring “${stored.label}”`,
|
|
490
|
+
reason: "before-restore",
|
|
491
|
+
keep: keep + 1
|
|
492
|
+
})).checkpoint;
|
|
493
|
+
const trash = join(world, ".trash", `restore-${stamp$1()}`);
|
|
494
|
+
const moved = [];
|
|
495
|
+
const placed = [];
|
|
496
|
+
try {
|
|
497
|
+
await mkdir(trash, { recursive: true });
|
|
498
|
+
for (const entry of await readdir(world)) {
|
|
499
|
+
if (leftOut(entry)) continue;
|
|
500
|
+
await rename(join(world, entry), join(trash, entry));
|
|
501
|
+
moved.push(entry);
|
|
502
|
+
}
|
|
503
|
+
for (const path of Object.keys(stored.manifest)) {
|
|
504
|
+
const to = join(world, path);
|
|
505
|
+
await mkdir(dirname(to), { recursive: true });
|
|
506
|
+
await copyFile(join(folderOf$3(world, id), FILES, path), to);
|
|
507
|
+
placed.push(path.split("/")[0]);
|
|
508
|
+
}
|
|
509
|
+
await atomicWriteJson(join(checkpointsOf(world), RESTORED), {
|
|
510
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
511
|
+
checkpoint: id,
|
|
512
|
+
label: stored.label
|
|
513
|
+
});
|
|
514
|
+
await prune(world, keep);
|
|
515
|
+
} catch (error) {
|
|
516
|
+
for (const top of new Set(placed)) await rm(join(world, top), {
|
|
517
|
+
recursive: true,
|
|
518
|
+
force: true
|
|
519
|
+
});
|
|
520
|
+
for (const entry of moved) await rename(join(trash, entry), join(world, entry)).catch(() => void 0);
|
|
521
|
+
throw error;
|
|
522
|
+
}
|
|
523
|
+
return {
|
|
524
|
+
restored: infoOf(stored),
|
|
525
|
+
before
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
/** When and to what the world was last restored by the person, so that an authoring chat can be told. */
|
|
529
|
+
async function lastRestore(world) {
|
|
530
|
+
try {
|
|
531
|
+
return JSON.parse(await readFile(join(checkpointsOf(world), RESTORED), "utf8"));
|
|
532
|
+
} catch (error) {
|
|
533
|
+
if (error.code === "ENOENT") return void 0;
|
|
534
|
+
throw error;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
// src/host/worlds/checkpoint-service.ts
|
|
538
|
+
/** A restore was asked for while the world's authoring assistant is working on it. */
|
|
539
|
+
var CheckpointBusyError = class extends CheckpointError {};
|
|
540
|
+
/** The checkpoints of the worlds, by world id: made at the first edit of an authoring turn or on request, read back, compared and restored. */
|
|
541
|
+
var WorldCheckpoints = class extends Service {
|
|
542
|
+
kept;
|
|
543
|
+
problem;
|
|
544
|
+
taken = /* @__PURE__ */ new Map();
|
|
545
|
+
told = /* @__PURE__ */ new Map();
|
|
546
|
+
constructor(ctx, kept, problem) {
|
|
547
|
+
super(ctx, "roleplayCheckpoints");
|
|
548
|
+
this.kept = kept;
|
|
549
|
+
this.problem = problem;
|
|
550
|
+
}
|
|
551
|
+
async directory(worldId) {
|
|
552
|
+
const record = await this.ctx.roleplayWorlds.find(worldId);
|
|
553
|
+
if (record === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
|
|
554
|
+
return record.directory;
|
|
555
|
+
}
|
|
556
|
+
async list(worldId) {
|
|
557
|
+
return await listCheckpoints(await this.directory(worldId));
|
|
558
|
+
}
|
|
559
|
+
async make(worldId, label) {
|
|
560
|
+
return (await makeCheckpoint(await this.directory(worldId), {
|
|
561
|
+
label: label.trim() === "" ? "Checkpoint" : label.trim(),
|
|
562
|
+
reason: "manual",
|
|
563
|
+
keep: this.kept()
|
|
564
|
+
})).checkpoint;
|
|
565
|
+
}
|
|
566
|
+
async diff(worldId, id) {
|
|
567
|
+
return await diffCheckpoint(await this.directory(worldId), id);
|
|
568
|
+
}
|
|
569
|
+
async read(worldId, id, path) {
|
|
570
|
+
return await readCheckpointFile(await this.directory(worldId), id, path);
|
|
571
|
+
}
|
|
572
|
+
/** Puts a world back as a checkpoint has it; refused while its authoring assistant is in the middle of a turn. */
|
|
573
|
+
async restore(worldId, id, running) {
|
|
574
|
+
if (running) throw new CheckpointBusyError("the authoring assistant is working on this world: wait for it to finish, then restore");
|
|
575
|
+
const outcome = await restoreCheckpoint(await this.directory(worldId), id, this.kept());
|
|
576
|
+
await this.ctx.roleplayWorlds.list({ refresh: true });
|
|
577
|
+
return outcome;
|
|
578
|
+
}
|
|
579
|
+
/** The first edit of an authoring chat's turn: the world as it is, before the turn changes it. A checkpoint that cannot be made never stops the edit. */
|
|
580
|
+
async beforeEdit(chat, turn, tool) {
|
|
581
|
+
const worldId = authoredWorldOf(chat);
|
|
582
|
+
if (worldId === void 0 || this.taken.get(chat) === turn) return;
|
|
583
|
+
this.taken.set(chat, turn);
|
|
584
|
+
try {
|
|
585
|
+
await makeCheckpoint(await this.directory(worldId), {
|
|
586
|
+
label: `Before the edits of turn ${turn} (${tool})`,
|
|
587
|
+
reason: "turn",
|
|
588
|
+
chat,
|
|
589
|
+
turn,
|
|
590
|
+
keep: this.kept()
|
|
591
|
+
});
|
|
592
|
+
} catch (error) {
|
|
593
|
+
this.problem(`could not make a checkpoint of world ${worldId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
/** What a chat has not been told yet about the person restoring its world. */
|
|
597
|
+
async unannouncedRestore(chat) {
|
|
598
|
+
const worldId = authoredWorldOf(chat);
|
|
599
|
+
if (worldId === void 0) return void 0;
|
|
600
|
+
const restored = await lastRestore(await this.directory(worldId));
|
|
601
|
+
if (restored === void 0 || this.told.get(chat) === restored.at) return void 0;
|
|
602
|
+
this.told.set(chat, restored.at);
|
|
603
|
+
return restored;
|
|
604
|
+
}
|
|
605
|
+
};
|
|
332
606
|
// src/host/worlds/draft.ts
|
|
333
607
|
/** Whether the world is an import that was written but would not start yet: its import state (kept in the world's `.import` folder) says it is being repaired. */
|
|
334
608
|
async function isDraftWorld(directory) {
|
|
@@ -3277,8 +3551,15 @@ function languageField(value) {
|
|
|
3277
3551
|
}
|
|
3278
3552
|
}
|
|
3279
3553
|
// src/host/http/routes/worlds.ts
|
|
3554
|
+
/** Answers a failed checkpoint request with the status that says what was wrong. */
|
|
3555
|
+
function checkpointFailure(res, error) {
|
|
3556
|
+
if (error instanceof WorldNotFoundError || error instanceof CheckpointNotFoundError) return sendError(res, 404, error.message);
|
|
3557
|
+
if (error instanceof CheckpointBusyError) return sendError(res, 409, error.message);
|
|
3558
|
+
if (error instanceof CheckpointError) return sendError(res, 422, error.message);
|
|
3559
|
+
throw error;
|
|
3560
|
+
}
|
|
3280
3561
|
/** The routes of the API for worlds. */
|
|
3281
|
-
function worldsRoutes({ worlds, createWorld, starter, authorWorld, sayToAuthor, authoringStatus, chatStatus, forgetAuthoring, translation, worldCharacters, avatars, playtest }) {
|
|
3562
|
+
function worldsRoutes({ worlds, createWorld, starter, authorWorld, sayToAuthor, authoringStatus, chatStatus, checkpoints, forgetAuthoring, translation, worldCharacters, avatars, playtest }) {
|
|
3282
3563
|
return {
|
|
3283
3564
|
"/worlds": {
|
|
3284
3565
|
GET: async (_req, res) => {
|
|
@@ -3366,6 +3647,41 @@ function worldsRoutes({ worlds, createWorld, starter, authorWorld, sayToAuthor,
|
|
|
3366
3647
|
throw error;
|
|
3367
3648
|
}
|
|
3368
3649
|
} },
|
|
3650
|
+
"/worlds/checkpoints": {
|
|
3651
|
+
GET: async (_req, res, url) => {
|
|
3652
|
+
try {
|
|
3653
|
+
sendJson(res, 200, { checkpoints: await checkpoints.list(url.searchParams.get("id") ?? "") });
|
|
3654
|
+
} catch (error) {
|
|
3655
|
+
return checkpointFailure(res, error);
|
|
3656
|
+
}
|
|
3657
|
+
},
|
|
3658
|
+
POST: async (req, res, url) => {
|
|
3659
|
+
const body = await readJsonBody(req);
|
|
3660
|
+
if (body.label !== void 0 && typeof body.label !== "string") return sendError(res, 400, "label must be text");
|
|
3661
|
+
try {
|
|
3662
|
+
sendJson(res, 201, await checkpoints.make(url.searchParams.get("id") ?? "", body.label ?? ""));
|
|
3663
|
+
} catch (error) {
|
|
3664
|
+
return checkpointFailure(res, error);
|
|
3665
|
+
}
|
|
3666
|
+
}
|
|
3667
|
+
},
|
|
3668
|
+
"/worlds/checkpoints/diff": { GET: async (_req, res, url) => {
|
|
3669
|
+
try {
|
|
3670
|
+
sendJson(res, 200, await checkpoints.diff(url.searchParams.get("id") ?? "", url.searchParams.get("checkpoint") ?? ""));
|
|
3671
|
+
} catch (error) {
|
|
3672
|
+
return checkpointFailure(res, error);
|
|
3673
|
+
}
|
|
3674
|
+
} },
|
|
3675
|
+
"/worlds/checkpoints/restore": { POST: async (req, res, url) => {
|
|
3676
|
+
const body = await readJsonBody(req);
|
|
3677
|
+
if (typeof body.checkpoint !== "string") return sendError(res, 400, "checkpoint must be text");
|
|
3678
|
+
const id = url.searchParams.get("id") ?? "";
|
|
3679
|
+
try {
|
|
3680
|
+
sendJson(res, 200, await checkpoints.restore(id, body.checkpoint, (await authoringStatus(id)).running));
|
|
3681
|
+
} catch (error) {
|
|
3682
|
+
return checkpointFailure(res, error);
|
|
3683
|
+
}
|
|
3684
|
+
} },
|
|
3369
3685
|
"/worlds/language": { GET: async (_req, res, url) => {
|
|
3370
3686
|
try {
|
|
3371
3687
|
const id = url.searchParams.get("id") ?? "";
|
|
@@ -9819,6 +10135,7 @@ const Config = z.object({
|
|
|
9819
10135
|
}).default({ ...DEFAULT_OFFLOAD }).volatile(),
|
|
9820
10136
|
catalogueMaxBytes: z.number().min(1024).default(268435456).volatile(),
|
|
9821
10137
|
catalogueTrashDays: z.number().min(0).default(30).volatile(),
|
|
10138
|
+
worldCheckpointsKept: z.number().min(1).max(500).default(30).volatile(),
|
|
9822
10139
|
autonomyTickSeconds: z.number().min(0).max(3600).default(30).volatile(),
|
|
9823
10140
|
importMaxUploadBytes: z.number().min(1024).default(104857600).volatile(),
|
|
9824
10141
|
importConcurrency: z.number().min(1).max(16).default(4).volatile(),
|
|
@@ -9883,6 +10200,9 @@ function apply(ctx, config) {
|
|
|
9883
10200
|
installFirstPartyPacks(root.path);
|
|
9884
10201
|
const languages = new AuthoringLanguages(ctx, () => join(root.path, "worlds"));
|
|
9885
10202
|
const authoringTools = new AuthoringTools(ctx, () => config.authoringTools.get());
|
|
10203
|
+
const checkpoints = new WorldCheckpoints(ctx, () => config.worldCheckpointsKept.get(), (message) => {
|
|
10204
|
+
ctx.logger.warn(message);
|
|
10205
|
+
});
|
|
9886
10206
|
const agent = new AgentSessions(agentServicesOf(ctx), () => root.path);
|
|
9887
10207
|
const autonomy = new AutonomyTicker({
|
|
9888
10208
|
sessions: () => listSessions({
|
|
@@ -10160,6 +10480,7 @@ function apply(ctx, config) {
|
|
|
10160
10480
|
return chatStatus(authoringChatSessionId(world.summary.id));
|
|
10161
10481
|
},
|
|
10162
10482
|
chatStatus,
|
|
10483
|
+
checkpoints,
|
|
10163
10484
|
forgetAuthoring: async (worldId) => {
|
|
10164
10485
|
const world = await worlds.find(worldId);
|
|
10165
10486
|
if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { l as runChild } from "./child-Bfj7-Iuo.js";
|
|
2
2
|
import { n as atomicWrite, t as promptFor } from "./access-5vtPAT3O.js";
|
|
3
|
-
import { a as updateImage, f as nextSceneSerial, g as writeImage, h as sceneImagePath, i as listGallery, m as referenceImagePath, r as galleryFile } from "./gallery-
|
|
3
|
+
import { a as updateImage, f as nextSceneSerial, g as writeImage, h as sceneImagePath, i as listGallery, m as referenceImagePath, r as galleryFile } from "./gallery-CT5uj50b.js";
|
|
4
4
|
import { join, relative, sep } from "node:path";
|
|
5
5
|
import { characterKey, itemKey, locationKey } from "@dsh-agentic-roleplay/state";
|
|
6
6
|
import { existsSync } from "node:fs";
|
|
@@ -852,7 +852,7 @@ const RESULT = {
|
|
|
852
852
|
/** A model given as `provider/model`, or the one the chat runs on when `chosen` is empty. */
|
|
853
853
|
function modelOf(parent, chosen) {
|
|
854
854
|
const named = chosen.trim();
|
|
855
|
-
const config = parent.session.requestHeader()?.config;
|
|
855
|
+
const config = parent.model.current() ?? parent.session.requestHeader()?.config;
|
|
856
856
|
const [provider, ...rest] = named === "" ? [config?.provider, config?.model] : named.split("/");
|
|
857
857
|
const model = named === "" ? config?.model : rest.join("/");
|
|
858
858
|
if (provider === void 0 || provider === "" || model === void 0 || model === "") throw new Error(named === "" ? "this chat has no model selected" : `"${named}" is not provider/model`);
|
|
@@ -936,4 +936,4 @@ async function interpretImage(job) {
|
|
|
936
936
|
}
|
|
937
937
|
export { searchImages as a, presentedFor as c, referencePrompt as d, transientPrompt as f, findImages as i, generateReferenceImage as l, interpretImage as n, tokensOf as o, uploadReferenceImage as p, imageTools as r, present as s, canReadImages as t, generateTransientImage as u };
|
|
938
938
|
|
|
939
|
-
//# sourceMappingURL=interpreter-
|
|
939
|
+
//# sourceMappingURL=interpreter-Cz5qsuXk.js.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import "./access-5vtPAT3O.js";
|
|
2
|
-
import { Gt as ImportCardError, o as contextOf, r as MAX_PREVIEW_TEXT } from "./authoring-tools-
|
|
3
|
-
import {
|
|
4
|
-
import { F as textLanguage, I as wrongLanguage, at as shippedPromptsDirectory } from "./hooks-
|
|
5
|
-
import { i as translator, r as languageOf } from "./text-
|
|
6
|
-
import { C as mapLimit, D as uniqueKey, E as trOf, T as slug } from "./gallery-
|
|
2
|
+
import { Gt as ImportCardError, o as contextOf, r as MAX_PREVIEW_TEXT } from "./authoring-tools-CKV1UnN7.js";
|
|
3
|
+
import { Ct as lorebookDirectory, Dt as writeLorebookEntry, Et as updateLorebookInfo, Ft as IMPORT_FOLDER, Nt as partsOf, Pt as withPlayer, Q as createPresetFromGuidance, St as loadLorebook, bn as LORE_KINDS, jt as cleanText, vt as deleteLorebookEntry, wt as readLorebook$1, xn as LORE_SCOPES, yt as entriesOf } from "./serial-xcAG57p_.js";
|
|
4
|
+
import { F as textLanguage, I as wrongLanguage, at as shippedPromptsDirectory } from "./hooks-CnxV2uEh.js";
|
|
5
|
+
import { i as translator, r as languageOf } from "./text-KnqhN_Zv.js";
|
|
6
|
+
import { C as mapLimit, D as uniqueKey, E as trOf, T as slug } from "./gallery-CT5uj50b.js";
|
|
7
7
|
import { join } from "node:path";
|
|
8
8
|
import { existsSync, readFileSync } from "node:fs";
|
|
9
9
|
import { readFile, rm, writeFile } from "node:fs/promises";
|
|
@@ -709,4 +709,4 @@ async function lorebookApproval(exec, next, state) {
|
|
|
709
709
|
}
|
|
710
710
|
export { lorebookImportMessage as a, readLorebook as c, lorebookOfChat as d, lorebookAuthorTools as i, selectEntries as l, LorebookReader as n, pendingTargets as o, lorebookApproval as r, previewLorebook as s, LOREBOOK_UPLOAD as t, lorebookChatSessionId as u };
|
|
711
711
|
|
|
712
|
-
//# sourceMappingURL=lorebook-author-tools-
|
|
712
|
+
//# sourceMappingURL=lorebook-author-tools-p3Nfpuxh.js.map
|