@dsh-agentic-roleplay/core 0.3.2 → 0.3.3

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.
package/lib/authoring.js CHANGED
@@ -1,5 +1,6 @@
1
- import { A as isReviewing, C as translateTools, Dt as parseRelationEdit, E as authoredWorldOf, K as TRIGGERS_FILE_NAME, St as InvalidEditProblems, T as importTools, a as replaceAuthoredEntity, at as deleteWorldPrompt, b as triggerProblemsOf, ct as writeWorldPrompt, d as editWorldPlots, f as editWorldRelation, g as readWorldEditor, i as readAuthoredEntityDocument, it as PROSE_PROMPTS, n as createAuthoredEntity, ot as listWorldPrompts, r as deleteAuthoredEntity, st as readWorldPrompt, t as AUTHORED_ENTITY_KINDS, w as importHooks, x as loadWorldParts } from "./documents-B5XAdfo2.js";
2
- import { A as formatIssue, T as parsePlotsFile, a as packIds, d as packPath, f as readPack, g as SURFACE_NAMES, h as PACK_MEDIA_TYPES, l as isPackId, m as PACK_LIMITS, p as PACK_ACTIONS, z as shippedPromptsDirectory } from "./packs-BCGK9KZV.js";
1
+ import { A as authoredWorldOf, D as translateTools, Et as InvalidEditProblems, O as importHooks, P as isReviewing, X as TRIGGERS_FILE_NAME, a as replaceAuthoredEntity, b as triggerProblemsOf, ct as PROSE_PROMPTS, d as editWorldPlots, dt as readWorldPrompt, f as editWorldRelation, ft as writeWorldPrompt, g as readWorldEditor, i as readAuthoredEntityDocument, jt as parseRelationEdit, k as importTools, lt as deleteWorldPrompt, n as createAuthoredEntity, r as deleteAuthoredEntity, t as AUTHORED_ENTITY_KINDS, ut as listWorldPrompts, w as presetTools, x as loadWorldParts } from "./documents-Do4lz4SB.js";
2
+ import { a as packIds, d as packPath, f as readPack, g as SURFACE_NAMES, h as PACK_MEDIA_TYPES, l as isPackId, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-BYjrAen6.js";
3
+ import { S as shippedPromptsDirectory, c as parsePlotsFile, p as formatIssue } from "./language-DWVwi1R7.js";
3
4
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
5
  import { existsSync, lstatSync } from "node:fs";
5
6
  import { randomUUID } from "node:crypto";
@@ -615,6 +616,7 @@ const keyParameter = {
615
616
  description: "Stable entity key."
616
617
  };
617
618
  const AUTHORING_MUTATION_TOOLS = /* @__PURE__ */ new Set([
619
+ "import_preset",
618
620
  "create_world_element",
619
621
  "replace_world_element",
620
622
  "delete_world_element",
@@ -801,6 +803,14 @@ function authoredWorldWriteTools(reader) {
801
803
  async function authoringApproval(exec, next, reviewing = () => Promise.resolve(false)) {
802
804
  if (!AUTHORING_MUTATION_TOOLS.has(exec.name) || exec.agent === void 0 || authoredWorldOf(exec.agent.session.id) === void 0) return await next();
803
805
  const args = exec.arguments;
806
+ if (exec.name === "import_preset" && exec.agent !== void 0) return {
807
+ kind: "ask",
808
+ reason: "replace the authored world's narration and character-style prompts with ones made from the uploaded preset",
809
+ displayReason: {
810
+ en: "Replace the world's narration and character-style prompts with ones made from the uploaded preset?",
811
+ zh: "用上传的预设生成的提示词,替换世界的叙述与角色风格提示词?"
812
+ }
813
+ };
804
814
  const prompt = PROMPT_MUTATION_TOOLS.includes(exec.name);
805
815
  const pack = PACK_MUTATION_TOOLS.includes(exec.name);
806
816
  const importing = await reviewing(exec.agent.session.id);
@@ -968,6 +978,7 @@ function apply(ctx) {
968
978
  for (const tool of worldPromptTools(reader)) ctx.tools.register(tool);
969
979
  for (const tool of worldPackTools(reader)) ctx.tools.register(tool);
970
980
  for (const tool of importTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
981
+ for (const tool of presetTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
971
982
  for (const tool of translateTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
972
983
  importHooks(ctx, ctx.roleplayWorlds, prompting);
973
984
  const reviewing = async (chat) => {
@@ -0,0 +1,380 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { SessionId } from "@deepseek-ai/dsh-session";
3
+ import { ReasoningEffortId, createUserMessage } from "@deepseek-ai/dsh-llm";
4
+ import { appendDelegatedPolicyOverrides, applyChildComposition, captureDelegatedPolicyOverrides, childSessionMeta, resolveChildAgentOptions, resolveChildDepth } from "@deepseek-ai/dsh-subagent";
5
+ import { ToolArgsError, validateJsonSchemaValue } from "@deepseek-ai/dsh-tools";
6
+ //#region src/host/agents/budget.ts
7
+ /** 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. */
8
+ function tokensOf(characters, language) {
9
+ return Math.ceil(language.toLowerCase().startsWith("zh") ? characters * 1.5 : characters / 3);
10
+ }
11
+ /**
12
+ * The most tokens to let a request produce, for an answer estimated at some tokens: the estimate with room to spare (`headroom` times it, rounded up to ten). The room is
13
+ * for a model that thinks or says a little before it answers; what is far more than that is a model that does not stop, and is cut off instead of waited for.
14
+ */
15
+ function outputBudget(estimate, headroom) {
16
+ return Math.ceil(estimate * headroom / 10) * 10;
17
+ }
18
+ /** The estimate of an answer made of texts that each have a declared limit in characters. */
19
+ function estimateAnswer(limits, language) {
20
+ return limits.reduce((sum, limit) => sum + tokensOf(limit, language) + 8, 0);
21
+ }
22
+ //#endregion
23
+ //#region src/shared/activity.ts
24
+ /** Longest text kept for one call's arguments or outcome, and for the persona, the prompt and the result. */
25
+ const MAX_RUN_TEXT = 4e3;
26
+ const MAX_RUN_PROMPT = 24e3;
27
+ //#endregion
28
+ //#region src/host/agents/child.ts
29
+ /** The tool every child ends with: its arguments are the child's result. */
30
+ const SUBMIT_TOOL = "submit_result";
31
+ /** 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. */
32
+ 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.`;
33
+ /** Calls a child may make before it is given up; a child that keeps going is not converging. */
34
+ const DEFAULT_MAX_CALLS = 40;
35
+ /** A child that stops without a result is told to submit this many times before it is given up. */
36
+ const MAX_REMINDERS = 2;
37
+ /** A child that goes on calling tools this many times past its budget, in spite of being told to submit, is stopped: it would otherwise loop for as long as the model keeps at it. */
38
+ const OVERRUN = 5;
39
+ /** Steps a child gets to submit once its other tools are withdrawn: a model that keeps calling tools that are gone is stopped. */
40
+ const STEPS_AFTER_RETIRE = 3;
41
+ /** The same call, with the same arguments, that failed before is refused after this many repeats, and the child is stopped at twice that: the model is not reading the reasons it was given. */
42
+ const REPEATS_TOLD = 1;
43
+ const REPEATS_STOPPED = 4;
44
+ /** 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. */
45
+ const MAX_REFUSALS = 5;
46
+ /**
47
+ * What the settings of a chat say about how a kind of helper is asked: prose is free, the keepers of records exact. A helper whose answer has a declared size (its `estimate`, in tokens)
48
+ * is let produce that with room to spare, no more than the chat's ceiling for its kind.
49
+ */
50
+ function childSampling(settings, kind, estimate) {
51
+ const ceiling = kind === "characters" || kind === "suggestions" ? settings.sampling.shortMaxTokens : settings.sampling.maxTokens;
52
+ return {
53
+ temperature: settings.sampling[kind],
54
+ toolChoice: settings.sampling.tools,
55
+ maxTokens: estimate === void 0 ? ceiling : Math.min(ceiling, outputBudget(estimate, settings.sampling.headroom)),
56
+ priority: kind === "characters" || kind === "authoring" ? "foreground" : "background"
57
+ };
58
+ }
59
+ /** What a caller passes as `trace`: files each run of a kind of helper under a label in the store's record of activity, with its detail when the chat keeps it. */
60
+ function childTrace(store, kind, label, extra = {}, named) {
61
+ const model = (named ?? store.settings().models[kind]).trim();
62
+ return (run) => {
63
+ const keep = store.settings().diagnostics.keepRuns;
64
+ const id = keep ? randomUUID() : void 0;
65
+ store.recordActivity({
66
+ at: Date.now(),
67
+ label,
68
+ model,
69
+ ms: run.ms,
70
+ calls: run.calls,
71
+ ...run.error === void 0 ? {} : { error: run.error.slice(0, 300) },
72
+ ...id === void 0 ? {} : { run: id }
73
+ }, keep ? {
74
+ ...run.detail,
75
+ ...extra
76
+ } : void 0);
77
+ };
78
+ }
79
+ /** The `model` the settings give a kind of helper, to spread into its task; nothing when it runs on the chat's own model. */
80
+ function childModel(settings, kind, override) {
81
+ const named = (override ?? settings.models[kind]).trim();
82
+ if (named === "") return {};
83
+ const slash = named.indexOf("/");
84
+ return { model: {
85
+ provider: named.slice(0, slash),
86
+ model: named.slice(slash + 1)
87
+ } };
88
+ }
89
+ const samplings = /* @__PURE__ */ new Map();
90
+ /** The controls set for a running child, by its session id. */
91
+ const childSamplingOf = (sessionId) => samplings.get(sessionId);
92
+ /**
93
+ * Run a child agent to its result. Unlike a sub-agent started through `ctx.subagents`, it can
94
+ * have tools of its own, so several can run side by side with different tools and different
95
+ * results from the same tool.
96
+ *
97
+ * This is the one place the bundle builds an agent below DSH's sub-agent API: it uses the
98
+ * composition helpers DSH exports for sub-agent providers (`applyChildComposition`,
99
+ * `childSessionMeta`, ...). They are not a stable interface; `docs/dsh-api-usage.md` says why
100
+ * this is accepted, which DSH version it is built against, and what to do when DSH changes.
101
+ * @throws {Error} when the child is cancelled, stops without a result, or exceeds its calls.
102
+ */
103
+ function childOptions(task) {
104
+ const maxTokens = task.maxTokens ?? task.sampling?.maxTokens;
105
+ const options = {
106
+ ...task.reasoningEffort === void 0 || task.reasoningEffort === "" ? {} : { reasoningEffort: ReasoningEffortId(task.reasoningEffort) },
107
+ ...maxTokens === void 0 ? {} : { maxTokens },
108
+ ...task.model === void 0 ? {} : {
109
+ provider: task.model.provider,
110
+ model: task.model.model
111
+ }
112
+ };
113
+ return Object.keys(options).length === 0 ? void 0 : options;
114
+ }
115
+ /** The schema an answer is checked against: the one the model was given, without requiring what it was only asked for ({@link ChildTask.unenforced}). */
116
+ function enforcedSchema(task) {
117
+ const skipped = task.unenforced ?? [];
118
+ return skipped.length === 0 || task.result.required === void 0 ? task.result : {
119
+ ...task.result,
120
+ required: task.result.required.filter((name) => !skipped.includes(name))
121
+ };
122
+ }
123
+ /** 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. */
124
+ const isUnfinishedCall = (error) => error instanceof Error && /parse tool call arguments|unfinished tool call/i.test(error.message);
125
+ async function runChild(task) {
126
+ for (let attempt = 1;; attempt += 1) {
127
+ const began = Date.now();
128
+ const stats = {
129
+ calls: 0,
130
+ record: []
131
+ };
132
+ const detail = () => ({
133
+ persona: task.persona.slice(0, MAX_RUN_PROMPT),
134
+ prompt: task.prompt.slice(0, MAX_RUN_PROMPT),
135
+ calls: stats.record,
136
+ ...stats.result === void 0 ? {} : { result: stats.result }
137
+ });
138
+ try {
139
+ const result = await execute(task, stats);
140
+ task.trace?.({
141
+ ms: Date.now() - began,
142
+ calls: stats.calls,
143
+ detail: detail()
144
+ });
145
+ return result;
146
+ } catch (error) {
147
+ task.trace?.({
148
+ ms: Date.now() - began,
149
+ calls: stats.calls,
150
+ error: error instanceof Error ? error.message : String(error),
151
+ detail: detail()
152
+ });
153
+ if (attempt >= 2 || task.signal.aborted || !isUnfinishedCall(error)) throw error;
154
+ }
155
+ }
156
+ }
157
+ /**
158
+ * The thinking level a child may be given on its model: the one asked for when the model offers it, none when it does not (a model chosen for a
159
+ * helper has its own levels, and one that lacks the level the chat asks for would refuse the request).
160
+ */
161
+ async function supportedEffort(task) {
162
+ const level = task.reasoningEffort;
163
+ if (level === void 0 || level === "" || task.model === void 0) return level;
164
+ try {
165
+ return (await task.parent.ctx.llm.resolveModelInfo(task.model.provider, task.model.model, task.signal)).reasoning?.efforts.some((effort) => effort.id === level) === true ? level : void 0;
166
+ } catch {
167
+ return level;
168
+ }
169
+ }
170
+ const cut = (value, limit = MAX_RUN_TEXT) => {
171
+ const text = typeof value === "string" ? value : JSON.stringify(value) ?? "";
172
+ return text.length > limit ? `${text.slice(0, limit)} ... (${text.length - limit} more characters)` : text;
173
+ };
174
+ async function execute(task, stats) {
175
+ const { parent, signal } = task;
176
+ const reasoningEffort = await supportedEffort(task);
177
+ let submitted;
178
+ let reminders = 0;
179
+ let stopped;
180
+ let retire;
181
+ let stepsAfterRetire = -1;
182
+ let overran = false;
183
+ let refusals = 0;
184
+ let lastRefusal = "";
185
+ let previous;
186
+ const budget = task.maxCalls ?? DEFAULT_MAX_CALLS;
187
+ const counted = (tool) => ({
188
+ ...tool,
189
+ execute: async (args, exec) => {
190
+ stats.calls += 1;
191
+ const note = (outcome, failed) => {
192
+ if (stats.record.length < 60) stats.record.push({
193
+ tool: tool.name,
194
+ args: cut(args),
195
+ outcome: cut(outcome),
196
+ failed
197
+ });
198
+ };
199
+ if (stats.calls > budget + OVERRUN) {
200
+ overran = true;
201
+ stopped?.();
202
+ }
203
+ if (stats.calls > budget) {
204
+ const message = `you have made ${budget} calls: submit your result now and say what is still missing`;
205
+ note(message, true);
206
+ throw new Error(message);
207
+ }
208
+ const signature = JSON.stringify(args);
209
+ const repeats = previous?.name === tool.name && previous.args === signature && previous.failed ? previous.repeats + 1 : 0;
210
+ if (repeats >= REPEATS_STOPPED) {
211
+ overran = true;
212
+ stopped?.();
213
+ }
214
+ if (repeats >= REPEATS_TOLD) {
215
+ previous = {
216
+ name: tool.name,
217
+ args: signature,
218
+ failed: true,
219
+ repeats
220
+ };
221
+ const message = "this is exactly the call that just failed, with the same arguments, so it fails for the same reasons: read the reasons the last result gave and change the arguments to fix every one of them";
222
+ note(message, true);
223
+ throw new Error(message);
224
+ }
225
+ previous = {
226
+ name: tool.name,
227
+ args: signature,
228
+ failed: false,
229
+ repeats
230
+ };
231
+ try {
232
+ const outcome = await tool.execute(args, exec);
233
+ note(outcome, false);
234
+ return outcome;
235
+ } catch (error) {
236
+ if (previous !== void 0) previous.failed = true;
237
+ note(error instanceof Error ? error.message : String(error), true);
238
+ throw error;
239
+ } finally {
240
+ if (stats.calls >= budget) retire?.();
241
+ }
242
+ }
243
+ });
244
+ const submit = {
245
+ name: SUBMIT_TOOL,
246
+ description: "Submit your final result. Call it exactly once, when you are done; the arguments are the result.",
247
+ parameters: task.result,
248
+ output: {
249
+ schema: {
250
+ type: "object",
251
+ properties: { recorded: {
252
+ type: "boolean",
253
+ const: true
254
+ } },
255
+ required: ["recorded"],
256
+ additionalProperties: false
257
+ },
258
+ render: () => [{
259
+ type: "text",
260
+ text: "Result recorded."
261
+ }]
262
+ },
263
+ execute(args, exec) {
264
+ const violations = validateJsonSchemaValue(enforcedSchema(task), args);
265
+ if (violations.length > 0) throw new ToolArgsError(violations);
266
+ const refusal = task.beforeSubmit?.(args);
267
+ if (refusal !== void 0) {
268
+ if (stats.record.length < 60) stats.record.push({
269
+ tool: SUBMIT_TOOL,
270
+ args: cut(args),
271
+ outcome: cut(refusal),
272
+ failed: true
273
+ });
274
+ refusals += 1;
275
+ lastRefusal = refusal;
276
+ if (refusals >= MAX_REFUSALS) {
277
+ overran = true;
278
+ stopped?.();
279
+ }
280
+ throw new Error(refusal);
281
+ }
282
+ submitted = { value: args };
283
+ stats.result = cut(args, MAX_RUN_PROMPT);
284
+ if (stats.record.length < 60) stats.record.push({
285
+ tool: SUBMIT_TOOL,
286
+ args: cut(args),
287
+ outcome: "Result recorded.",
288
+ failed: false
289
+ });
290
+ exec.concludeTurn();
291
+ return Promise.resolve({ recorded: true });
292
+ }
293
+ };
294
+ const depth = resolveChildDepth(parent, void 0);
295
+ const inherited = captureDelegatedPolicyOverrides(parent);
296
+ const sessionId = SessionId(randomUUID());
297
+ if (task.sampling !== void 0) samplings.set(sessionId, task.sampling);
298
+ const handle = await parent.ctx.agents.create({
299
+ sessionId,
300
+ parentAgent: parent,
301
+ meta: childSessionMeta(parent, depth, false),
302
+ agentOptions: resolveChildAgentOptions(parent, childOptions({
303
+ ...task,
304
+ ...reasoningEffort === void 0 ? { reasoningEffort: "" } : { reasoningEffort }
305
+ }), depth),
306
+ signal,
307
+ setup: (childCtx, child) => {
308
+ appendDelegatedPolicyOverrides(child.session, inherited);
309
+ applyChildComposition(childCtx, parent, {
310
+ persona: `${task.persona}\n\n${SUBMIT_RULE}`,
311
+ toolFilter: { allow: [...task.external ?? []] }
312
+ });
313
+ const registered = (task.tools ?? []).map((tool) => childCtx.tools.register(counted(tool)));
314
+ retire = () => {
315
+ for (const dispose of registered) dispose();
316
+ if (stepsAfterRetire < 0) stepsAfterRetire = 0;
317
+ };
318
+ childCtx.on("agent/pre-step", async (_payload, next) => {
319
+ const decision = await next();
320
+ if (stepsAfterRetire < 0) return decision;
321
+ stepsAfterRetire += 1;
322
+ if (stepsAfterRetire > STEPS_AFTER_RETIRE && submitted === void 0) {
323
+ overran = true;
324
+ stopped?.();
325
+ }
326
+ return decision;
327
+ });
328
+ childCtx.tools.register(submit);
329
+ childCtx.on("agent/turn-stopping", () => {
330
+ if (submitted !== void 0 || reminders >= MAX_REMINDERS) return;
331
+ reminders += 1;
332
+ child.steer(createUserMessage({
333
+ content: [{
334
+ type: "text",
335
+ text: `You have not finished: call ${SUBMIT_TOOL} with your result, as the tool lists it.`
336
+ }],
337
+ source: { kind: "roleplay" }
338
+ }));
339
+ });
340
+ childCtx.tools.guard((exec) => submitted === void 0 ? void 0 : `the result is already submitted, so \`${exec.name}\` is not run`);
341
+ }
342
+ });
343
+ stopped = () => {
344
+ handle.agent.cancel({ kind: "parent" });
345
+ };
346
+ const onAbort = () => {
347
+ handle.agent.cancel({ kind: "parent" });
348
+ };
349
+ signal.addEventListener("abort", onAbort, { once: true });
350
+ try {
351
+ handle.agent.followup(createUserMessage({
352
+ content: [{
353
+ type: "text",
354
+ text: task.prompt
355
+ }, ...(task.images ?? []).map((attachment) => ({
356
+ type: "image",
357
+ attachment
358
+ }))],
359
+ source: { kind: "user" }
360
+ }));
361
+ await handle.agent.whenIdle();
362
+ } finally {
363
+ signal.removeEventListener("abort", onAbort);
364
+ samplings.delete(sessionId);
365
+ await handle.dispose();
366
+ }
367
+ if (signal.aborted) throw new Error("cancelled");
368
+ 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`);
369
+ if (submitted === void 0) {
370
+ const ended = handle.agent.session.snapshotEvents().findLast((event) => event.type === "turn/end");
371
+ const reason = ended?.type === "turn/end" ? ended.data.reason : void 0;
372
+ if (reason?.kind === "error") throw new Error(`the agent failed: ${reason.error.message}`);
373
+ throw new Error(`the agent stopped without submitting a result (${stats.calls} call(s))`);
374
+ }
375
+ return submitted.value;
376
+ }
377
+ //#endregion
378
+ export { runChild as a, childTrace as i, childSampling as n, estimateAnswer as o, childSamplingOf as r, tokensOf as s, childModel as t };
379
+
380
+ //# sourceMappingURL=child-lPncV1ps.js.map