@dsh-agentic-roleplay/core 0.11.1 → 0.12.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.
Files changed (50) hide show
  1. package/lib/{access-Md1YTSX1.js → access-DAw54-NI.js} +3 -15
  2. package/lib/{authoring-tools-BFdw7ahj.js → authoring-tools-4NgDhIJV.js} +51 -11
  3. package/lib/authoring.js +8 -8
  4. package/lib/{child-C9nPIy9j.js → child-D3QUNb3m.js} +121 -2
  5. package/lib/client.js +1013 -449
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -3
  8. package/lib/doctor.js +3 -3
  9. package/lib/{gallery-BWHmjogd.js → gallery-Ct6nm4UQ.js} +3 -3
  10. package/lib/{generator-QCdm8nUh.js → generator-CI8fOnXy.js} +2 -2
  11. package/lib/helper.js +13 -1
  12. package/lib/{hooks-C2U1-8ur.js → hooks-BNeoGMHZ.js} +722 -334
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +234 -20
  15. package/lib/jail-BIF79PJO.js +107 -0
  16. package/lib/{library-4zmCAshR.js → library-BF9ZMSFz.js} +3 -3
  17. package/lib/{lorebook-author-tools-Bjfjt3bg.js → lorebook-author-tools-DBk-V0hp.js} +7 -7
  18. package/lib/lorebook-authoring.js +4 -4
  19. package/lib/{narration-b_VBEUWn.js → narration-xvErE2yp.js} +29 -2
  20. package/lib/orchestration.js +593 -47
  21. package/lib/{pack-jail-Ci9bIeDI.js → pack-jail-C8EyX9Ix.js} +12 -11
  22. package/lib/{packs-CYkozh8Q.js → packs-S0SzrVv-.js} +2 -2
  23. package/lib/{presenter-agent-CqkAL03Q.js → presenter-agent-Bc478nTA.js} +6 -6
  24. package/lib/{preset-B-35yUmt.js → preset-SJZyw0kt.js} +4 -4
  25. package/lib/{preset-author-tools-BUymqZM5.js → preset-author-tools-CzogjK42.js} +7 -7
  26. package/lib/preset-authoring.js +5 -5
  27. package/lib/{presets-_U-xroo0.js → presets-DQ5rioMh.js} +231 -48
  28. package/lib/{reflection-B9N0z3KY.js → reflection-buQiSdvq.js} +15 -8
  29. package/lib/service-mRKwpWjX.js +140 -0
  30. package/lib/{text-C2AGl7Je.js → text-Dfv8S8eq.js} +27 -2
  31. package/lib/{turn-guard-C0M3rXEN.js → turn-guard-BSAba8sp.js} +3 -3
  32. package/package.json +3 -3
  33. package/prompts/en/import/finish-ok.md +1 -1
  34. package/prompts/en/import/generator.md +1 -1
  35. package/prompts/en/import/style.md +1 -1
  36. package/prompts/en/import/variables.md +2 -1
  37. package/prompts/en/roleplay/character-lookup.md +1 -1
  38. package/prompts/en/roleplay/decide-errand.md +1 -0
  39. package/prompts/en/roleplay/decide-message.md +1 -0
  40. package/prompts/en/roleplay/dream.md +1 -0
  41. package/prompts/en/roleplay/gate-repeat.md +1 -0
  42. package/prompts/zh/import/finish-ok.md +1 -1
  43. package/prompts/zh/import/generator.md +1 -1
  44. package/prompts/zh/import/style.md +1 -1
  45. package/prompts/zh/import/variables.md +2 -1
  46. package/prompts/zh/roleplay/character-lookup.md +1 -1
  47. package/prompts/zh/roleplay/decide-errand.md +1 -0
  48. package/prompts/zh/roleplay/decide-message.md +1 -0
  49. package/prompts/zh/roleplay/dream.md +1 -0
  50. package/prompts/zh/roleplay/gate-repeat.md +1 -0
@@ -1,20 +1,8 @@
1
+ import { j as roleplaySessionOf } from "./child-D3QUNb3m.js";
1
2
  import { basename, dirname, join } from "node:path";
2
3
  import { chmodSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
4
  import { randomUUID } from "node:crypto";
4
5
  import { chmod, mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
5
- // src/shared/chat.ts
6
- const CHAT_PREFIX = "session-";
7
- const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
8
- /** The DSH chat of a roleplay session is named after the session's id. */
9
- function chatSessionId(sessionId) {
10
- return `${CHAT_PREFIX}${sessionId}`;
11
- }
12
- /** The roleplay session a DSH chat id could belong to; ordinary DSH chats have ids of the same shape. */
13
- function roleplaySessionOf(chat) {
14
- if (!chat.startsWith(CHAT_PREFIX)) return void 0;
15
- const id = chat.slice(8);
16
- return UUID_V4.test(id) ? id : void 0;
17
- }
18
6
  // ../dsh-roleplay-model/src/variable.ts
19
7
  /** What a variable holds: a number within bounds, a yes or no, or one of a list of words. */
20
8
  const VARIABLE_KINDS = [
@@ -193,6 +181,6 @@ function promptFor(agent, id, language, variables) {
193
181
  if (library === void 0) throw new Error("the prompt library is not running");
194
182
  return library.text(id, language, variables, roleplaySessionOf(agent.session.id));
195
183
  }
196
- export { VARIABLE_KINDS as a, chatSessionId as c, atomicWriteSync as i, roleplaySessionOf as l, atomicWrite as n, VARIABLE_SUBJECTS as o, atomicWriteJson as r, VARIABLE_VISIBILITIES as s, promptFor as t };
184
+ export { VARIABLE_KINDS as a, atomicWriteSync as i, atomicWrite as n, VARIABLE_SUBJECTS as o, atomicWriteJson as r, VARIABLE_VISIBILITIES as s, promptFor as t };
197
185
 
198
- //# sourceMappingURL=access-Md1YTSX1.js.map
186
+ //# sourceMappingURL=access-DAw54-NI.js.map
@@ -1,10 +1,10 @@
1
- import { n as atomicWrite, r as atomicWriteJson } from "./access-Md1YTSX1.js";
2
- import { $ as IMPORT_FOLDER, A as sourcesFor, At as InvalidEditProblems, Bt as WEEKDAY_NAMES, C as inert, Ct as parseSlotsFile, D as pruneLoreSubjects, Dt as parseCharacterFile, E as pruneLinks, Et as CHARACTER_FILE_NAME, F as ROLE_TABLE, I as isLeftOut, Lt as guarded, M as classifyItems, N as findEntity, O as pruneMembers, Ot as readVariableValues, P as ROLES, Q as withPlayer, R as askYesNo, Rt as LORE_KINDS, S as extractVariables, St as parseItemFile, T as pruneKnowledge, Tt as parseFactionFile, U as yesAt, V as noAt, Vt as DEFAULT_SLOTS, X as itemise, Y as cleanText, _ as characterDocument, _t as parseLoreFile, a as isPresetName, at as readImportFolder, b as extractStyle, bt as ITEM_FILE_NAME, ft as VARIABLES_FILE_NAME, g as asWritten, gt as LORE_FILE_NAME, h as addLore, ht as variableProblems, j as buildRoster, k as pruneRelationships, kt as readIdentifier, nt as PICTURE_FILE, pt as loadVariables, rt as openingText, st as dialectOf, ut as parseImportCommand, v as emptyExtracted, vt as LOCATION_FILE_NAME, w as loreDocuments, wt as FACTION_FILE_NAME, xt as SLOTS_FILE_NAME, y as extractEntities, yt as parseLocationFile, zt as LORE_SCOPES } from "./presets-_U-xroo0.js";
3
- import { f as parseSwitchboard } from "./narration-b_VBEUWn.js";
4
- import { G as readDocument$1, J as errorMessage, K as Reader, Q as copyWorldPrompts, U as commandFlagKey, V as plotReferenceProblems, X as PROMPTS_FOLDER, _t as COMPARISONS, a as externalWithheld, at as shippedText, ct as InvalidWorldError, nt as promptProblem, q as formatIssue, r as externalGiven, rt as shippedLanguages, t as externalToolLimit, tt as listFiles, z as loadPlots } from "./hooks-C2U1-8ur.js";
5
- import { t as trimCharacters } from "./text-C2AGl7Je.js";
6
- import { S as currentTurn, c as namedModel, d as parseSampling, l as runChild, t as ChildTimeoutError } from "./child-C9nPIy9j.js";
7
- import { C as slug, S as norm, T as uniqueKey, _ as writeImageFileMetadata, b as NoEmbeddingService, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as trOf, x as mapLimit } from "./library-4zmCAshR.js";
1
+ import { T as currentTurn, c as namedModel, l as runChild, m as parseSampling, t as ChildTimeoutError } from "./child-D3QUNb3m.js";
2
+ import { $ as IMPORT_FOLDER, A as sourcesFor, At as readVariableValues, Bt as LORE_KINDS, C as inert, Ct as SLOTS_FILE_NAME, D as pruneLoreSubjects, Dt as parseFactionFile, E as pruneLinks, Et as FACTION_FILE_NAME, F as ROLE_TABLE, Ht as WEEKDAY_NAMES, I as isLeftOut, M as classifyItems, Mt as InvalidEditProblems, N as findEntity, O as pruneMembers, Ot as CHARACTER_FILE_NAME, P as ROLES, Q as withPlayer, R as askYesNo, S as extractVariables, St as ITEM_FILE_NAME, T as pruneKnowledge, Tt as parseSlotsFile, U as yesAt, Ut as DEFAULT_SLOTS, V as noAt, Vt as LORE_SCOPES, X as itemise, Y as cleanText, _ as characterDocument, _t as variableProblems, a as isPresetName, at as readImportFolder, b as extractStyle, bt as LOCATION_FILE_NAME, ct as parseImportCommand, dt as splitPanels, ft as dialectOf, g as asWritten, h as addLore, ht as loadVariables, j as buildRoster, jt as readIdentifier, k as pruneRelationships, kt as parseCharacterFile, mt as VARIABLES_FILE_NAME, nt as PICTURE_FILE, rt as openingText, ut as findPanel, v as emptyExtracted, vt as LORE_FILE_NAME, w as loreDocuments, wt as parseItemFile, xt as parseLocationFile, y as extractEntities, yt as parseLoreFile, zt as guarded } from "./presets-DQ5rioMh.js";
3
+ import { f as parseSwitchboard } from "./narration-xvErE2yp.js";
4
+ import { n as atomicWrite, r as atomicWriteJson } from "./access-DAw54-NI.js";
5
+ import { G as readDocument$1, J as errorMessage, K as Reader, Q as copyWorldPrompts, U as commandFlagKey, V as plotReferenceProblems, X as PROMPTS_FOLDER, _t as COMPARISONS, a as externalGiven, at as shippedText, ct as InvalidWorldError, nt as promptProblem, q as formatIssue, rt as shippedLanguages, s as externalWithheld, t as externalToolLimit, tt as listFiles, z as loadPlots } from "./hooks-BNeoGMHZ.js";
6
+ import { t as trimCharacters } from "./text-Dfv8S8eq.js";
7
+ import { C as slug, S as norm, T as uniqueKey, _ as writeImageFileMetadata, b as NoEmbeddingService, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as trOf, x as mapLimit } from "./library-BF9ZMSFz.js";
8
8
  import { dirname, join, relative } from "node:path";
9
9
  import { MINUTE, MONTH_NAMES, SEASONS, checkProblems, createSessionStore, dayTokenProblems, isTimeZone, lintWorld, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, writeCalendar } from "@dsh-agentic-roleplay/state";
10
10
  import { existsSync, readFileSync } from "node:fs";
@@ -1118,6 +1118,7 @@ function populateRoutines(session, characters) {
1118
1118
  end: parseTimeOfDay(window.to),
1119
1119
  activity: window.activity,
1120
1120
  interruptible: window.interruptible,
1121
+ ...window.sleep === true ? { sleep: true } : {},
1121
1122
  ...window.location === void 0 ? {} : { locationId: session.locations.getBySourceId(window.location).id },
1122
1123
  ...window.feature === void 0 ? {} : { featureKey: window.feature },
1123
1124
  ...window.position === void 0 ? {} : { position: window.position }
@@ -2145,7 +2146,7 @@ function parseWorldInfoEdit(value) {
2145
2146
  const input = typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2146
2147
  if (input === void 0) throw new InvalidEditProblems(["the changes must be an object"]);
2147
2148
  const edit = {};
2148
- for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings" && key !== "startQuestions" && key !== "tools" && key !== "sampling") problems.push(`there is no field "${key}"`);
2149
+ for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings" && key !== "startQuestions" && key !== "tools" && key !== "sampling" && key !== "autonomy") problems.push(`there is no field "${key}"`);
2149
2150
  for (const key of TEXT_FIELDS) {
2150
2151
  if (input[key] === void 0) continue;
2151
2152
  if (typeof input[key] === "string") edit[key] = input[key].trim();
@@ -2180,6 +2181,10 @@ function parseWorldInfoEdit(value) {
2180
2181
  if (typeof board === "string") problems.push(board);
2181
2182
  else edit["tools"] = board;
2182
2183
  }
2184
+ if (input["autonomy"] !== void 0) {
2185
+ if (typeof input["autonomy"] === "boolean") edit["autonomy"] = input["autonomy"];
2186
+ else problems.push("autonomy must be true or false");
2187
+ }
2183
2188
  if (input["sampling"] !== void 0) edit["sampling"] = parseSampling(input["sampling"], "sampling", problems);
2184
2189
  if (typeof edit["version"] === "string" && edit["version"].length > 40) problems.push(`the version is longer than 40 characters`);
2185
2190
  if (edit["name"] === "") problems.push("the world needs a name");
@@ -2426,6 +2431,9 @@ function parseWorldFile(text) {
2426
2431
  const variables = readVariableValues(reader);
2427
2432
  const rules = readRules(reader);
2428
2433
  const tools = readTools(reader);
2434
+ const autonomyValue = reader.raw("autonomy");
2435
+ if (autonomyValue !== void 0 && autonomyValue !== null && typeof autonomyValue !== "boolean") reader.fail("autonomy", "must be true or false");
2436
+ const autonomy = autonomyValue === true ? true : void 0;
2429
2437
  const alternateOpenings = readAlternateOpenings(reader);
2430
2438
  const startQuestions = readStartQuestions(reader, alternateOpenings?.length ?? 0);
2431
2439
  const narrationVoice = reader.string("narration_voice")?.trim() || void 0;
@@ -2453,6 +2461,7 @@ function parseWorldFile(text) {
2453
2461
  ...variables === void 0 ? {} : { variables },
2454
2462
  ...rules === void 0 ? {} : { rules },
2455
2463
  ...tools === void 0 ? {} : { tools },
2464
+ ...autonomy === void 0 ? {} : { autonomy },
2456
2465
  ...alternateOpenings === void 0 ? {} : { alternateOpenings },
2457
2466
  ...startQuestions === void 0 ? {} : { startQuestions },
2458
2467
  ...narrationVoice === void 0 ? {} : { narrationVoice },
@@ -3110,7 +3119,7 @@ async function writePortrait(directory, picture, characters, cardName) {
3110
3119
  }
3111
3120
  /** The card's opening as the world's opening message: plain paragraphs, without the markup the card's tool read as emphasis. */
3112
3121
  function openingMessage(raw, cardName, player) {
3113
- const text = cleanText(raw, cardName).replace(/<\/?[a-z][^>\n]*>/gi, "").replace(/```[a-z]*\n?|```/g, "").replace(/\*\*([^*\n]+)\*\*/g, "$1").replace(/(^|[^*])\*(?!\s)([^*\n]+?)(?<!\s)\*(?!\*)/g, "$1$2").replace(/\n{3,}/g, "\n\n").trim();
3122
+ const text = cleanText(splitPanels(raw).prose, cardName).replace(/<\/?[a-z][^>\n]*>/gi, "").replace(/```[a-z]*\n?|```/g, "").replace(/\*\*([^*\n]+)\*\*/g, "$1").replace(/(^|[^*])\*(?!\s)([^*\n]+?)(?<!\s)\*(?!\*)/g, "$1$2").replace(/\n{3,}/g, "\n\n").trim();
3114
3123
  return withPlayer(text, player);
3115
3124
  }
3116
3125
  /** Every player marker in the strings of a value, replaced by the player's character or a plain word for the player; the value is changed in place. */
@@ -4138,6 +4147,7 @@ function infoOf(document, startQuestions = []) {
4138
4147
  version: typeof document["version"] === "number" ? String(document["version"]) : textOf(document["version"]),
4139
4148
  sampling: parseSampling(document["sampling"], "sampling", []),
4140
4149
  tools: toolsOf(document["tools"]),
4150
+ autonomy: document["autonomy"] === true,
4141
4151
  startQuestions,
4142
4152
  alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
4143
4153
  title: textOf(entry["title"]),
@@ -4225,6 +4235,10 @@ async function changeWorldInfo(directory, edit) {
4225
4235
  if (Object.keys(edit.sampling).length === 0) delete document["sampling"];
4226
4236
  else document["sampling"] = edit.sampling;
4227
4237
  }
4238
+ if (edit.autonomy !== void 0) {
4239
+ if (edit.autonomy) document["autonomy"] = true;
4240
+ else delete document["autonomy"];
4241
+ }
4228
4242
  if (edit.tools !== void 0) {
4229
4243
  if (Object.keys(edit.tools).length === 0) delete document["tools"];
4230
4244
  else document["tools"] = edit.tools;
@@ -4837,7 +4851,7 @@ function worldFieldChanges(before, after) {
4837
4851
  field: "authorName",
4838
4852
  because: `the card\'s creator is now “${after.card.creator}”`
4839
4853
  });
4840
- if (differ(openingText(before.card, before.choices.opening) ?? "", openingText(after.card, after.choices.opening) ?? "")) changes.push({
4854
+ if (differ(splitPanels(openingText(before.card, before.choices.opening) ?? "").prose, splitPanels(openingText(after.card, after.choices.opening) ?? "").prose)) changes.push({
4841
4855
  field: "opening",
4842
4856
  because: "the greeting the world opens with changed; suggested is the new greeting as the import writes an opening (plain paragraphs, the card's markup removed, the player named by the world's player character where the card says {{user}})",
4843
4857
  suggested: openingMessage(openingText(after.card, after.choices.opening) ?? "", after.card.name)
@@ -5981,6 +5995,31 @@ const about = {
5981
5995
  return foundBy("quality-world", found);
5982
5996
  }
5983
5997
  };
5998
+ const PANEL_QUOTE_CHARS = 120;
5999
+ const panels = {
6000
+ id: "quality-panels",
6001
+ kit: "quality",
6002
+ mode: "code",
6003
+ needs: [],
6004
+ description: "Status bars, panels and update blocks written into the opening, the prompts, the lore or the characters: a story shows its tracked values itself, and a game master that is told to print one writes it into the narration.",
6005
+ async run(input) {
6006
+ const { texts } = await loaded.text(input);
6007
+ const found = [];
6008
+ for (const [where, body] of texts) {
6009
+ const panel = findPanel(body);
6010
+ if (panel === void 0) continue;
6011
+ const quote = panel.replace(/\s+/g, " ").slice(0, PANEL_QUOTE_CHARS);
6012
+ found.push({
6013
+ severity: "warning",
6014
+ code: "output-panel",
6015
+ where,
6016
+ message: `${where} holds a status bar or markup a story would print: ${quote}`,
6017
+ hint: "Take it out with the editing tools; keeping it is never intended. Declare the values it shows in variables.json (the story shows them) and do not keep the layout or an instruction to print it."
6018
+ });
6019
+ }
6020
+ return foundBy("quality-panels", found);
6021
+ }
6022
+ };
5984
6023
  const SHEET_SCHEMA = {
5985
6024
  type: "object",
5986
6025
  properties: {
@@ -6059,6 +6098,7 @@ const qualityChecks = [
6059
6098
  cast,
6060
6099
  places,
6061
6100
  about,
6101
+ panels,
6062
6102
  sheets,
6063
6103
  {
6064
6104
  id: "world-gaps",
@@ -6929,4 +6969,4 @@ function limitAuthoringAgents(ctx, kindOf) {
6929
6969
  }
6930
6970
  export { readSource as $, subfolders as $t, editsSince as A, populateLore as At, addressesToFetch as B, loadLocations as Bt, worldFieldChanges as C, populateCharacters as Ct, loadCardEvidence as D, populateItems as Dt, loadWorldParts as E, populateFactions as Et, localChanges as F, TRIGGERS_FILE_NAME as Ft, vetUrl as G, DICE_FILE_NAME as Gt, fetchPictures as H, loadItems as Ht, readOrigin as I, loadTriggers as It, UPDATE_FOLDER as J, CALENDAR_FILE_NAME as Jt, cardCharacter as K, loadDice as Kt, writeOrigin as L, LORE_DIR as Lt, describeChanges as M, populateTriggers as Mt, hashWorld as N, populateVariables as Nt, CHECK_COMMANDS as O, populateKnowledge as Ot, isUnchanged as P, routineProblems as Pt, entitiesByPiece as Q, loadCharacters as Qt, CatalogueError as R, loadLore as Rt, pictureChange as S, populateCalendar as St, readWorldInfo as T, populateDice as Tt, guardedLookup as U, FACTIONS_DIR as Ut, candidateUrls as V, ITEMS_DIR as Vt, mergeReports as W, loadFactions as Wt, cardPieces as X, parseCalendarFile as Xt, baseId as Y, loadCalendar as Yt, cardTools as Z, CHARACTERS_DIR as Zt, runChecks as _, writeLorebookEntry as _t, importHooks as a, readCard as an, addLorebookEntries as at, diffText as b, withScratchStory as bt, importPhase as c, DICE_RESULTS as cn, deleteLorebookEntry as ct, markReady as d, listLorebooks as dt, knownOutputCeiling as en, WORLD_FILE_NAME as et, settleDraft as f, loadLorebook as ft, CHECKS as g, updateLorebookInfo as gt, presentReport as h, reserveLorebook as ht, contextOf as i, pictureOf as in, questionView as it, writeSnapshot as j, populateRoutines as jt, recordProvenance as k, populateLocations as kt, isReviewing as l, authoredWorldOf as ln, entriesOf as lt, checkImported as m, readLorebook as mt, limitAuthoringAgents as n, cardFormat as nn, parseWorldInfoEdit as nt, importTools as o, DICE_COMPARISONS as on, createLorebook as ot, structureImport as p, lorebookDirectory as pt, writePortrait as q, parseDiceFile as qt, MAX_PREVIEW_TEXT as r, isPng as rn, combineAnswers as rt, worldOf as s, DICE_READINGS as sn, deleteLorebook as st, AuthoringTools as t, ImportCardError as tn, parseWorldFile as tt, keepDraft as u, authoringChatSessionId as un, isLorebookName as ut, addressChanges as v, checkWorld as vt, editWorldInfo as w, populateClock as wt, matchPieces as x, knowsCharacter as xt, cardChanges as y, loadValidatedWorld as yt, addressKey as z, LOCATIONS_DIR as zt };
6931
6971
 
6932
- //# sourceMappingURL=authoring-tools-BFdw7ahj.js.map
6972
+ //# sourceMappingURL=authoring-tools-4NgDhIJV.js.map
package/lib/authoring.js CHANGED
@@ -1,11 +1,11 @@
1
- import { $ as readSource, A as editsSince, C as worldFieldChanges, D as loadCardEvidence, E as loadWorldParts, J as UPDATE_FOLDER, O as CHECK_COMMANDS, Q as entitiesByPiece, S as pictureChange, T as readWorldInfo, Z as cardTools, _ as runChecks, a as importHooks, b as diffText, g as CHECKS, h as presentReport, i as contextOf, l as isReviewing, ln as authoredWorldOf, m as checkImported, n as limitAuthoringAgents, nt as parseWorldInfoEdit, o as importTools, v as addressChanges, vt as checkWorld, w as editWorldInfo, x as matchPieces, y as cardChanges } from "./authoring-tools-BFdw7ahj.js";
2
- import { t as guardAuthoringTurns } from "./turn-guard-C0M3rXEN.js";
3
- import { C as readWorldEditor, L as presetTools, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, U as finishUpdate, W as pendingUpdate, _ as editWorldPlots, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, i as checkWorldPack, l as deleteAuthoredEntity, o as listWorldPacks, r as registerPackJail, s as AUTHORED_ENTITY_KINDS, u as readAuthoredEntityDocument, v as editWorldRelation, z as translateTools } from "./pack-jail-Ci9bIeDI.js";
4
- import { $ as IMPORT_FOLDER, At as InvalidEditProblems, Ft as parseRelationEdit, G as deleteWorldPrompt, J as writeWorldPrompt, K as listWorldPrompts, W as PROSE_PROMPTS, dt as parseAuthoringCommand, nt as PICTURE_FILE, q as readWorldPrompt } from "./presets-_U-xroo0.js";
5
- import { i as translator, r as languageOf } from "./text-C2AGl7Je.js";
6
- import { B as parsePlotsFile, it as shippedPromptsDirectory, q as formatIssue } from "./hooks-C2U1-8ur.js";
7
- import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-CYkozh8Q.js";
8
- import "./access-Md1YTSX1.js";
1
+ import { $ as readSource, A as editsSince, C as worldFieldChanges, D as loadCardEvidence, E as loadWorldParts, J as UPDATE_FOLDER, O as CHECK_COMMANDS, Q as entitiesByPiece, S as pictureChange, T as readWorldInfo, Z as cardTools, _ as runChecks, a as importHooks, b as diffText, g as CHECKS, h as presentReport, i as contextOf, l as isReviewing, ln as authoredWorldOf, m as checkImported, n as limitAuthoringAgents, nt as parseWorldInfoEdit, o as importTools, v as addressChanges, vt as checkWorld, w as editWorldInfo, x as matchPieces, y as cardChanges } from "./authoring-tools-4NgDhIJV.js";
2
+ import { t as guardAuthoringTurns } from "./turn-guard-BSAba8sp.js";
3
+ import { C as readWorldEditor, L as presetTools, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, U as finishUpdate, W as pendingUpdate, _ as editWorldPlots, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, i as checkWorldPack, l as deleteAuthoredEntity, o as listWorldPacks, r as registerPackJail, s as AUTHORED_ENTITY_KINDS, u as readAuthoredEntityDocument, v as editWorldRelation, z as translateTools } from "./pack-jail-C8EyX9Ix.js";
4
+ import { $ as IMPORT_FOLDER, G as deleteWorldPrompt, J as writeWorldPrompt, K as listWorldPrompts, Lt as parseRelationEdit, Mt as InvalidEditProblems, W as PROSE_PROMPTS, lt as parseAuthoringCommand, nt as PICTURE_FILE, q as readWorldPrompt } from "./presets-DQ5rioMh.js";
5
+ import { i as translator, r as languageOf } from "./text-Dfv8S8eq.js";
6
+ import { B as parsePlotsFile, it as shippedPromptsDirectory, q as formatIssue } from "./hooks-BNeoGMHZ.js";
7
+ import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-S0SzrVv-.js";
8
+ import "./access-DAw54-NI.js";
9
9
  import { join, relative } from "node:path";
10
10
  import { createHash } from "node:crypto";
11
11
  import { readFile, readdir } from "node:fs/promises";
@@ -2,6 +2,19 @@ import { randomUUID } from "node:crypto";
2
2
  import { SessionId } from "@deepseek-ai/dsh-session";
3
3
  import { ReasoningEffortId, createUserMessage, lastAssistantStreamChunk } from "@deepseek-ai/dsh-llm";
4
4
  import { ToolArgsError, validateJsonSchemaValue } from "@deepseek-ai/dsh-tools";
5
+ // src/shared/chat.ts
6
+ const CHAT_PREFIX = "session-";
7
+ const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
8
+ /** The DSH chat of a roleplay session is named after the session's id. */
9
+ function chatSessionId(sessionId) {
10
+ return `${CHAT_PREFIX}${sessionId}`;
11
+ }
12
+ /** The roleplay session a DSH chat id could belong to; ordinary DSH chats have ids of the same shape. */
13
+ function roleplaySessionOf(chat) {
14
+ if (!chat.startsWith(CHAT_PREFIX)) return void 0;
15
+ const id = chat.slice(8);
16
+ return UUID_V4.test(id) ? id : void 0;
17
+ }
5
18
  // src/host/agents/budget.ts
6
19
  /** Tokens a text of a number of characters comes to: a character of a script written without spaces takes about one and a half, of the others about a third. */
7
20
  function tokensOf$1(characters, language) {
@@ -274,6 +287,84 @@ function parseSampling(value, where, problems) {
274
287
  function sharedSamplingOf(settings) {
275
288
  return Object.fromEntries(SHARED_SAMPLING.flatMap((key) => settings[key] === SAMPLING_RANGES[key].neutral ? [] : [[key, settings[key]]]));
276
289
  }
290
+ // src/host/observability/trace.ts
291
+ function tracerOf(ctx) {
292
+ const found = ctx.get("aiTrace");
293
+ return typeof found?.start === "function" && typeof found.link === "function" ? found : void 0;
294
+ }
295
+ const TAGS = ["roleplay"];
296
+ /** Where a chat's work belongs in the trace: the story is the Langfuse session, so everything a story does is found under it. */
297
+ const sessionOfChat = (chat) => roleplaySessionOf(chat) ?? chat;
298
+ /** A span for work with no turn around it (an autonomy tick, an off-stage round, a background job), filed under the story. */
299
+ function startHelperSpan(tracer, chat, start) {
300
+ const parent = tracer.linked(chat);
301
+ return tracer.start({
302
+ ...start,
303
+ parent,
304
+ ...parent === void 0 ? { trace: {
305
+ name: start.name,
306
+ sessionId: sessionOfChat(chat),
307
+ tags: TAGS
308
+ } } : {}
309
+ });
310
+ }
311
+ /**
312
+ * One trace per turn: its span is open from the game master's first step to the turn's end, linked to the chat so that the game master's
313
+ * requests and every helper the turn starts nest under it.
314
+ */
315
+ var TurnTraces = class {
316
+ tracer;
317
+ open = /* @__PURE__ */ new Map();
318
+ constructor(tracer) {
319
+ this.tracer = tracer;
320
+ }
321
+ begin(chat, turn, input) {
322
+ const tracer = this.tracer();
323
+ if (tracer === void 0) return;
324
+ this.end(chat, { metadata: { ended: "replaced by a later turn" } });
325
+ const span = tracer.start({
326
+ name: `turn ${turn}`,
327
+ kind: "agent",
328
+ input,
329
+ metadata: { turn },
330
+ trace: {
331
+ name: `turn ${turn}`,
332
+ sessionId: sessionOfChat(chat),
333
+ tags: TAGS
334
+ }
335
+ });
336
+ this.open.set(chat, {
337
+ span,
338
+ unlink: tracer.link(chat, span.ref)
339
+ });
340
+ }
341
+ of(chat) {
342
+ return this.open.get(chat)?.span.ref;
343
+ }
344
+ /** What the player was shown, which becomes the output of the turn's trace. */
345
+ output(chat, text) {
346
+ const held = this.open.get(chat);
347
+ if (held !== void 0) held.output = text;
348
+ }
349
+ /** A span for a piece of the turn (a round of characters), filed under it; absent when nothing is traced. */
350
+ child(chat, start) {
351
+ const parent = this.open.get(chat)?.span.ref;
352
+ return parent === void 0 ? void 0 : this.tracer()?.start({
353
+ ...start,
354
+ parent
355
+ });
356
+ }
357
+ end(chat, result) {
358
+ const held = this.open.get(chat);
359
+ if (held === void 0) return;
360
+ this.open.delete(chat);
361
+ held.unlink();
362
+ held.span.end({
363
+ ...held.output === void 0 ? {} : { output: held.output },
364
+ ...result
365
+ });
366
+ }
367
+ };
277
368
  // src/host/agents/child.ts
278
369
  /** The tool every child ends with: its arguments are the child's result. */
279
370
  const SUBMIT_TOOL = "submit_result";
@@ -719,6 +810,20 @@ async function execute(task, stats) {
719
810
  }
720
811
  };
721
812
  helpers.set(childId, entry);
813
+ const tracer = tracerOf(parent.ctx);
814
+ const chat = String(parent.session.id);
815
+ const span = tracer === void 0 ? void 0 : startHelperSpan(tracer, chat, {
816
+ name: task.persona.split("\n", 1)[0].slice(0, 80),
817
+ kind: "agent",
818
+ input: task.prompt,
819
+ metadata: {
820
+ turn: task.turn ?? currentTurn(parent),
821
+ session: sessionOfChat(chat),
822
+ tools: (task.tools ?? []).map((tool) => tool.name),
823
+ external: task.external ?? []
824
+ }
825
+ });
826
+ const unlink = span === void 0 ? void 0 : tracer?.link(String(childId), span.ref);
722
827
  if (task.structured === true) {
723
828
  const { toolChoice: _unused, ...rest } = task.sampling ?? {};
724
829
  samplings.set(childId, {
@@ -776,9 +881,23 @@ async function execute(task, stats) {
776
881
  setTimeout(resolve, STOP_GRACE_MS);
777
882
  })]) : activation.dispose());
778
883
  }
884
+ } catch (error) {
885
+ span?.update({
886
+ level: "ERROR",
887
+ statusMessage: error instanceof Error ? error.message : String(error)
888
+ });
889
+ throw error;
779
890
  } finally {
780
891
  helpers.delete(childId);
781
892
  samplings.delete(childId);
893
+ unlink?.();
894
+ span?.end({
895
+ ...submitted === void 0 ? {} : { output: submitted.value },
896
+ metadata: {
897
+ calls: stats.calls,
898
+ tokens: stats.tokens ?? NO_TOKENS
899
+ }
900
+ });
782
901
  }
783
902
  if (signal.aborted) throw new Error("cancelled");
784
903
  if (rambled && submitted === void 0) throw new Error(`the agent wrote text up to the limit of ${task.maxTokens ?? task.sampling?.maxTokens ?? "its model"} tokens and never called ${SUBMIT_TOOL}, and was stopped`);
@@ -791,6 +910,6 @@ async function execute(task, stats) {
791
910
  }
792
911
  return submitted.value;
793
912
  }
794
- export { cutOff as C, tokensOf$1 as E, currentTurn as S, estimateAnswer as T, estimateTokens as _, childTrace as a, addTokens as b, namedModel as c, parseSampling as d, sharedSamplingOf as f, blockText as g, requestsOf as h, childSamplingOf as i, runChild as l, RECOVERY_SHRINK as m, childModel as n, helpers as o, RECOVERY_FLOOR as p, childSampling as r, isUnfinishedCall as s, ChildTimeoutError as t, SAMPLING_RANGES as u, tokensOf as v, finishOf as w, totalTokens as x, NO_TOKENS as y };
913
+ export { chatSessionId as A, addTokens as C, finishOf as D, cutOff as E, estimateAnswer as O, NO_TOKENS as S, currentTurn as T, RECOVERY_SHRINK as _, childTrace as a, estimateTokens as b, namedModel as c, sessionOfChat as d, tracerOf as f, RECOVERY_FLOOR as g, sharedSamplingOf as h, childSamplingOf as i, roleplaySessionOf as j, tokensOf$1 as k, runChild as l, parseSampling as m, childModel as n, helpers as o, SAMPLING_RANGES as p, childSampling as r, isUnfinishedCall as s, ChildTimeoutError as t, TurnTraces as u, requestsOf as v, totalTokens as w, tokensOf as x, blockText as y };
795
914
 
796
- //# sourceMappingURL=child-C9nPIy9j.js.map
915
+ //# sourceMappingURL=child-D3QUNb3m.js.map