@dsh-agentic-roleplay/core 0.12.6 → 0.13.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 (46) hide show
  1. package/lib/{authoring-tools-BpkpGMSO.js → authoring-tools-CKV1UnN7.js} +1133 -139
  2. package/lib/authoring.js +340 -54
  3. package/lib/client.js +1675 -729
  4. package/lib/client.js.map +1 -1
  5. package/lib/compaction.js +2 -2
  6. package/lib/doctor.js +2 -2
  7. package/lib/{library-CnWOHwQl.js → gallery-CT5uj50b.js} +212 -7
  8. package/lib/{hooks-P_--KSFl.js → hooks-CnxV2uEh.js} +46 -17
  9. package/lib/images.js +3 -4
  10. package/lib/index.js +409 -26
  11. package/lib/{presenter-agent-BTpJxmGi.js → interpreter-Cz5qsuXk.js} +155 -64
  12. package/lib/{lorebook-author-tools-CWZ6WRN-.js → lorebook-author-tools-p3Nfpuxh.js} +6 -6
  13. package/lib/lorebook-authoring.js +5 -5
  14. package/lib/{narration-DAHmte8p.js → narration-CUZIXzab.js} +8 -2
  15. package/lib/orchestration.js +64 -19
  16. package/lib/{pack-jail-DSTyLhMc.js → pack-jail-KyZen_gy.js} +19 -13
  17. package/lib/{packs-D9_N8kDF.js → packs-DU171pDX.js} +2 -2
  18. package/lib/presenter-agent-CwDg0WE8.js +59 -0
  19. package/lib/{preset-B69AXtip.js → preset-BO8iWQ-n.js} +3 -3
  20. package/lib/{preset-author-tools-BJtt7D0J.js → preset-author-tools-C83shASm.js} +6 -6
  21. package/lib/preset-authoring.js +5 -5
  22. package/lib/{reflection-2uzE3U-v.js → reflection-CXS87Di3.js} +8 -7
  23. package/lib/{serial-DnVqMDe5.js → serial-xcAG57p_.js} +199 -43
  24. package/lib/{text-B-HsLdb-.js → text-KnqhN_Zv.js} +4 -1
  25. package/lib/{turn-guard-D4YHE00t.js → turn-guard-CfsGepCg.js} +2 -2
  26. package/package.json +3 -2
  27. package/prompts/en/import/finish-ok.md +2 -0
  28. package/prompts/en/import/next-stage-go.md +1 -0
  29. package/prompts/en/import/next-stage-paused.md +1 -0
  30. package/prompts/en/import/next-survey-paused.md +1 -0
  31. package/prompts/en/import/notice-staged.md +5 -0
  32. package/prompts/en/import/pause-stages.md +1 -0
  33. package/prompts/en/import/pause-survey.md +1 -0
  34. package/prompts/en/roleplay/image-worth.md +5 -0
  35. package/prompts/en/world/procedure.md +3 -0
  36. package/prompts/zh/import/finish-ok.md +2 -0
  37. package/prompts/zh/import/next-stage-go.md +1 -0
  38. package/prompts/zh/import/next-stage-paused.md +1 -0
  39. package/prompts/zh/import/next-survey-paused.md +1 -0
  40. package/prompts/zh/import/notice-staged.md +5 -0
  41. package/prompts/zh/import/pause-stages.md +1 -0
  42. package/prompts/zh/import/pause-survey.md +1 -0
  43. package/prompts/zh/roleplay/image-worth.md +5 -0
  44. package/prompts/zh/world/procedure.md +3 -0
  45. package/lib/gallery-D0h0X7Jy.js +0 -190
  46. package/lib/generator-CAJkevKl.js +0 -150
package/lib/compaction.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as liveSettings, t as decodeOutput } from "./narration-DAHmte8p.js";
1
+ import { i as wordsOf, o as liveSettings, t as decodeOutput } from "./narration-CUZIXzab.js";
2
2
  import { j as roleplaySessionOf, k as tokensOf, l as runChild, n as childModel, r as childSampling } from "./child-Bfj7-Iuo.js";
3
3
  import { t as promptFor } from "./access-5vtPAT3O.js";
4
4
  import { join } from "node:path";
@@ -216,7 +216,7 @@ function readFolded(messages) {
216
216
  told.push(`Player: ${text.trim()}`);
217
217
  } else if (message.role === "tool") {
218
218
  const output = decodeOutput(text);
219
- if (output !== void 0) told.push(output.segments.map((segment) => segment.type === "utterance" ? `${segment.name}: "${segment.text}"` : segment.text).join("\n"));
219
+ if (output !== void 0) told.push(wordsOf(output.segments, (segment) => `${segment.name}: "${segment.text}"`).join("\n"));
220
220
  }
221
221
  }
222
222
  return {
package/lib/doctor.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { n as silenceRuntimeContext, t as silenceHarnessDevContext } from "./dev-context-Cgv_wZbG.js";
2
2
  import { A as chatSessionId } from "./child-Bfj7-Iuo.js";
3
3
  import { n as doctorSessionOf } from "./doctor-chat-hL1a61hp.js";
4
- import { s as externalTools, t as externalToolLimit } from "./hooks-P_--KSFl.js";
5
- import { a as liveSettings } from "./narration-DAHmte8p.js";
4
+ import { s as externalTools, t as externalToolLimit } from "./hooks-CnxV2uEh.js";
5
+ import { o as liveSettings } from "./narration-CUZIXzab.js";
6
6
  import { join } from "node:path";
7
7
  import { createTools, isSessionId, sessionDatabase, sessionFolder } from "@dsh-agentic-roleplay/state";
8
8
  import { existsSync } from "node:fs";
@@ -1,9 +1,9 @@
1
1
  import { n as atomicWrite } from "./access-5vtPAT3O.js";
2
- import { i as translator, n as withoutExtension, r as languageOf, t as trimCharacters } from "./text-B-HsLdb-.js";
3
- import { dirname, extname, join } from "node:path";
2
+ import { i as translator, n as withoutExtension, r as languageOf, t as trimCharacters } from "./text-KnqhN_Zv.js";
3
+ import { dirname, extname, join, sep } from "node:path";
4
4
  import { existsSync } from "node:fs";
5
5
  import { createHash } from "node:crypto";
6
- import { copyFile, link, mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
6
+ import { copyFile, link, lstat, mkdir, readFile, readdir, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
7
7
  // src/host/import/run.ts
8
8
  /** What `ImportContext.embed` rejects with when no embedding provider is selected or loaded: the checks that would use it go without. */
9
9
  var NoEmbeddingService = class extends Error {};
@@ -333,10 +333,11 @@ function libraryName(original, extension, taken) {
333
333
  * Puts a picture into the library unless the library already holds that picture (the same image, whatever metadata the file carries), whatever it came from: an upload, an address, a generation.
334
334
  * Metadata says where it came from and that it is reusable; what it shows is not known yet, and the interpreter fills that in.
335
335
  * @param known the hashes of the library when the caller has read them (kept up to date here), to avoid reading the library again for each picture.
336
+ * @param link the address of a card the picture was downloaded for, with the ids of the card pieces that held it; written into the picture.
336
337
  * @throws {Error} when the bytes are not a PNG, JPEG, WebP or GIF image.
337
338
  * @returns its path under `images/`, and whether it was added or an equal picture was there.
338
339
  */
339
- async function addToLibraryOnce(sessionFolder, bytes, originalName, known) {
340
+ async function addToLibraryOnce(sessionFolder, bytes, originalName, known, link) {
340
341
  const extension = imageExtensionOf(bytes);
341
342
  if (extension === void 0 || MEDIA_TYPES[extension] === void 0) throw new Error("only PNG, JPEG, WebP and GIF images can be added");
342
343
  const hashes = known ?? await libraryHashes(sessionFolder);
@@ -359,7 +360,8 @@ async function addToLibraryOnce(sessionFolder, bytes, originalName, known) {
359
360
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
360
361
  originalName,
361
362
  subjects: [],
362
- tags: []
363
+ tags: [],
364
+ ...link === void 0 ? {} : { cardLinks: [link] }
363
365
  });
364
366
  const path = `${LIBRARY_FOLDER}/${name}`;
365
367
  hashes.set(hash, path);
@@ -372,6 +374,209 @@ async function addToLibraryOnce(sessionFolder, bytes, originalName, known) {
372
374
  async function addToLibrary(sessionFolder, bytes, originalName) {
373
375
  return (await addToLibraryOnce(sessionFolder, bytes, originalName)).path;
374
376
  }
375
- export { slug as C, norm as S, uniqueKey as T, writeImageFileMetadata as _, LIBRARY_FOLDER as a, NoEmbeddingService as b, nextSceneSerial as c, sceneImagePath as d, writeImage as f, sidecarOf as g, readImageFileMetadata as h, libraryHashes as i, readImageMetadata as l, mediaTypeOf as m, addToLibraryOnce as n, entityImageDirectory as o, MEDIA_TYPES as p, imageExtensionOf as r, inheritImages as s, addToLibrary as t, referenceImagePath as u, readPngMetadata as v, trOf as w, mapLimit as x, withPngMetadata as y };
377
+ // src/host/images/gallery.ts
378
+ const READ_AT_ONCE = 8;
379
+ const SEGMENT = /^[\p{L}\p{N}][\p{L}\p{N}\p{M}._-]{0,199}$/u;
380
+ const CACHE_FILE = ".index.json";
381
+ const CACHE_VERSION = 1;
382
+ /** The images of the folder: every PNG, and the other raster formats inside the library, whose metadata is beside them. */
383
+ async function imageFiles(images, prefix = "") {
384
+ let entries;
385
+ try {
386
+ entries = await readdir(join(images, prefix), { withFileTypes: true });
387
+ } catch (error) {
388
+ if (error.code === "ENOENT") return [];
389
+ throw error;
390
+ }
391
+ const found = [];
392
+ for (const entry of entries) {
393
+ if (entry.isSymbolicLink()) continue;
394
+ const path = `${prefix}${entry.name}`;
395
+ if (entry.isDirectory()) found.push(...await imageFiles(images, `${path}/`));
396
+ else if (entry.isFile() && (entry.name.toLowerCase().endsWith(".png") || path.startsWith(`library/`) && mediaTypeOf(entry.name) !== void 0)) found.push(path);
397
+ }
398
+ return found;
399
+ }
400
+ async function factsOf(images, path) {
401
+ const file = join(images, ...path.split("/"));
402
+ const info = await lstat(file);
403
+ const beside = path.toLowerCase().endsWith(".png") ? void 0 : await stat(sidecarOf(file)).then((value) => value.mtimeMs, () => 0);
404
+ return {
405
+ path,
406
+ signature: `${info.mtimeMs}:${info.size}:${beside ?? ""}`
407
+ };
408
+ }
409
+ async function describe(images, path) {
410
+ const file = join(images, ...path.split("/"));
411
+ const { mtime } = await lstat(file);
412
+ const library = path.startsWith(`${LIBRARY_FOLDER}/`);
413
+ const metadata = await readImageFileMetadata(file);
414
+ if (metadata === void 0 || typeof metadata !== "object") return library ? {
415
+ path,
416
+ purpose: "uploaded",
417
+ origin: "uploaded",
418
+ reusable: true,
419
+ createdAt: mtime.toISOString(),
420
+ tags: [],
421
+ subjects: [],
422
+ pending: true
423
+ } : {
424
+ path,
425
+ purpose: path.startsWith("scenes/") ? "transient" : "reference",
426
+ origin: "generated",
427
+ reusable: false,
428
+ createdAt: mtime.toISOString(),
429
+ tags: [],
430
+ subjects: [],
431
+ unreadable: true
432
+ };
433
+ const origin = metadata.origin ?? (library ? "uploaded" : "generated");
434
+ const purpose = metadata.purpose ?? (origin === "uploaded" ? "uploaded" : path.startsWith("scenes/") ? "transient" : "reference");
435
+ return {
436
+ path,
437
+ purpose,
438
+ origin,
439
+ reusable: origin === "uploaded" ? true : metadata.reusable ?? purpose === "reference",
440
+ createdAt: metadata.createdAt ?? mtime.toISOString(),
441
+ ...metadata.prompt === void 0 ? {} : { prompt: metadata.prompt },
442
+ ...metadata.revisedPrompt === void 0 ? {} : { revisedPrompt: metadata.revisedPrompt },
443
+ ...metadata.description === void 0 ? {} : { description: metadata.description },
444
+ tags: metadata.tags ?? [],
445
+ ...metadata.provider === void 0 ? {} : { provider: metadata.provider },
446
+ ...metadata.model === void 0 ? {} : { model: metadata.model },
447
+ subjects: (metadata.subjects ?? []).map((subject) => ({
448
+ kind: subject.kind,
449
+ name: subject.name
450
+ })),
451
+ ...metadata.source === void 0 ? {} : { source: metadata.source },
452
+ ...metadata.originalName === void 0 ? {} : { originalName: metadata.originalName },
453
+ ...metadata.cardLinks === void 0 || metadata.cardLinks.length === 0 ? {} : { cardLinks: metadata.cardLinks },
454
+ ...origin === "uploaded" && metadata.description === void 0 ? { pending: true } : {}
455
+ };
456
+ }
457
+ async function describeGalleryImage(sessionFolder, path) {
458
+ return await describe(join(sessionFolder, "images"), path);
459
+ }
460
+ async function readCache(images) {
461
+ try {
462
+ const cache = JSON.parse(await readFile(join(images, CACHE_FILE), "utf8"));
463
+ if (cache.version === CACHE_VERSION && typeof cache.entries === "object" && cache.entries !== null) return cache;
464
+ } catch {}
465
+ return {
466
+ version: CACHE_VERSION,
467
+ entries: {}
468
+ };
469
+ }
470
+ async function writeCache(images, cache) {
471
+ await atomicWrite(join(images, CACHE_FILE), JSON.stringify(cache), { createDirectory: true });
472
+ }
473
+ /**
474
+ * Every image of a session folder with what its file says, newest first. The files are the truth; `images/.index.json` only remembers what
475
+ * was read from each, keyed by its size and time, so that a listing reads just the files that are new or changed. It can be deleted at any time.
476
+ */
477
+ async function listGallery(sessionFolder) {
478
+ const images = join(sessionFolder, "images");
479
+ const paths = await imageFiles(images);
480
+ if (paths.length === 0) return [];
481
+ const cache = await readCache(images);
482
+ const facts = await mapLimit(paths, READ_AT_ONCE, (path) => factsOf(images, path));
483
+ const entries = {};
484
+ let changed = Object.keys(cache.entries).length !== paths.length;
485
+ const described = await mapLimit(facts, READ_AT_ONCE, async ({ path, signature }) => {
486
+ const known = cache.entries[path];
487
+ if (known?.signature === signature) {
488
+ entries[path] = known;
489
+ return known.image;
490
+ }
491
+ changed = true;
492
+ const image = await describe(images, path);
493
+ entries[path] = {
494
+ signature,
495
+ image
496
+ };
497
+ return image;
498
+ });
499
+ if (changed) await writeCache(images, {
500
+ version: CACHE_VERSION,
501
+ entries
502
+ });
503
+ return described.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.path.localeCompare(b.path));
504
+ }
505
+ /**
506
+ * The file of a gallery image by its path, which must be one the listing gives: a raster image inside the session's images, not reached through a link.
507
+ * @throws {Error} when the path names no such image.
508
+ */
509
+ async function galleryFile(sessionFolder, path) {
510
+ const parts = path.split("/");
511
+ const mediaType = mediaTypeOf(path);
512
+ if (parts.length === 0 || mediaType === void 0 || mediaType !== "image/png" && parts[0] !== "library" || parts.some((part) => !SEGMENT.test(part) || part === "." || part === "..")) throw new Error("there is no such image");
513
+ const images = join(sessionFolder, "images");
514
+ const file = join(images, ...parts);
515
+ const info = await lstat(file).catch(() => void 0);
516
+ if (info === void 0 || !info.isFile()) throw new Error("there is no such image");
517
+ if (!(await realpath(file)).startsWith(`${await realpath(images)}${sep}`)) throw new Error("there is no such image");
518
+ return {
519
+ file,
520
+ size: info.size,
521
+ mediaType
522
+ };
523
+ }
524
+ /** Notes one more address a picture of the library came from, or more pieces of the card for an address it already has. */
525
+ async function addCardLink(sessionFolder, path, link) {
526
+ const { file } = await galleryFile(sessionFolder, path);
527
+ const existing = await readImageFileMetadata(file);
528
+ if (existing === void 0) return;
529
+ const links = [...existing.cardLinks ?? []];
530
+ const at = links.findIndex((entry) => entry.url === link.url);
531
+ if (at < 0) links.push({
532
+ url: link.url,
533
+ pieces: [...link.pieces]
534
+ });
535
+ else links[at] = {
536
+ url: link.url,
537
+ pieces: [.../* @__PURE__ */ new Set([...links[at].pieces, ...link.pieces])]
538
+ };
539
+ await writeImageFileMetadata(file, {
540
+ ...existing,
541
+ cardLinks: links
542
+ });
543
+ }
544
+ /**
545
+ * Changes what an image says about itself, in the file. An image the person brought is always reusable.
546
+ * @throws {Error} when the path names no image of the session, or an uploaded image is made not reusable.
547
+ */
548
+ async function updateImage(sessionFolder, path, update) {
549
+ const { file } = await galleryFile(sessionFolder, path);
550
+ const current = await describe(join(sessionFolder, "images"), path);
551
+ if (update.reusable === false && current.origin === "uploaded") throw new Error("an image you brought is always reusable: otherwise it would only sit there");
552
+ const existing = await readImageFileMetadata(file);
553
+ await writeImageFileMetadata(file, {
554
+ schema: "dsh-roleplay-image/v3",
555
+ purpose: current.purpose,
556
+ origin: current.origin,
557
+ reusable: current.reusable,
558
+ createdAt: current.createdAt,
559
+ tags: current.tags,
560
+ subjects: current.subjects.map((subject) => ({
561
+ kind: subject.kind,
562
+ localId: subject.name,
563
+ name: subject.name
564
+ })),
565
+ ...existing,
566
+ schema: "dsh-roleplay-image/v3",
567
+ origin: current.origin,
568
+ ...update.description === void 0 ? {} : { description: update.description },
569
+ ...update.tags === void 0 ? {} : { tags: update.tags },
570
+ ...update.subjects === void 0 ? {} : { subjects: update.subjects.map((subject) => ({
571
+ kind: subject.kind,
572
+ localId: subject.name,
573
+ name: subject.name
574
+ })) },
575
+ ...update.reusable === void 0 ? {} : { reusable: update.reusable },
576
+ ...update.interpretedBy === void 0 ? {} : { interpretedBy: update.interpretedBy }
577
+ });
578
+ return await describe(join(sessionFolder, "images"), path);
579
+ }
580
+ export { mapLimit as C, uniqueKey as D, trOf as E, NoEmbeddingService as S, slug as T, MEDIA_TYPES as _, updateImage as a, readPngMetadata as b, imageExtensionOf as c, inheritImages as d, nextSceneSerial as f, writeImage as g, sceneImagePath as h, listGallery as i, libraryHashes as l, referenceImagePath as m, describeGalleryImage as n, addToLibrary as o, readImageMetadata as p, galleryFile as r, addToLibraryOnce as s, addCardLink as t, entityImageDirectory as u, readImageFileMetadata as v, norm as w, withPngMetadata as x, writeImageFileMetadata as y };
376
581
 
377
- //# sourceMappingURL=library-CnWOHwQl.js.map
582
+ //# sourceMappingURL=gallery-CT5uj50b.js.map
@@ -1,7 +1,7 @@
1
1
  import { C as addTokens, D as finishOf, E as cutOff, O as estimateAnswer, S as NO_TOKENS, a as childTrace, b as estimateTokens, f as tracerOf, j as roleplaySessionOf, l as runChild, n as childModel, r as childSampling, u as TurnTraces, v as requestsOf, x as tokensOf, y as blockText } from "./child-Bfj7-Iuo.js";
2
- import { _ as emptyStats, a as liveSettings, h as DECISION_SITES, m as rulesOf, n as encodeOutput, p as WORLD_RULES_KEY, r as encodePreview } from "./narration-DAHmte8p.js";
2
+ import { g as DECISION_SITES, h as rulesOf, m as WORLD_RULES_KEY, n as encodeOutput, o as liveSettings, r as encodePreview, v as emptyStats } from "./narration-CUZIXzab.js";
3
3
  import { t as promptFor } from "./access-5vtPAT3O.js";
4
- import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-B-HsLdb-.js";
4
+ import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-KnqhN_Zv.js";
5
5
  import { n as storyRoots } from "./service-mRKwpWjX.js";
6
6
  import { dirname, join } from "node:path";
7
7
  import { DAY, ENGAGEMENT_GRACE, ITEM_ACTIONS, MINUTE, SECOND, addLocalDays, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, clockTime, createCharacterTools, createDiceTools, createTools, dayPart, describeDuration, describeInstant, describeValue, holidaysOn, inAudience, isSessionId, itemKey, localTime, locationKey, mentioned, nextOccurrence, nextTimeOfDay, occurrenceAt, overlap, parseInstant, planItemChange, planVariableChange, readCalendar, rollPlain, seasonOf, sessionDatabase, sessionFolder, shownVariables, tokens } from "@dsh-agentic-roleplay/state";
@@ -469,10 +469,6 @@ function inheritPrompts(from, to) {
469
469
  function shippedLanguages(shipped = shippedPromptsDirectory()) {
470
470
  return readdirSync(shipped, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
471
471
  }
472
- // src/host/errors.ts
473
- function errorMessage(error) {
474
- return error instanceof Error ? error.message : String(error);
475
- }
476
472
  // src/host/validation.ts
477
473
  function formatIssue({ path, message }) {
478
474
  return path === "" ? message : `${path}: ${message}`;
@@ -640,6 +636,10 @@ var Reader = class Reader {
640
636
  return this.path === "" ? key : key === "" ? this.path : `${this.path}.${key}`;
641
637
  }
642
638
  };
639
+ // src/host/errors.ts
640
+ function errorMessage(error) {
641
+ return error instanceof Error ? error.message : String(error);
642
+ }
643
643
  // src/host/read-document.ts
644
644
  /** Authored documents are short; a larger file is not one. */
645
645
  const MAX_DOCUMENT_BYTES = 1048576;
@@ -1574,6 +1574,7 @@ const exactUtterances = {
1574
1574
  let latest = 0;
1575
1575
  segments.forEach((segment, index) => {
1576
1576
  const at = `segment ${index + 1}`;
1577
+ if (segment.type === "image") return;
1577
1578
  if (segment.type === "narration") {
1578
1579
  if (segment.text.trim() === "") problems.push(`${at}: the narration is empty`);
1579
1580
  return;
@@ -1601,6 +1602,7 @@ const exactUtterances = {
1601
1602
  const used = /* @__PURE__ */ new Set();
1602
1603
  const kept = [];
1603
1604
  for (const segment of segments) {
1605
+ if (segment.type === "image") continue;
1604
1606
  if (segment.type === "narration") {
1605
1607
  if (segment.text.trim() !== "") kept.push({
1606
1608
  segment,
@@ -4561,32 +4563,59 @@ function worldCommands(intents, defined) {
4561
4563
  }
4562
4564
  // src/host/agents/repeat-guard.ts
4563
4565
  /**
4564
- * Keeps an agent that is stuck from making the same call again and again (found live: an assistant made one create-and-list pair 47 times in a review, a game master repeated one
4565
- * refused round resolution): past `limit` identical calls in one turn the call is refused with a word that sends it on, and when it goes on regardless the turn is ended. The count starts over at the first step of every turn.
4566
+ * Keeps an agent that is stuck from going on (found live: an assistant made one create-and-list pair 47 times in a review, a game master repeated one refused round resolution,
4567
+ * a review read entry 132, 133 ... 4000 of a card that has fewer):
4568
+ * - past `limit` identical calls in one turn the call is refused with a word that sends it on;
4569
+ * - past `FAILING_RUN` failures of one tool in a row, with whatever arguments, the tool is refused for the rest of the turn;
4570
+ * - when the model goes on regardless the turn is ended.
4571
+ * The counts start over at the first step of every turn.
4566
4572
  * @param languageOf the language of the chat the call belongs to, or nothing when the guard does not apply to it.
4567
4573
  */
4568
4574
  function guardRepeatedCalls(ctx, languageOf, limit) {
4569
- const calls = /* @__PURE__ */ new Map();
4575
+ const chats = /* @__PURE__ */ new Map();
4570
4576
  ctx.on("agent/pre-step", async (payload, next) => {
4571
- if (payload.step === 1) calls.delete(payload.agent.session.id);
4577
+ if (payload.step === 1) chats.delete(payload.agent.session.id);
4572
4578
  return await next();
4573
4579
  });
4574
4580
  ctx.on("tools/pre-execute", async (exec, next) => {
4575
4581
  const chat = exec.agent?.session.id;
4576
4582
  const language = chat === void 0 || exec.agent?.session.header.origin === "subagent" ? void 0 : languageOf(exec);
4577
4583
  if (chat === void 0 || language === void 0) return await next();
4584
+ const state = chats.get(chat) ?? {
4585
+ calls: /* @__PURE__ */ new Map(),
4586
+ failures: /* @__PURE__ */ new Map(),
4587
+ refused: 0
4588
+ };
4589
+ chats.set(chat, state);
4590
+ const tr = translator(languageOf$1(language));
4591
+ const failing = state.failures.get(exec.name) ?? 0;
4592
+ if (failing >= 6) {
4593
+ state.refused += 1;
4594
+ if (state.refused > 5) exec.agent?.cancel({ kind: "user" }, { keepInbox: true });
4595
+ return {
4596
+ kind: "deny",
4597
+ reason: tr("`{tool}` failed {count} times in a row in this turn, with different arguments each time, so guessing more will not work. Do not call it again this turn: use another tool to find what you need (a search or an overview), or finish and say what is left.", {
4598
+ tool: exec.name,
4599
+ count: failing
4600
+ })
4601
+ };
4602
+ }
4578
4603
  const signature = `${exec.name}:${JSON.stringify(exec.arguments)}`;
4579
- const seen = calls.get(chat) ?? /* @__PURE__ */ new Map();
4580
- calls.set(chat, seen);
4581
- const count = (seen.get(signature) ?? 0) + 1;
4582
- seen.set(signature, count);
4604
+ const count = (state.calls.get(signature) ?? 0) + 1;
4605
+ state.calls.set(signature, count);
4583
4606
  if (count <= limit) return await next();
4584
4607
  if (count > limit + 5) exec.agent?.cancel({ kind: "user" }, { keepInbox: true });
4585
4608
  return {
4586
4609
  kind: "deny",
4587
- reason: translator(languageOf$1(language))("This exact call was already made {count} times in this turn with the same result. Do not repeat it: go on with the next step, or finish and say what is left.", { count: count - 1 })
4610
+ reason: tr("This exact call was already made {count} times in this turn with the same result. Do not repeat it: go on with the next step, or finish and say what is left.", { count: count - 1 })
4588
4611
  };
4589
4612
  }, { prepend: true });
4613
+ ctx.on("tools/result", (exec, result) => {
4614
+ const state = exec.agent === void 0 ? void 0 : chats.get(exec.agent.session.id);
4615
+ if (state === void 0) return;
4616
+ const failures = result.isError ? (state.failures.get(exec.name) ?? 0) + 1 : 0;
4617
+ state.failures.set(exec.name, failures);
4618
+ });
4590
4619
  }
4591
4620
  // src/host/orchestration/runaway.ts
4592
4621
  /** The levels of thinking that mean none, as models name them. */
@@ -5047,6 +5076,6 @@ function installHooks(ctx, deps) {
5047
5076
  };
5048
5077
  });
5049
5078
  }
5050
- export { copyWorldPrompts as $, plotProgressOf as A, parsePlotsFile as B, readNotes as C, referent as D, sameWords as E, textLanguage as F, readDocument as G, COMMANDS_KEY as H, wrongLanguage as I, errorMessage as J, Reader as K, readUsage as L, LANGUAGE_NAMES as M, STORY_LANGUAGES as N, RESULTS as O, isStoryLanguage as P, PromptLibrary as Q, PLOTS_FILE_NAME as R, notesOfSession as S, defaultBoundaries as T, commandFlagKey as U, plotReferenceProblems as V, commandsOf as W, LANGUAGE_TAG as X, LANGUAGE_FOLDER as Y, PROMPTS_FOLDER as Z, readTraces as _, ClockError as _t, MAX_OOC_ANSWER as a, shippedPromptsDirectory as at, readWithdrawn as b, AUTHORING_NEEDS as bt, externalWithheld as c, InvalidStartError as ct, record as d, SessionArchivedError as dt, inheritPrompts as et, toolEnabled as f, SessionNotFoundError as ft, readRunDetail as g, runCommandLine as gt, readActivity as h, registerCommands as ht, characterRunner as i, shippedLanguages as it, populatePlots as j, PLOTS_METADATA_KEY as k, PREVIEW_TOOL as l, InvalidWorldError as lt, readDecisionStats as m, CommandRefusedError as mt, installHooks as n, listFiles as nt, externalGiven as o, shippedText as ot, storesOf as p, WorldNotFoundError as pt, formatIssue as q, guardRepeatedCalls as r, promptProblem as rt, externalTools as s, AgentUnavailableError as st, externalToolLimit as t, languageOf as tt, createTools$1 as u, ReflectionRefusedError as ut, readVerdicts as v, describeWhen as vt, observeAsPlayer as w, addToNote as x, COMPARISONS as xt, writeVerdicts as y, zoneOf as yt, loadPlots as z };
5079
+ export { copyWorldPrompts as $, plotProgressOf as A, parsePlotsFile as B, readNotes as C, referent as D, sameWords as E, textLanguage as F, readDocument as G, COMMANDS_KEY as H, wrongLanguage as I, formatIssue as J, errorMessage as K, readUsage as L, LANGUAGE_NAMES as M, STORY_LANGUAGES as N, RESULTS as O, isStoryLanguage as P, PromptLibrary as Q, PLOTS_FILE_NAME as R, notesOfSession as S, defaultBoundaries as T, commandFlagKey as U, plotReferenceProblems as V, commandsOf as W, LANGUAGE_TAG as X, LANGUAGE_FOLDER as Y, PROMPTS_FOLDER as Z, readTraces as _, ClockError as _t, MAX_OOC_ANSWER as a, shippedPromptsDirectory as at, readWithdrawn as b, AUTHORING_NEEDS as bt, externalWithheld as c, InvalidStartError as ct, record as d, SessionArchivedError as dt, inheritPrompts as et, toolEnabled as f, SessionNotFoundError as ft, readRunDetail as g, runCommandLine as gt, readActivity as h, registerCommands as ht, characterRunner as i, shippedLanguages as it, populatePlots as j, PLOTS_METADATA_KEY as k, PREVIEW_TOOL as l, InvalidWorldError as lt, readDecisionStats as m, CommandRefusedError as mt, installHooks as n, listFiles as nt, externalGiven as o, shippedText as ot, storesOf as p, WorldNotFoundError as pt, Reader as q, guardRepeatedCalls as r, promptProblem as rt, externalTools as s, AgentUnavailableError as st, externalToolLimit as t, languageOf as tt, createTools$1 as u, ReflectionRefusedError as ut, readVerdicts as v, describeWhen as vt, observeAsPlayer as w, addToNote as x, COMPARISONS as xt, writeVerdicts as y, zoneOf as yt, loadPlots as z };
5051
5080
 
5052
- //# sourceMappingURL=hooks-P_--KSFl.js.map
5081
+ //# sourceMappingURL=hooks-CnxV2uEh.js.map
package/lib/images.js CHANGED
@@ -1,5 +1,4 @@
1
- import { a as searchImages, c as presentedFor, n as interpretImage, o as tokensOf, r as imageTools, s as present, t as runImagePresenter } from "./presenter-agent-BTpJxmGi.js";
2
- import { i as updateImage, r as listGallery } from "./gallery-D0h0X7Jy.js";
3
- import { c as nextSceneSerial, d as sceneImagePath, l as readImageMetadata, o as entityImageDirectory, s as inheritImages, t as addToLibrary, u as referenceImagePath, v as readPngMetadata, y as withPngMetadata } from "./library-CnWOHwQl.js";
4
- import { i as transientPrompt, n as generateTransientImage, r as referencePrompt, t as generateReferenceImage } from "./generator-CAJkevKl.js";
1
+ import { t as runImagePresenter } from "./presenter-agent-CwDg0WE8.js";
2
+ import { a as searchImages, c as presentedFor, d as referencePrompt, f as transientPrompt, l as generateReferenceImage, n as interpretImage, o as tokensOf, r as imageTools, s as present, u as generateTransientImage } from "./interpreter-Cz5qsuXk.js";
3
+ import { a as updateImage, b as readPngMetadata, d as inheritImages, f as nextSceneSerial, h as sceneImagePath, i as listGallery, m as referenceImagePath, o as addToLibrary, p as readImageMetadata, u as entityImageDirectory, x as withPngMetadata } from "./gallery-CT5uj50b.js";
5
4
  export { addToLibrary, entityImageDirectory, generateReferenceImage, generateTransientImage, imageTools, inheritImages, interpretImage, listGallery, nextSceneSerial, present, presentedFor, readImageMetadata, readPngMetadata, referenceImagePath, referencePrompt, runImagePresenter, sceneImagePath, searchImages, tokensOf, transientPrompt, updateImage, withPngMetadata };