@dsh-agentic-roleplay/core 0.12.4 → 0.12.6

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 (31) hide show
  1. package/lib/{access-Csp80TFX.js → access-5vtPAT3O.js} +2 -2
  2. package/lib/{authoring-tools-B_qYKK8c.js → authoring-tools-BpkpGMSO.js} +21 -14
  3. package/lib/authoring.js +8 -8
  4. package/lib/{child-DTdY14S9.js → child-Bfj7-Iuo.js} +73 -21
  5. package/lib/client.js +1688 -1213
  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-Bu6eZMKk.js → gallery-D0h0X7Jy.js} +3 -3
  10. package/lib/{generator-CTWQWbSW.js → generator-CAJkevKl.js} +2 -2
  11. package/lib/helper.js +2 -2
  12. package/lib/{hooks-YXQZ9G2d.js → hooks-P_--KSFl.js} +67 -28
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +70 -18
  15. package/lib/{jail-DVbPSC0R.js → jail-D83JnxKg.js} +2 -2
  16. package/lib/{library-BmlHNCah.js → library-CnWOHwQl.js} +3 -3
  17. package/lib/{lorebook-author-tools-C3rRpMt7.js → lorebook-author-tools-CWZ6WRN-.js} +7 -7
  18. package/lib/lorebook-authoring.js +5 -5
  19. package/lib/{narration--K2XVIHI.js → narration-DAHmte8p.js} +2 -2
  20. package/lib/orchestration.js +37 -38
  21. package/lib/{pack-jail-VbcXiukr.js → pack-jail-DSTyLhMc.js} +15 -15
  22. package/lib/{packs-CzVh2ZNe.js → packs-D9_N8kDF.js} +2 -2
  23. package/lib/{presenter-agent-CF3fneuJ.js → presenter-agent-BTpJxmGi.js} +7 -6
  24. package/lib/{preset-C595KRUM.js → preset-B69AXtip.js} +4 -4
  25. package/lib/{preset-author-tools-CF_JKKTE.js → preset-author-tools-BJtt7D0J.js} +7 -7
  26. package/lib/preset-authoring.js +5 -5
  27. package/lib/{reflection-ByIQSOKC.js → reflection-2uzE3U-v.js} +9 -9
  28. package/lib/{serial-ULGUKWsu.js → serial-DnVqMDe5.js} +114 -25
  29. package/lib/{text-hiKTooVb.js → text-B-HsLdb-.js} +2 -1
  30. package/lib/{turn-guard-DXMeAJdv.js → turn-guard-D4YHE00t.js} +3 -3
  31. package/package.json +31 -31
@@ -1,4 +1,4 @@
1
- import { j as roleplaySessionOf } from "./child-DTdY14S9.js";
1
+ import { j as roleplaySessionOf } from "./child-Bfj7-Iuo.js";
2
2
  import { basename, dirname, join } from "node:path";
3
3
  import { chmodSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
4
  import { randomUUID } from "node:crypto";
@@ -183,4 +183,4 @@ function promptFor(agent, id, language, variables) {
183
183
  }
184
184
  export { VARIABLE_KINDS as a, atomicWriteSync as i, atomicWrite as n, VARIABLE_SUBJECTS as o, atomicWriteJson as r, VARIABLE_VISIBILITIES as s, promptFor as t };
185
185
 
186
- //# sourceMappingURL=access-Csp80TFX.js.map
186
+ //# sourceMappingURL=access-5vtPAT3O.js.map
@@ -1,10 +1,10 @@
1
- import { T as currentTurn, c as namedModel, l as runChild, m as parseSampling, t as ChildTimeoutError } from "./child-DTdY14S9.js";
2
- import { $t as LOCATION_FILE_NAME, At as openingText, C as ROLE_TABLE, Ct as itemise, E as askYesNo, Et as IMPORT_FOLDER, Gt as dialectOf, Ht as importRequestOf, Jt as loadVariables, L as parseOpeningParts, M as WORLD_FILE_NAME, Mt as readImportFolder, N as parseWorldFile, P as MAX_OPENING_CHARS, Pt as InvalidEditProblems, Qt as parseLoreFile, R as partsText, S as ROLES, St as cleanText, Tt as withPlayer, Ut as findPanel, V as startQuestionsToFile, Vt as IMPORT_COMMAND, Wt as splitPanels, Xt as variableProblems, Zt as LORE_FILE_NAME, _ as pruneRelationships, a as characterDocument, an as FACTION_FILE_NAME, b as classifyItems, bt as loadLore, c as extractStyle, cn as parseCharacterFile, d as inert, en as parseLocationFile, f as loreDocuments, fn as WEEKDAY_NAMES, g as pruneMembers, h as pruneLoreSubjects, i as asWritten, in as parseSlotsFile, j as yesAt, k as noAt, kt as PICTURE_FILE, ln as guarded, m as pruneLinks, nn as SLOTS_FILE_NAME, o as emptyExtracted, on as parseFactionFile, p as pruneKnowledge, pn as DEFAULT_SLOTS, qt as VARIABLES_FILE_NAME, r as addLore, rn as parseItemFile, s as extractEntities, sn as CHARACTER_FILE_NAME, t as SerialQueue, tn as ITEM_FILE_NAME, u as extractVariables, v as sourcesFor, w as isLeftOut, x as findEntity, xt as subfolders, y as buildRoster, yt as LORE_DIR } from "./serial-ULGUKWsu.js";
3
- import { f as parseSwitchboard } from "./narration--K2XVIHI.js";
4
- import { n as atomicWrite, r as atomicWriteJson } from "./access-Csp80TFX.js";
5
- import { $ as copyWorldPrompts, G as readDocument$1, J as errorMessage, K as Reader, U as commandFlagKey, V as plotReferenceProblems, Z as PROMPTS_FOLDER, c as externalWithheld, ht as registerCommands, it as shippedLanguages, lt as InvalidWorldError, nt as listFiles, o as externalGiven, ot as shippedText, q as formatIssue, rt as promptProblem, t as externalToolLimit, xt as COMPARISONS, z as loadPlots } from "./hooks-YXQZ9G2d.js";
6
- import { t as trimCharacters } from "./text-hiKTooVb.js";
7
- import { C as slug, S as norm, T as uniqueKey, _ as writeImageFileMetadata, b as NoEmbeddingService, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as trOf, x as mapLimit } from "./library-BmlHNCah.js";
1
+ import { T as currentTurn, c as namedModel, l as runChild, m as parseSampling, t as ChildTimeoutError } from "./child-Bfj7-Iuo.js";
2
+ import { $t as LOCATION_FILE_NAME, At as openingText, C as ROLE_TABLE, Ct as itemise, E as askYesNo, Et as IMPORT_FOLDER, Gt as dialectOf, Ht as importRequestOf, Jt as loadVariables, L as parseOpeningParts, M as WORLD_FILE_NAME, Mt as readImportFolder, N as parseWorldFile, P as MAX_OPENING_CHARS, Pt as InvalidEditProblems, Qt as parseLoreFile, R as partsText, S as ROLES, St as cleanText, Tt as withPlayer, Ut as findPanel, V as startQuestionsToFile, Vt as IMPORT_COMMAND, Wt as splitPanels, Xt as variableProblems, Zt as LORE_FILE_NAME, _ as pruneRelationships, a as characterDocument, an as FACTION_FILE_NAME, b as classifyItems, bt as loadLore, c as extractStyle, cn as parseCharacterFile, d as inert, en as parseLocationFile, f as loreDocuments, fn as WEEKDAY_NAMES, g as pruneMembers, h as pruneLoreSubjects, i as asWritten, in as parseSlotsFile, j as yesAt, k as noAt, kt as PICTURE_FILE, ln as guarded, m as pruneLinks, nn as SLOTS_FILE_NAME, o as emptyExtracted, on as parseFactionFile, p as pruneKnowledge, pn as DEFAULT_SLOTS, qt as VARIABLES_FILE_NAME, r as addLore, rn as parseItemFile, s as extractEntities, sn as CHARACTER_FILE_NAME, t as SerialQueue, tn as ITEM_FILE_NAME, u as extractVariables, v as sourcesFor, w as isLeftOut, x as findEntity, xt as subfolders, y as buildRoster, yt as LORE_DIR } from "./serial-DnVqMDe5.js";
3
+ import { f as parseSwitchboard } from "./narration-DAHmte8p.js";
4
+ import { n as atomicWrite, r as atomicWriteJson } from "./access-5vtPAT3O.js";
5
+ import { $ as copyWorldPrompts, G as readDocument$1, J as errorMessage, K as Reader, U as commandFlagKey, V as plotReferenceProblems, Z as PROMPTS_FOLDER, c as externalWithheld, ht as registerCommands, it as shippedLanguages, lt as InvalidWorldError, nt as listFiles, o as externalGiven, ot as shippedText, q as formatIssue, rt as promptProblem, t as externalToolLimit, xt as COMPARISONS, z as loadPlots } from "./hooks-P_--KSFl.js";
6
+ import { t as trimCharacters } from "./text-B-HsLdb-.js";
7
+ import { C as slug, S as norm, T as uniqueKey, _ as writeImageFileMetadata, b as NoEmbeddingService, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as trOf, x as mapLimit } from "./library-CnWOHwQl.js";
8
8
  import { join, relative, sep } from "node:path";
9
9
  import { MINUTE, MONTH_NAMES, SEASONS, checkProblems, createSessionStore, dayTokenProblems, lintWorld, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, writeCalendar } from "@dsh-agentic-roleplay/state";
10
10
  import { createHash } from "node:crypto";
@@ -581,17 +581,24 @@ async function extractCasting(ctx, card, passages) {
581
581
  const MAX_EXAMPLES = 8;
582
582
  /** The summary is the start of the description: a sentence or two. */
583
583
  const SUMMARY_CHARS = 280;
584
+ /** A line an example speaks through: a short name, a colon, and what the character says. */
585
+ function spoken(line) {
586
+ const colon = line.indexOf(":");
587
+ if (colon < 1 || colon > 100) return void 0;
588
+ return {
589
+ name: line.slice(0, colon),
590
+ utterance: line.slice(colon + 1).trimStart()
591
+ };
592
+ }
584
593
  /** The lines of the example messages that the character speaks, as written; the markers of the tool that wrote them are taken out. */
585
594
  function exampleLines(text, name) {
586
595
  const lines = cleanText(text, name).split("\n").map((line) => line.trim()).filter((line) => line !== "");
587
- const speaker = /^([^:\n]{1,100}):\s*(.*)$/;
588
- if (!lines.some((line) => speaker.test(line))) return lines.slice(0, MAX_EXAMPLES);
596
+ if (!lines.some((line) => spoken(line) !== void 0)) return lines.slice(0, MAX_EXAMPLES);
589
597
  const names = new Set([name, name.split(/\s+/)[0] ?? ""].map((part) => part.toLocaleLowerCase()));
590
598
  return lines.flatMap((line) => {
591
- const match = speaker.exec(line);
592
- if (match?.[1] === void 0 || !names.has(match[1].trim().toLocaleLowerCase())) return [];
593
- const utterance = match[2]?.trim();
594
- return utterance === void 0 || utterance === "" ? [] : [utterance];
599
+ const match = spoken(line);
600
+ if (match === void 0 || !names.has(match.name.trim().toLocaleLowerCase())) return [];
601
+ return match.utterance === "" ? [] : [match.utterance];
595
602
  }).slice(0, MAX_EXAMPLES);
596
603
  }
597
604
  /**
@@ -6495,4 +6502,4 @@ function limitAuthoringAgents(ctx, kindOf) {
6495
6502
  }
6496
6503
  export { checkWorld as $, authoringChatSessionId as $t, loadWorldParts as A, lettersOf$1 as At, localChanges as B, loadCommands as Bt, cardChanges as C, loadDice as Ct, worldFieldChanges as D, parseCalendarFile as Dt, pictureChange as E, loadCalendar as Et, editsSince as F, cardTools as Ft, addressesToFetch as G, cardFormat as Gt, writeOrigin as H, TRIGGERS_FILE_NAME as Ht, writeSnapshot as I, entitiesByPiece as It, guardedLookup as J, readCard as Jt, candidateUrls as K, isPng as Kt, describeChanges as L, readSource as Lt, CHECK_COMMANDS as M, UPDATE_FOLDER as Mt, CHECK_COMMAND_DESCRIPTIONS as N, baseId as Nt, editWorldInfo as O, CHARACTERS_DIR as Ot, recordProvenance as P, cardPieces as Pt, writePortrait as Q, authoredWorldOf as Qt, hashWorld as R, COMMANDS_FILE_NAME as Rt, addressChanges as S, DICE_FILE_NAME as St, matchPieces as T, CALENDAR_FILE_NAME as Tt, CatalogueError as U, loadTriggers as Ut, readOrigin as V, parseCommandsFile as Vt, addressKey as W, ImportCardError as Wt, vetUrl as X, DICE_READINGS as Xt, mergeReports as Y, DICE_COMPARISONS as Yt, cardCharacter as Z, DICE_RESULTS as Zt, structureImport as _, loadLocations as _t, beginImport as a, populateClock as at, CHECKS as b, FACTIONS_DIR as bt, importTextFor as c, populateItems as ct, knownOutputCeiling as d, populateLore as dt, loadValidatedWorld as et, importPhase as f, populateRoutines as ft, settleDraft as g, LOCATIONS_DIR as gt, markReady as h, routineProblems as ht, ImportState as i, populateCharacters as it, loadCardEvidence as j, shapeOpening as jt, readWorldInfo as k, loadCharacters as kt, importTools as l, populateKnowledge as lt, keepDraft as m, populateVariables as mt, limitAuthoringAgents as n, knowsCharacter as nt, contextOf as o, populateDice as ot, isReviewing as p, populateTriggers as pt, fetchPictures as q, pictureOf as qt, MAX_PREVIEW_TEXT as r, populateCalendar as rt, importHooks as s, populateFactions as st, AuthoringTools as t, withScratchStory as tt, worldOf as u, populateLocations as ut, checkImported as v, ITEMS_DIR as vt, diffText as w, parseDiceFile as wt, runChecks as x, loadFactions as xt, presentReport as y, loadItems as yt, isUnchanged as z, commandVariable as zt };
6497
6504
 
6498
- //# sourceMappingURL=authoring-tools-B_qYKK8c.js.map
6505
+ //# sourceMappingURL=authoring-tools-BpkpGMSO.js.map
package/lib/authoring.js CHANGED
@@ -1,12 +1,12 @@
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-B_qYKK8c.js";
2
- import { t as guardAuthoringTurns } from "./turn-guard-DXMeAJdv.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-BpkpGMSO.js";
2
+ import { t as guardAuthoringTurns } from "./turn-guard-D4YHE00t.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-VbcXiukr.js";
5
- import { i as translator, r as languageOf } from "./text-hiKTooVb.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-ULGUKWsu.js";
7
- import { B as parsePlotsFile, at as shippedPromptsDirectory, ht as registerCommands, q as formatIssue } from "./hooks-YXQZ9G2d.js";
8
- import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-CzVh2ZNe.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-DSTyLhMc.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-DnVqMDe5.js";
7
+ import { B as parsePlotsFile, at as shippedPromptsDirectory, ht as registerCommands, q as formatIssue } from "./hooks-P_--KSFl.js";
8
+ import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-D9_N8kDF.js";
9
+ import "./access-5vtPAT3O.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";
@@ -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 {
@@ -901,18 +927,16 @@ async function execute(task, stats) {
901
927
  childId,
902
928
  delivery: "caller",
903
929
  signal,
904
- request: {
905
- parent,
906
- agentPreset: HELPER_PRESET,
907
- ...options === void 0 ? {} : { agentOptions: options },
908
- prompt: [{
909
- type: "text",
910
- text: task.prompt
911
- }, ...(task.images ?? []).map((attachment) => ({
912
- type: "image",
913
- attachment
914
- }))]
915
- }
930
+ parent,
931
+ agentPreset: HELPER_PRESET,
932
+ ...options === void 0 ? {} : { agentOptions: options },
933
+ prompt: [{
934
+ type: "text",
935
+ text: task.prompt
936
+ }, ...(task.images ?? []).map((attachment) => ({
937
+ type: "image",
938
+ attachment
939
+ }))]
916
940
  });
917
941
  try {
918
942
  await Promise.race([activation.result, gaveUp]);
@@ -946,18 +970,46 @@ async function execute(task, stats) {
946
970
  }
947
971
  });
948
972
  }
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`);
973
+ if (signal.aborted) throw new ChildResultError("cancelled", { key: "cancelled" });
974
+ if (rambled && submitted === void 0) {
975
+ const limit = task.maxTokens ?? task.sampling?.maxTokens;
976
+ 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`, {
977
+ key: "tokenLimit",
978
+ ...limit === void 0 ? {} : { limit },
979
+ tool: SUBMIT_TOOL
980
+ });
981
+ }
951
982
  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`);
983
+ if (overran && submitted === void 0) {
984
+ if (refusals >= 5) throw new ChildResultError(`the result was refused ${refusals} times and the agent was stopped; the last reason: ${lastRefusal}`, {
985
+ key: "resultRefused",
986
+ count: refusals,
987
+ reason: lastRefusal
988
+ });
989
+ const failed = stats.record.findLast((call) => call.failed && call.tool !== "submit_result");
990
+ 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)}`}`, {
991
+ key: "callLimit",
992
+ budget,
993
+ ...failed === void 0 ? {} : {
994
+ tool: failed.tool,
995
+ outcome: failed.outcome.slice(0, 300)
996
+ }
997
+ });
998
+ }
953
999
  if (submitted === void 0) {
954
1000
  const ended = entry.agent?.session.snapshotEvents().findLast((event) => event.type === "turn/end");
955
1001
  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))`);
1002
+ if (reason?.kind === "error") throw new ChildResultError(`the agent failed: ${reason.error.message}`, {
1003
+ key: "agentFailed",
1004
+ message: reason.error.message
1005
+ });
1006
+ throw new ChildResultError(`the agent stopped without submitting a result (${stats.calls} call(s))`, {
1007
+ key: "noResult",
1008
+ calls: stats.calls
1009
+ });
958
1010
  }
959
1011
  return submitted.value;
960
1012
  }
961
1013
  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
1014
 
963
- //# sourceMappingURL=child-DTdY14S9.js.map
1015
+ //# sourceMappingURL=child-Bfj7-Iuo.js.map