@dsh-agentic-roleplay/core 0.11.1 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/lib/{access-Md1YTSX1.js → access-DifaiHrI.js} +3 -15
  2. package/lib/{authoring-tools-BFdw7ahj.js → authoring-tools-VOaXzr_R.js} +58 -766
  3. package/lib/authoring.js +136 -13
  4. package/lib/{child-C9nPIy9j.js → child-DzZ-aI6k.js} +130 -2
  5. package/lib/client.js +17093 -2269
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -3
  8. package/lib/dev-context-Bdm-eVer.js +40 -0
  9. package/lib/doctor.js +5 -3
  10. package/lib/{gallery-BWHmjogd.js → gallery-Ctz-UoFk.js} +3 -3
  11. package/lib/{generator-QCdm8nUh.js → generator-Cv6WWmZT.js} +2 -2
  12. package/lib/helper.js +15 -1
  13. package/lib/{hooks-C2U1-8ur.js → hooks-BdR3mBeM.js} +751 -344
  14. package/lib/images.js +4 -4
  15. package/lib/index.js +342 -463
  16. package/lib/jail-Cp4zEfip.js +107 -0
  17. package/lib/{library-4zmCAshR.js → library-BU2A_Dx8.js} +3 -3
  18. package/lib/{lorebook-author-tools-Bjfjt3bg.js → lorebook-author-tools-DUKcQu8P.js} +20 -7
  19. package/lib/lorebook-authoring.js +12 -5
  20. package/lib/{narration-b_VBEUWn.js → narration-CDsJ5wxH.js} +29 -2
  21. package/lib/orchestration.js +615 -48
  22. package/lib/{pack-jail-Ci9bIeDI.js → pack-jail-CzHQu0n3.js} +559 -23
  23. package/lib/{packs-CYkozh8Q.js → packs-BZ-45J4-.js} +2 -2
  24. package/lib/{presenter-agent-CqkAL03Q.js → presenter-agent-C2ZkoxZu.js} +9 -9
  25. package/lib/{preset-B-35yUmt.js → preset-BPnRPW-1.js} +4 -4
  26. package/lib/{preset-author-tools-BUymqZM5.js → preset-author-tools-DBqPwn-o.js} +9 -8
  27. package/lib/preset-authoring.js +11 -6
  28. package/lib/{reflection-B9N0z3KY.js → reflection-Cuy0YLv0.js} +22 -16
  29. package/lib/{presets-_U-xroo0.js → serial-BZNeK57v.js} +1305 -331
  30. package/lib/service-mRKwpWjX.js +140 -0
  31. package/lib/{text-C2AGl7Je.js → text-Dfv8S8eq.js} +27 -2
  32. package/lib/{turn-guard-C0M3rXEN.js → turn-guard-xaFxYc1T.js} +3 -3
  33. package/locale/de.json +6 -0
  34. package/locale/en.json +6 -0
  35. package/locale/es.json +6 -0
  36. package/locale/fr.json +6 -0
  37. package/locale/ja.json +6 -0
  38. package/locale/pt.json +6 -0
  39. package/locale/ru.json +6 -0
  40. package/locale/zh.json +6 -0
  41. package/package.json +34 -34
  42. package/prompts/en/import/finish-ok.md +1 -1
  43. package/prompts/en/import/generator.md +1 -1
  44. package/prompts/en/import/style.md +2 -1
  45. package/prompts/en/import/variables.md +2 -1
  46. package/prompts/en/roleplay/character-lookup.md +1 -1
  47. package/prompts/en/roleplay/decide-errand.md +1 -0
  48. package/prompts/en/roleplay/decide-message.md +1 -0
  49. package/prompts/en/roleplay/dream.md +1 -0
  50. package/prompts/en/roleplay/gate-repeat.md +1 -0
  51. package/prompts/en/world/procedure.md +1 -1
  52. package/prompts/zh/import/finish-ok.md +1 -1
  53. package/prompts/zh/import/generator.md +1 -1
  54. package/prompts/zh/import/style.md +2 -1
  55. package/prompts/zh/import/variables.md +2 -1
  56. package/prompts/zh/roleplay/character-lookup.md +1 -1
  57. package/prompts/zh/roleplay/decide-errand.md +1 -0
  58. package/prompts/zh/roleplay/decide-message.md +1 -0
  59. package/prompts/zh/roleplay/dream.md +1 -0
  60. package/prompts/zh/roleplay/gate-repeat.md +1 -0
  61. package/prompts/zh/world/procedure.md +1 -1
package/lib/authoring.js CHANGED
@@ -1,17 +1,70 @@
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, Kt as authoredWorldOf, Mt as CALENDAR_FILE_NAME, O as CHECK_COMMANDS, Ot as COMMANDS_FILE_NAME, Q as entitiesByPiece, S as pictureChange, T as readWorldInfo, Tt as DICE_FILE_NAME, Z as cardTools, _ as runChecks, a as importHooks, b as diffText, et as checkWorld, g as CHECKS, h as presentReport, i as contextOf, l as isReviewing, m as checkImported, n as limitAuthoringAgents, o as importTools, v as addressChanges, w as editWorldInfo, x as matchPieces, y as cardChanges } from "./authoring-tools-VOaXzr_R.js";
2
+ import { t as guardAuthoringTurns } from "./turn-guard-xaFxYc1T.js";
3
+ import { t as silenceHarnessDevContext } from "./dev-context-Bdm-eVer.js";
4
+ import { B as deleteTriggerDocument, D as editWorldPlots, G as parseVariablesEdit, H as writeTriggerDocument, K as parseDiceEdit, M as readWorldEditor, O as editWorldRelation, Q as translateTools, U as parseCalendarEdit, V as readTriggerDocuments, X as presetTools, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, f as editCalendar, g as editVariables, i as checkWorldPack, l as deleteAuthoredEntity, m as editDice, nt as finishUpdate, o as listWorldPacks, p as editCommands, q as parseCommandsEdit, r as registerPackJail, rt as pendingUpdate, s as AUTHORED_ENTITY_KINDS, u as readAuthoredEntityDocument } from "./pack-jail-CzHQu0n3.js";
5
+ import { i as translator, r as languageOf } from "./text-Dfv8S8eq.js";
6
+ import { $ as deleteWorldPrompt, At as parseAuthoringCommand, Ct as PICTURE_FILE, F as parseWorldInfoEdit, Ft as VARIABLES_FILE_NAME, Q as PROSE_PROMPTS, an as parseRelationEdit, bt as IMPORT_FOLDER, en as InvalidEditProblems, et as listWorldPrompts, nt as writeWorldPrompt, tt as readWorldPrompt } from "./serial-BZNeK57v.js";
7
+ import { B as parsePlotsFile, it as shippedPromptsDirectory, q as formatIssue } from "./hooks-BdR3mBeM.js";
8
+ import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-BZ-45J4-.js";
9
+ import "./access-DifaiHrI.js";
9
10
  import { join, relative } from "node:path";
10
11
  import { createHash } from "node:crypto";
11
12
  import { readFile, readdir } from "node:fs/promises";
12
13
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
13
14
  import { defineTool } from "@deepseek-ai/dsh-tools";
14
15
  import { isDeepStrictEqual } from "node:util";
16
+ // src/host/authoring/world-files.ts
17
+ /**
18
+ * The whole-world files that belong to no single character, place or thing. The assistant writes them through the same functions as the world editor's panels,
19
+ * so a document is refused for the same reasons wherever it comes from (a value a character still has, a holiday a trigger still names).
20
+ */
21
+ const FILES = {
22
+ variables: {
23
+ file: VARIABLES_FILE_NAME,
24
+ empty: [],
25
+ write: (world, document, options) => editVariables(world, parseVariablesEdit({ variables: document }), options)
26
+ },
27
+ dice: {
28
+ file: DICE_FILE_NAME,
29
+ empty: { checks: [] },
30
+ write: (world, document, options) => editDice(world, parseDiceEdit(document), options)
31
+ },
32
+ commands: {
33
+ file: COMMANDS_FILE_NAME,
34
+ empty: { commands: [] },
35
+ write: (world, document, options) => editCommands(world, parseCommandsEdit(document), options)
36
+ },
37
+ calendar: {
38
+ file: CALENDAR_FILE_NAME,
39
+ empty: {
40
+ hemisphere: "north",
41
+ holidays: []
42
+ },
43
+ write: (world, document, options) => editCalendar(world, parseCalendarEdit(document), options)
44
+ }
45
+ };
46
+ const WORLD_FILE_KINDS = Object.keys(FILES);
47
+ const isWorldFileKind = (value) => typeof value === "string" && value in FILES;
48
+ /** The stored document of one of these files, or its empty form when the world has none. */
49
+ async function readWorldFile(directory, kind) {
50
+ try {
51
+ return JSON.parse((await readFile(join(directory, FILES[kind].file), "utf8")).replace(/^\uFEFF/, ""));
52
+ } catch (error) {
53
+ if (error.code === "ENOENT") return FILES[kind].empty;
54
+ throw error;
55
+ }
56
+ }
57
+ /**
58
+ * Replaces one of the files with a complete document, checked against the rest of the world; an empty one removes the file.
59
+ * @throws {InvalidEditProblems} naming each problem; nothing is written.
60
+ */
61
+ async function writeWorldFile(world, kind, document, options = {}) {
62
+ if (kind === "variables") {
63
+ const silent = (Array.isArray(document) ? document : []).flatMap((entry) => entry !== null && typeof entry === "object" && entry["kind"] !== "flag" && String(entry["update"] ?? "").trim() === "" ? [String(entry["key"] ?? entry["name"] ?? "?")] : []);
64
+ if (silent.length > 0) throw new InvalidEditProblems(silent.map((key) => `${key}: say when and how it changes, in the field "update" (for example "rises by 1 when the town hears good news"): a tracked value without that rule moves for nothing`));
65
+ }
66
+ await FILES[kind].write(world, document, options);
67
+ }
15
68
  // src/host/authoring/read-tools.ts
16
69
  const output$5 = (value) => [{
17
70
  type: "text",
@@ -221,6 +274,22 @@ function authoredWorldReadTools(reader) {
221
274
  return json$1(found);
222
275
  }
223
276
  }),
277
+ defineTool({
278
+ name: "get_world_file",
279
+ description: `Read the exact stored document of a whole-world file: ${WORLD_FILE_KINDS.join(", ")} (tracked values, dice checks, the world's own slash commands, the holidays). Its empty form is returned when the world has none. Use this before replacing one.`,
280
+ parameters: { kind: {
281
+ type: "string",
282
+ required: true,
283
+ enum: WORLD_FILE_KINDS
284
+ } },
285
+ output: jsonOutput$3,
286
+ isConcurrencySafe: () => true,
287
+ async execute(args, exec) {
288
+ const { record } = await reader.read(exec);
289
+ if (!isWorldFileKind(args.kind)) throw new Error(`kind must be one of ${WORLD_FILE_KINDS.join(", ")}`);
290
+ return json$1(await readWorldFile(record.directory, args.kind));
291
+ }
292
+ }),
224
293
  defineTool({
225
294
  name: "list_relationships",
226
295
  description: "Read authored character relationships, knowledge, faction memberships, social ties and map exits. Optionally narrow by kind or endpoint key.",
@@ -548,6 +617,7 @@ const WORLD_INFO_FIELDS = [
548
617
  "rules",
549
618
  "opening",
550
619
  "alternateOpenings",
620
+ "startQuestions",
551
621
  "startingTime",
552
622
  "timeZone",
553
623
  "version",
@@ -564,6 +634,7 @@ const AUTHORING_MUTATION_TOOLS = /* @__PURE__ */ new Set([
564
634
  "replace_world_plots",
565
635
  "write_world_trigger",
566
636
  "delete_world_trigger",
637
+ "write_world_file",
567
638
  ...PROMPT_MUTATION_TOOLS,
568
639
  ...PACK_MUTATION_TOOLS
569
640
  ]);
@@ -584,6 +655,10 @@ function result(action, kind, key, state, extra = {}) {
584
655
  ...extra
585
656
  };
586
657
  }
658
+ function fileKind(value) {
659
+ if (!isWorldFileKind(value)) throw new InvalidEditProblems([`kind must be one of ${WORLD_FILE_KINDS.join(", ")}`]);
660
+ return value;
661
+ }
587
662
  function plotDocument(value) {
588
663
  const parsed = parsePlotsFile(JSON.stringify([value]));
589
664
  if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
@@ -592,8 +667,15 @@ function plotDocument(value) {
592
667
  /** Checks a write the way its tool will, and writes nothing: a change the tool would refuse is not put to the person. @throws {InvalidEditProblems} */
593
668
  async function validateMutation(reader, exec) {
594
669
  const args = exec.arguments;
595
- if (exec.name !== "create_world_element" && exec.name !== "replace_world_element" && exec.name !== "write_world_trigger") return;
670
+ if (exec.name !== "create_world_element" && exec.name !== "replace_world_element" && exec.name !== "write_world_trigger" && exec.name !== "write_world_file") return;
596
671
  const { record } = await reader.read(exec);
672
+ if (exec.name === "write_world_file") {
673
+ await writeWorldFile({
674
+ id: record.summary.id,
675
+ directory: record.directory
676
+ }, fileKind(args["kind"]), args["document"], { dryRun: true });
677
+ return;
678
+ }
597
679
  const world = {
598
680
  id: record.summary.id,
599
681
  directory: record.directory
@@ -644,7 +726,7 @@ function authoredWorldWriteTools(reader) {
644
726
  return [
645
727
  defineTool({
646
728
  name: "create_world_element",
647
- description: "Create a character, location, item, faction or lore entry from a complete authored JSON document. The key becomes its stable id. Requires user approval.",
729
+ description: "Create a character, location, item, faction or lore entry from a complete authored JSON document. The key becomes its stable id. A character that is somewhere in the story needs start.location, the key of an existing place (start: {\"location\": \"yard\"}); one without it is in no place. Requires user approval.",
648
730
  parameters: {
649
731
  kind: kindParameter,
650
732
  key: keyParameter,
@@ -711,7 +793,7 @@ function authoredWorldWriteTools(reader) {
711
793
  }),
712
794
  defineTool({
713
795
  name: "edit_world_info",
714
- description: `Change what the world says about itself in world.json: ${WORLD_INFO_FIELDS.join(", ")}. Give only the fields to change, as {"description": "...", "tags": ["..."], "opening": "...", "alternateOpenings": [{"title": "...", "text": "..."}]}: a list replaces the whole list, so read get_world_info first. The description is a short summary (a few sentences). An opening with lines spoken by characters cannot be edited as text. The name, preset, lorebooks, sampling and tool switches are the person's and cannot be changed here. Requires user approval.`,
796
+ description: `Change what the world says about itself in world.json: ${WORLD_INFO_FIELDS.join(", ")}. Give only the fields to change, as {"description": "...", "tags": ["..."], "opening": "...", "alternateOpenings": [{"title": "...", "text": "..."}]}: a list replaces the whole list, so read get_world_info first. The description is a short summary (a few sentences). An opening with lines spoken by characters cannot be edited as text. startQuestions is a list of {"id", "text", "options": [{"id", "label", "effect": {...}}]} with two to eight options each; an effect may hold rules (a list of text), opening (the position of an alternate opening), startingTime, clockMode (simulated or real), tools and plots, and {} changes nothing. The name, preset, lorebooks, sampling and tool switches are the person's and cannot be changed here. Requires user approval.`,
715
797
  parameters: { changes: {
716
798
  type: "json",
717
799
  required: true,
@@ -792,6 +874,34 @@ function authoredWorldWriteTools(reader) {
792
874
  }));
793
875
  }
794
876
  }),
877
+ defineTool({
878
+ name: "write_world_file",
879
+ description: `Replace one whole-world file with a complete document: variables (variables.json, a list of what stories track: key, name, kind number|flag|choice, subject character|item|location|world, min and max for a number (copy the limits the person gave), default, integer, visibility, and an "update" field, a sentence saying when and how it changes, which a tracked value needs so that it moves only when it should; visibility is public, private or hidden), dice (dice.json, {checks: [...]}), commands (commands.json, {commands: [{word, description}]}, the world's own slash commands) or calendar (calendar.json, {hemisphere, holidays: [{id, name, on}]}). Read it with get_world_file first and send the whole document, since it replaces the file; an empty document removes the file. It is checked against the rest of the world as the editor does (a value a character still has, a holiday a trigger names) and refused with every problem. Requires user approval.`,
880
+ parameters: {
881
+ kind: {
882
+ type: "string",
883
+ required: true,
884
+ enum: WORLD_FILE_KINDS
885
+ },
886
+ document: {
887
+ type: "json",
888
+ required: true,
889
+ description: "The complete document in the file format: a list for variables, an object holding the list for the others."
890
+ }
891
+ },
892
+ output: jsonOutput,
893
+ async execute(args, exec) {
894
+ const { record } = await reader.read(exec);
895
+ await writeWorldFile({
896
+ id: record.summary.id,
897
+ directory: record.directory
898
+ }, fileKind(args.kind), args.document);
899
+ return result("written", args.kind, args.kind, await readWorldEditor({
900
+ id: record.summary.id,
901
+ directory: record.directory
902
+ }));
903
+ }
904
+ }),
795
905
  defineTool({
796
906
  name: "delete_world_trigger",
797
907
  description: "Remove one trigger from triggers.json. Its document is kept in the world’s .trash/triggers so it can be put back. A trigger that others wait for cannot be removed. Requires user approval.",
@@ -882,10 +992,10 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
882
992
  zh: "编辑世界对自身的描述"
883
993
  }, await infoDetail(args["changes"], await options.info?.(exec.agent.session.id).catch(() => void 0)))
884
994
  };
885
- const kind = typeof args["kind"] === "string" ? args["kind"] : exec.name === "edit_world_relationship" ? "relationship" : exec.name.endsWith("trigger") ? "trigger" : "plots";
995
+ const kind = typeof args["kind"] === "string" ? args["kind"] : exec.name === "edit_world_relationship" ? "relationship" : exec.name.endsWith("trigger") ? "trigger" : exec.name === "write_world_file" ? "file" : "plots";
886
996
  const key = typeof args["key"] === "string" ? args["key"] : "";
887
997
  const target = key === "" ? kind : `${kind} “${key}”`;
888
- const action = exec.name.startsWith("create") ? "Create" : exec.name.startsWith("delete") ? "Delete" : exec.name === "write_world_trigger" ? "Write" : "Edit";
998
+ const action = exec.name.startsWith("create") ? "Create" : exec.name.startsWith("delete") ? "Delete" : exec.name === "write_world_trigger" || exec.name === "write_world_file" ? "Write" : "Edit";
889
999
  const detail = await detailOf(exec, kind, key, options.current).catch(() => void 0);
890
1000
  return {
891
1001
  kind: "ask",
@@ -909,6 +1019,14 @@ async function infoDetail(changes, before) {
909
1019
  ...edit
910
1020
  });
911
1021
  }
1022
+ function fileDetail(document) {
1023
+ const lists = Array.isArray(document) ? [document] : typeof document === "object" && document !== null ? Object.values(document).filter(Array.isArray) : [];
1024
+ const entries = lists.length === 0 ? void 0 : lists.reduce((sum, list) => sum + list.length, 0);
1025
+ return entries === void 0 ? void 0 : {
1026
+ en: `${entries} entries`,
1027
+ zh: `${entries} 项`
1028
+ };
1029
+ }
912
1030
  function withDetail(headline, detail) {
913
1031
  return detail === void 0 || detail.en === "" ? {
914
1032
  en: `${headline.en}?`,
@@ -933,6 +1051,7 @@ async function detailOf(exec, kind, key, current) {
933
1051
  zh: `${args["plots"].length} 条剧情`
934
1052
  } : void 0;
935
1053
  case "write_world_trigger": return createdFields(args["document"]);
1054
+ case "write_world_file": return fileDetail(args["document"]);
936
1055
  default: return;
937
1056
  }
938
1057
  }
@@ -1253,6 +1372,7 @@ const inject = [
1253
1372
  "systemPrompt"
1254
1373
  ];
1255
1374
  function apply(ctx) {
1375
+ silenceHarnessDevContext(ctx);
1256
1376
  const prompting = {
1257
1377
  prompts: () => ctx.roleplayPrompts,
1258
1378
  languages: () => ctx.roleplayAuthoringLanguages
@@ -1309,6 +1429,9 @@ function apply(ctx) {
1309
1429
  const directory = await worldDirectory(chat);
1310
1430
  return directory === void 0 ? void 0 : await readWorldInfo(directory);
1311
1431
  };
1432
+ ctx.on("session/event", (session, event) => {
1433
+ if (event.type === "turn/end" && session.header.origin !== "subagent" && authoredWorldOf(session.id) !== void 0) ctx.roleplayImport.turnEnded(session.id);
1434
+ });
1312
1435
  ctx.on("tools/pre-execute", (exec, next) => authoringApproval(exec, next, reviewing, {
1313
1436
  auto: () => ctx.roleplayImport.settings.approval === "auto",
1314
1437
  validate: (exec) => validateMutation(reader, exec),
@@ -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) {
@@ -30,6 +43,8 @@ const cutOff = (agent) => finishOf(agent) === "max-tokens";
30
43
  // src/host/orchestration/current-turn.ts
31
44
  /** The last turn the session started. */
32
45
  function currentTurn(agent) {
46
+ const last = lastProjectedTurn(agent);
47
+ if (last !== void 0) return last;
33
48
  const events = agent.session.snapshotEvents();
34
49
  for (let index = events.length - 1; index >= 0; index--) {
35
50
  const event = events[index];
@@ -37,6 +52,13 @@ function currentTurn(agent) {
37
52
  }
38
53
  return 0;
39
54
  }
55
+ function lastProjectedTurn(agent) {
56
+ try {
57
+ return (agent.ctx?.get("agents"))?.turnBoundaryOf(agent.session)?.lastTurn;
58
+ } catch {
59
+ return;
60
+ }
61
+ }
40
62
  // src/shared/usage.ts
41
63
  const NO_TOKENS = {
42
64
  input: 0,
@@ -274,6 +296,84 @@ function parseSampling(value, where, problems) {
274
296
  function sharedSamplingOf(settings) {
275
297
  return Object.fromEntries(SHARED_SAMPLING.flatMap((key) => settings[key] === SAMPLING_RANGES[key].neutral ? [] : [[key, settings[key]]]));
276
298
  }
299
+ // src/host/observability/trace.ts
300
+ function tracerOf(ctx) {
301
+ const found = ctx.get("aiTrace");
302
+ return typeof found?.start === "function" && typeof found.link === "function" ? found : void 0;
303
+ }
304
+ const TAGS = ["roleplay"];
305
+ /** Where a chat's work belongs in the trace: the story is the Langfuse session, so everything a story does is found under it. */
306
+ const sessionOfChat = (chat) => roleplaySessionOf(chat) ?? chat;
307
+ /** A span for work with no turn around it (an autonomy tick, an off-stage round, a background job), filed under the story. */
308
+ function startHelperSpan(tracer, chat, start) {
309
+ const parent = tracer.linked(chat);
310
+ return tracer.start({
311
+ ...start,
312
+ parent,
313
+ ...parent === void 0 ? { trace: {
314
+ name: start.name,
315
+ sessionId: sessionOfChat(chat),
316
+ tags: TAGS
317
+ } } : {}
318
+ });
319
+ }
320
+ /**
321
+ * 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
322
+ * requests and every helper the turn starts nest under it.
323
+ */
324
+ var TurnTraces = class {
325
+ tracer;
326
+ open = /* @__PURE__ */ new Map();
327
+ constructor(tracer) {
328
+ this.tracer = tracer;
329
+ }
330
+ begin(chat, turn, input) {
331
+ const tracer = this.tracer();
332
+ if (tracer === void 0) return;
333
+ this.end(chat, { metadata: { ended: "replaced by a later turn" } });
334
+ const span = tracer.start({
335
+ name: `turn ${turn}`,
336
+ kind: "agent",
337
+ input,
338
+ metadata: { turn },
339
+ trace: {
340
+ name: `turn ${turn}`,
341
+ sessionId: sessionOfChat(chat),
342
+ tags: TAGS
343
+ }
344
+ });
345
+ this.open.set(chat, {
346
+ span,
347
+ unlink: tracer.link(chat, span.ref)
348
+ });
349
+ }
350
+ of(chat) {
351
+ return this.open.get(chat)?.span.ref;
352
+ }
353
+ /** What the player was shown, which becomes the output of the turn's trace. */
354
+ output(chat, text) {
355
+ const held = this.open.get(chat);
356
+ if (held !== void 0) held.output = text;
357
+ }
358
+ /** A span for a piece of the turn (a round of characters), filed under it; absent when nothing is traced. */
359
+ child(chat, start) {
360
+ const parent = this.open.get(chat)?.span.ref;
361
+ return parent === void 0 ? void 0 : this.tracer()?.start({
362
+ ...start,
363
+ parent
364
+ });
365
+ }
366
+ end(chat, result) {
367
+ const held = this.open.get(chat);
368
+ if (held === void 0) return;
369
+ this.open.delete(chat);
370
+ held.unlink();
371
+ held.span.end({
372
+ ...held.output === void 0 ? {} : { output: held.output },
373
+ ...result
374
+ });
375
+ }
376
+ };
277
377
  // src/host/agents/child.ts
278
378
  /** The tool every child ends with: its arguments are the child's result. */
279
379
  const SUBMIT_TOOL = "submit_result";
@@ -719,6 +819,20 @@ async function execute(task, stats) {
719
819
  }
720
820
  };
721
821
  helpers.set(childId, entry);
822
+ const tracer = tracerOf(parent.ctx);
823
+ const chat = String(parent.session.id);
824
+ const span = tracer === void 0 ? void 0 : startHelperSpan(tracer, chat, {
825
+ name: task.persona.split("\n", 1)[0].slice(0, 80),
826
+ kind: "agent",
827
+ input: task.prompt,
828
+ metadata: {
829
+ turn: task.turn ?? currentTurn(parent),
830
+ session: sessionOfChat(chat),
831
+ tools: (task.tools ?? []).map((tool) => tool.name),
832
+ external: task.external ?? []
833
+ }
834
+ });
835
+ const unlink = span === void 0 ? void 0 : tracer?.link(String(childId), span.ref);
722
836
  if (task.structured === true) {
723
837
  const { toolChoice: _unused, ...rest } = task.sampling ?? {};
724
838
  samplings.set(childId, {
@@ -776,9 +890,23 @@ async function execute(task, stats) {
776
890
  setTimeout(resolve, STOP_GRACE_MS);
777
891
  })]) : activation.dispose());
778
892
  }
893
+ } catch (error) {
894
+ span?.update({
895
+ level: "ERROR",
896
+ statusMessage: error instanceof Error ? error.message : String(error)
897
+ });
898
+ throw error;
779
899
  } finally {
780
900
  helpers.delete(childId);
781
901
  samplings.delete(childId);
902
+ unlink?.();
903
+ span?.end({
904
+ ...submitted === void 0 ? {} : { output: submitted.value },
905
+ metadata: {
906
+ calls: stats.calls,
907
+ tokens: stats.tokens ?? NO_TOKENS
908
+ }
909
+ });
782
910
  }
783
911
  if (signal.aborted) throw new Error("cancelled");
784
912
  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 +919,6 @@ async function execute(task, stats) {
791
919
  }
792
920
  return submitted.value;
793
921
  }
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 };
922
+ 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
923
 
796
- //# sourceMappingURL=child-C9nPIy9j.js.map
924
+ //# sourceMappingURL=child-DzZ-aI6k.js.map