@dsh-agentic-roleplay/core 0.12.3 → 0.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/lib/{access-Csp80TFX.js → access-DjA0kvPM.js} +2 -2
  2. package/lib/{authoring-tools-hacA5fG-.js → authoring-tools-DqAttdUN.js} +260 -36
  3. package/lib/authoring.js +176 -10
  4. package/lib/{child-DTdY14S9.js → child-SMvjNsb8.js} +63 -9
  5. package/lib/client.js +2043 -1236
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -3
  8. package/lib/doctor.js +3 -3
  9. package/lib/{gallery-BNg0rPTp.js → gallery-Dahi5TkO.js} +3 -3
  10. package/lib/{generator-9-5at9cZ.js → generator-BvSZGpzy.js} +2 -2
  11. package/lib/helper.js +2 -2
  12. package/lib/{hooks-DlrFO4aQ.js → hooks-OLl-1AOS.js} +67 -28
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +45 -30
  15. package/lib/{jail-DVbPSC0R.js → jail-CDW5iymd.js} +2 -2
  16. package/lib/{library-DTxakw0z.js → library-D6AcyxGZ.js} +3 -3
  17. package/lib/{lorebook-author-tools-dupq-kb_.js → lorebook-author-tools-CXV1KD4Q.js} +7 -7
  18. package/lib/lorebook-authoring.js +5 -5
  19. package/lib/{narration--K2XVIHI.js → narration-Bnrvl0UQ.js} +2 -2
  20. package/lib/orchestration.js +37 -38
  21. package/lib/{pack-jail-Bq0fzKi4.js → pack-jail-CZAmlgE1.js} +16 -15
  22. package/lib/{packs-D-7EU3yU.js → packs-DUVCSHqi.js} +2 -2
  23. package/lib/{presenter-agent-vFOxIuWv.js → presenter-agent-CGCJrg7V.js} +7 -6
  24. package/lib/{preset-RHcOG55T.js → preset-BYfXYvp0.js} +4 -4
  25. package/lib/{preset-author-tools-Dwxnpv6V.js → preset-author-tools-DYxTLm9U.js} +7 -7
  26. package/lib/preset-authoring.js +5 -5
  27. package/lib/{reflection-DibpEUQK.js → reflection-C3zdufN9.js} +8 -8
  28. package/lib/{serial-CDGoXYh-.js → serial-Bh6gqb3f.js} +239 -51
  29. package/lib/{text-Dfv8S8eq.js → text-B-HsLdb-.js} +4 -1
  30. package/lib/{turn-guard-DDxikrq7.js → turn-guard-CNFvmz_F.js} +3 -3
  31. package/package.json +2 -2
  32. package/prompts/en/import/opening.md +17 -0
  33. package/prompts/en/roleplay/decide-opening.md +1 -0
  34. package/prompts/en/world/procedure.md +1 -1
  35. package/prompts/zh/import/opening.md +17 -0
  36. package/prompts/zh/roleplay/decide-opening.md +1 -0
  37. package/prompts/zh/world/procedure.md +1 -1
package/lib/authoring.js CHANGED
@@ -1,12 +1,12 @@
1
- import { $ as checkWorld, A as loadWorldParts, At as UPDATE_FOLDER, C as cardChanges, D as worldFieldChanges, E as pictureChange, F as editsSince, Ft as readSource, It as COMMANDS_FILE_NAME, M as CHECK_COMMANDS, N as CHECK_COMMAND_DESCRIPTIONS, Nt as cardTools, O as editWorldInfo, Pt as entitiesByPiece, S as addressChanges, St as DICE_FILE_NAME, T as matchPieces, Tt as CALENDAR_FILE_NAME, Xt as authoredWorldOf, b as CHECKS, j as loadCardEvidence, k as readWorldInfo, l as importTools, n as limitAuthoringAgents, o as contextOf, p as isReviewing, s as importHooks, v as checkImported, w as diffText, x as runChecks, y as presentReport } from "./authoring-tools-hacA5fG-.js";
2
- import { t as guardAuthoringTurns } from "./turn-guard-DDxikrq7.js";
1
+ import { $ as checkWorld, A as loadWorldParts, At as lettersOf, C as cardChanges, D as worldFieldChanges, E as pictureChange, F as editsSince, Ft as cardTools, It as entitiesByPiece, Lt as readSource, M as CHECK_COMMANDS, Mt as UPDATE_FOLDER, N as CHECK_COMMAND_DESCRIPTIONS, O as editWorldInfo, Qt as authoredWorldOf, Rt as COMMANDS_FILE_NAME, S as addressChanges, St as DICE_FILE_NAME, T as matchPieces, Tt as CALENDAR_FILE_NAME, b as CHECKS, j as loadCardEvidence, jt as shapeOpening, k as readWorldInfo, kt as loadCharacters, l as importTools, n as limitAuthoringAgents, o as contextOf, p as isReviewing, s as importHooks, u as worldOf, v as checkImported, w as diffText, x as runChecks, y as presentReport } from "./authoring-tools-DqAttdUN.js";
2
+ import { t as guardAuthoringTurns } from "./turn-guard-CNFvmz_F.js";
3
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-Bq0fzKi4.js";
5
- import { i as translator, r as languageOf } from "./text-Dfv8S8eq.js";
6
- import { $ as deleteWorldPrompt, Ct as IMPORT_FOLDER, Et as PICTURE_FILE, F as parseWorldInfoEdit, It as parseRelationEdit, Q as PROSE_PROMPTS, Wt as VARIABLES_FILE_NAME, et as listWorldPrompts, jt as InvalidEditProblems, nt as writeWorldPrompt, tt as readWorldPrompt } from "./serial-CDGoXYh-.js";
7
- import { B as parsePlotsFile, at as shippedPromptsDirectory, ht as registerCommands, q as formatIssue } from "./hooks-DlrFO4aQ.js";
8
- import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-D-7EU3yU.js";
9
- import "./access-Csp80TFX.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-CZAmlgE1.js";
5
+ import { i as translator, r as languageOf } from "./text-B-HsLdb-.js";
6
+ import { Et as IMPORT_FOLDER, F as parseWorldInfoEdit, I as hasSpeech, Pt as InvalidEditProblems, R as partsText, at as writeWorldPrompt, it as readWorldPrompt, kt as PICTURE_FILE, nt as deleteWorldPrompt, qt as VARIABLES_FILE_NAME, rt as listWorldPrompts, tt as PROSE_PROMPTS, zt as parseRelationEdit } from "./serial-Bh6gqb3f.js";
7
+ import { B as parsePlotsFile, at as shippedPromptsDirectory, ht as registerCommands, q as formatIssue } from "./hooks-OLl-1AOS.js";
8
+ import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-DUVCSHqi.js";
9
+ import "./access-DjA0kvPM.js";
10
10
  import { join, relative } from "node:path";
11
11
  import { createHash } from "node:crypto";
12
12
  import { readFile, readdir } from "node:fs/promises";
@@ -321,6 +321,26 @@ function authoredWorldReadTools(reader) {
321
321
  })
322
322
  ];
323
323
  }
324
+ // src/host/authoring/opening-speakers.ts
325
+ /**
326
+ * Refuses an opening whose lines are spoken by someone the world does not have, and lists the ids it does have: a model asked to change who speaks writes a name's initials or an
327
+ * invented id unless it is told the real ones (found live: "hale" and "oldge" for a character whose id was "miller").
328
+ * @throws {InvalidEditProblems}
329
+ */
330
+ async function checkOpeningSpeakers(directory, edit) {
331
+ const spoken = [...(edit.openingParts ?? []).map((part) => ({
332
+ where: "openingParts",
333
+ part
334
+ })), ...(edit.alternateOpenings ?? []).flatMap((entry, index) => (entry.parts ?? []).map((part) => ({
335
+ where: `alternateOpenings[${index}].parts`,
336
+ part
337
+ })))].filter((entry) => entry.part.type === "utterance");
338
+ if (spoken.length === 0) return;
339
+ const { characters } = await loadCharacters(directory);
340
+ const ids = new Set(characters.map((character) => character.id));
341
+ const problems = spoken.flatMap(({ where, part }) => part.type === "utterance" && !ids.has(part.character) ? [`${where}: "${part.character}" is not a character of this world; the characters are ${characters.map((character) => `${character.id} (${character.name})`).join(", ")}`] : []);
342
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
343
+ }
324
344
  // src/host/authoring/pack-tools.ts
325
345
  const PACK_MUTATION_TOOLS = ["delete_world_pack_file"];
326
346
  const output$4 = (value) => [{
@@ -616,6 +636,7 @@ const WORLD_INFO_FIELDS = [
616
636
  "tags",
617
637
  "rules",
618
638
  "opening",
639
+ "openingParts",
619
640
  "alternateOpenings",
620
641
  "startQuestions",
621
642
  "startingTime",
@@ -626,6 +647,7 @@ const WORLD_INFO_FIELDS = [
626
647
  ];
627
648
  const AUTHORING_MUTATION_TOOLS = /* @__PURE__ */ new Set([
628
649
  "import_preset",
650
+ "reshape_opening",
629
651
  "edit_world_info",
630
652
  "create_world_element",
631
653
  "replace_world_element",
@@ -667,6 +689,11 @@ function plotDocument(value) {
667
689
  /** 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} */
668
690
  async function validateMutation(reader, exec) {
669
691
  const args = exec.arguments;
692
+ if (exec.name === "edit_world_info") {
693
+ const { record } = await reader.read(exec);
694
+ await checkOpeningSpeakers(record.directory, parseWorldInfoEdit(args["changes"]));
695
+ return;
696
+ }
670
697
  if (exec.name !== "create_world_element" && exec.name !== "replace_world_element" && exec.name !== "write_world_trigger" && exec.name !== "write_world_file") return;
671
698
  const { record } = await reader.read(exec);
672
699
  if (exec.name === "write_world_file") {
@@ -690,6 +717,16 @@ async function validateMutation(reader, exec) {
690
717
  dryRun: true
691
718
  });
692
719
  }
720
+ /** Which openings (the world's own, or an alternate by position) hold other words than before, ignoring quotation marks and spacing: a change of form alone must not change them. */
721
+ function openingWordsChanged(before, after) {
722
+ const changed = [];
723
+ if (lettersOf(before.opening) !== lettersOf(after.opening)) changed.push("opening");
724
+ after.alternateOpenings.forEach((entry, index) => {
725
+ const was = before.alternateOpenings[index];
726
+ if (was !== void 0 && lettersOf(was.text) !== lettersOf(entry.text)) changed.push(`alternate:${index}`);
727
+ });
728
+ return changed;
729
+ }
693
730
  /** The most problems a write reports back; `check_world` lists the rest. */
694
731
  const REPORTED_PROBLEMS = 8;
695
732
  /**
@@ -793,7 +830,7 @@ function authoredWorldWriteTools(reader) {
793
830
  }),
794
831
  defineTool({
795
832
  name: "edit_world_info",
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.`,
833
+ 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 is either plain text, which is narration only (opening, and text in an alternate opening), or an ordered list of parts, [{"type": "narration", "text": "..."}, {"type": "utterance", "character": "<character id>", "text": "..."}] (openingParts, and parts in an alternate opening); give one form, not both. Use parts whenever a character speaks, with the speaker's id from list_characters, and plain text only for pure narration; the words must stay exactly as they are when you only change the form, and a speaker you are not sure of stays narration. To only change the form of an opening, or to split it, use reshape_opening: it keeps every word, while retyping the opening here can lose some. Giving opening replaces parts with plain text; giving openingParts replaces plain text with parts. 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.`,
797
834
  parameters: { changes: {
798
835
  type: "json",
799
836
  required: true,
@@ -805,13 +842,20 @@ function authoredWorldWriteTools(reader) {
805
842
  const edit = parseWorldInfoEdit(args.changes);
806
843
  const refused = Object.keys(edit).filter((key) => !WORLD_INFO_FIELDS.includes(key));
807
844
  if (refused.length > 0) throw new InvalidEditProblems([`${refused.join(", ")} cannot be changed here: ${WORLD_INFO_FIELDS.join(", ")} can`]);
845
+ await checkOpeningSpeakers(record.directory, edit);
846
+ const before = await readWorldInfo(record.directory);
808
847
  const info = await editWorldInfo(record.directory, edit);
809
848
  await reader.refresh();
849
+ const reworded = openingWordsChanged(before, info);
810
850
  return {
811
851
  action: "edited",
812
852
  kind: "world info",
813
853
  changed: Object.keys(edit),
814
- info
854
+ info,
855
+ ...reworded.length === 0 ? {} : {
856
+ opening_words_changed: reworded,
857
+ note: "The words of these openings are not what they were. If you only meant to change their form (plain text or parts), put the original words back or use reshape_opening, which keeps every word."
858
+ }
815
859
  };
816
860
  }
817
861
  }),
@@ -984,6 +1028,17 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
984
1028
  }, remove ? void 0 : sizeOf(args["text"]))
985
1029
  };
986
1030
  }
1031
+ if (exec.name === "reshape_opening") {
1032
+ const target = String(args["target"]);
1033
+ return {
1034
+ kind: "ask",
1035
+ reason: `change the form of the authored world's ${target}`,
1036
+ displayReason: {
1037
+ en: `Change the opening “${target}” to ${String(args["form"]) === "parts" ? "parts (narration and spoken lines)" : "plain text"}? Its words stay the same.`,
1038
+ zh: `把开场“${target}”改为${String(args["form"]) === "parts" ? "分段形式(叙述与台词)" : "纯文本"}?文字内容不变。`
1039
+ }
1040
+ };
1041
+ }
987
1042
  if (exec.name === "edit_world_info") return {
988
1043
  kind: "ask",
989
1044
  reason: "edit the authored world's description, tags, opening or other world.json fields",
@@ -1250,6 +1305,116 @@ function updateHooks(ctx, worlds, languageOf$1) {
1250
1305
  }));
1251
1306
  });
1252
1307
  }
1308
+ // src/host/import/opening-tools.ts
1309
+ const OPENING_TOOL = "reshape_opening";
1310
+ /**
1311
+ * The tool that turns an opening of the world into parts (narration and lines of characters) or back into plain text, for a world imported before openings could have parts
1312
+ * or whose split was wrong. It keeps every word: a split that changes the text is refused. Every call asks the person first.
1313
+ */
1314
+ function openingTools(worlds, settings, prompting) {
1315
+ return [defineTool({
1316
+ name: OPENING_TOOL,
1317
+ description: "Change the form of an opening without changing its words. form \"parts\" splits plain text into narration and the lines that characters of this world speak (a speaker you are not sure of stays narration; an opening with no spoken line stays plain text); form \"plain\" joins parts that are only narration back into plain text and is refused when a character speaks. target is \"opening\" (the world's opening message) or \"alternate:<position>\" (an alternate opening, counting from 0). To correct who speaks a line, or to change words, use edit_world_info with openingParts instead. When the person asks to change the form of an opening, call this at once: the person approves the call itself, so do not ask first, and never retype the opening with edit_world_info to do it. Requires user approval.",
1318
+ parameters: {
1319
+ target: {
1320
+ type: "string",
1321
+ required: true,
1322
+ description: "\"opening\" or \"alternate:<position>\"."
1323
+ },
1324
+ form: {
1325
+ type: "string",
1326
+ required: true,
1327
+ enum: ["parts", "plain"],
1328
+ description: "The form to give it."
1329
+ }
1330
+ },
1331
+ output: {
1332
+ schema: { type: "json" },
1333
+ render: (_args, value) => [{
1334
+ type: "text",
1335
+ text: JSON.stringify(value, null, 1)
1336
+ }]
1337
+ },
1338
+ isConcurrencySafe: () => false,
1339
+ async execute(args, exec) {
1340
+ const world = await worldOf(worlds, exec);
1341
+ const info = await readWorldInfo(world.directory);
1342
+ const match = /^alternate:(\d+)$/.exec(args.target.trim());
1343
+ const position = match === null ? void 0 : Number(match[1]);
1344
+ if (args.target.trim() !== "opening" && position === void 0) throw new Error("target is \"opening\" or \"alternate:<position>\"");
1345
+ const alternate = position === void 0 ? void 0 : info.alternateOpenings[position];
1346
+ if (position !== void 0 && alternate === void 0) throw new Error(`the world has no alternate opening ${position}`);
1347
+ const current = alternate === void 0 ? {
1348
+ text: info.opening,
1349
+ parts: info.openingParts
1350
+ } : {
1351
+ text: alternate.text,
1352
+ parts: alternate.parts
1353
+ };
1354
+ if (current.text.trim() === "") throw new Error("that opening is empty");
1355
+ const write = async (form) => {
1356
+ if (alternate === void 0 || position === void 0) {
1357
+ await editWorldInfo(world.directory, form);
1358
+ return;
1359
+ }
1360
+ const { text: _text, parts: _parts, ...rest } = alternate;
1361
+ const entry = "opening" in form ? {
1362
+ ...rest,
1363
+ text: form.opening
1364
+ } : {
1365
+ ...rest,
1366
+ text: partsText(form.openingParts),
1367
+ parts: form.openingParts
1368
+ };
1369
+ await editWorldInfo(world.directory, { alternateOpenings: info.alternateOpenings.map((item, index) => index === position ? entry : item) });
1370
+ };
1371
+ if (args.form === "plain") {
1372
+ if (current.parts === void 0) return {
1373
+ target: args.target,
1374
+ form: "plain",
1375
+ changed: false,
1376
+ note: "it is already plain text"
1377
+ };
1378
+ if (hasSpeech(current.parts)) throw new Error("characters speak in this opening, so it cannot be plain text; remove their lines first");
1379
+ await write({ opening: partsText(current.parts) });
1380
+ await worlds.list({ refresh: true });
1381
+ return {
1382
+ target: args.target,
1383
+ form: "plain",
1384
+ changed: true
1385
+ };
1386
+ }
1387
+ if (current.parts !== void 0) return {
1388
+ target: args.target,
1389
+ form: "parts",
1390
+ changed: false,
1391
+ note: "it is already in parts"
1392
+ };
1393
+ const language = prompting.languages().get(world.id);
1394
+ const ctx = contextOf(exec, settings(), (id, variables) => prompting.prompts().text(id, language, variables), language);
1395
+ const cast = (await loadCharacters(world.directory)).characters.map((character) => ({
1396
+ id: character.id,
1397
+ name: character.name,
1398
+ aliases: character.aliases ?? []
1399
+ }));
1400
+ const shaped = await shapeOpening(ctx, current.text, cast);
1401
+ if (shaped.parts === void 0) return {
1402
+ target: args.target,
1403
+ form: "parts",
1404
+ changed: false,
1405
+ note: shaped.note ?? "no character speaks in it, so it stays plain text"
1406
+ };
1407
+ await write({ openingParts: shaped.parts });
1408
+ await worlds.list({ refresh: true });
1409
+ return {
1410
+ target: args.target,
1411
+ form: "parts",
1412
+ changed: true,
1413
+ parts: shaped.parts
1414
+ };
1415
+ }
1416
+ })];
1417
+ }
1253
1418
  // src/host/checks/tools.ts
1254
1419
  const output = {
1255
1420
  schema: { type: "json" },
@@ -1399,6 +1564,7 @@ function apply(ctx) {
1399
1564
  for (const tool of cardTools(ctx.roleplayWorlds)) ctx.tools.register(tool);
1400
1565
  for (const tool of updateTools(ctx.roleplayWorlds)) ctx.tools.register(tool);
1401
1566
  for (const tool of presetTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1567
+ for (const tool of openingTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1402
1568
  for (const tool of translateTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1403
1569
  for (const tool of checkTools(reader, {
1404
1570
  settings: () => ctx.roleplayImport.settings,
@@ -382,10 +382,30 @@ const SUBMIT_RULE = `When you are done, call ${SUBMIT_TOOL} with your result. It
382
382
  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.";
383
383
  /** A child ran out of the time it was given; asking again would only spend it again. */
384
384
  var ChildTimeoutError = class extends Error {
385
+ failure;
385
386
  constructor(minutes) {
386
387
  super(`the agent was stopped after ${minutes} minute${minutes === 1 ? "" : "s"} without a result (a model that keeps thinking never answers: lower its thinking level, or raise the limit in the settings)`);
388
+ this.failure = {
389
+ key: "timeout",
390
+ minutes
391
+ };
392
+ }
393
+ };
394
+ var ChildResultError = class extends Error {
395
+ failure;
396
+ constructor(message, failure) {
397
+ super(message);
398
+ this.failure = failure;
387
399
  }
388
400
  };
401
+ function activityFailure(error) {
402
+ if (error instanceof ChildTimeoutError || error instanceof ChildResultError) return error.failure;
403
+ if (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") return { key: "answeredInThinking" };
404
+ return {
405
+ key: "unexpected",
406
+ message: error instanceof Error ? error.message : String(error)
407
+ };
408
+ }
389
409
  /**
390
410
  * 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)
391
411
  * is let produce that with room to spare, no more than the chat's ceiling for its kind.
@@ -422,7 +442,7 @@ function childTrace(store, kind, label, extra = {}, named, cause) {
422
442
  turn: run.turn,
423
443
  tokens: run.tokens,
424
444
  ...(run.requests ?? []).length === 0 ? {} : { requests: run.requests },
425
- ...run.error === void 0 ? {} : { error: run.error.slice(0, 300) },
445
+ ...run.error === void 0 ? {} : { error: run.error },
426
446
  ...id === void 0 ? {} : { run: id }
427
447
  }, keep ? {
428
448
  ...run.detail,
@@ -522,7 +542,7 @@ async function runChild(asked) {
522
542
  task.trace?.({
523
543
  ms: Date.now() - began,
524
544
  calls: stats.calls,
525
- error: error instanceof Error ? error.message : String(error),
545
+ error: activityFailure(error),
526
546
  detail: detail(),
527
547
  turn: turnAtStart,
528
548
  tokens: stats.tokens ?? NO_TOKENS,
@@ -605,11 +625,17 @@ function repairedJson(text, accepts = () => true) {
605
625
  }
606
626
  /** A constrained result was returned only as reasoning, leaving the answer empty. */
607
627
  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";
628
+ /** A reply that a model wrapped in a code fence, without the fence: the opening one and the closing one at the end. */
629
+ function unfenced(text) {
630
+ const open = text.startsWith("```json") ? 7 : text.startsWith("```") ? 3 : 0;
631
+ const body = text.slice(open).trimEnd();
632
+ return (body.endsWith("```") ? body.slice(0, -3) : body).trim();
633
+ }
608
634
  /** The result in the last reply of a structured child: its JSON, which must fit the schema; else what is wrong with it. */
609
635
  function structuredReply(child, schema, cut = false) {
610
636
  const message = child.session.snapshotEvents().findLast((event) => event.type === "assistant/message");
611
637
  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, "");
638
+ const text = unfenced(content.flatMap((block) => block.type === "text" ? [block.text] : []).join("").trim());
613
639
  if (text === "") return { problem: content.some((block) => block.type === "reasoning" && block.text.trim() !== "") ? ANSWERED_IN_THINKING : "the reply is empty" };
614
640
  let value;
615
641
  try {
@@ -946,18 +972,46 @@ async function execute(task, stats) {
946
972
  }
947
973
  });
948
974
  }
949
- if (signal.aborted) throw new Error("cancelled");
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`);
975
+ if (signal.aborted) throw new ChildResultError("cancelled", { key: "cancelled" });
976
+ if (rambled && submitted === void 0) {
977
+ const limit = task.maxTokens ?? task.sampling?.maxTokens;
978
+ throw new ChildResultError(limit === void 0 ? `the agent wrote text up to the limit of its model and never called ${SUBMIT_TOOL}, and was stopped` : `the agent wrote text up to the limit of ${limit} tokens and never called ${SUBMIT_TOOL}, and was stopped`, {
979
+ key: "tokenLimit",
980
+ ...limit === void 0 ? {} : { limit },
981
+ tool: SUBMIT_TOOL
982
+ });
983
+ }
951
984
  if (hidden && submitted === void 0) throw new Error(ANSWERED_IN_THINKING);
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`);
985
+ if (overran && submitted === void 0) {
986
+ if (refusals >= 5) throw new ChildResultError(`the result was refused ${refusals} times and the agent was stopped; the last reason: ${lastRefusal}`, {
987
+ key: "resultRefused",
988
+ count: refusals,
989
+ reason: lastRefusal
990
+ });
991
+ const failed = stats.record.findLast((call) => call.failed && call.tool !== "submit_result");
992
+ throw new ChildResultError(`the agent went on past its ${budget} calls, or kept repeating a call that failed, without submitting a result and was stopped${failed === void 0 ? "" : ` The last call that failed was ${failed.tool}: ${failed.outcome.slice(0, 300)}`}`, {
993
+ key: "callLimit",
994
+ budget,
995
+ ...failed === void 0 ? {} : {
996
+ tool: failed.tool,
997
+ outcome: failed.outcome.slice(0, 300)
998
+ }
999
+ });
1000
+ }
953
1001
  if (submitted === void 0) {
954
1002
  const ended = entry.agent?.session.snapshotEvents().findLast((event) => event.type === "turn/end");
955
1003
  const reason = ended?.type === "turn/end" ? ended.data.reason : void 0;
956
- if (reason?.kind === "error") throw new Error(`the agent failed: ${reason.error.message}`);
957
- throw new Error(`the agent stopped without submitting a result (${stats.calls} call(s))`);
1004
+ if (reason?.kind === "error") throw new ChildResultError(`the agent failed: ${reason.error.message}`, {
1005
+ key: "agentFailed",
1006
+ message: reason.error.message
1007
+ });
1008
+ throw new ChildResultError(`the agent stopped without submitting a result (${stats.calls} call(s))`, {
1009
+ key: "noResult",
1010
+ calls: stats.calls
1011
+ });
958
1012
  }
959
1013
  return submitted.value;
960
1014
  }
961
1015
  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 };
962
1016
 
963
- //# sourceMappingURL=child-DTdY14S9.js.map
1017
+ //# sourceMappingURL=child-SMvjNsb8.js.map