@dsh-agentic-roleplay/core 0.8.1 → 0.9.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 (51) hide show
  1. package/lib/{access-DtOxFKBK.js → access-CfQWbNZP.js} +4 -7
  2. package/lib/{authoring-tools-DNnx0Nts.js → authoring-tools-CdHlvx32.js} +2125 -152
  3. package/lib/authoring.js +143 -47
  4. package/lib/{child-D6mpkkCE.js → child-lYYeOwl2.js} +28 -51
  5. package/lib/client.js +611 -774
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +8 -13
  8. package/lib/{doctor-chat-ByDfCMeo.js → doctor-chat-hL1a61hp.js} +2 -3
  9. package/lib/doctor.js +6 -8
  10. package/lib/{gallery-D9nG3C78.js → gallery-BKh7eu80.js} +3 -4
  11. package/lib/{generator-r1Czm7oi.js → generator-DdZ1-sgv.js} +3 -4
  12. package/lib/helper.js +2 -3
  13. package/lib/{hooks-BQCzgggH.js → hooks-CcQj_dJo.js} +69 -97
  14. package/lib/images.js +4 -4
  15. package/lib/index.js +195 -265
  16. package/lib/{library-zI-2tG7h.js → library-QFL6Z_Nr.js} +9 -15
  17. package/lib/{lorebook-author-tools-ywaYicwd.js → lorebook-author-tools-DWBnYo1E.js} +10 -13
  18. package/lib/lorebook-authoring.js +5 -6
  19. package/lib/{narration-CnBlVure.js → narration-CjB_KwwY.js} +9 -15
  20. package/lib/orchestration.js +53 -64
  21. package/lib/{pack-jail-5EJ-WYyW.js → pack-jail-BMy6NcCY.js} +81 -788
  22. package/lib/{packs-Cv8hanXJ.js → packs-BREPSfHy.js} +6 -10
  23. package/lib/{presenter-agent-BSaMSd3G.js → presenter-agent-B49-_iUm.js} +12 -18
  24. package/lib/{preset-CWI3-0r1.js → preset-BqgY1Tz4.js} +5 -6
  25. package/lib/{preset-author-tools-BrJYa2cr.js → preset-author-tools-BB_Dcv2o.js} +12 -14
  26. package/lib/preset-authoring.js +6 -7
  27. package/lib/{presets-MwOSMMyu.js → presets-Bwnrx7p0.js} +69 -63
  28. package/lib/{reflection-zSaMsjKj.js → reflection-CUWG-6Qg.js} +19 -30
  29. package/lib/{text-BzudpQLS.js → text-CbGQhK1-.js} +9 -10
  30. package/lib/{turn-guard-Cv8pfHEA.js → turn-guard-Bb8Ew-1z.js} +6 -11
  31. package/package.json +29 -29
  32. package/prompts/en/checks/decide-sheet.md +1 -0
  33. package/prompts/en/checks/fidelity.md +7 -0
  34. package/prompts/en/checks/gaps.md +4 -0
  35. package/prompts/en/checks/notice.md +3 -0
  36. package/prompts/en/import/casting.md +1 -1
  37. package/prompts/en/import/character.md +1 -0
  38. package/prompts/en/import/finish-draft.md +1 -1
  39. package/prompts/en/import/finish-ok.md +3 -1
  40. package/prompts/en/import/notice-repair.md +2 -2
  41. package/prompts/en/import/repair-again.md +2 -2
  42. package/prompts/zh/checks/decide-sheet.md +1 -0
  43. package/prompts/zh/checks/fidelity.md +7 -0
  44. package/prompts/zh/checks/gaps.md +4 -0
  45. package/prompts/zh/checks/notice.md +3 -0
  46. package/prompts/zh/import/casting.md +1 -1
  47. package/prompts/zh/import/character.md +1 -0
  48. package/prompts/zh/import/finish-draft.md +1 -1
  49. package/prompts/zh/import/finish-ok.md +3 -1
  50. package/prompts/zh/import/notice-repair.md +2 -2
  51. package/prompts/zh/import/repair-again.md +2 -2
package/lib/authoring.js CHANGED
@@ -1,24 +1,24 @@
1
- import "./access-DtOxFKBK.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";
1
+ import { A as cardTools, C as worldFieldChanges, E as loadCardEvidence, F as editsSince, M as readSource, N as CHECK_COMMANDS, S as matchPieces, T as loadWorldParts, _ as runChecks, a as importHooks, b as cardChanges, g as CHECKS, h as presentReport, ht as checkWorld, i as contextOf, in as authoredWorldOf, j as entitiesByPiece, l as isReviewing, m as checkImported, n as limitAuthoringAgents, o as importTools, tt as parseWorldInfoEdit, v as editWorldInfo, x as diffText, y as readWorldInfo } from "./authoring-tools-CdHlvx32.js";
2
+ import { t as guardAuthoringTurns } from "./turn-guard-Bb8Ew-1z.js";
3
+ import { C as readWorldEditor, L as presetTools, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, U as finishUpdate, W as pendingUpdate, _ 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, z as translateTools } from "./pack-jail-BMy6NcCY.js";
4
+ import { Dt as InvalidEditProblems, G as listWorldPrompts, K as readWorldPrompt, Mt as parseRelationEdit, Q as IMPORT_FOLDER, U as PROSE_PROMPTS, W as deleteWorldPrompt, ct as parseAuthoringCommand, q as writeWorldPrompt } from "./presets-Bwnrx7p0.js";
5
+ import { i as translator, r as languageOf } from "./text-CbGQhK1-.js";
6
+ import { J as formatIssue, V as parsePlotsFile, at as shippedPromptsDirectory } from "./hooks-CcQj_dJo.js";
7
+ import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-BREPSfHy.js";
8
+ import "./access-CfQWbNZP.js";
9
9
  import { join, relative } from "node:path";
10
10
  import { readFile, readdir } from "node:fs/promises";
11
11
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
12
12
  import { defineTool } from "@deepseek-ai/dsh-tools";
13
13
  import { isDeepStrictEqual } from "node:util";
14
- //#region src/host/authoring/read-tools.ts
15
- const output$4 = (value) => [{
14
+ // src/host/authoring/read-tools.ts
15
+ const output$5 = (value) => [{
16
16
  type: "text",
17
17
  text: JSON.stringify(value, null, 2)
18
18
  }];
19
19
  const jsonOutput$3 = {
20
20
  schema: { type: "json" },
21
- render: (_args, value) => output$4(value)
21
+ render: (_args, value) => output$5(value)
22
22
  };
23
23
  const keyParameter$1 = {
24
24
  type: "string",
@@ -119,16 +119,6 @@ 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
- }),
132
122
  listTool(reader, "list_characters", "List authored characters with stable keys and concise identifying information.", (world) => world.characters, (entry) => ({
133
123
  key: entry.key,
134
124
  name: entry.name,
@@ -261,16 +251,15 @@ function authoredWorldReadTools(reader) {
261
251
  })
262
252
  ];
263
253
  }
264
- //#endregion
265
- //#region src/host/authoring/pack-tools.ts
254
+ // src/host/authoring/pack-tools.ts
266
255
  const PACK_MUTATION_TOOLS = ["delete_world_pack_file"];
267
- const output$3 = (value) => [{
256
+ const output$4 = (value) => [{
268
257
  type: "text",
269
258
  text: JSON.stringify(value, null, 2)
270
259
  }];
271
260
  const jsonOutput$2 = {
272
261
  schema: { type: "json" },
273
- render: (_args, value) => output$3(value)
262
+ render: (_args, value) => output$4(value)
274
263
  };
275
264
  /** A path as the file tools take it: relative to the chat's folder when it has one, which is short and hard to mistype. */
276
265
  function relativeTo(exec, path) {
@@ -370,16 +359,15 @@ function worldPackTools(reader) {
370
359
  })
371
360
  ];
372
361
  }
373
- //#endregion
374
- //#region src/host/authoring/prompt-tools.ts
362
+ // src/host/authoring/prompt-tools.ts
375
363
  const PROMPT_MUTATION_TOOLS = ["write_world_prompt", "delete_world_prompt"];
376
- const output$2 = (value) => [{
364
+ const output$3 = (value) => [{
377
365
  type: "text",
378
366
  text: JSON.stringify(value, null, 2)
379
367
  }];
380
368
  const jsonOutput$1 = {
381
369
  schema: { type: "json" },
382
- render: (_args, value) => output$2(value)
370
+ render: (_args, value) => output$3(value)
383
371
  };
384
372
  const idParameter = {
385
373
  type: "string",
@@ -466,8 +454,7 @@ function worldPromptTools(reader, shipped = shippedPromptsDirectory()) {
466
454
  })
467
455
  ];
468
456
  }
469
- //#endregion
470
- //#region src/host/authoring/approval-summary.ts
457
+ // src/host/authoring/approval-summary.ts
471
458
  const MAX_FIELDS = 5;
472
459
  function clip(value, max) {
473
460
  const flat = (typeof value === "string" ? `“${value}”` : JSON.stringify(value) ?? "").replace(/\s+/g, " ");
@@ -534,15 +521,14 @@ function plain(value, max = 220) {
534
521
  zh: text
535
522
  };
536
523
  }
537
- //#endregion
538
- //#region src/host/authoring/write-tools.ts
539
- const output$1 = (value) => [{
524
+ // src/host/authoring/write-tools.ts
525
+ const output$2 = (value) => [{
540
526
  type: "text",
541
527
  text: JSON.stringify(value, null, 2)
542
528
  }];
543
529
  const jsonOutput = {
544
530
  schema: { type: "json" },
545
- render: (_args, value) => output$1(value)
531
+ render: (_args, value) => output$2(value)
546
532
  };
547
533
  const kindParameter = {
548
534
  type: "string",
@@ -602,7 +588,7 @@ function plotDocument(value) {
602
588
  if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
603
589
  return parsed.value[0];
604
590
  }
605
- /** The most problems a write reports back; `world_check` lists the rest. */
591
+ /** The most problems a write reports back; `check_world` lists the rest. */
606
592
  const REPORTED_PROBLEMS = 8;
607
593
  /**
608
594
  * 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
@@ -619,16 +605,16 @@ function withWorldCheck(reader, tool) {
619
605
  const check = await checkWorld(record);
620
606
  if (check.ok) return {
621
607
  ...done,
622
- world_check: "ok: a story could start from this world"
608
+ check_world: "ok: a story could start from this world"
623
609
  };
624
610
  const shown = check.problems.slice(0, REPORTED_PROBLEMS).map((problem) => `${problem.where}: ${problem.message}`);
625
611
  return {
626
612
  ...done,
627
- world_check: {
613
+ check_world: {
628
614
  ok: false,
629
615
  still_open: shown,
630
616
  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)."
617
+ note: "Not an error of this edit; fix what the world still needs before the end of the turn (check_world lists all)."
632
618
  }
633
619
  };
634
620
  }
@@ -920,8 +906,7 @@ async function detailOf(exec, kind, key, current) {
920
906
  default: return;
921
907
  }
922
908
  }
923
- //#endregion
924
- //#region src/host/import/update-tools.ts
909
+ // src/host/import/update-tools.ts
925
910
  const MAX_HUNKS = 10;
926
911
  const MAX_PIECES = 60;
927
912
  const PREVIEW_CHARS = 300;
@@ -936,7 +921,7 @@ async function loreTitles(directory) {
936
921
  }
937
922
  return titles;
938
923
  }
939
- const output = {
924
+ const output$1 = {
940
925
  schema: { type: "json" },
941
926
  render: (_args, value) => [{
942
927
  type: "text",
@@ -961,7 +946,7 @@ function updateTools(worlds) {
961
946
  name: "card_diff",
962
947
  description: "What a newer version of the card this world was imported from changes. For each piece (field, greeting, lorebook entry) that changed, was added or was dropped: the sentences that differ, and the characters, places and things the import made from it, which are what may need to change. Also the files of the world that were edited since the import, and what the newer version changes about the card itself. Start here when asked to update the world from its card; read whole pieces with card_read (version current or new).",
963
948
  parameters: {},
964
- output,
949
+ output: output$1,
965
950
  isConcurrencySafe: () => true,
966
951
  async execute(_args, exec) {
967
952
  const directory = await worldOf(exec);
@@ -1031,12 +1016,14 @@ function updateTools(worlds) {
1031
1016
  name: "card_update_finish",
1032
1017
  description: `Makes the newer card the card this world was made from, once the world has been brought up to date with it: the old card is kept in ${IMPORT_FOLDER}/previous, and what the world holds now is what later edits are measured against. Run it after your edits, and only then.`,
1033
1018
  parameters: {},
1034
- output,
1019
+ output: output$1,
1035
1020
  async execute(_args, exec) {
1036
1021
  const directory = await worldOf(exec);
1037
1022
  const outcome = await finishUpdate(directory, exec.signal === void 0 ? {} : { signal: exec.signal });
1023
+ const checks = await checkImported(directory, (await readWorldInfo(directory)).name);
1038
1024
  return json({
1039
1025
  done: true,
1026
+ checks,
1040
1027
  card: `${IMPORT_FOLDER}/card.json`,
1041
1028
  previous: join(IMPORT_FOLDER, "previous"),
1042
1029
  forgottenRecords: outcome.forgotten,
@@ -1104,8 +1091,113 @@ function updateHooks(ctx, worlds, languageOf$1) {
1104
1091
  }));
1105
1092
  });
1106
1093
  }
1107
- //#endregion
1108
- //#region src/authoring.ts
1094
+ // src/host/checks/tools.ts
1095
+ const output = {
1096
+ schema: { type: "json" },
1097
+ render: (_args, value) => [{
1098
+ type: "text",
1099
+ text: JSON.stringify(value, null, 2)
1100
+ }]
1101
+ };
1102
+ const deepParameter = {
1103
+ type: "boolean",
1104
+ description: "Also run the checks a model judges (slower, one or more model requests each). Leave it off for a quick look; turn it on when the quick checks leave the world looking thin, when the person asks for a thorough check, or before you say an import is done."
1105
+ };
1106
+ function kitTool(reader, judging, name, kit, description, card = false) {
1107
+ return defineTool({
1108
+ name,
1109
+ description,
1110
+ parameters: {
1111
+ ...card ? { version: {
1112
+ type: "string",
1113
+ enum: ["current", "new"],
1114
+ description: "current (the default) is the card the world was made from; new is the newer version waiting to update it."
1115
+ } } : {},
1116
+ deep: deepParameter
1117
+ },
1118
+ output,
1119
+ isConcurrencySafe: () => false,
1120
+ async execute(args, exec) {
1121
+ const { record } = await reader.read(exec);
1122
+ const version = args.version === "new" ? "new" : "current";
1123
+ const evidence = card ? await loadCardEvidence(record.directory, version) : void 0;
1124
+ if (card && evidence === void 0) throw new Error(version === "new" ? "no newer version of the card is waiting to update this world" : "this world has no source card: it was not imported from one, or its .import folder was removed");
1125
+ const language = judging.prompting.languages().get(record.summary.id);
1126
+ const text = (id, variables) => judging.prompting.prompts().text(id, language, variables);
1127
+ const model = args.deep === true ? contextOf(exec, judging.settings(), text, language) : void 0;
1128
+ const report = await runChecks({
1129
+ world: record,
1130
+ ...evidence === void 0 ? {} : { card: evidence },
1131
+ ...model === void 0 ? {} : { model }
1132
+ }, {
1133
+ kits: [kit],
1134
+ deep: args.deep === true
1135
+ });
1136
+ return JSON.parse(JSON.stringify(presentReport(report)));
1137
+ }
1138
+ });
1139
+ }
1140
+ /** The checks of the suite as tools of a world authoring chat; each kit is one call, and what it finds is stored with the world for the next run to compare with. */
1141
+ function checkTools(reader, judging) {
1142
+ return [
1143
+ kitTool(reader, judging, "check_world", "consistency", "Check the world for inconsistencies: whether a story could start from it (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, so run it again after fixing them), places no one can reach, names that clash, tracked values that are the same thing twice, and prompts the story could not use. Run it before you say a world is done. It reads only; each finding says where it is and, when clear, what would fix it."),
1144
+ kitTool(reader, judging, "check_card", "fidelity", "Compare the world with the card it was imported from, which is kept: whether every piece of the card the import read is in the world, whether every name in the world occurs in the card, whether the numbers the card gives were kept, and, with version new, what a newer card waiting to update the world changed that the world does not say yet. With deep, a model also compares each document with the pieces it was made from and quotes the facts that were lost or made up. A finding is a pointer: read the piece with card_read before you change anything. It reads only.", true),
1145
+ kitTool(reader, judging, "check_quality", "quality", "Check the authoring quality of the world: whether someone can be played, whether the characters that matter have sheets to play from, places with nothing in them, what the world says about itself. With deep, a model also judges whether each sheet is enough to play and what the world is missing to play well. It reads only; a finding is a gap to fill from what the card or the person says, never from invention."),
1146
+ defineTool({
1147
+ name: "check_list",
1148
+ description: "List the checks of the suite: which kit each belongs to, whether the program or a model decides it, and what it needs.",
1149
+ parameters: {},
1150
+ output,
1151
+ isConcurrencySafe: () => true,
1152
+ async execute() {
1153
+ return JSON.parse(JSON.stringify(CHECKS.map((check) => ({
1154
+ id: check.id,
1155
+ kit: check.kit,
1156
+ mode: check.mode,
1157
+ needs: check.needs,
1158
+ description: check.description
1159
+ }))));
1160
+ }
1161
+ })
1162
+ ];
1163
+ }
1164
+ // src/host/checks/hooks.ts
1165
+ /** The tool each kit is run with, for the notice of a check command. */
1166
+ const KIT_TOOLS = {
1167
+ consistency: "check_world",
1168
+ fidelity: "check_card",
1169
+ quality: "check_quality"
1170
+ };
1171
+ /** Hears the check commands (`/check`, `/check-world`) in an authoring chat and tells the assistant to run those kits and what to do with what they find. */
1172
+ function checkHooks(ctx, prompting) {
1173
+ const authoring = (agent) => agent.session.header.origin === "subagent" || authoredWorldOf(agent.session.id) === void 0 ? void 0 : agent.session.id;
1174
+ ctx.on("agent/pre-step", async (payload, next) => {
1175
+ const decision = await next();
1176
+ const chat = authoring(payload.agent);
1177
+ if (decision.kind !== "enter" || payload.step !== 1 || chat === void 0) return decision;
1178
+ const text = payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n");
1179
+ const command = parseAuthoringCommand(text, Object.keys(CHECK_COMMANDS));
1180
+ if (command === void 0) return decision;
1181
+ const world = authoredWorldOf(chat);
1182
+ const tools = CHECK_COMMANDS[command.name].map((kit) => KIT_TOOLS[kit]).join(", ");
1183
+ const notice = prompting.prompts().text("checks/notice", world === void 0 ? void 0 : prompting.languages().get(world), {
1184
+ command: `/${command.name}`,
1185
+ tools,
1186
+ request: command.rest === "" ? "-" : command.rest
1187
+ });
1188
+ return {
1189
+ ...decision,
1190
+ messages: [...decision.messages, createUserMessage({
1191
+ content: [{
1192
+ type: "text",
1193
+ text: notice
1194
+ }],
1195
+ source: { kind: "roleplay" }
1196
+ })]
1197
+ };
1198
+ });
1199
+ }
1200
+ // src/authoring.ts
1109
1201
  const name = "@dsh-agentic-roleplay/core/authoring";
1110
1202
  const inject = [
1111
1203
  "roleplayWorlds",
@@ -1136,7 +1228,12 @@ function apply(ctx) {
1136
1228
  for (const tool of updateTools(ctx.roleplayWorlds)) ctx.tools.register(tool);
1137
1229
  for (const tool of presetTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1138
1230
  for (const tool of translateTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1231
+ for (const tool of checkTools(reader, {
1232
+ settings: () => ctx.roleplayImport.settings,
1233
+ prompting
1234
+ })) ctx.tools.register(tool);
1139
1235
  importHooks(ctx, ctx.roleplayWorlds, prompting);
1236
+ checkHooks(ctx, prompting);
1140
1237
  updateHooks(ctx, ctx.roleplayWorlds, (world) => ctx.roleplayAuthoringLanguages.get(world));
1141
1238
  const reviewing = async (chat) => {
1142
1239
  const id = authoredWorldOf(chat);
@@ -1188,7 +1285,6 @@ function apply(ctx) {
1188
1285
  text: (context) => ctx.roleplayPrompts.text(id, languageOf(context))
1189
1286
  });
1190
1287
  }
1191
- //#endregion
1192
1288
  export { apply, inject, name };
1193
1289
 
1194
1290
  //# sourceMappingURL=authoring.js.map
@@ -2,7 +2,7 @@ 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
4
  import { ToolArgsError, validateJsonSchemaValue } from "@deepseek-ai/dsh-tools";
5
- //#region src/host/agents/budget.ts
5
+ // src/host/agents/budget.ts
6
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. */
7
7
  function tokensOf$1(characters, language) {
8
8
  return Math.ceil(language.toLowerCase().startsWith("zh") ? characters * 1.5 : characters / 3);
@@ -18,8 +18,7 @@ function outputBudget(estimate, headroom) {
18
18
  function estimateAnswer(limits, language) {
19
19
  return limits.reduce((sum, limit) => sum + tokensOf$1(limit, language) + 8, 0);
20
20
  }
21
- //#endregion
22
- //#region src/host/agents/cut-off.ts
21
+ // src/host/agents/cut-off.ts
23
22
  /** How the model's last reply ended (`stop`, `tool-calls`, `max-tokens`), or nothing when it has made none. */
24
23
  function finishOf(agent) {
25
24
  const last = agent.session.snapshotEvents().findLast((event) => event.type === "assistant/message");
@@ -28,8 +27,7 @@ function finishOf(agent) {
28
27
  }
29
28
  /** Whether the model's last reply ended because it reached the most it may write in one request. */
30
29
  const cutOff = (agent) => finishOf(agent) === "max-tokens";
31
- //#endregion
32
- //#region src/host/orchestration/current-turn.ts
30
+ // src/host/orchestration/current-turn.ts
33
31
  /** The last turn the session started. */
34
32
  function currentTurn(agent) {
35
33
  const events = agent.session.snapshotEvents();
@@ -39,8 +37,7 @@ function currentTurn(agent) {
39
37
  }
40
38
  return 0;
41
39
  }
42
- //#endregion
43
- //#region src/shared/usage.ts
40
+ // src/shared/usage.ts
44
41
  const NO_TOKENS = {
45
42
  input: 0,
46
43
  cached: 0,
@@ -51,8 +48,7 @@ const addTokens = (a, b) => ({
51
48
  cached: a.cached + b.cached,
52
49
  output: a.output + b.output
53
50
  });
54
- //#endregion
55
- //#region src/host/agents/usage.ts
51
+ // src/host/agents/usage.ts
56
52
  /** The tokens the model service reported for the requests it answered in a session's events; a request it reported nothing for adds nothing. */
57
53
  function tokensOf(events) {
58
54
  let total = NO_TOKENS;
@@ -68,13 +64,17 @@ function tokensOf(events) {
68
64
  }
69
65
  return total;
70
66
  }
71
- //#endregion
72
- //#region src/shared/activity.ts
67
+ // src/shared/activity.ts
73
68
  /** Longest text kept for one call's arguments or outcome, and for the persona, the prompt and the result. */
74
69
  const MAX_RUN_TEXT = 4e3;
75
70
  const MAX_RUN_PROMPT = 24e3;
76
- //#endregion
77
- //#region src/shared/sampling.ts
71
+ // src/host/agents/limits.ts
72
+ /**
73
+ * 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
74
+ * minutes, a game master's turn never ended), so what the stop decided is not waited on past this.
75
+ */
76
+ const STOP_GRACE_MS = 15e3;
77
+ // src/shared/sampling.ts
78
78
  /** The controls beyond temperature, which apply to the game master and the characters (the helpers that must be exact are never asked more freely). */
79
79
  const SHARED_SAMPLING = [
80
80
  "topP",
@@ -149,33 +149,12 @@ function parseSampling(value, where, problems) {
149
149
  function sharedSamplingOf(settings) {
150
150
  return Object.fromEntries(SHARED_SAMPLING.flatMap((key) => settings[key] === SAMPLING_RANGES[key].neutral ? [] : [[key, settings[key]]]));
151
151
  }
152
- //#endregion
153
- //#region src/host/agents/child.ts
152
+ // src/host/agents/child.ts
154
153
  /** The tool every child ends with: its arguments are the child's result. */
155
154
  const SUBMIT_TOOL = "submit_result";
156
155
  /** 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
156
  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
157
  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.";
159
- /** Calls a child may make before it is given up; a child that keeps going is not converging. */
160
- const DEFAULT_MAX_CALLS = 40;
161
- /** A child that stops without a result is told to submit this many times before it is given up. */
162
- const MAX_REMINDERS = 2;
163
- /** 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. */
164
- const OVERRUN = 5;
165
- /** Steps a child gets to submit once its other tools are withdrawn: a model that keeps calling tools that are gone is stopped. */
166
- const STEPS_AFTER_RETIRE = 3;
167
- /** The most model steps a child may take past its call budget in all (calls the harness refuses before they run, such as a result that does not fit its schema, are not counted as calls). */
168
- const STEPS_PAST_BUDGET = 20;
169
- /** 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. */
170
- const REPEATS_TOLD = 1;
171
- const REPEATS_STOPPED = 4;
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. */
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;
179
158
  /** A child ran out of the time it was given; asking again would only spend it again. */
180
159
  var ChildTimeoutError = class extends Error {
181
160
  constructor(minutes) {
@@ -329,7 +308,7 @@ async function supportedEffort(task) {
329
308
  /**
330
309
  * 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
310
  */
332
- function repairedJson(text) {
311
+ function repairedJson(text, accepts = () => true) {
333
312
  const cuts = [];
334
313
  for (const marks of ["}]", ","]) for (let at = text.length - 1, found = 0; at >= 0 && found < 300; at -= 1) if (marks.includes(text[at])) {
335
314
  cuts.push(at);
@@ -354,8 +333,7 @@ function repairedJson(text) {
354
333
  if (inString) continue;
355
334
  const closed = head + stack.reverse().join("");
356
335
  try {
357
- JSON.parse(closed);
358
- return closed;
336
+ if (accepts(JSON.parse(closed))) return closed;
359
337
  } catch {
360
338
  continue;
361
339
  }
@@ -370,7 +348,7 @@ function structuredReply(child, schema, cut = false) {
370
348
  try {
371
349
  value = JSON.parse(text);
372
350
  } catch (error) {
373
- const mended = cut ? repairedJson(text) : void 0;
351
+ const mended = cut ? repairedJson(text, (candidate) => validateJsonSchemaValue(schema, candidate).length === 0) : void 0;
374
352
  if (mended === void 0) return { problem: `the reply is not valid JSON (${error instanceof Error ? error.message : String(error)})` };
375
353
  value = JSON.parse(mended);
376
354
  }
@@ -398,7 +376,7 @@ async function execute(task, stats) {
398
376
  let refusals = 0;
399
377
  let lastRefusal = "";
400
378
  let previous;
401
- const budget = task.maxCalls ?? DEFAULT_MAX_CALLS;
379
+ const budget = task.maxCalls ?? 40;
402
380
  const counted = (tool) => ({
403
381
  ...tool,
404
382
  execute: async (args, exec) => {
@@ -411,7 +389,7 @@ async function execute(task, stats) {
411
389
  failed
412
390
  });
413
391
  };
414
- if (stats.calls > budget + OVERRUN) {
392
+ if (stats.calls > budget + 5) {
415
393
  overran = true;
416
394
  stopped?.();
417
395
  }
@@ -422,11 +400,11 @@ async function execute(task, stats) {
422
400
  }
423
401
  const signature = JSON.stringify(args);
424
402
  const repeats = previous?.name === tool.name && previous.args === signature && previous.failed ? previous.repeats + 1 : 0;
425
- if (repeats >= REPEATS_STOPPED) {
403
+ if (repeats >= 4) {
426
404
  overran = true;
427
405
  stopped?.();
428
406
  }
429
- if (repeats >= REPEATS_TOLD) {
407
+ if (repeats >= 1) {
430
408
  previous = {
431
409
  name: tool.name,
432
410
  args: signature,
@@ -488,7 +466,7 @@ async function execute(task, stats) {
488
466
  });
489
467
  refusals += 1;
490
468
  lastRefusal = refusal;
491
- if (refusals >= MAX_REFUSALS) {
469
+ if (refusals >= 5) {
492
470
  overran = true;
493
471
  stopped?.();
494
472
  }
@@ -528,13 +506,13 @@ async function execute(task, stats) {
528
506
  childCtx.on("agent/pre-step", async (_payload, next) => {
529
507
  const decision = await next();
530
508
  steps += 1;
531
- if (steps > budget + STEPS_PAST_BUDGET && submitted === void 0) {
509
+ if (steps > budget + 20 && submitted === void 0) {
532
510
  overran = true;
533
511
  stopped?.();
534
512
  }
535
513
  if (stepsAfterRetire < 0) return decision;
536
514
  stepsAfterRetire += 1;
537
- if (stepsAfterRetire > STEPS_AFTER_RETIRE && submitted === void 0) {
515
+ if (stepsAfterRetire > 3 && submitted === void 0) {
538
516
  overran = true;
539
517
  stopped?.();
540
518
  }
@@ -571,7 +549,7 @@ async function execute(task, stats) {
571
549
  outcome: cut(lastRefusal),
572
550
  failed: true
573
551
  });
574
- if (refusals >= MAX_REFUSALS) {
552
+ if (refusals >= 5) {
575
553
  overran = true;
576
554
  stopped?.();
577
555
  return;
@@ -591,7 +569,7 @@ async function execute(task, stats) {
591
569
  stopped?.();
592
570
  return;
593
571
  }
594
- if (reminders >= MAX_REMINDERS) return;
572
+ if (reminders >= 2) return;
595
573
  reminders += 1;
596
574
  child.steer(createUserMessage({
597
575
  content: [{
@@ -664,7 +642,7 @@ async function execute(task, stats) {
664
642
  }
665
643
  if (signal.aborted) throw new Error("cancelled");
666
644
  if (rambled && submitted === void 0) throw new Error(`the agent wrote text up to the limit of ${task.maxTokens ?? task.sampling?.maxTokens ?? "its model"} tokens and never called ${SUBMIT_TOOL}, and was stopped`);
667
- 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`);
645
+ if (overran && submitted === void 0) throw new Error(refusals >= 5 ? `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`);
668
646
  if (submitted === void 0) {
669
647
  const ended = entry.agent?.session.snapshotEvents().findLast((event) => event.type === "turn/end");
670
648
  const reason = ended?.type === "turn/end" ? ended.data.reason : void 0;
@@ -673,7 +651,6 @@ async function execute(task, stats) {
673
651
  }
674
652
  return submitted.value;
675
653
  }
676
- //#endregion
677
654
  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 };
678
655
 
679
- //# sourceMappingURL=child-D6mpkkCE.js.map
656
+ //# sourceMappingURL=child-lYYeOwl2.js.map