@dsh-agentic-roleplay/core 0.5.0 → 0.6.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 (37) hide show
  1. package/lib/access-EbNdZFbk.js +25 -0
  2. package/lib/{authoring-tools-Ch_3oIKC.js → authoring-tools-BGzzW6O5.js} +5 -5
  3. package/lib/authoring.js +5 -5
  4. package/lib/{access-tN5D3WI8.js → child-D5SVNk4O.js} +58 -78
  5. package/lib/client.js +819 -327
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -2
  8. package/lib/doctor.js +3 -3
  9. package/lib/helper.js +26 -0
  10. package/lib/{hooks-C7gt2c01.js → hooks-BLperIIB.js} +70 -7
  11. package/lib/images.js +1 -1
  12. package/lib/index.js +43 -11
  13. package/lib/{lorebook-author-tools-DII7Xt7Q.js → lorebook-author-tools-C-cFiE6E.js} +5 -5
  14. package/lib/lorebook-authoring.js +3 -3
  15. package/lib/{narration-DstnwrvX.js → narration-_dA9oIt2.js} +57 -2
  16. package/lib/orchestration.js +364 -46
  17. package/lib/{pack-jail-AzR6dCNm.js → pack-jail-BKFmbYP8.js} +8 -8
  18. package/lib/{packs-C7g534Mi.js → packs-ZTG7fWut.js} +2 -2
  19. package/lib/{presenter-agent-BsC6Vftz.js → presenter-agent-BHSbyWwZ.js} +3 -2
  20. package/lib/{preset-Drfu_K-H.js → preset-CJLW8Mp0.js} +3 -3
  21. package/lib/{preset-author-tools-CdIsFhQw.js → preset-author-tools-1RstgEZs.js} +5 -5
  22. package/lib/preset-authoring.js +4 -4
  23. package/lib/{presets-CADd77WB.js → presets-DcPCnn8O.js} +3 -3
  24. package/lib/{reflection-CUGuPAZR.js → reflection-6qfOC5OT.js} +235 -31
  25. package/package.json +4 -3
  26. package/prompts/en/roleplay/check-rule.md +3 -0
  27. package/prompts/en/roleplay/decide-reflection.md +3 -0
  28. package/prompts/en/roleplay/decide-trigger.md +3 -0
  29. package/prompts/en/roleplay/gate-agency.md +1 -0
  30. package/prompts/en/roleplay/gate-refusal.md +1 -0
  31. package/prompts/en/roleplay/gate-secret.md +3 -0
  32. package/prompts/zh/roleplay/check-rule.md +3 -0
  33. package/prompts/zh/roleplay/decide-reflection.md +3 -0
  34. package/prompts/zh/roleplay/decide-trigger.md +3 -0
  35. package/prompts/zh/roleplay/gate-agency.md +1 -0
  36. package/prompts/zh/roleplay/gate-refusal.md +1 -0
  37. package/prompts/zh/roleplay/gate-secret.md +3 -0
@@ -0,0 +1,25 @@
1
+ //#region src/shared/chat.ts
2
+ const CHAT_PREFIX = "session-";
3
+ 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}$/;
4
+ /** The DSH chat of a roleplay session is named after the session's id. */
5
+ function chatSessionId(sessionId) {
6
+ return `${CHAT_PREFIX}${sessionId}`;
7
+ }
8
+ /** The roleplay session a DSH chat id could belong to; ordinary DSH chats have ids of the same shape. */
9
+ function roleplaySessionOf(chat) {
10
+ if (!chat.startsWith(CHAT_PREFIX)) return void 0;
11
+ const id = chat.slice(8);
12
+ return UUID_V4.test(id) ? id : void 0;
13
+ }
14
+ //#endregion
15
+ //#region src/host/prompts/access.ts
16
+ /** The prompt `id` in `language`, from the library of the agent's own context. */
17
+ function promptFor(agent, id, language, variables) {
18
+ const library = agent.ctx.get("roleplayPrompts");
19
+ if (library === void 0) throw new Error("the prompt library is not running");
20
+ return library.text(id, language, variables, roleplaySessionOf(agent.session.id));
21
+ }
22
+ //#endregion
23
+ export { chatSessionId as n, roleplaySessionOf as r, promptFor as t };
24
+
25
+ //# sourceMappingURL=access-EbNdZFbk.js.map
@@ -1,8 +1,8 @@
1
- import { c as parseSampling, o as runChild } from "./access-tN5D3WI8.js";
2
- import { a as isPresetName, b as INTENT_STATUSES, m as PROSE_PROMPTS, x as INTENT_TYPES, y as INTENT_HORIZONS } from "./presets-CADd77WB.js";
3
- import { _ as VARIABLE_VISIBILITIES, f as parseSwitchboard, g as VARIABLE_SUBJECTS, h as VARIABLE_KINDS } from "./narration-DstnwrvX.js";
4
- 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-C7gt2c01.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";
5
4
  import { t as trimCharacters } from "./text-CT1re6XT.js";
5
+ import { c as parseSampling, o as runChild } from "./child-D5SVNk4O.js";
6
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";
7
7
  import { dirname, join } from "node:path";
8
8
  import { existsSync, readFileSync } from "node:fs";
@@ -6051,4 +6051,4 @@ function limitAuthoringAgents(ctx, kindOf) {
6051
6051
  //#endregion
6052
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 };
6053
6053
 
6054
- //# sourceMappingURL=authoring-tools-Ch_3oIKC.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-Ch_3oIKC.js";
2
- import { _ as readWorldPrompt, g as listWorldPrompts, h as deleteWorldPrompt, m as PROSE_PROMPTS, v as writeWorldPrompt } from "./presets-CADd77WB.js";
3
- import { B as parsePlotsFile, W as formatIssue, tt as shippedPromptsDirectory } from "./hooks-C7gt2c01.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-AzR6dCNm.js";
5
- import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-C7g534Mi.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,22 +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/chat.ts
7
- const CHAT_PREFIX = "session-";
8
- 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}$/;
9
- /** The DSH chat of a roleplay session is named after the session's id. */
10
- function chatSessionId(sessionId) {
11
- return `${CHAT_PREFIX}${sessionId}`;
12
- }
13
- /** The roleplay session a DSH chat id could belong to; ordinary DSH chats have ids of the same shape. */
14
- function roleplaySessionOf(chat) {
15
- if (!chat.startsWith(CHAT_PREFIX)) return void 0;
16
- const id = chat.slice(8);
17
- return UUID_V4.test(id) ? id : void 0;
18
- }
19
- //#endregion
20
5
  //#region src/host/agents/budget.ts
21
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. */
22
7
  function tokensOf$1(characters, language) {
@@ -222,19 +207,11 @@ function childModel(settings, kind, override) {
222
207
  } };
223
208
  }
224
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();
225
213
  /** The controls set for a running child, by its session id. */
226
214
  const childSamplingOf = (sessionId) => samplings.get(sessionId);
227
- /**
228
- * Run a child agent to its result. Unlike a sub-agent started through `ctx.subagents`, it can
229
- * have tools of its own, so several can run side by side with different tools and different
230
- * results from the same tool.
231
- *
232
- * This is the one place the bundle builds an agent below DSH's sub-agent API: it uses the
233
- * composition helpers DSH exports for sub-agent providers (`applyChildComposition`,
234
- * `childSessionMeta`, ...). They are not a stable interface; `docs/dsh-api-usage.md` says why
235
- * this is accepted, which DSH version it is built against, and what to do when DSH changes.
236
- * @throws {Error} when the child is cancelled, stops without a result, or exceeds its calls.
237
- */
238
215
  function childOptions(task) {
239
216
  const maxTokens = task.maxTokens ?? task.sampling?.maxTokens;
240
217
  const options = {
@@ -257,6 +234,11 @@ function enforcedSchema(task) {
257
234
  }
258
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. */
259
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
+ */
260
242
  async function runChild(task) {
261
243
  for (let attempt = 1;; attempt += 1) {
262
244
  const began = Date.now();
@@ -430,25 +412,16 @@ async function execute(task, stats) {
430
412
  return Promise.resolve({ recorded: true });
431
413
  }
432
414
  };
433
- const depth = resolveChildDepth(parent, void 0);
434
- const inherited = captureDelegatedPolicyOverrides(parent);
435
- const sessionId = SessionId(randomUUID());
436
- if (task.sampling !== void 0) samplings.set(sessionId, task.sampling);
437
- const handle = await parent.ctx.agents.create({
438
- sessionId,
439
- parentAgent: parent,
440
- meta: childSessionMeta(parent, depth, false),
441
- agentOptions: resolveChildAgentOptions(parent, childOptions({
442
- ...task,
443
- ...reasoningEffort === void 0 ? { reasoningEffort: "" } : { reasoningEffort }
444
- }), depth),
445
- signal,
446
- setup: (childCtx, child) => {
447
- appendDelegatedPolicyOverrides(child.session, inherited);
448
- applyChildComposition(childCtx, parent, {
449
- persona: `${task.persona}\n\n${SUBMIT_RULE}`,
450
- toolFilter: { allow: [...task.external ?? []] }
451
- });
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 ?? []] });
452
425
  const registered = (task.tools ?? []).map((tool) => childCtx.tools.register(counted(tool)));
453
426
  retire = () => {
454
427
  for (const dispose of registered) dispose();
@@ -484,36 +457,51 @@ async function execute(task, stats) {
484
457
  });
485
458
  childCtx.tools.guard((exec) => submitted === void 0 ? void 0 : `the result is already submitted, so \`${exec.name}\` is not run`);
486
459
  }
487
- });
488
- stopped = () => {
489
- handle.agent.cancel({ kind: "parent" });
490
- };
491
- const onAbort = () => {
492
- handle.agent.cancel({ kind: "parent" });
493
460
  };
494
- signal.addEventListener("abort", onAbort, { once: true });
461
+ helpers.set(childId, entry);
462
+ if (task.sampling !== void 0) samplings.set(childId, task.sampling);
495
463
  try {
496
- handle.agent.followup(createUserMessage({
497
- content: [{
498
- type: "text",
499
- text: task.prompt
500
- }, ...(task.images ?? []).map((attachment) => ({
501
- type: "image",
502
- attachment
503
- }))],
504
- source: { kind: "user" }
505
- }));
506
- 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
+ }
507
497
  } finally {
508
- signal.removeEventListener("abort", onAbort);
509
- stats.tokens = tokensOf(handle.agent.session.snapshotEvents());
510
- samplings.delete(sessionId);
511
- await handle.dispose();
498
+ helpers.delete(childId);
499
+ samplings.delete(childId);
512
500
  }
513
501
  if (signal.aborted) throw new Error("cancelled");
514
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`);
515
503
  if (submitted === void 0) {
516
- 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");
517
505
  const reason = ended?.type === "turn/end" ? ended.data.reason : void 0;
518
506
  if (reason?.kind === "error") throw new Error(`the agent failed: ${reason.error.message}`);
519
507
  throw new Error(`the agent stopped without submitting a result (${stats.calls} call(s))`);
@@ -521,14 +509,6 @@ async function execute(task, stats) {
521
509
  return submitted.value;
522
510
  }
523
511
  //#endregion
524
- //#region src/host/prompts/access.ts
525
- /** The prompt `id` in `language`, from the library of the agent's own context. */
526
- function promptFor(agent, id, language, variables) {
527
- const library = agent.ctx.get("roleplayPrompts");
528
- if (library === void 0) throw new Error("the prompt library is not running");
529
- return library.text(id, language, variables, roleplaySessionOf(agent.session.id));
530
- }
531
- //#endregion
532
- export { roleplaySessionOf as _, childTrace as a, parseSampling as c, NO_TOKENS as d, addTokens as f, chatSessionId as g, tokensOf$1 as h, childSamplingOf as i, sharedSamplingOf as l, estimateAnswer as m, childModel as n, runChild as o, currentTurn as p, childSampling as r, SAMPLING_RANGES as s, promptFor as t, tokensOf 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 };
533
513
 
534
- //# sourceMappingURL=access-tN5D3WI8.js.map
514
+ //# sourceMappingURL=child-D5SVNk4O.js.map