@dsh-agentic-roleplay/core 0.7.3 → 0.8.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 (53) hide show
  1. package/README.md +1 -1
  2. package/lib/{authoring-tools-CIsWbq0B.js → authoring-tools-DNnx0Nts.js} +1774 -4517
  3. package/lib/authoring.js +51 -9
  4. package/lib/{child-CyCViUKa.js → child-D6mpkkCE.js} +130 -6
  5. package/lib/client.js +661 -427
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +2 -2
  8. package/lib/doctor.js +2 -2
  9. package/lib/{gallery-DmBZ2L5l.js → gallery-D9nG3C78.js} +2 -2
  10. package/lib/{generator-BmdoTIL2.js → generator-r1Czm7oi.js} +2 -2
  11. package/lib/helper.js +1 -1
  12. package/lib/{hooks-C8eELrni.js → hooks-BQCzgggH.js} +92 -8
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +920 -739
  15. package/lib/{library-lVNf9qG_.js → library-zI-2tG7h.js} +25 -8
  16. package/lib/{lorebook-author-tools-BDOs4i5C.js → lorebook-author-tools-ywaYicwd.js} +7 -7
  17. package/lib/lorebook-authoring.js +4 -4
  18. package/lib/{narration-DvFBqmqe.js → narration-CnBlVure.js} +52 -8
  19. package/lib/orchestration.js +95 -18
  20. package/lib/{pack-jail-DeTscGT2.js → pack-jail-5EJ-WYyW.js} +30 -68
  21. package/lib/{packs-CY8ms8v_.js → packs-Cv8hanXJ.js} +2 -2
  22. package/lib/{presenter-agent-cFR4sos3.js → presenter-agent-BSaMSd3G.js} +6 -6
  23. package/lib/{preset-n4-j6k4S.js → preset-CWI3-0r1.js} +4 -3
  24. package/lib/{preset-author-tools-2m4BLtws.js → preset-author-tools-BrJYa2cr.js} +7 -7
  25. package/lib/preset-authoring.js +5 -5
  26. package/lib/presets-MwOSMMyu.js +3998 -0
  27. package/lib/{reflection-CJB5s0ip.js → reflection-zSaMsjKj.js} +127 -127
  28. package/lib/{text-Cwl5s0j0.js → text-BzudpQLS.js} +9 -1
  29. package/lib/{turn-guard-BvCs1VxB.js → turn-guard-Cv8pfHEA.js} +6 -2
  30. package/package.json +2 -2
  31. package/prompts/en/import/casting.md +14 -0
  32. package/prompts/en/import/classifier.md +9 -0
  33. package/prompts/en/import/finish-draft.md +1 -0
  34. package/prompts/en/import/generator.md +8 -0
  35. package/prompts/en/import/notice-repair.md +4 -0
  36. package/prompts/en/import/repair-again.md +3 -0
  37. package/prompts/en/import/roster.md +1 -0
  38. package/prompts/en/import/variables.md +1 -0
  39. package/prompts/en/roleplay/game-master.md +3 -0
  40. package/prompts/en/roleplay/standing.md +1 -0
  41. package/prompts/en/world/author.md +1 -1
  42. package/prompts/zh/import/casting.md +14 -0
  43. package/prompts/zh/import/classifier.md +9 -0
  44. package/prompts/zh/import/finish-draft.md +1 -0
  45. package/prompts/zh/import/generator.md +8 -0
  46. package/prompts/zh/import/notice-repair.md +4 -0
  47. package/prompts/zh/import/repair-again.md +3 -0
  48. package/prompts/zh/import/roster.md +1 -0
  49. package/prompts/zh/import/variables.md +1 -0
  50. package/prompts/zh/roleplay/game-master.md +3 -0
  51. package/prompts/zh/roleplay/standing.md +1 -0
  52. package/prompts/zh/world/author.md +1 -1
  53. package/lib/route-C6SHz9j2.js +0 -518
package/lib/authoring.js CHANGED
@@ -1,15 +1,15 @@
1
1
  import "./access-DtOxFKBK.js";
2
- import { Dt as IMPORT_FOLDER, Lt as parseWorldInfoEdit, a as importHooks, d as editsSince, l as isReviewing, n as limitAuthoringAgents, nn as InvalidEditProblems, o as importTools, sn as parseRelationEdit, yn as authoredWorldOf } from "./authoring-tools-CIsWbq0B.js";
3
- import { C as readWorldPrompt, S as listWorldPrompts, b as PROSE_PROMPTS, w as writeWorldPrompt, x as deleteWorldPrompt } from "./route-C6SHz9j2.js";
4
- import { G as formatIssue, V as parsePlotsFile, nt as shippedPromptsDirectory } from "./hooks-C8eELrni.js";
5
- import { i as translator, r as languageOf } from "./text-Cwl5s0j0.js";
6
- import { $ as matchPieces, B as readWorldInfo, C as readWorldEditor, F as loadWorldParts, H as translateTools, K as finishUpdate, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, Q as diffText, R as presetTools, Z as cardChanges, _ as editWorldPlots, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, et as worldFieldChanges, i as checkWorldPack, l as deleteAuthoredEntity, nt as entitiesByPiece, o as listWorldPacks, q as pendingUpdate, r as registerPackJail, rt as readSource, s as AUTHORED_ENTITY_KINDS, tt as cardTools, u as readAuthoredEntityDocument, v as editWorldRelation, z as editWorldInfo } from "./pack-jail-DeTscGT2.js";
7
- import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-CY8ms8v_.js";
8
- import { t as guardAuthoringTurns } from "./turn-guard-BvCs1VxB.js";
2
+ import { Bt as authoredWorldOf, L as parseWorldInfoEdit, Z as checkWorld, a as importHooks, l as isReviewing, m as editsSince, n as limitAuthoringAgents, o as importTools } from "./authoring-tools-DNnx0Nts.js";
3
+ import { B as readWorldPrompt, K as IMPORT_FOLDER, L as PROSE_PROMPTS, R as deleteWorldPrompt, Tt as parseRelationEdit, V as writeWorldPrompt, bt as InvalidEditProblems, z as listWorldPrompts } from "./presets-MwOSMMyu.js";
4
+ import { H as parsePlotsFile, J as formatIssue, at as shippedPromptsDirectory } from "./hooks-BQCzgggH.js";
5
+ import { i as translator, r as languageOf } from "./text-BzudpQLS.js";
6
+ import { $ as matchPieces, B as readWorldInfo, C as readWorldEditor, F as loadWorldParts, H as translateTools, K as finishUpdate, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, Q as diffText, R as presetTools, Z as cardChanges, _ as editWorldPlots, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, et as worldFieldChanges, i as checkWorldPack, l as deleteAuthoredEntity, nt as entitiesByPiece, o as listWorldPacks, q as pendingUpdate, r as registerPackJail, rt as readSource, s as AUTHORED_ENTITY_KINDS, tt as cardTools, u as readAuthoredEntityDocument, v as editWorldRelation, z as editWorldInfo } from "./pack-jail-5EJ-WYyW.js";
7
+ import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-Cv8hanXJ.js";
8
+ import { t as guardAuthoringTurns } from "./turn-guard-Cv8pfHEA.js";
9
9
  import { join, relative } from "node:path";
10
+ import { readFile, readdir } from "node:fs/promises";
10
11
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
11
12
  import { defineTool } from "@deepseek-ai/dsh-tools";
12
- import { readFile, readdir } from "node:fs/promises";
13
13
  import { isDeepStrictEqual } from "node:util";
14
14
  //#region src/host/authoring/read-tools.ts
15
15
  const output$4 = (value) => [{
@@ -119,6 +119,16 @@ function authoredWorldReadTools(reader) {
119
119
  return json$1(await readWorldInfo((await reader.read(exec)).record.directory));
120
120
  }
121
121
  }),
122
+ defineTool({
123
+ name: "world_check",
124
+ description: "Check the world as starting a story from it would: every file reads and everything that refers to something refers to something that is there. It names the problems of the first part of the world that has any (characters, factions, places, calendar, dice, items, lore, tracked values, triggers, plots), so run it again after fixing them to see whether another part has some. Run it before you say a world is done.",
125
+ parameters: {},
126
+ output: jsonOutput$3,
127
+ isConcurrencySafe: () => true,
128
+ async execute(_args, exec) {
129
+ return json$1(await checkWorld((await reader.read(exec)).record));
130
+ }
131
+ }),
122
132
  listTool(reader, "list_characters", "List authored characters with stable keys and concise identifying information.", (world) => world.characters, (entry) => ({
123
133
  key: entry.key,
124
134
  name: entry.name,
@@ -592,6 +602,38 @@ function plotDocument(value) {
592
602
  if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
593
603
  return parsed.value[0];
594
604
  }
605
+ /** The most problems a write reports back; `world_check` lists the rest. */
606
+ const REPORTED_PROBLEMS = 8;
607
+ /**
608
+ * A write is allowed to leave the world unfinished (a character first, its place next), so the check is advice, not a refusal: the assistant sees at once what its edit
609
+ * left open instead of finding out when a story is started.
610
+ */
611
+ function withWorldCheck(reader, tool) {
612
+ const run = tool.execute;
613
+ return {
614
+ ...tool,
615
+ async execute(args, exec) {
616
+ const done = await run(args, exec);
617
+ if (done === null || typeof done !== "object") return done;
618
+ const { record } = await reader.read(exec);
619
+ const check = await checkWorld(record);
620
+ if (check.ok) return {
621
+ ...done,
622
+ world_check: "ok: a story could start from this world"
623
+ };
624
+ const shown = check.problems.slice(0, REPORTED_PROBLEMS).map((problem) => `${problem.where}: ${problem.message}`);
625
+ return {
626
+ ...done,
627
+ world_check: {
628
+ ok: false,
629
+ still_open: shown,
630
+ more: check.problems.length - shown.length + check.more,
631
+ note: "Not an error of this edit; fix what the world still needs before the end of the turn (world_check lists all)."
632
+ }
633
+ };
634
+ }
635
+ };
636
+ }
595
637
  function authoredWorldWriteTools(reader) {
596
638
  return [
597
639
  defineTool({
@@ -761,7 +803,7 @@ function authoredWorldWriteTools(reader) {
761
803
  });
762
804
  }
763
805
  })
764
- ];
806
+ ].map((tool) => withWorldCheck(reader, tool));
765
807
  }
766
808
  /**
767
809
  * Every change to the world files is put to the person, except in the turn that has just imported a card into the world: it reviews and corrects what it made.
@@ -155,6 +155,7 @@ function sharedSamplingOf(settings) {
155
155
  const SUBMIT_TOOL = "submit_result";
156
156
  /** Said to every child once, after its persona, so it is the same for all of them and the start of every request stays the same. */
157
157
  const SUBMIT_RULE = `When you are done, call ${SUBMIT_TOOL} with your result. It is the only way to finish: text you write instead is lost.`;
158
+ const STRUCTURED_RULE = "Your whole reply is the result, as one JSON object of the shape you were given: write nothing before or after it.";
158
159
  /** Calls a child may make before it is given up; a child that keeps going is not converging. */
159
160
  const DEFAULT_MAX_CALLS = 40;
160
161
  /** A child that stops without a result is told to submit this many times before it is given up. */
@@ -170,6 +171,11 @@ const REPEATS_TOLD = 1;
170
171
  const REPEATS_STOPPED = 4;
171
172
  /** A result that is refused this many times is not going to be fixed by asking again: the child is stopped and the caller decides what to do without it. */
172
173
  const MAX_REFUSALS = 5;
174
+ /**
175
+ * How long a child that was stopped has to wind down. Found live twice: a stopped child's activation never settled and the caller waited for ever (an import stood still for
176
+ * minutes, a game master's turn never ended), so what the stop decided is not waited on past this.
177
+ */
178
+ const STOP_GRACE_MS = 15e3;
173
179
  /** A child ran out of the time it was given; asking again would only spend it again. */
174
180
  var ChildTimeoutError = class extends Error {
175
181
  constructor(minutes) {
@@ -320,6 +326,57 @@ async function supportedEffort(task) {
320
326
  return level;
321
327
  }
322
328
  }
329
+ /**
330
+ * A JSON text that was cut off, closed after the last whole entry it holds: what a reply that ran into its limit in the middle of a long list still says. Nothing when no such cut makes it JSON.
331
+ */
332
+ function repairedJson(text) {
333
+ const cuts = [];
334
+ for (const marks of ["}]", ","]) for (let at = text.length - 1, found = 0; at >= 0 && found < 300; at -= 1) if (marks.includes(text[at])) {
335
+ cuts.push(at);
336
+ found += 1;
337
+ }
338
+ for (const at of cuts) {
339
+ const head = text.slice(0, text[at] === "," ? at : at + 1);
340
+ const stack = [];
341
+ let inString = false;
342
+ for (let index = 0; index < head.length; index += 1) {
343
+ const char = head[index];
344
+ if (inString) {
345
+ if (char === "\\") index += 1;
346
+ else if (char === "\"") inString = false;
347
+ continue;
348
+ }
349
+ if (char === "\"") inString = true;
350
+ else if (char === "{") stack.push("}");
351
+ else if (char === "[") stack.push("]");
352
+ else if (char === "}" || char === "]") stack.pop();
353
+ }
354
+ if (inString) continue;
355
+ const closed = head + stack.reverse().join("");
356
+ try {
357
+ JSON.parse(closed);
358
+ return closed;
359
+ } catch {
360
+ continue;
361
+ }
362
+ }
363
+ }
364
+ /** The result in the last reply of a structured child: its JSON, which must fit the schema; else what is wrong with it. */
365
+ function structuredReply(child, schema, cut = false) {
366
+ const message = child.session.snapshotEvents().findLast((event) => event.type === "assistant/message");
367
+ const text = (message?.type === "assistant/message" ? message.data.message.content : []).flatMap((block) => block.type === "text" ? [block.text] : []).join("").trim().replace(/^```(?:json)?\s*|\s*```$/g, "");
368
+ if (text === "") return { problem: "the reply is empty" };
369
+ let value;
370
+ try {
371
+ value = JSON.parse(text);
372
+ } catch (error) {
373
+ const mended = cut ? repairedJson(text) : void 0;
374
+ if (mended === void 0) return { problem: `the reply is not valid JSON (${error instanceof Error ? error.message : String(error)})` };
375
+ value = JSON.parse(mended);
376
+ }
377
+ const violations = validateJsonSchemaValue(schema, value);
378
+ return violations.length > 0 ? { problem: violations.map((violation) => String(violation)).join("; ") } : { value };
379
+ }
323
380
  const cut = (value, limit = MAX_RUN_TEXT) => {
324
381
  const text = typeof value === "string" ? value : JSON.stringify(value) ?? "";
325
382
  return text.length > limit ? `${text.slice(0, limit)} ... (${text.length - limit} more characters)` : text;
@@ -330,6 +387,10 @@ async function execute(task, stats) {
330
387
  let submitted;
331
388
  let reminders = 0;
332
389
  let stopped;
390
+ let giveUp;
391
+ const gaveUp = new Promise((resolve) => {
392
+ giveUp = resolve;
393
+ });
333
394
  let retire;
334
395
  let stepsAfterRetire = -1;
335
396
  let overran = false;
@@ -447,11 +508,14 @@ async function execute(task, stats) {
447
508
  };
448
509
  const childId = SessionId(randomUUID());
449
510
  const entry = {
450
- persona: `${task.persona}\n\n${SUBMIT_RULE}`,
511
+ persona: `${task.persona}\n\n${task.structured === true ? STRUCTURED_RULE : SUBMIT_RULE}`,
451
512
  setup(child) {
452
513
  entry.agent = child;
453
514
  stopped = () => {
454
515
  child.cancel({ kind: "parent" });
516
+ setTimeout(() => {
517
+ giveUp?.();
518
+ }, STOP_GRACE_MS);
455
519
  };
456
520
  const childCtx = child.ctx;
457
521
  childCtx.tools.restrict({ allow: [...task.external ?? []] });
@@ -476,9 +540,51 @@ async function execute(task, stats) {
476
540
  }
477
541
  return decision;
478
542
  });
479
- childCtx.tools.register(submit);
543
+ if (task.structured !== true) childCtx.tools.register(submit);
480
544
  childCtx.on("agent/turn-stopping", () => {
481
545
  if (submitted !== void 0) return;
546
+ if (task.structured === true) {
547
+ const reply = structuredReply(child, enforcedSchema(task), cutOff(child));
548
+ if (cutOff(child) && !("value" in reply)) {
549
+ rambled = true;
550
+ overran = true;
551
+ stopped?.();
552
+ return;
553
+ }
554
+ const refusal = "value" in reply ? task.beforeSubmit?.(reply.value) : reply.problem;
555
+ if ("value" in reply && refusal === void 0) {
556
+ submitted = { value: reply.value };
557
+ stats.result = cut(reply.value, MAX_RUN_PROMPT);
558
+ if (stats.record.length < 60) stats.record.push({
559
+ tool: "reply",
560
+ args: "",
561
+ outcome: cut(reply.value),
562
+ failed: false
563
+ });
564
+ return;
565
+ }
566
+ refusals += 1;
567
+ lastRefusal = refusal ?? "";
568
+ if (stats.record.length < 60) stats.record.push({
569
+ tool: "reply",
570
+ args: "",
571
+ outcome: cut(lastRefusal),
572
+ failed: true
573
+ });
574
+ if (refusals >= MAX_REFUSALS) {
575
+ overran = true;
576
+ stopped?.();
577
+ return;
578
+ }
579
+ child.steer(createUserMessage({
580
+ content: [{
581
+ type: "text",
582
+ text: `That reply cannot be used: ${lastRefusal}\nReply again with the whole result as one JSON object.`
583
+ }],
584
+ source: { kind: "roleplay" }
585
+ }));
586
+ return;
587
+ }
482
588
  if (cutOff(child)) {
483
589
  rambled = true;
484
590
  overran = true;
@@ -499,7 +605,23 @@ async function execute(task, stats) {
499
605
  }
500
606
  };
501
607
  helpers.set(childId, entry);
502
- if (task.sampling !== void 0) samplings.set(childId, task.sampling);
608
+ if (task.structured === true) {
609
+ const { toolChoice: _unused, ...rest } = task.sampling ?? {};
610
+ samplings.set(childId, {
611
+ ...rest,
612
+ body: {
613
+ ...rest.body,
614
+ response_format: {
615
+ type: "json_schema",
616
+ json_schema: {
617
+ name: "result",
618
+ strict: true,
619
+ schema: task.result
620
+ }
621
+ }
622
+ }
623
+ });
624
+ } else if (task.sampling !== void 0) samplings.set(childId, task.sampling);
503
625
  try {
504
626
  const subagents = parent.ctx.get("subagents");
505
627
  if (subagents === void 0) throw new Error("the sub-agent service is not loaded");
@@ -527,12 +649,14 @@ async function execute(task, stats) {
527
649
  }
528
650
  });
529
651
  try {
530
- await activation.result;
652
+ await Promise.race([activation.result, gaveUp]);
531
653
  } catch (error) {
532
654
  if (submitted === void 0 && !overran && !signal.aborted) throw error;
533
655
  } finally {
534
656
  if (entry.agent !== void 0) stats.tokens = tokensOf(entry.agent.session.snapshotEvents());
535
- await activation.dispose();
657
+ await (overran ? Promise.race([activation.dispose(), new Promise((resolve) => {
658
+ setTimeout(resolve, STOP_GRACE_MS);
659
+ })]) : activation.dispose());
536
660
  }
537
661
  } finally {
538
662
  helpers.delete(childId);
@@ -552,4 +676,4 @@ async function execute(task, stats) {
552
676
  //#endregion
553
677
  export { finishOf as _, childTrace as a, runChild as c, sharedSamplingOf as d, tokensOf as f, cutOff as g, currentTurn as h, childSamplingOf as i, SAMPLING_RANGES as l, addTokens as m, childModel as n, helpers as o, NO_TOKENS as p, childSampling as r, namedModel as s, ChildTimeoutError as t, parseSampling as u, estimateAnswer as v, tokensOf$1 as y };
554
678
 
555
- //# sourceMappingURL=child-CyCViUKa.js.map
679
+ //# sourceMappingURL=child-D6mpkkCE.js.map