@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.
@@ -1,4 +1,4 @@
1
- import { S as mapLimit, _ as readImageFileMetadata, c as LIBRARY_FOLDER, g as mediaTypeOf, v as sidecarOf, y as writeImageFileMetadata } from "./generator-BzeepLd2.js";
1
+ import { S as mapLimit, _ as readImageFileMetadata, c as LIBRARY_FOLDER, g as mediaTypeOf, v as sidecarOf, y as writeImageFileMetadata } from "./generator-B6FxlKOV.js";
2
2
  import { join, sep } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { lstat, mkdir, readFile, readdir, realpath, rename, stat, writeFile } from "node:fs/promises";
@@ -192,4 +192,4 @@ async function updateImage(sessionFolder, path, update) {
192
192
  //#endregion
193
193
  export { updateImage as i, galleryFile as n, listGallery as r, describeGalleryImage as t };
194
194
 
195
- //# sourceMappingURL=gallery-DS5-qH9F.js.map
195
+ //# sourceMappingURL=gallery-CtFDL22W.js.map
@@ -1,383 +1,7 @@
1
1
  import { dirname, extname, join } from "node:path";
2
2
  import { existsSync } from "node:fs";
3
3
  import { randomUUID } from "node:crypto";
4
- import { SessionId } from "@deepseek-ai/dsh-session";
5
- import { ReasoningEffortId, createUserMessage } from "@deepseek-ai/dsh-llm";
6
- import { appendDelegatedPolicyOverrides, applyChildComposition, captureDelegatedPolicyOverrides, childSessionMeta, resolveChildAgentOptions, resolveChildDepth } from "@deepseek-ai/dsh-subagent";
7
- import { ToolArgsError, validateJsonSchemaValue } from "@deepseek-ai/dsh-tools";
8
4
  import { copyFile, link, mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
9
- //#region src/host/agents/budget.ts
10
- /** 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. */
11
- function tokensOf(characters, language) {
12
- return Math.ceil(language.toLowerCase().startsWith("zh") ? characters * 1.5 : characters / 3);
13
- }
14
- /**
15
- * 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
16
- * 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.
17
- */
18
- function outputBudget(estimate, headroom) {
19
- return Math.ceil(estimate * headroom / 10) * 10;
20
- }
21
- /** The estimate of an answer made of texts that each have a declared limit in characters. */
22
- function estimateAnswer(limits, language) {
23
- return limits.reduce((sum, limit) => sum + tokensOf(limit, language) + 8, 0);
24
- }
25
- //#endregion
26
- //#region src/shared/activity.ts
27
- /** Longest text kept for one call's arguments or outcome, and for the persona, the prompt and the result. */
28
- const MAX_RUN_TEXT = 4e3;
29
- const MAX_RUN_PROMPT = 24e3;
30
- //#endregion
31
- //#region src/host/agents/child.ts
32
- /** The tool every child ends with: its arguments are the child's result. */
33
- const SUBMIT_TOOL = "submit_result";
34
- /** 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. */
35
- 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.`;
36
- /** Calls a child may make before it is given up; a child that keeps going is not converging. */
37
- const DEFAULT_MAX_CALLS = 40;
38
- /** A child that stops without a result is told to submit this many times before it is given up. */
39
- const MAX_REMINDERS = 2;
40
- /** 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. */
41
- const OVERRUN = 5;
42
- /** Steps a child gets to submit once its other tools are withdrawn: a model that keeps calling tools that are gone is stopped. */
43
- const STEPS_AFTER_RETIRE = 3;
44
- /** 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. */
45
- const REPEATS_TOLD = 1;
46
- const REPEATS_STOPPED = 4;
47
- /** 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. */
48
- const MAX_REFUSALS = 5;
49
- /**
50
- * 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)
51
- * is let produce that with room to spare, no more than the chat's ceiling for its kind.
52
- */
53
- function childSampling(settings, kind, estimate) {
54
- const ceiling = kind === "characters" || kind === "suggestions" ? settings.sampling.shortMaxTokens : settings.sampling.maxTokens;
55
- return {
56
- temperature: settings.sampling[kind],
57
- toolChoice: settings.sampling.tools,
58
- maxTokens: estimate === void 0 ? ceiling : Math.min(ceiling, outputBudget(estimate, settings.sampling.headroom)),
59
- priority: kind === "characters" || kind === "authoring" ? "foreground" : "background"
60
- };
61
- }
62
- /** 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. */
63
- function childTrace(store, kind, label, extra = {}, named) {
64
- const model = (named ?? store.settings().models[kind]).trim();
65
- return (run) => {
66
- const keep = store.settings().diagnostics.keepRuns;
67
- const id = keep ? randomUUID() : void 0;
68
- store.recordActivity({
69
- at: Date.now(),
70
- label,
71
- model,
72
- ms: run.ms,
73
- calls: run.calls,
74
- ...run.error === void 0 ? {} : { error: run.error.slice(0, 300) },
75
- ...id === void 0 ? {} : { run: id }
76
- }, keep ? {
77
- ...run.detail,
78
- ...extra
79
- } : void 0);
80
- };
81
- }
82
- /** The `model` the settings give a kind of helper, to spread into its task; nothing when it runs on the chat's own model. */
83
- function childModel(settings, kind, override) {
84
- const named = (override ?? settings.models[kind]).trim();
85
- if (named === "") return {};
86
- const slash = named.indexOf("/");
87
- return { model: {
88
- provider: named.slice(0, slash),
89
- model: named.slice(slash + 1)
90
- } };
91
- }
92
- const samplings = /* @__PURE__ */ new Map();
93
- /** The controls set for a running child, by its session id. */
94
- const childSamplingOf = (sessionId) => samplings.get(sessionId);
95
- /**
96
- * Run a child agent to its result. Unlike a sub-agent started through `ctx.subagents`, it can
97
- * have tools of its own, so several can run side by side with different tools and different
98
- * results from the same tool.
99
- *
100
- * This is the one place the bundle builds an agent below DSH's sub-agent API: it uses the
101
- * composition helpers DSH exports for sub-agent providers (`applyChildComposition`,
102
- * `childSessionMeta`, ...). They are not a stable interface; `docs/dsh-api-usage.md` says why
103
- * this is accepted, which DSH version it is built against, and what to do when DSH changes.
104
- * @throws {Error} when the child is cancelled, stops without a result, or exceeds its calls.
105
- */
106
- function childOptions(task) {
107
- const maxTokens = task.maxTokens ?? task.sampling?.maxTokens;
108
- const options = {
109
- ...task.reasoningEffort === void 0 || task.reasoningEffort === "" ? {} : { reasoningEffort: ReasoningEffortId(task.reasoningEffort) },
110
- ...maxTokens === void 0 ? {} : { maxTokens },
111
- ...task.model === void 0 ? {} : {
112
- provider: task.model.provider,
113
- model: task.model.model
114
- }
115
- };
116
- return Object.keys(options).length === 0 ? void 0 : options;
117
- }
118
- /** The schema an answer is checked against: the one the model was given, without requiring what it was only asked for ({@link ChildTask.unenforced}). */
119
- function enforcedSchema(task) {
120
- const skipped = task.unenforced ?? [];
121
- return skipped.length === 0 || task.result.required === void 0 ? task.result : {
122
- ...task.result,
123
- required: task.result.required.filter((name) => !skipped.includes(name))
124
- };
125
- }
126
- /** 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. */
127
- const isUnfinishedCall = (error) => error instanceof Error && /parse tool call arguments|unfinished tool call/i.test(error.message);
128
- async function runChild(task) {
129
- for (let attempt = 1;; attempt += 1) {
130
- const began = Date.now();
131
- const stats = {
132
- calls: 0,
133
- record: []
134
- };
135
- const detail = () => ({
136
- persona: task.persona.slice(0, MAX_RUN_PROMPT),
137
- prompt: task.prompt.slice(0, MAX_RUN_PROMPT),
138
- calls: stats.record,
139
- ...stats.result === void 0 ? {} : { result: stats.result }
140
- });
141
- try {
142
- const result = await execute(task, stats);
143
- task.trace?.({
144
- ms: Date.now() - began,
145
- calls: stats.calls,
146
- detail: detail()
147
- });
148
- return result;
149
- } catch (error) {
150
- task.trace?.({
151
- ms: Date.now() - began,
152
- calls: stats.calls,
153
- error: error instanceof Error ? error.message : String(error),
154
- detail: detail()
155
- });
156
- if (attempt >= 2 || task.signal.aborted || !isUnfinishedCall(error)) throw error;
157
- }
158
- }
159
- }
160
- /**
161
- * 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
162
- * helper has its own levels, and one that lacks the level the chat asks for would refuse the request).
163
- */
164
- async function supportedEffort(task) {
165
- const level = task.reasoningEffort;
166
- if (level === void 0 || level === "" || task.model === void 0) return level;
167
- try {
168
- 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;
169
- } catch {
170
- return level;
171
- }
172
- }
173
- const cut = (value, limit = MAX_RUN_TEXT) => {
174
- const text = typeof value === "string" ? value : JSON.stringify(value) ?? "";
175
- return text.length > limit ? `${text.slice(0, limit)} ... (${text.length - limit} more characters)` : text;
176
- };
177
- async function execute(task, stats) {
178
- const { parent, signal } = task;
179
- const reasoningEffort = await supportedEffort(task);
180
- let submitted;
181
- let reminders = 0;
182
- let stopped;
183
- let retire;
184
- let stepsAfterRetire = -1;
185
- let overran = false;
186
- let refusals = 0;
187
- let lastRefusal = "";
188
- let previous;
189
- const budget = task.maxCalls ?? DEFAULT_MAX_CALLS;
190
- const counted = (tool) => ({
191
- ...tool,
192
- execute: async (args, exec) => {
193
- stats.calls += 1;
194
- const note = (outcome, failed) => {
195
- if (stats.record.length < 60) stats.record.push({
196
- tool: tool.name,
197
- args: cut(args),
198
- outcome: cut(outcome),
199
- failed
200
- });
201
- };
202
- if (stats.calls > budget + OVERRUN) {
203
- overran = true;
204
- stopped?.();
205
- }
206
- if (stats.calls > budget) {
207
- const message = `you have made ${budget} calls: submit your result now and say what is still missing`;
208
- note(message, true);
209
- throw new Error(message);
210
- }
211
- const signature = JSON.stringify(args);
212
- const repeats = previous?.name === tool.name && previous.args === signature && previous.failed ? previous.repeats + 1 : 0;
213
- if (repeats >= REPEATS_STOPPED) {
214
- overran = true;
215
- stopped?.();
216
- }
217
- if (repeats >= REPEATS_TOLD) {
218
- previous = {
219
- name: tool.name,
220
- args: signature,
221
- failed: true,
222
- repeats
223
- };
224
- 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";
225
- note(message, true);
226
- throw new Error(message);
227
- }
228
- previous = {
229
- name: tool.name,
230
- args: signature,
231
- failed: false,
232
- repeats
233
- };
234
- try {
235
- const outcome = await tool.execute(args, exec);
236
- note(outcome, false);
237
- return outcome;
238
- } catch (error) {
239
- if (previous !== void 0) previous.failed = true;
240
- note(error instanceof Error ? error.message : String(error), true);
241
- throw error;
242
- } finally {
243
- if (stats.calls >= budget) retire?.();
244
- }
245
- }
246
- });
247
- const submit = {
248
- name: SUBMIT_TOOL,
249
- description: "Submit your final result. Call it exactly once, when you are done; the arguments are the result.",
250
- parameters: task.result,
251
- output: {
252
- schema: {
253
- type: "object",
254
- properties: { recorded: {
255
- type: "boolean",
256
- const: true
257
- } },
258
- required: ["recorded"],
259
- additionalProperties: false
260
- },
261
- render: () => [{
262
- type: "text",
263
- text: "Result recorded."
264
- }]
265
- },
266
- execute(args, exec) {
267
- const violations = validateJsonSchemaValue(enforcedSchema(task), args);
268
- if (violations.length > 0) throw new ToolArgsError(violations);
269
- const refusal = task.beforeSubmit?.(args);
270
- if (refusal !== void 0) {
271
- if (stats.record.length < 60) stats.record.push({
272
- tool: SUBMIT_TOOL,
273
- args: cut(args),
274
- outcome: cut(refusal),
275
- failed: true
276
- });
277
- refusals += 1;
278
- lastRefusal = refusal;
279
- if (refusals >= MAX_REFUSALS) {
280
- overran = true;
281
- stopped?.();
282
- }
283
- throw new Error(refusal);
284
- }
285
- submitted = { value: args };
286
- stats.result = cut(args, MAX_RUN_PROMPT);
287
- if (stats.record.length < 60) stats.record.push({
288
- tool: SUBMIT_TOOL,
289
- args: cut(args),
290
- outcome: "Result recorded.",
291
- failed: false
292
- });
293
- exec.concludeTurn();
294
- return Promise.resolve({ recorded: true });
295
- }
296
- };
297
- const depth = resolveChildDepth(parent, void 0);
298
- const inherited = captureDelegatedPolicyOverrides(parent);
299
- const sessionId = SessionId(randomUUID());
300
- if (task.sampling !== void 0) samplings.set(sessionId, task.sampling);
301
- const handle = await parent.ctx.agents.create({
302
- sessionId,
303
- parentAgent: parent,
304
- meta: childSessionMeta(parent, depth, false),
305
- agentOptions: resolveChildAgentOptions(parent, childOptions({
306
- ...task,
307
- ...reasoningEffort === void 0 ? { reasoningEffort: "" } : { reasoningEffort }
308
- }), depth),
309
- signal,
310
- setup: (childCtx, child) => {
311
- appendDelegatedPolicyOverrides(child.session, inherited);
312
- applyChildComposition(childCtx, parent, {
313
- persona: `${task.persona}\n\n${SUBMIT_RULE}`,
314
- toolFilter: { allow: [...task.external ?? []] }
315
- });
316
- const registered = (task.tools ?? []).map((tool) => childCtx.tools.register(counted(tool)));
317
- retire = () => {
318
- for (const dispose of registered) dispose();
319
- if (stepsAfterRetire < 0) stepsAfterRetire = 0;
320
- };
321
- childCtx.on("agent/pre-step", async (_payload, next) => {
322
- const decision = await next();
323
- if (stepsAfterRetire < 0) return decision;
324
- stepsAfterRetire += 1;
325
- if (stepsAfterRetire > STEPS_AFTER_RETIRE && submitted === void 0) {
326
- overran = true;
327
- stopped?.();
328
- }
329
- return decision;
330
- });
331
- childCtx.tools.register(submit);
332
- childCtx.on("agent/turn-stopping", () => {
333
- if (submitted !== void 0 || reminders >= MAX_REMINDERS) return;
334
- reminders += 1;
335
- child.steer(createUserMessage({
336
- content: [{
337
- type: "text",
338
- text: `You have not finished: call ${SUBMIT_TOOL} with your result, as the tool lists it.`
339
- }],
340
- source: { kind: "roleplay" }
341
- }));
342
- });
343
- childCtx.tools.guard((exec) => submitted === void 0 ? void 0 : `the result is already submitted, so \`${exec.name}\` is not run`);
344
- }
345
- });
346
- stopped = () => {
347
- handle.agent.cancel({ kind: "parent" });
348
- };
349
- const onAbort = () => {
350
- handle.agent.cancel({ kind: "parent" });
351
- };
352
- signal.addEventListener("abort", onAbort, { once: true });
353
- try {
354
- handle.agent.followup(createUserMessage({
355
- content: [{
356
- type: "text",
357
- text: task.prompt
358
- }, ...(task.images ?? []).map((attachment) => ({
359
- type: "image",
360
- attachment
361
- }))],
362
- source: { kind: "user" }
363
- }));
364
- await handle.agent.whenIdle();
365
- } finally {
366
- signal.removeEventListener("abort", onAbort);
367
- samplings.delete(sessionId);
368
- await handle.dispose();
369
- }
370
- if (signal.aborted) throw new Error("cancelled");
371
- 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`);
372
- if (submitted === void 0) {
373
- const ended = handle.agent.session.snapshotEvents().findLast((event) => event.type === "turn/end");
374
- const reason = ended?.type === "turn/end" ? ended.data.reason : void 0;
375
- if (reason?.kind === "error") throw new Error(`the agent failed: ${reason.error.message}`);
376
- throw new Error(`the agent stopped without submitting a result (${stats.calls} call(s))`);
377
- }
378
- return submitted.value;
379
- }
380
- //#endregion
381
5
  //#region src/host/import/run.ts
382
6
  /** Runs `work` on every item, at most `limit` at a time, and returns the results in the order of the items. */
383
7
  async function mapLimit(items, limit, work) {
@@ -846,6 +470,6 @@ async function generateTransientImage(service, request) {
846
470
  return path;
847
471
  }
848
472
  //#endregion
849
- export { runChild as A, norm as C, childSampling as D, childModel as E, tokensOf as M, childSamplingOf as O, mapLimit as S, uniqueKey as T, readImageFileMetadata as _, uploadReferenceImage as a, readPngMetadata as b, LIBRARY_FOLDER as c, nextSceneSerial as d, readImageMetadata as f, mediaTypeOf as g, MEDIA_TYPES as h, transientPrompt as i, estimateAnswer as j, childTrace as k, entityImageDirectory as l, sceneImagePath as m, generateTransientImage as n, addToLibrary as o, referenceImagePath as p, referencePrompt as r, imageExtensionOf as s, generateReferenceImage as t, inheritImages as u, sidecarOf as v, slug as w, withPngMetadata as x, writeImageFileMetadata as y };
473
+ export { norm as C, mapLimit as S, uniqueKey as T, readImageFileMetadata as _, uploadReferenceImage as a, readPngMetadata as b, LIBRARY_FOLDER as c, nextSceneSerial as d, readImageMetadata as f, mediaTypeOf as g, MEDIA_TYPES as h, transientPrompt as i, entityImageDirectory as l, sceneImagePath as m, generateTransientImage as n, addToLibrary as o, referenceImagePath as p, referencePrompt as r, imageExtensionOf as s, generateReferenceImage as t, inheritImages as u, sidecarOf as v, slug as w, withPngMetadata as x, writeImageFileMetadata as y };
850
474
 
851
- //# sourceMappingURL=generator-BzeepLd2.js.map
475
+ //# sourceMappingURL=generator-B6FxlKOV.js.map