@dsh-agentic-roleplay/core 0.12.0 → 0.12.2

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 (44) hide show
  1. package/cordis.patch.yml +108 -0
  2. package/lib/{access-DAw54-NI.js → access-Csp80TFX.js} +2 -2
  3. package/lib/{authoring-tools-4NgDhIJV.js → authoring-tools-BZr4bgBy.js} +25 -771
  4. package/lib/authoring.js +136 -12
  5. package/lib/{child-D3QUNb3m.js → child-DTdY14S9.js} +54 -6
  6. package/lib/client.js +16457 -1938
  7. package/lib/client.js.map +1 -1
  8. package/lib/compaction.js +3 -3
  9. package/lib/dev-context-Cgv_wZbG.js +50 -0
  10. package/lib/doctor.js +6 -3
  11. package/lib/{gallery-Ct6nm4UQ.js → gallery-BNg0rPTp.js} +3 -3
  12. package/lib/{generator-CI8fOnXy.js → generator-9-5at9cZ.js} +2 -2
  13. package/lib/helper.js +5 -9
  14. package/lib/{hooks-BNeoGMHZ.js → hooks-Dtq5KZQX.js} +47 -16
  15. package/lib/images.js +4 -4
  16. package/lib/index.js +152 -476
  17. package/lib/{jail-BIF79PJO.js → jail-DVbPSC0R.js} +2 -2
  18. package/lib/{library-BF9ZMSFz.js → library-DTxakw0z.js} +2 -2
  19. package/lib/{lorebook-author-tools-DBk-V0hp.js → lorebook-author-tools-BjcEUo22.js} +19 -6
  20. package/lib/lorebook-authoring.js +13 -5
  21. package/lib/{narration-xvErE2yp.js → narration--K2XVIHI.js} +2 -2
  22. package/lib/orchestration.js +33 -12
  23. package/lib/{pack-jail-C8EyX9Ix.js → pack-jail-Dt0VTsu0.js} +558 -23
  24. package/lib/{packs-S0SzrVv-.js → packs-DWfR2Ted.js} +2 -2
  25. package/lib/{presenter-agent-Bc478nTA.js → presenter-agent-vFOxIuWv.js} +9 -9
  26. package/lib/{preset-SJZyw0kt.js → preset-Dv5YF2qj.js} +4 -4
  27. package/lib/{preset-author-tools-CzogjK42.js → preset-author-tools-BUzO9mTW.js} +8 -7
  28. package/lib/preset-authoring.js +12 -6
  29. package/lib/{reflection-buQiSdvq.js → reflection-Dd3pEiZB.js} +14 -15
  30. package/lib/{presets-DQ5rioMh.js → serial-BUaJGwVy.js} +1241 -390
  31. package/lib/{turn-guard-BSAba8sp.js → turn-guard-87NE-Cnp.js} +3 -3
  32. package/locale/de.json +6 -0
  33. package/locale/en.json +6 -0
  34. package/locale/es.json +6 -0
  35. package/locale/fr.json +6 -0
  36. package/locale/ja.json +6 -0
  37. package/locale/pt.json +6 -0
  38. package/locale/ru.json +6 -0
  39. package/locale/zh.json +6 -0
  40. package/package.json +34 -34
  41. package/prompts/en/import/style.md +2 -1
  42. package/prompts/en/world/procedure.md +1 -1
  43. package/prompts/zh/import/style.md +2 -1
  44. package/prompts/zh/world/procedure.md +1 -1
package/lib/authoring.js CHANGED
@@ -1,17 +1,70 @@
1
- import { $ as readSource, A as editsSince, C as worldFieldChanges, D as loadCardEvidence, E as loadWorldParts, J as UPDATE_FOLDER, O as CHECK_COMMANDS, Q as entitiesByPiece, S as pictureChange, T as readWorldInfo, Z as cardTools, _ as runChecks, a as importHooks, b as diffText, g as CHECKS, h as presentReport, i as contextOf, l as isReviewing, ln as authoredWorldOf, m as checkImported, n as limitAuthoringAgents, nt as parseWorldInfoEdit, o as importTools, v as addressChanges, vt as checkWorld, w as editWorldInfo, x as matchPieces, y as cardChanges } from "./authoring-tools-4NgDhIJV.js";
2
- import { t as guardAuthoringTurns } from "./turn-guard-BSAba8sp.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-C8EyX9Ix.js";
4
- import { $ as IMPORT_FOLDER, G as deleteWorldPrompt, J as writeWorldPrompt, K as listWorldPrompts, Lt as parseRelationEdit, Mt as InvalidEditProblems, W as PROSE_PROMPTS, lt as parseAuthoringCommand, nt as PICTURE_FILE, q as readWorldPrompt } from "./presets-DQ5rioMh.js";
1
+ import { $ as readSource, A as editsSince, C as worldFieldChanges, D as loadCardEvidence, E as loadWorldParts, J as UPDATE_FOLDER, Kt as authoredWorldOf, Mt as CALENDAR_FILE_NAME, O as CHECK_COMMANDS, Ot as COMMANDS_FILE_NAME, Q as entitiesByPiece, S as pictureChange, T as readWorldInfo, Tt as DICE_FILE_NAME, Z as cardTools, _ as runChecks, a as importHooks, b as diffText, et as checkWorld, g as CHECKS, h as presentReport, i as contextOf, l as isReviewing, m as checkImported, n as limitAuthoringAgents, o as importTools, v as addressChanges, w as editWorldInfo, x as matchPieces, y as cardChanges } from "./authoring-tools-BZr4bgBy.js";
2
+ import { t as guardAuthoringTurns } from "./turn-guard-87NE-Cnp.js";
3
+ import { n as silenceRuntimeContext, t as silenceHarnessDevContext } from "./dev-context-Cgv_wZbG.js";
4
+ import { B as deleteTriggerDocument, D as editWorldPlots, G as parseVariablesEdit, H as writeTriggerDocument, K as parseDiceEdit, M as readWorldEditor, O as editWorldRelation, Q as translateTools, U as parseCalendarEdit, V as readTriggerDocuments, X as presetTools, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, f as editCalendar, g as editVariables, i as checkWorldPack, l as deleteAuthoredEntity, m as editDice, nt as finishUpdate, o as listWorldPacks, p as editCommands, q as parseCommandsEdit, r as registerPackJail, rt as pendingUpdate, s as AUTHORED_ENTITY_KINDS, u as readAuthoredEntityDocument } from "./pack-jail-Dt0VTsu0.js";
5
5
  import { i as translator, r as languageOf } from "./text-Dfv8S8eq.js";
6
- import { B as parsePlotsFile, it as shippedPromptsDirectory, q as formatIssue } from "./hooks-BNeoGMHZ.js";
7
- import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-S0SzrVv-.js";
8
- import "./access-DAw54-NI.js";
6
+ import { $ as deleteWorldPrompt, At as parseAuthoringCommand, Ct as PICTURE_FILE, F as parseWorldInfoEdit, Ft as VARIABLES_FILE_NAME, Q as PROSE_PROMPTS, an as parseRelationEdit, bt as IMPORT_FOLDER, en as InvalidEditProblems, et as listWorldPrompts, nt as writeWorldPrompt, tt as readWorldPrompt } from "./serial-BUaJGwVy.js";
7
+ import { B as parsePlotsFile, at as shippedPromptsDirectory, q as formatIssue } from "./hooks-Dtq5KZQX.js";
8
+ import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-DWfR2Ted.js";
9
+ import "./access-Csp80TFX.js";
9
10
  import { join, relative } from "node:path";
10
11
  import { createHash } from "node:crypto";
11
12
  import { readFile, readdir } from "node:fs/promises";
12
13
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
13
14
  import { defineTool } from "@deepseek-ai/dsh-tools";
14
15
  import { isDeepStrictEqual } from "node:util";
16
+ // src/host/authoring/world-files.ts
17
+ /**
18
+ * The whole-world files that belong to no single character, place or thing. The assistant writes them through the same functions as the world editor's panels,
19
+ * so a document is refused for the same reasons wherever it comes from (a value a character still has, a holiday a trigger still names).
20
+ */
21
+ const FILES = {
22
+ variables: {
23
+ file: VARIABLES_FILE_NAME,
24
+ empty: [],
25
+ write: (world, document, options) => editVariables(world, parseVariablesEdit({ variables: document }), options)
26
+ },
27
+ dice: {
28
+ file: DICE_FILE_NAME,
29
+ empty: { checks: [] },
30
+ write: (world, document, options) => editDice(world, parseDiceEdit(document), options)
31
+ },
32
+ commands: {
33
+ file: COMMANDS_FILE_NAME,
34
+ empty: { commands: [] },
35
+ write: (world, document, options) => editCommands(world, parseCommandsEdit(document), options)
36
+ },
37
+ calendar: {
38
+ file: CALENDAR_FILE_NAME,
39
+ empty: {
40
+ hemisphere: "north",
41
+ holidays: []
42
+ },
43
+ write: (world, document, options) => editCalendar(world, parseCalendarEdit(document), options)
44
+ }
45
+ };
46
+ const WORLD_FILE_KINDS = Object.keys(FILES);
47
+ const isWorldFileKind = (value) => typeof value === "string" && value in FILES;
48
+ /** The stored document of one of these files, or its empty form when the world has none. */
49
+ async function readWorldFile(directory, kind) {
50
+ try {
51
+ return JSON.parse((await readFile(join(directory, FILES[kind].file), "utf8")).replace(/^\uFEFF/, ""));
52
+ } catch (error) {
53
+ if (error.code === "ENOENT") return FILES[kind].empty;
54
+ throw error;
55
+ }
56
+ }
57
+ /**
58
+ * Replaces one of the files with a complete document, checked against the rest of the world; an empty one removes the file.
59
+ * @throws {InvalidEditProblems} naming each problem; nothing is written.
60
+ */
61
+ async function writeWorldFile(world, kind, document, options = {}) {
62
+ if (kind === "variables") {
63
+ const silent = (Array.isArray(document) ? document : []).flatMap((entry) => entry !== null && typeof entry === "object" && entry["kind"] !== "flag" && String(entry["update"] ?? "").trim() === "" ? [String(entry["key"] ?? entry["name"] ?? "?")] : []);
64
+ if (silent.length > 0) throw new InvalidEditProblems(silent.map((key) => `${key}: say when and how it changes, in the field "update" (for example "rises by 1 when the town hears good news"): a tracked value without that rule moves for nothing`));
65
+ }
66
+ await FILES[kind].write(world, document, options);
67
+ }
15
68
  // src/host/authoring/read-tools.ts
16
69
  const output$5 = (value) => [{
17
70
  type: "text",
@@ -221,6 +274,22 @@ function authoredWorldReadTools(reader) {
221
274
  return json$1(found);
222
275
  }
223
276
  }),
277
+ defineTool({
278
+ name: "get_world_file",
279
+ description: `Read the exact stored document of a whole-world file: ${WORLD_FILE_KINDS.join(", ")} (tracked values, dice checks, the world's own slash commands, the holidays). Its empty form is returned when the world has none. Use this before replacing one.`,
280
+ parameters: { kind: {
281
+ type: "string",
282
+ required: true,
283
+ enum: WORLD_FILE_KINDS
284
+ } },
285
+ output: jsonOutput$3,
286
+ isConcurrencySafe: () => true,
287
+ async execute(args, exec) {
288
+ const { record } = await reader.read(exec);
289
+ if (!isWorldFileKind(args.kind)) throw new Error(`kind must be one of ${WORLD_FILE_KINDS.join(", ")}`);
290
+ return json$1(await readWorldFile(record.directory, args.kind));
291
+ }
292
+ }),
224
293
  defineTool({
225
294
  name: "list_relationships",
226
295
  description: "Read authored character relationships, knowledge, faction memberships, social ties and map exits. Optionally narrow by kind or endpoint key.",
@@ -548,6 +617,7 @@ const WORLD_INFO_FIELDS = [
548
617
  "rules",
549
618
  "opening",
550
619
  "alternateOpenings",
620
+ "startQuestions",
551
621
  "startingTime",
552
622
  "timeZone",
553
623
  "version",
@@ -564,6 +634,7 @@ const AUTHORING_MUTATION_TOOLS = /* @__PURE__ */ new Set([
564
634
  "replace_world_plots",
565
635
  "write_world_trigger",
566
636
  "delete_world_trigger",
637
+ "write_world_file",
567
638
  ...PROMPT_MUTATION_TOOLS,
568
639
  ...PACK_MUTATION_TOOLS
569
640
  ]);
@@ -584,6 +655,10 @@ function result(action, kind, key, state, extra = {}) {
584
655
  ...extra
585
656
  };
586
657
  }
658
+ function fileKind(value) {
659
+ if (!isWorldFileKind(value)) throw new InvalidEditProblems([`kind must be one of ${WORLD_FILE_KINDS.join(", ")}`]);
660
+ return value;
661
+ }
587
662
  function plotDocument(value) {
588
663
  const parsed = parsePlotsFile(JSON.stringify([value]));
589
664
  if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
@@ -592,8 +667,15 @@ function plotDocument(value) {
592
667
  /** Checks a write the way its tool will, and writes nothing: a change the tool would refuse is not put to the person. @throws {InvalidEditProblems} */
593
668
  async function validateMutation(reader, exec) {
594
669
  const args = exec.arguments;
595
- if (exec.name !== "create_world_element" && exec.name !== "replace_world_element" && exec.name !== "write_world_trigger") return;
670
+ if (exec.name !== "create_world_element" && exec.name !== "replace_world_element" && exec.name !== "write_world_trigger" && exec.name !== "write_world_file") return;
596
671
  const { record } = await reader.read(exec);
672
+ if (exec.name === "write_world_file") {
673
+ await writeWorldFile({
674
+ id: record.summary.id,
675
+ directory: record.directory
676
+ }, fileKind(args["kind"]), args["document"], { dryRun: true });
677
+ return;
678
+ }
597
679
  const world = {
598
680
  id: record.summary.id,
599
681
  directory: record.directory
@@ -644,7 +726,7 @@ function authoredWorldWriteTools(reader) {
644
726
  return [
645
727
  defineTool({
646
728
  name: "create_world_element",
647
- description: "Create a character, location, item, faction or lore entry from a complete authored JSON document. The key becomes its stable id. Requires user approval.",
729
+ description: "Create a character, location, item, faction or lore entry from a complete authored JSON document. The key becomes its stable id. A character that is somewhere in the story needs start.location, the key of an existing place (start: {\"location\": \"yard\"}); one without it is in no place. Requires user approval.",
648
730
  parameters: {
649
731
  kind: kindParameter,
650
732
  key: keyParameter,
@@ -711,7 +793,7 @@ function authoredWorldWriteTools(reader) {
711
793
  }),
712
794
  defineTool({
713
795
  name: "edit_world_info",
714
- description: `Change what the world says about itself in world.json: ${WORLD_INFO_FIELDS.join(", ")}. Give only the fields to change, as {"description": "...", "tags": ["..."], "opening": "...", "alternateOpenings": [{"title": "...", "text": "..."}]}: a list replaces the whole list, so read get_world_info first. The description is a short summary (a few sentences). An opening with lines spoken by characters cannot be edited as text. The name, preset, lorebooks, sampling and tool switches are the person's and cannot be changed here. Requires user approval.`,
796
+ description: `Change what the world says about itself in world.json: ${WORLD_INFO_FIELDS.join(", ")}. Give only the fields to change, as {"description": "...", "tags": ["..."], "opening": "...", "alternateOpenings": [{"title": "...", "text": "..."}]}: a list replaces the whole list, so read get_world_info first. The description is a short summary (a few sentences). An opening with lines spoken by characters cannot be edited as text. startQuestions is a list of {"id", "text", "options": [{"id", "label", "effect": {...}}]} with two to eight options each; an effect may hold rules (a list of text), opening (the position of an alternate opening), startingTime, clockMode (simulated or real), tools and plots, and {} changes nothing. The name, preset, lorebooks, sampling and tool switches are the person's and cannot be changed here. Requires user approval.`,
715
797
  parameters: { changes: {
716
798
  type: "json",
717
799
  required: true,
@@ -792,6 +874,34 @@ function authoredWorldWriteTools(reader) {
792
874
  }));
793
875
  }
794
876
  }),
877
+ defineTool({
878
+ name: "write_world_file",
879
+ description: `Replace one whole-world file with a complete document: variables (variables.json, a list of what stories track: key, name, kind number|flag|choice, subject character|item|location|world, min and max for a number (copy the limits the person gave), default, integer, visibility, and an "update" field, a sentence saying when and how it changes, which a tracked value needs so that it moves only when it should; visibility is public, private or hidden), dice (dice.json, {checks: [...]}), commands (commands.json, {commands: [{word, description}]}, the world's own slash commands) or calendar (calendar.json, {hemisphere, holidays: [{id, name, on}]}). Read it with get_world_file first and send the whole document, since it replaces the file; an empty document removes the file. It is checked against the rest of the world as the editor does (a value a character still has, a holiday a trigger names) and refused with every problem. Requires user approval.`,
880
+ parameters: {
881
+ kind: {
882
+ type: "string",
883
+ required: true,
884
+ enum: WORLD_FILE_KINDS
885
+ },
886
+ document: {
887
+ type: "json",
888
+ required: true,
889
+ description: "The complete document in the file format: a list for variables, an object holding the list for the others."
890
+ }
891
+ },
892
+ output: jsonOutput,
893
+ async execute(args, exec) {
894
+ const { record } = await reader.read(exec);
895
+ await writeWorldFile({
896
+ id: record.summary.id,
897
+ directory: record.directory
898
+ }, fileKind(args.kind), args.document);
899
+ return result("written", args.kind, args.kind, await readWorldEditor({
900
+ id: record.summary.id,
901
+ directory: record.directory
902
+ }));
903
+ }
904
+ }),
795
905
  defineTool({
796
906
  name: "delete_world_trigger",
797
907
  description: "Remove one trigger from triggers.json. Its document is kept in the world’s .trash/triggers so it can be put back. A trigger that others wait for cannot be removed. Requires user approval.",
@@ -882,10 +992,10 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
882
992
  zh: "编辑世界对自身的描述"
883
993
  }, await infoDetail(args["changes"], await options.info?.(exec.agent.session.id).catch(() => void 0)))
884
994
  };
885
- const kind = typeof args["kind"] === "string" ? args["kind"] : exec.name === "edit_world_relationship" ? "relationship" : exec.name.endsWith("trigger") ? "trigger" : "plots";
995
+ const kind = typeof args["kind"] === "string" ? args["kind"] : exec.name === "edit_world_relationship" ? "relationship" : exec.name.endsWith("trigger") ? "trigger" : exec.name === "write_world_file" ? "file" : "plots";
886
996
  const key = typeof args["key"] === "string" ? args["key"] : "";
887
997
  const target = key === "" ? kind : `${kind} “${key}”`;
888
- const action = exec.name.startsWith("create") ? "Create" : exec.name.startsWith("delete") ? "Delete" : exec.name === "write_world_trigger" ? "Write" : "Edit";
998
+ const action = exec.name.startsWith("create") ? "Create" : exec.name.startsWith("delete") ? "Delete" : exec.name === "write_world_trigger" || exec.name === "write_world_file" ? "Write" : "Edit";
889
999
  const detail = await detailOf(exec, kind, key, options.current).catch(() => void 0);
890
1000
  return {
891
1001
  kind: "ask",
@@ -909,6 +1019,14 @@ async function infoDetail(changes, before) {
909
1019
  ...edit
910
1020
  });
911
1021
  }
1022
+ function fileDetail(document) {
1023
+ const lists = Array.isArray(document) ? [document] : typeof document === "object" && document !== null ? Object.values(document).filter(Array.isArray) : [];
1024
+ const entries = lists.length === 0 ? void 0 : lists.reduce((sum, list) => sum + list.length, 0);
1025
+ return entries === void 0 ? void 0 : {
1026
+ en: `${entries} entries`,
1027
+ zh: `${entries} 项`
1028
+ };
1029
+ }
912
1030
  function withDetail(headline, detail) {
913
1031
  return detail === void 0 || detail.en === "" ? {
914
1032
  en: `${headline.en}?`,
@@ -933,6 +1051,7 @@ async function detailOf(exec, kind, key, current) {
933
1051
  zh: `${args["plots"].length} 条剧情`
934
1052
  } : void 0;
935
1053
  case "write_world_trigger": return createdFields(args["document"]);
1054
+ case "write_world_file": return fileDetail(args["document"]);
936
1055
  default: return;
937
1056
  }
938
1057
  }
@@ -1253,6 +1372,8 @@ const inject = [
1253
1372
  "systemPrompt"
1254
1373
  ];
1255
1374
  function apply(ctx) {
1375
+ silenceHarnessDevContext(ctx);
1376
+ silenceRuntimeContext(ctx);
1256
1377
  const prompting = {
1257
1378
  prompts: () => ctx.roleplayPrompts,
1258
1379
  languages: () => ctx.roleplayAuthoringLanguages
@@ -1309,6 +1430,9 @@ function apply(ctx) {
1309
1430
  const directory = await worldDirectory(chat);
1310
1431
  return directory === void 0 ? void 0 : await readWorldInfo(directory);
1311
1432
  };
1433
+ ctx.on("session/event", (session, event) => {
1434
+ if (event.type === "turn/end" && session.header.origin !== "subagent" && authoredWorldOf(session.id) !== void 0) ctx.roleplayImport.turnEnded(session.id);
1435
+ });
1312
1436
  ctx.on("tools/pre-execute", (exec, next) => authoringApproval(exec, next, reviewing, {
1313
1437
  auto: () => ctx.roleplayImport.settings.approval === "auto",
1314
1438
  validate: (exec) => validateMutation(reader, exec),
@@ -43,6 +43,8 @@ const cutOff = (agent) => finishOf(agent) === "max-tokens";
43
43
  // src/host/orchestration/current-turn.ts
44
44
  /** The last turn the session started. */
45
45
  function currentTurn(agent) {
46
+ const last = lastProjectedTurn(agent);
47
+ if (last !== void 0) return last;
46
48
  const events = agent.session.snapshotEvents();
47
49
  for (let index = events.length - 1; index >= 0; index--) {
48
50
  const event = events[index];
@@ -50,6 +52,13 @@ function currentTurn(agent) {
50
52
  }
51
53
  return 0;
52
54
  }
55
+ function lastProjectedTurn(agent) {
56
+ try {
57
+ return (agent.ctx?.get("agents"))?.turnBoundaryOf(agent.session)?.lastTurn;
58
+ } catch {
59
+ return;
60
+ }
61
+ }
53
62
  // src/shared/usage.ts
54
63
  const NO_TOKENS = {
55
64
  input: 0,
@@ -468,8 +477,14 @@ const isUnfinishedCall = (error) => error instanceof Error && /parse tool call a
468
477
  * 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.
469
478
  * @throws {Error} when the child is cancelled, stops without a result, or exceeds its calls.
470
479
  */
471
- async function runChild(task) {
472
- for (let attempt = 1;; attempt += 1) {
480
+ async function runChild(asked) {
481
+ let task = asked;
482
+ let unfinished = 0;
483
+ for (;;) {
484
+ if (task.structured === true && hidesAnswers.has(modelOf(task))) task = {
485
+ ...task,
486
+ structured: false
487
+ };
473
488
  const began = Date.now();
474
489
  const turnAtStart = task.turn ?? currentTurn(task.parent);
475
490
  const stats = {
@@ -513,12 +528,34 @@ async function runChild(task) {
513
528
  tokens: stats.tokens ?? NO_TOKENS,
514
529
  requests: stats.requests ?? []
515
530
  });
516
- if (attempt >= 2 || task.signal.aborted || error instanceof ChildTimeoutError || !isUnfinishedCall(error)) throw error;
531
+ if (task.signal.aborted) throw error;
532
+ if (task.structured === true && error instanceof Error && error.message === "the reply is empty: the answer was written as thinking, which this endpoint does with a constrained reply while the model thinks") {
533
+ const model = modelOf(task);
534
+ if (model !== "") hidesAnswers.add(model);
535
+ task = {
536
+ ...task,
537
+ structured: false
538
+ };
539
+ continue;
540
+ }
541
+ unfinished += 1;
542
+ if (unfinished >= 2 || error instanceof ChildTimeoutError || !isUnfinishedCall(error)) throw error;
517
543
  } finally {
518
544
  if (timer !== void 0) clearTimeout(timer);
519
545
  }
520
546
  }
521
547
  }
548
+ /** Models known to return constrained output only in their reasoning block. */
549
+ const hidesAnswers = /* @__PURE__ */ new Set();
550
+ /** The selected model as `provider/model`, or an empty string when it is unknown. */
551
+ function modelOf(task) {
552
+ const config = task.model === void 0 ? task.parent.session.requestHeader?.()?.config : void 0;
553
+ const model = task.model ?? (config?.provider === void 0 || config.model === void 0 ? void 0 : {
554
+ provider: config.provider,
555
+ model: config.model
556
+ });
557
+ return model === void 0 ? "" : `${model.provider}/${model.model}`;
558
+ }
522
559
  /**
523
560
  * 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
524
561
  * helper has its own levels, and one that lacks the level the chat asks for would refuse the request).
@@ -566,11 +603,14 @@ function repairedJson(text, accepts = () => true) {
566
603
  }
567
604
  }
568
605
  }
606
+ /** A constrained result was returned only as reasoning, leaving the answer empty. */
607
+ const ANSWERED_IN_THINKING = "the reply is empty: the answer was written as thinking, which this endpoint does with a constrained reply while the model thinks";
569
608
  /** The result in the last reply of a structured child: its JSON, which must fit the schema; else what is wrong with it. */
570
609
  function structuredReply(child, schema, cut = false) {
571
610
  const message = child.session.snapshotEvents().findLast((event) => event.type === "assistant/message");
572
- const text = (message?.type === "assistant/message" ? message.data.message.content : []).flatMap((block) => block.type === "text" ? [block.text] : []).join("").trim().replace(/^```(?:json)?\s*|\s*```$/g, "");
573
- if (text === "") return { problem: "the reply is empty" };
611
+ const content = message?.type === "assistant/message" ? message.data.message.content : [];
612
+ const text = content.flatMap((block) => block.type === "text" ? [block.text] : []).join("").trim().replace(/^```(?:json)?\s*|\s*```$/g, "");
613
+ if (text === "") return { problem: content.some((block) => block.type === "reasoning" && block.text.trim() !== "") ? ANSWERED_IN_THINKING : "the reply is empty" };
574
614
  let value;
575
615
  try {
576
616
  value = JSON.parse(text);
@@ -600,6 +640,7 @@ async function execute(task, stats) {
600
640
  let stepsAfterRetire = -1;
601
641
  let overran = false;
602
642
  let rambled = false;
643
+ let hidden = false;
603
644
  let refusals = 0;
604
645
  let lastRefusal = "";
605
646
  let previous;
@@ -776,6 +817,12 @@ async function execute(task, stats) {
776
817
  outcome: cut(lastRefusal),
777
818
  failed: true
778
819
  });
820
+ if (lastRefusal === "the reply is empty: the answer was written as thinking, which this endpoint does with a constrained reply while the model thinks") {
821
+ hidden = true;
822
+ overran = true;
823
+ stopped?.();
824
+ return;
825
+ }
779
826
  if (refusals >= 5) {
780
827
  overran = true;
781
828
  stopped?.();
@@ -901,6 +948,7 @@ async function execute(task, stats) {
901
948
  }
902
949
  if (signal.aborted) throw new Error("cancelled");
903
950
  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`);
951
+ if (hidden && submitted === void 0) throw new Error(ANSWERED_IN_THINKING);
904
952
  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`);
905
953
  if (submitted === void 0) {
906
954
  const ended = entry.agent?.session.snapshotEvents().findLast((event) => event.type === "turn/end");
@@ -912,4 +960,4 @@ async function execute(task, stats) {
912
960
  }
913
961
  export { chatSessionId as A, addTokens as C, finishOf as D, cutOff as E, estimateAnswer as O, NO_TOKENS as S, currentTurn as T, RECOVERY_SHRINK as _, childTrace as a, estimateTokens as b, namedModel as c, sessionOfChat as d, tracerOf as f, RECOVERY_FLOOR as g, sharedSamplingOf as h, childSamplingOf as i, roleplaySessionOf as j, tokensOf$1 as k, runChild as l, parseSampling as m, childModel as n, helpers as o, SAMPLING_RANGES as p, childSampling as r, isUnfinishedCall as s, ChildTimeoutError as t, TurnTraces as u, requestsOf as v, totalTokens as w, tokensOf as x, blockText as y };
914
962
 
915
- //# sourceMappingURL=child-D3QUNb3m.js.map
963
+ //# sourceMappingURL=child-DTdY14S9.js.map