@dsh-agentic-roleplay/core 0.4.1 → 0.6.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 (40) hide show
  1. package/lib/{authoring-tools-C2BHkEFP.js → authoring-tools-BGzzW6O5.js} +7 -6
  2. package/lib/authoring.js +5 -5
  3. package/lib/{child-DsixtqTw.js → child-D5SVNk4O.js} +58 -71
  4. package/lib/client.js +747 -316
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +18 -23
  7. package/lib/doctor.js +2 -2
  8. package/lib/{gallery-CDYKJf_O.js → gallery-C7VOJ3xH.js} +2 -2
  9. package/lib/{generator-BR1ugzln.js → generator-CO8usAjE.js} +2 -2
  10. package/lib/helper.js +26 -0
  11. package/lib/{hooks-CHmUksFS.js → hooks-BLperIIB.js} +70 -7
  12. package/lib/images.js +4 -4
  13. package/lib/index.js +64 -22
  14. package/lib/{library-COIktKBa.js → library-DsDc6fQa.js} +2 -2
  15. package/lib/{lorebook-author-tools-CaT74Q7v.js → lorebook-author-tools-C-cFiE6E.js} +6 -6
  16. package/lib/lorebook-authoring.js +3 -3
  17. package/lib/{narration-DstnwrvX.js → narration-_dA9oIt2.js} +57 -2
  18. package/lib/orchestration.js +372 -48
  19. package/lib/{pack-jail-CEDDI4Xw.js → pack-jail-BKFmbYP8.js} +10 -10
  20. package/lib/{packs-DB_9xiCp.js → packs-ZTG7fWut.js} +2 -2
  21. package/lib/{presenter-agent-Gu34bZwd.js → presenter-agent-BHSbyWwZ.js} +5 -5
  22. package/lib/{preset-BL1d40oG.js → preset-CJLW8Mp0.js} +3 -3
  23. package/lib/{preset-author-tools-B2wZXKZo.js → preset-author-tools-1RstgEZs.js} +5 -5
  24. package/lib/preset-authoring.js +4 -4
  25. package/lib/{presets-Dc15L6OU.js → presets-DcPCnn8O.js} +3 -3
  26. package/lib/{reflection-BWMVdHhR.js → reflection-6qfOC5OT.js} +236 -32
  27. package/lib/text-CT1re6XT.js +18 -0
  28. package/package.json +38 -41
  29. package/prompts/en/roleplay/check-rule.md +3 -0
  30. package/prompts/en/roleplay/decide-reflection.md +3 -0
  31. package/prompts/en/roleplay/decide-trigger.md +3 -0
  32. package/prompts/en/roleplay/gate-agency.md +1 -0
  33. package/prompts/en/roleplay/gate-refusal.md +1 -0
  34. package/prompts/en/roleplay/gate-secret.md +3 -0
  35. package/prompts/zh/roleplay/check-rule.md +3 -0
  36. package/prompts/zh/roleplay/decide-reflection.md +3 -0
  37. package/prompts/zh/roleplay/decide-trigger.md +3 -0
  38. package/prompts/zh/roleplay/gate-agency.md +1 -0
  39. package/prompts/zh/roleplay/gate-refusal.md +1 -0
  40. package/prompts/zh/roleplay/gate-secret.md +3 -0
@@ -1,8 +1,9 @@
1
- import { a as isPresetName, b as INTENT_STATUSES, m as PROSE_PROMPTS, x as INTENT_TYPES, y as INTENT_HORIZONS } from "./presets-Dc15L6OU.js";
2
- import { _ as VARIABLE_VISIBILITIES, f as parseSwitchboard, g as VARIABLE_SUBJECTS, h as VARIABLE_KINDS } from "./narration-DstnwrvX.js";
3
- import { $ as promptProblem, G as errorMessage, H as readDocument, U as Reader, V as plotReferenceProblems, W as formatIssue, a as externalWithheld, et as shippedLanguages, it as InvalidWorldError, q as PROMPTS_FOLDER, r as externalGiven, t as externalToolLimit, z as loadPlots } from "./hooks-CHmUksFS.js";
4
- import { a as runChild, h as trimCharacters, s as parseSampling } from "./child-DsixtqTw.js";
5
- import { b as slug, c as referenceImagePath, d as MEDIA_TYPES, h as writeImageFileMetadata, n as imageExtensionOf, t as addToLibrary, v as mapLimit, x as uniqueKey, y as norm } from "./library-COIktKBa.js";
1
+ import { a as isPresetName, b as INTENT_STATUSES, m as PROSE_PROMPTS, x as INTENT_TYPES, y as INTENT_HORIZONS } from "./presets-DcPCnn8O.js";
2
+ import { b as VARIABLE_VISIBILITIES, f as parseSwitchboard, v as VARIABLE_KINDS, y as VARIABLE_SUBJECTS } from "./narration-_dA9oIt2.js";
3
+ import { B as loadPlots, G as formatIssue, H as plotReferenceProblems, J as PROMPTS_FOLDER, K as errorMessage, U as readDocument, W as Reader, a as externalWithheld, at as InvalidWorldError, et as promptProblem, r as externalGiven, t as externalToolLimit, tt as shippedLanguages } from "./hooks-BLperIIB.js";
4
+ import { t as trimCharacters } from "./text-CT1re6XT.js";
5
+ import { c as parseSampling, o as runChild } from "./child-D5SVNk4O.js";
6
+ import { b as slug, c as referenceImagePath, d as MEDIA_TYPES, h as writeImageFileMetadata, n as imageExtensionOf, t as addToLibrary, v as mapLimit, x as uniqueKey, y as norm } from "./library-DsDc6fQa.js";
6
7
  import { dirname, join } from "node:path";
7
8
  import { existsSync, readFileSync } from "node:fs";
8
9
  import { createHash, randomUUID } from "node:crypto";
@@ -6050,4 +6051,4 @@ function limitAuthoringAgents(ctx, kindOf) {
6050
6051
  //#endregion
6051
6052
  export { LOCATION_FILE_NAME as $, loadTriggers as A, parseLoreFile as At, loadItems as B, ImportCardError as Bt, populateLocations as C, readLorebook as Ct, populateVariables as D, LORE_DIR as Dt, populateTriggers as E, writeLorebookEntry as Et, loadCalendar as F, parseLoreEdit as Ft, extractStyleFrom as G, LORE_SCOPES as Gt, loadFactions as H, pictureOf as Ht, parseCalendarFile as I, parsePlaceEdit as It, withPlayer as J, DICE_RESULTS as Jt, cleanText as K, DICE_COMPARISONS as Kt, LOCATIONS_DIR as L, parseRelationEdit as Lt, loadDice as M, InvalidEditProblems as Mt, parseDiceFile as N, parseCharacterEdit as Nt, routineProblems as O, loadLore as Ot, CALENDAR_FILE_NAME as P, parseFactionEdit as Pt, variableProblems as Q, loadLocations as R, parseThingEdit as Rt, populateKnowledge as S, lorebookDirectory as St, populateRoutines as T, updateLorebookInfo as Tt, CHARACTERS_DIR as U, readCard as Ut, FACTIONS_DIR as V, isPng as Vt, loadCharacters as W, LORE_KINDS as Wt, loadVariables as X, VARIABLES_FILE_NAME as Y, parseVariablesFile as Z, populateCharacters as _, deleteLorebookEntry as _t, importHooks as a, CHARACTER_FILE_NAME as at, populateFactions as b, listLorebooks as bt, authoredWorldOf as c, ImportNotFoundError as ct, markReady as d, WORLD_FILE_NAME as dt, parseLocationFile as et, guardedLookup as f, parseWorldFile as ft, populateCalendar as g, deleteLorebook as gt, knowsCharacter as h, createLorebook as ht, contextOf as i, parseFactionFile as it, DICE_FILE_NAME as j, subfolders as jt, TRIGGERS_FILE_NAME as k, LORE_FILE_NAME as kt, authoringChatSessionId as l, ImportStore as lt, loadValidatedWorld as m, addLorebookEntries as mt, limitAuthoringAgents as n, parseItemFile as nt, importTools as o, parseCharacterFile as ot, vetUrl as p, parseWorldInfoEdit as pt, partsOf as q, DICE_READINGS as qt, MAX_PREVIEW_TEXT as r, FACTION_FILE_NAME as rt, worldOf as s, IMPORT_FOLDER as st, AuthoringTools as t, ITEM_FILE_NAME as tt, isReviewing as u, parseChoices as ut, populateClock as v, entriesOf as vt, populateLore as w, reserveLorebook as wt, populateItems as x, loadLorebook as xt, populateDice as y, isLorebookName as yt, ITEMS_DIR as z, IMPORT_COMMAND as zt };
6052
6053
 
6053
- //# sourceMappingURL=authoring-tools-C2BHkEFP.js.map
6054
+ //# sourceMappingURL=authoring-tools-BGzzW6O5.js.map
package/lib/authoring.js CHANGED
@@ -1,8 +1,8 @@
1
- import { Lt as parseRelationEdit, Mt as InvalidEditProblems, a as importHooks, c as authoredWorldOf, n as limitAuthoringAgents, o as importTools, u as isReviewing } from "./authoring-tools-C2BHkEFP.js";
2
- import { _ as readWorldPrompt, g as listWorldPrompts, h as deleteWorldPrompt, m as PROSE_PROMPTS, v as writeWorldPrompt } from "./presets-Dc15L6OU.js";
3
- import { B as parsePlotsFile, W as formatIssue, tt as shippedPromptsDirectory } from "./hooks-CHmUksFS.js";
4
- import { C as readWorldEditor, F as loadWorldParts, H as translateTools, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, R as presetTools, _ 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 } from "./pack-jail-CEDDI4Xw.js";
5
- import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-DB_9xiCp.js";
1
+ import { Lt as parseRelationEdit, Mt as InvalidEditProblems, a as importHooks, c as authoredWorldOf, n as limitAuthoringAgents, o as importTools, u as isReviewing } from "./authoring-tools-BGzzW6O5.js";
2
+ import { _ as readWorldPrompt, g as listWorldPrompts, h as deleteWorldPrompt, m as PROSE_PROMPTS, v as writeWorldPrompt } from "./presets-DcPCnn8O.js";
3
+ import { G as formatIssue, V as parsePlotsFile, nt as shippedPromptsDirectory } from "./hooks-BLperIIB.js";
4
+ import { C as readWorldEditor, F as loadWorldParts, H as translateTools, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, R as presetTools, _ 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 } from "./pack-jail-BKFmbYP8.js";
5
+ import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-ZTG7fWut.js";
6
6
  import { join, relative } from "node:path";
7
7
  import { defineTool } from "@deepseek-ai/dsh-tools";
8
8
  import { readFile } from "node:fs/promises";
@@ -1,23 +1,7 @@
1
1
  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
- import { appendDelegatedPolicyOverrides, applyChildComposition, captureDelegatedPolicyOverrides, childSessionMeta, resolveChildAgentOptions, resolveChildDepth } from "@deepseek-ai/dsh-subagent";
5
4
  import { ToolArgsError, validateJsonSchemaValue } from "@deepseek-ai/dsh-tools";
6
- //#region src/shared/text.ts
7
- /** Remove characters from either end without a backtracking regular expression. */
8
- function trimCharacters(value, characters, edge = "both") {
9
- let start = 0;
10
- let end = value.length;
11
- if (edge !== "end") while (start < end && characters.includes(value[start])) start += 1;
12
- if (edge !== "start") while (end > start && characters.includes(value[end - 1])) end -= 1;
13
- return value.slice(start, end);
14
- }
15
- /** A path-like name without its last extension. */
16
- function withoutExtension(value) {
17
- const dot = value.lastIndexOf(".");
18
- return dot < 0 ? value : value.slice(0, dot);
19
- }
20
- //#endregion
21
5
  //#region src/host/agents/budget.ts
22
6
  /** 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. */
23
7
  function tokensOf$1(characters, language) {
@@ -223,19 +207,11 @@ function childModel(settings, kind, override) {
223
207
  } };
224
208
  }
225
209
  const samplings = /* @__PURE__ */ new Map();
210
+ /** The id of the agent preset every helper runs under; it must match the preset row in the bundle's patch. */
211
+ const HELPER_PRESET = "roleplay-helper";
212
+ const helpers = /* @__PURE__ */ new Map();
226
213
  /** The controls set for a running child, by its session id. */
227
214
  const childSamplingOf = (sessionId) => samplings.get(sessionId);
228
- /**
229
- * Run a child agent to its result. Unlike a sub-agent started through `ctx.subagents`, it can
230
- * have tools of its own, so several can run side by side with different tools and different
231
- * results from the same tool.
232
- *
233
- * This is the one place the bundle builds an agent below DSH's sub-agent API: it uses the
234
- * composition helpers DSH exports for sub-agent providers (`applyChildComposition`,
235
- * `childSessionMeta`, ...). They are not a stable interface; `docs/dsh-api-usage.md` says why
236
- * this is accepted, which DSH version it is built against, and what to do when DSH changes.
237
- * @throws {Error} when the child is cancelled, stops without a result, or exceeds its calls.
238
- */
239
215
  function childOptions(task) {
240
216
  const maxTokens = task.maxTokens ?? task.sampling?.maxTokens;
241
217
  const options = {
@@ -258,6 +234,11 @@ function enforcedSchema(task) {
258
234
  }
259
235
  /** A model that is cut off in the middle of its tool call leaves an unfinished argument no one can read; asking again usually gives a whole one. */
260
236
  const isUnfinishedCall = (error) => error instanceof Error && /parse tool call arguments|unfinished tool call/i.test(error.message);
237
+ /**
238
+ * Run a child agent to its result through DSH's public sub-agent API: the child starts under the helper preset, whose plugin hands it its persona and
239
+ * lets {@link HelperEntry.setup} give it tools of its own. Several run side by side with different tools and different results from the same tool.
240
+ * @throws {Error} when the child is cancelled, stops without a result, or exceeds its calls.
241
+ */
261
242
  async function runChild(task) {
262
243
  for (let attempt = 1;; attempt += 1) {
263
244
  const began = Date.now();
@@ -431,25 +412,16 @@ async function execute(task, stats) {
431
412
  return Promise.resolve({ recorded: true });
432
413
  }
433
414
  };
434
- const depth = resolveChildDepth(parent, void 0);
435
- const inherited = captureDelegatedPolicyOverrides(parent);
436
- const sessionId = SessionId(randomUUID());
437
- if (task.sampling !== void 0) samplings.set(sessionId, task.sampling);
438
- const handle = await parent.ctx.agents.create({
439
- sessionId,
440
- parentAgent: parent,
441
- meta: childSessionMeta(parent, depth, false),
442
- agentOptions: resolveChildAgentOptions(parent, childOptions({
443
- ...task,
444
- ...reasoningEffort === void 0 ? { reasoningEffort: "" } : { reasoningEffort }
445
- }), depth),
446
- signal,
447
- setup: (childCtx, child) => {
448
- appendDelegatedPolicyOverrides(child.session, inherited);
449
- applyChildComposition(childCtx, parent, {
450
- persona: `${task.persona}\n\n${SUBMIT_RULE}`,
451
- toolFilter: { allow: [...task.external ?? []] }
452
- });
415
+ const childId = SessionId(randomUUID());
416
+ const entry = {
417
+ persona: `${task.persona}\n\n${SUBMIT_RULE}`,
418
+ setup(child) {
419
+ entry.agent = child;
420
+ stopped = () => {
421
+ child.cancel({ kind: "parent" });
422
+ };
423
+ const childCtx = child.ctx;
424
+ childCtx.tools.restrict({ allow: [...task.external ?? []] });
453
425
  const registered = (task.tools ?? []).map((tool) => childCtx.tools.register(counted(tool)));
454
426
  retire = () => {
455
427
  for (const dispose of registered) dispose();
@@ -485,36 +457,51 @@ async function execute(task, stats) {
485
457
  });
486
458
  childCtx.tools.guard((exec) => submitted === void 0 ? void 0 : `the result is already submitted, so \`${exec.name}\` is not run`);
487
459
  }
488
- });
489
- stopped = () => {
490
- handle.agent.cancel({ kind: "parent" });
491
- };
492
- const onAbort = () => {
493
- handle.agent.cancel({ kind: "parent" });
494
460
  };
495
- signal.addEventListener("abort", onAbort, { once: true });
461
+ helpers.set(childId, entry);
462
+ if (task.sampling !== void 0) samplings.set(childId, task.sampling);
496
463
  try {
497
- handle.agent.followup(createUserMessage({
498
- content: [{
499
- type: "text",
500
- text: task.prompt
501
- }, ...(task.images ?? []).map((attachment) => ({
502
- type: "image",
503
- attachment
504
- }))],
505
- source: { kind: "user" }
506
- }));
507
- await handle.agent.whenIdle();
464
+ const subagents = parent.ctx.get("subagents");
465
+ if (subagents === void 0) throw new Error("the sub-agent service is not loaded");
466
+ const options = childOptions({
467
+ ...task,
468
+ ...reasoningEffort === void 0 ? { reasoningEffort: "" } : { reasoningEffort }
469
+ });
470
+ const activation = await subagents.startActivation({
471
+ provider: "spawn",
472
+ label: "roleplay helper",
473
+ childId,
474
+ delivery: "caller",
475
+ signal,
476
+ request: {
477
+ parent,
478
+ agentPreset: HELPER_PRESET,
479
+ ...options === void 0 ? {} : { agentOptions: options },
480
+ prompt: [{
481
+ type: "text",
482
+ text: task.prompt
483
+ }, ...(task.images ?? []).map((attachment) => ({
484
+ type: "image",
485
+ attachment
486
+ }))]
487
+ }
488
+ });
489
+ try {
490
+ await activation.result;
491
+ } catch (error) {
492
+ if (submitted === void 0 && !overran && !signal.aborted) throw error;
493
+ } finally {
494
+ if (entry.agent !== void 0) stats.tokens = tokensOf(entry.agent.session.snapshotEvents());
495
+ await activation.dispose();
496
+ }
508
497
  } finally {
509
- signal.removeEventListener("abort", onAbort);
510
- stats.tokens = tokensOf(handle.agent.session.snapshotEvents());
511
- samplings.delete(sessionId);
512
- await handle.dispose();
498
+ helpers.delete(childId);
499
+ samplings.delete(childId);
513
500
  }
514
501
  if (signal.aborted) throw new Error("cancelled");
515
502
  if (overran && submitted === void 0) throw new Error(refusals >= MAX_REFUSALS ? `the result was refused ${refusals} times and the agent was stopped; the last reason: ${lastRefusal}` : `the agent went on past its ${budget} calls, or kept repeating a call that failed, without submitting a result and was stopped`);
516
503
  if (submitted === void 0) {
517
- const ended = handle.agent.session.snapshotEvents().findLast((event) => event.type === "turn/end");
504
+ const ended = entry.agent?.session.snapshotEvents().findLast((event) => event.type === "turn/end");
518
505
  const reason = ended?.type === "turn/end" ? ended.data.reason : void 0;
519
506
  if (reason?.kind === "error") throw new Error(`the agent failed: ${reason.error.message}`);
520
507
  throw new Error(`the agent stopped without submitting a result (${stats.calls} call(s))`);
@@ -522,6 +509,6 @@ async function execute(task, stats) {
522
509
  return submitted.value;
523
510
  }
524
511
  //#endregion
525
- export { runChild as a, sharedSamplingOf as c, addTokens as d, currentTurn as f, withoutExtension as g, trimCharacters as h, childTrace as i, tokensOf as l, tokensOf$1 as m, childSampling as n, SAMPLING_RANGES as o, estimateAnswer as p, childSamplingOf as r, parseSampling as s, childModel as t, NO_TOKENS as u };
512
+ export { helpers as a, parseSampling as c, NO_TOKENS as d, addTokens as f, tokensOf$1 as h, childTrace as i, sharedSamplingOf as l, estimateAnswer as m, childSampling as n, runChild as o, currentTurn as p, childSamplingOf as r, SAMPLING_RANGES as s, childModel as t, tokensOf as u };
526
513
 
527
- //# sourceMappingURL=child-DsixtqTw.js.map
514
+ //# sourceMappingURL=child-D5SVNk4O.js.map