@dsh-agentic-roleplay/core 0.1.0 → 0.1.1

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 (55) hide show
  1. package/lib/{notes-CJzbN_-E.js → activity-BbqFG9-3.js} +35 -9
  2. package/lib/authoring.js +3 -3
  3. package/lib/client.js +880 -372
  4. package/lib/client.js.map +1 -1
  5. package/lib/compaction.js +1 -1
  6. package/lib/{documents-BBq88wXP.js → documents-ZVoUTnD2.js} +54 -33
  7. package/lib/{gallery-CjG9_4Sz.js → gallery-KGCdeCnM.js} +2 -2
  8. package/lib/{generator-pxZS-pu-.js → generator-NYnNdpWb.js} +100 -9
  9. package/lib/images.js +3 -3
  10. package/lib/index.js +220 -15
  11. package/lib/{narration-tYy6Rkfr.js → narration-DcnCqA1l.js} +20 -3
  12. package/lib/orchestration.js +510 -82
  13. package/lib/{presenter-agent-DbZALurg.js → presenter-agent-7j1c7QEz.js} +3 -3
  14. package/lib/{worlds-Bj-EGS_i.js → worlds-DYgjdH8O.js} +28 -2
  15. package/package.json +3 -2
  16. package/prompts/en/roleplay/faction-strategist.md +5 -0
  17. package/prompts/en/roleplay/trigger-judge.md +3 -0
  18. package/prompts/zh/roleplay/faction-strategist.md +5 -0
  19. package/prompts/zh/roleplay/trigger-judge.md +3 -0
  20. package/starter-worlds/blackwater-observatory/characters/arthur-moore/character.json +65 -0
  21. package/starter-worlds/blackwater-observatory/characters/clara-whitlock/character.json +87 -0
  22. package/starter-worlds/blackwater-observatory/characters/eleanor-graves/character.json +80 -0
  23. package/starter-worlds/blackwater-observatory/characters/marcus-reed/character.json +73 -0
  24. package/starter-worlds/blackwater-observatory/items/anonymous-letter/item.json +9 -0
  25. package/starter-worlds/blackwater-observatory/items/brass-laboratory-key/item.json +10 -0
  26. package/starter-worlds/blackwater-observatory/items/claras-gossip-notebook/item.json +9 -0
  27. package/starter-worlds/blackwater-observatory/items/harlans-notebook/item.json +10 -0
  28. package/starter-worlds/blackwater-observatory/items/investigators-coat/item.json +10 -0
  29. package/starter-worlds/blackwater-observatory/items/investigators-notebook/item.json +9 -0
  30. package/starter-worlds/blackwater-observatory/items/locked-filing-cabinet/item.json +10 -0
  31. package/starter-worlds/blackwater-observatory/items/marcus-calibration-notes/item.json +9 -0
  32. package/starter-worlds/blackwater-observatory/items/mayors-administrative-seal/item.json +9 -0
  33. package/starter-worlds/blackwater-observatory/items/municipal-lockbox/item.json +10 -0
  34. package/starter-worlds/blackwater-observatory/items/pocket-revolver/item.json +10 -0
  35. package/starter-worlds/blackwater-observatory/items/room-7-cash-receipt/item.json +9 -0
  36. package/starter-worlds/blackwater-observatory/items/rusting-mine-cart/item.json +10 -0
  37. package/starter-worlds/blackwater-observatory/items/signal-recording-strip/item.json +9 -0
  38. package/starter-worlds/blackwater-observatory/items/silver-pocket-watch/item.json +9 -0
  39. package/starter-worlds/blackwater-observatory/items/survey-archive-cabinet/item.json +10 -0
  40. package/starter-worlds/blackwater-observatory/items/surveyors-map/item.json +10 -0
  41. package/starter-worlds/blackwater-observatory/items/unknown-visitors-note-fragment/item.json +10 -0
  42. package/starter-worlds/blackwater-observatory/locations/blackwater-ridge/location.json +5 -0
  43. package/starter-worlds/blackwater-observatory/locations/iron-stag-bar/location.json +30 -0
  44. package/starter-worlds/blackwater-observatory/locations/iron-stag-room-7/location.json +18 -0
  45. package/starter-worlds/blackwater-observatory/locations/north-forest-cabin/location.json +18 -0
  46. package/starter-worlds/blackwater-observatory/locations/observatory-directors-office/location.json +20 -0
  47. package/starter-worlds/blackwater-observatory/locations/observatory-telescope-chamber/location.json +25 -0
  48. package/starter-worlds/blackwater-observatory/locations/old-mine-entrance/location.json +27 -0
  49. package/starter-worlds/blackwater-observatory/locations/old-mine-main-tunnel/location.json +13 -0
  50. package/starter-worlds/blackwater-observatory/locations/town-hall-mayors-office/location.json +25 -0
  51. package/starter-worlds/blackwater-observatory/locations/town-hall-records-room/location.json +13 -0
  52. package/starter-worlds/blackwater-observatory/locations/town-square/location.json +30 -0
  53. package/starter-worlds/blackwater-observatory/triggers.json +20 -0
  54. package/starter-worlds/blackwater-observatory/variables.json +39 -0
  55. package/starter-worlds/blackwater-observatory/world.json +27 -0
@@ -1,18 +1,19 @@
1
1
  import { n as roleplaySessionOf, t as chatSessionId } from "./chat-AKrVcWIC.js";
2
- import { a as liveSettings, f as WORLD_RULES_KEY, n as encodeOutput, p as rulesOf, r as encodePreview } from "./narration-tYy6Rkfr.js";
3
- import { i as parsePlotsFile, t as API_PREFIX, y as shippedText } from "./worlds-Bj-EGS_i.js";
4
- import { C as slug, D as runChild, T as childSampling, a as addToLibrary, w as uniqueKey } from "./generator-pxZS-pu-.js";
5
- import { C as readTime, S as endRound, T as zoneOf, _ as sameWords, a as readNotes, b as describeTime, c as describePacingAdvice, h as Timelines, i as putNote, l as pacingAdvice, n as clearNotes, p as updatePlotProgress, s as addSessionPlot, t as addToNote, u as plotAuthorNeeded, v as ClockError, w as skipTime, x as describeWhen, y as beginTurn } from "./notes-CJzbN_-E.js";
6
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-CjG9_4Sz.js";
2
+ import { D as INTENT_STATUSES, i as parsePlotsFile, t as API_PREFIX, y as shippedText } from "./worlds-DYgjdH8O.js";
3
+ import { a as liveSettings, f as WORLD_RULES_KEY, n as encodeOutput, p as rulesOf, r as encodePreview } from "./narration-DcnCqA1l.js";
4
+ import "./src-CWTNeL6Y.js";
5
+ import { A as runChild, D as childSampling, E as childModel, T as uniqueKey, k as childTrace, o as addToLibrary, w as slug } from "./generator-NYnNdpWb.js";
6
+ import { C as describeWhen, D as zoneOf, E as skipTime, S as describeTime, T as readTime, _ as Timelines, b as ClockError, d as pacingAdvice, f as plotAuthorNeeded, h as updatePlotProgress, i as clearNotes, l as addSessionPlot, n as recordActivity, o as putNote, r as addToNote, s as readNotes, u as describePacingAdvice, w as endRound, x as beginTurn, y as sameWords } from "./activity-BbqFG9-3.js";
7
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-KGCdeCnM.js";
7
8
  import { t as promptFor } from "./access-C1nFQiyT.js";
8
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-DbZALurg.js";
9
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-7j1c7QEz.js";
9
10
  import { join } from "node:path";
10
11
  import { existsSync } from "node:fs";
11
12
  import { SessionId } from "@deepseek-ai/dsh-session";
12
13
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
13
14
  import { defineTool } from "@deepseek-ai/dsh-tools";
14
15
  import { readdir } from "node:fs/promises";
15
- import { ENGAGEMENT_GRACE, ITEM_ACTIONS, InvalidEditError, MINUTE, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, characterKey, createCharacterTools, createTools, dayPart, describeDuration, describeHolder, describeInstant, describeValue, inAudience, itemKey, lintWorld, localTime, locationKey, mentioned, nextOccurrence, occurrenceAt, parseInstant, parseRecordsEdit, planItemChange, planVariableChange, sessionDatabase, sessionFolder, shownVariables } from "@dsh-agentic-roleplay/state";
16
+ import { ENGAGEMENT_GRACE, ITEM_ACTIONS, InvalidEditError, MINUTE, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, characterKey, createCharacterTools, createTools, dayPart, describeDuration, describeHolder, describeInstant, describeValue, inAudience, itemKey, judgedStatements, lintWorld, localTime, locationKey, mentioned, nextOccurrence, occurrenceAt, parseInstant, parseRecordsEdit, planItemChange, planVariableChange, sessionDatabase, sessionFolder, shownVariables } from "@dsh-agentic-roleplay/state";
16
17
  //#region src/host/orchestration/committer.ts
17
18
  /** What the keeper reads back by default: the parts of the records its edits write. */
18
19
  const VERIFY_SECTIONS = [
@@ -86,7 +87,7 @@ function describePrompt(job, memory) {
86
87
  ...records.open_threads.length === 0 ? ["- none"] : records.open_threads.map((thread) => `- id ${thread.id}: ${thread.text}`)
87
88
  ].join("\n");
88
89
  }
89
- const RESULT$2 = {
90
+ const RESULT$4 = {
90
91
  type: "object",
91
92
  properties: {
92
93
  complete: {
@@ -186,10 +187,12 @@ function recordKeeper(deps) {
186
187
  signal,
187
188
  reasoningEffort: job.store.settings().reasoning.children,
188
189
  sampling: childSampling(job.store.settings(), "records"),
190
+ ...childModel(job.store.settings(), "records"),
191
+ trace: childTrace(job.store, "records", "record keeper"),
189
192
  persona: promptFor(parent, "roleplay/record-keeper", job.store.settings().prompts.language),
190
193
  prompt: describePrompt(job, memory),
191
194
  tools: keeperTools(job, memory, progress),
192
- result: RESULT$2,
195
+ result: RESULT$4,
193
196
  beforeSubmit: () => {
194
197
  if (progress.edits === 0 && !warned) {
195
198
  warned = true;
@@ -218,7 +221,7 @@ function suggestionProblems(lines, wanted) {
218
221
  const tidySuggestions = (lines) => lines.map((line) => line.trim().replace(/\s+/g, " "));
219
222
  //#endregion
220
223
  //#region src/host/orchestration/suggester.ts
221
- const RESULT$1 = {
224
+ const RESULT$3 = {
222
225
  type: "object",
223
226
  properties: { options: {
224
227
  type: "array",
@@ -253,9 +256,11 @@ function suggestionWriter(deps) {
253
256
  signal,
254
257
  reasoningEffort: job.store.settings().reasoning.children,
255
258
  sampling: childSampling(job.store.settings(), "suggestions"),
259
+ ...childModel(job.store.settings(), "suggestions"),
260
+ trace: childTrace(job.store, "suggestions", "suggestions"),
256
261
  persona: promptFor(parent, "roleplay/suggester", job.store.settings().prompts.language, { max: 200 }),
257
262
  prompt: promptOf(job),
258
- result: RESULT$1,
263
+ result: RESULT$3,
259
264
  beforeSubmit: (value) => {
260
265
  const problems = suggestionProblems(tidySuggestions(value.options), job.count);
261
266
  return problems.length === 0 ? void 0 : `not acceptable: ${problems.join("; ")}`;
@@ -265,6 +270,317 @@ function suggestionWriter(deps) {
265
270
  } };
266
271
  }
267
272
  //#endregion
273
+ //#region src/host/triggers/judged.ts
274
+ const KEY = "triggers.judged";
275
+ function readVerdicts(session) {
276
+ const stored = session.metadata.getValue(KEY);
277
+ if (typeof stored !== "object" || stored === null || Array.isArray(stored)) return {};
278
+ const verdicts = {};
279
+ for (const [statement, value] of Object.entries(stored)) {
280
+ const verdict = value;
281
+ if (typeof verdict === "object" && verdict !== null && typeof verdict.holds === "boolean" && typeof verdict.turn === "number") verdicts[statement] = {
282
+ holds: verdict.holds,
283
+ turn: verdict.turn
284
+ };
285
+ }
286
+ return verdicts;
287
+ }
288
+ /** Keeps the verdicts of the given statements as they stand and drops every other: a statement no trigger waits on is no longer judged. */
289
+ function writeVerdicts(session, verdicts, keep) {
290
+ session.metadata.setValue(KEY, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
291
+ }
292
+ /** For `runTriggers`: a statement is true when its last verdict says so, and false when nobody judged it. */
293
+ const verdictReader = (session) => {
294
+ const verdicts = readVerdicts(session);
295
+ return (statement) => verdicts[statement]?.holds === true;
296
+ };
297
+ //#endregion
298
+ //#region src/host/triggers/judge.ts
299
+ const RESULT$2 = {
300
+ type: "object",
301
+ properties: { verdicts: {
302
+ type: "array",
303
+ items: {
304
+ type: "object",
305
+ properties: {
306
+ number: {
307
+ type: "integer",
308
+ description: "The number of the statement, as listed."
309
+ },
310
+ holds: { type: "boolean" },
311
+ reason: {
312
+ type: "string",
313
+ description: "A short reason that points at what you were shown."
314
+ }
315
+ },
316
+ required: [
317
+ "number",
318
+ "holds",
319
+ "reason"
320
+ ],
321
+ additionalProperties: false
322
+ },
323
+ description: "One verdict for each statement."
324
+ } },
325
+ required: ["verdicts"],
326
+ additionalProperties: false
327
+ };
328
+ /** The statements of the triggers still waiting, each once. */
329
+ function waitingStatements(job) {
330
+ return [...new Set(job.store.story.triggers.list({ status: "dormant" }).flatMap((trigger) => judgedStatements(trigger.condition)))];
331
+ }
332
+ function brief$1(job, statements) {
333
+ const events = job.store.story.events.list().slice(-15).map((event) => `- ${event.text}`);
334
+ const cast = job.store.cast().map((member) => `- ${member.character.name}${member.place === void 0 ? "" : ` (at ${member.place.location.name})`}${member.state === void 0 ? "" : `: ${[member.state.publicState, member.state.activity].filter((text) => text !== "").join("; ")}`}`);
335
+ return [
336
+ "Statements to judge:",
337
+ ...statements.map((statement, index) => `${index + 1}. ${statement}`),
338
+ `Recorded events, the latest last:\n${events.join("\n") || "- none yet"}`,
339
+ `Where everyone is and what they are doing:\n${cast.join("\n") || "- nobody"}`
340
+ ].join("\n\n");
341
+ }
342
+ /**
343
+ * After a turn, has a model say whether the statements that triggers wait on hold now, for no more than `triggers.judgedPerTurn` of them, the
344
+ * longest unjudged first, in one request. The verdicts are stored; a trigger fires from them at the next look, like from any other condition.
345
+ */
346
+ function triggerJudge(deps) {
347
+ return { async judge(job, signal) {
348
+ const { judgedPerTurn } = job.store.settings().triggers;
349
+ const waiting = waitingStatements(job);
350
+ const verdicts = readVerdicts(job.store.story);
351
+ writeVerdicts(job.store.story, verdicts, new Set(waiting));
352
+ if (judgedPerTurn === 0 || waiting.length === 0) return { judged: 0 };
353
+ const statements = [...waiting].sort((a, b) => (verdicts[a]?.turn ?? -1) - (verdicts[b]?.turn ?? -1)).slice(0, judgedPerTurn);
354
+ const parent = deps.agentOf(job.chat);
355
+ if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
356
+ const store = job.store;
357
+ const answer = await runChild({
358
+ parent,
359
+ signal,
360
+ reasoningEffort: store.settings().reasoning.children,
361
+ sampling: childSampling(store.settings(), "records"),
362
+ ...childModel(store.settings(), "records"),
363
+ trace: childTrace(store, "records", "trigger judge"),
364
+ persona: promptFor(parent, "roleplay/trigger-judge", store.settings().prompts.language),
365
+ prompt: brief$1(job, statements),
366
+ result: RESULT$2,
367
+ beforeSubmit: (value) => {
368
+ const numbers = value.verdicts.map((verdict) => verdict.number);
369
+ const missing = statements.flatMap((_, index) => numbers.includes(index + 1) ? [] : [index + 1]);
370
+ return missing.length === 0 ? void 0 : `judge every statement: ${missing.join(", ")} ${missing.length === 1 ? "has" : "have"} no verdict`;
371
+ },
372
+ maxCalls: 3
373
+ });
374
+ const next = readVerdicts(store.story);
375
+ for (const verdict of answer.verdicts) {
376
+ const statement = statements[verdict.number - 1];
377
+ if (statement !== void 0) next[statement] = {
378
+ holds: verdict.holds,
379
+ turn: job.turn
380
+ };
381
+ }
382
+ writeVerdicts(store.story, next, new Set(waiting));
383
+ return { judged: answer.verdicts.length };
384
+ } };
385
+ }
386
+ //#endregion
387
+ //#region src/host/factions/strategist.ts
388
+ const LAST_KEY = "strategy.last";
389
+ const DAY_MS = 864e5;
390
+ /** Rounds numbered from here belong to what organisations did, as off-stage rounds have their own range. */
391
+ const STRATEGY_ROUND = 200;
392
+ const MAX_ACTIVE_GOALS = 8;
393
+ const MAX_TEXT = 400;
394
+ const keyOf$1 = (faction) => faction.sourceId ?? String(faction.id);
395
+ function lastActed(session) {
396
+ const stored = session.metadata.getValue(LAST_KEY);
397
+ return typeof stored === "object" && stored !== null && !Array.isArray(stored) ? Object.fromEntries(Object.entries(stored).filter((entry) => typeof entry[1] === "number")) : {};
398
+ }
399
+ /**
400
+ * The organisations whose time has come: they have a goal in hand, and `everyDays` of story time have passed since they last decided.
401
+ * One seen for the first time starts its clock now and is not due yet. Longest waiting first.
402
+ */
403
+ function dueFactions(session, now, everyDays) {
404
+ const last = lastActed(session);
405
+ const due = [];
406
+ for (const faction of session.factions.list()) {
407
+ const key = keyOf$1(faction);
408
+ if (last[key] === void 0) {
409
+ last[key] = now;
410
+ continue;
411
+ }
412
+ if (now - last[key] < everyDays * DAY_MS) continue;
413
+ if (session.factionIntents.list(faction.id, { status: "active" }).length === 0) continue;
414
+ due.push({
415
+ faction,
416
+ since: last[key]
417
+ });
418
+ }
419
+ session.metadata.setValue(LAST_KEY, last);
420
+ return due.sort((a, b) => a.since - b.since).map((entry) => entry.faction);
421
+ }
422
+ function markActed(session, faction, now) {
423
+ session.metadata.setValue(LAST_KEY, {
424
+ ...lastActed(session),
425
+ [keyOf$1(faction)]: now
426
+ });
427
+ }
428
+ const RESULT$1 = {
429
+ type: "object",
430
+ properties: {
431
+ summary: {
432
+ type: "string",
433
+ description: "One concrete thing the organisation does in this time, in the past tense, in one or two sentences; or that it waits, and why."
434
+ },
435
+ public_state: {
436
+ type: "string",
437
+ description: "Its public state afterwards, only when outsiders could see it change."
438
+ },
439
+ inner_state: {
440
+ type: "string",
441
+ description: "Its private state afterwards, only when its inner position moved."
442
+ },
443
+ goal_updates: {
444
+ type: "array",
445
+ items: {
446
+ type: "object",
447
+ properties: {
448
+ id: {
449
+ type: "integer",
450
+ description: "The number of the goal, as listed."
451
+ },
452
+ status: {
453
+ type: "string",
454
+ enum: [...INTENT_STATUSES]
455
+ }
456
+ },
457
+ required: ["id", "status"],
458
+ additionalProperties: false
459
+ },
460
+ description: "Goals whose status changed."
461
+ },
462
+ new_goal: {
463
+ type: "object",
464
+ properties: {
465
+ name: { type: "string" },
466
+ description: { type: "string" },
467
+ plan: {
468
+ type: "array",
469
+ items: { type: "string" }
470
+ }
471
+ },
472
+ required: [
473
+ "name",
474
+ "description",
475
+ "plan"
476
+ ],
477
+ additionalProperties: false,
478
+ description: "At most one new goal, when the situation calls for it."
479
+ }
480
+ },
481
+ required: ["summary"],
482
+ additionalProperties: false
483
+ };
484
+ function brief(session, faction, now, zone, since) {
485
+ const state = session.factionStates.get(faction.id);
486
+ const named = (id) => session.characters.get(id)?.name ?? String(id);
487
+ const goals = session.factionIntents.list(faction.id, { status: "active" });
488
+ const members = session.factionMemberships.ofFaction(faction.id, "active").map((member) => `${named(member.characterId)} (${[member.role, member.rank].filter((part) => part !== "").join(", ") || "member"})`);
489
+ const standing = session.factionRelationships.from("faction", faction.id).map((relation) => {
490
+ return `${(relation.toKind === "faction" ? session.factions.get(relation.toId)?.name : named(relation.toId)) ?? relation.toId}: ${relation.label}${relation.summary === "" ? "" : ` - ${relation.summary}`}`;
491
+ });
492
+ const events = session.events.list().slice(-8).map((event) => `- ${event.text}`);
493
+ return [
494
+ `Organisation: ${faction.name}${faction.summary === "" ? "" : ` - ${faction.summary}`}`,
495
+ faction.description === "" ? "" : `About it: ${faction.description}`,
496
+ faction.values.length === 0 ? "" : `Values: ${faction.values.join("; ")}`,
497
+ faction.structure === "" ? "" : `Structure: ${faction.structure}`,
498
+ `Public state: ${state?.publicState || "(nothing stated)"}`,
499
+ `Private state: ${state?.innerState || "(nothing stated)"}`,
500
+ "Goals in hand:",
501
+ ...goals.map((goal) => `- ${goal.id}. ${goal.name} (${goal.type}): ${goal.description}${goal.plan.length === 0 ? "" : ` Next: ${goal.plan.join("; ")}.`}${goal.deadline === void 0 ? "" : ` By ${goal.deadline}.`}`),
502
+ members.length === 0 ? "" : `Members: ${members.join("; ")}`,
503
+ standing.length === 0 ? "" : `Its standing with others:\n${standing.map((line) => `- ${line}`).join("\n")}`,
504
+ `It is ${describeWhen(now, now, zone)} now; the organisation last decided ${describeDuration(now - since)} ago.`,
505
+ events.length === 0 ? "" : `What has happened lately:\n${events.join("\n")}`,
506
+ "Decide what the organisation does."
507
+ ].filter((line) => line !== "").join("\n");
508
+ }
509
+ function applyStrategy(job, session, faction, strategy, now) {
510
+ const active = session.factionIntents.list(faction.id, { status: "active" });
511
+ session.transaction(() => {
512
+ if (strategy.public_state !== void 0 || strategy.inner_state !== void 0) session.factionStates.update(faction.id, {
513
+ ...strategy.public_state === void 0 ? {} : { publicState: strategy.public_state.slice(0, MAX_TEXT) },
514
+ ...strategy.inner_state === void 0 ? {} : { innerState: strategy.inner_state.slice(0, MAX_TEXT) }
515
+ });
516
+ for (const update of strategy.goal_updates ?? []) if (active.some((goal) => goal.id === update.id)) session.factionIntents.update(update.id, { status: update.status });
517
+ const goal = strategy.new_goal;
518
+ const room = MAX_ACTIVE_GOALS - session.factionIntents.list(faction.id, { status: "active" }).length;
519
+ if (goal !== void 0 && goal.name.trim() !== "" && room > 0) session.factionIntents.add(faction.id, {
520
+ type: "agenda",
521
+ name: goal.name.trim().slice(0, 120),
522
+ description: goal.description.slice(0, MAX_TEXT),
523
+ status: "active",
524
+ horizon: "short",
525
+ priority: .5,
526
+ urgency: .4,
527
+ plan: goal.plan.slice(0, 6).map((step) => step.slice(0, 200)),
528
+ openThreads: [],
529
+ constraints: []
530
+ });
531
+ session.edit({
532
+ turn: job.turn,
533
+ events: [{
534
+ turn: job.turn,
535
+ round: STRATEGY_ROUND,
536
+ text: `${faction.name}: ${strategy.summary.slice(0, MAX_TEXT)}`,
537
+ importance: 3,
538
+ tags: ["faction", faction.name],
539
+ involves: [],
540
+ perceivedBy: []
541
+ }]
542
+ }, { seal: true });
543
+ });
544
+ markActed(session, faction, now);
545
+ }
546
+ /**
547
+ * Has organisations decide, one request each and one after another, what they do as story time passes. They are bounded by the chat
548
+ * (`factions.perTurn`, one decision per `factions.everyDays` of story time each), and a failure leaves the organisation as it was.
549
+ */
550
+ function factionStrategist(deps) {
551
+ return { async strategize(job, signal) {
552
+ const { perTurn, everyDays } = job.store.settings().factions;
553
+ const acted = [];
554
+ if (perTurn === 0) return { acted };
555
+ const parent = deps.agentOf(job.chat);
556
+ if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
557
+ const session = job.store.story;
558
+ const { now, zone } = job.store.time(job.turn);
559
+ const last = lastActed(session);
560
+ for (const faction of dueFactions(session, now, everyDays).slice(0, perTurn)) {
561
+ const store = job.store;
562
+ const strategy = await runChild({
563
+ parent,
564
+ signal,
565
+ reasoningEffort: store.settings().reasoning.children,
566
+ sampling: childSampling(store.settings(), "authoring"),
567
+ ...childModel(store.settings(), "authoring"),
568
+ trace: childTrace(store, "authoring", `faction ${faction.name}`),
569
+ persona: promptFor(parent, "roleplay/faction-strategist", store.settings().prompts.language),
570
+ prompt: brief(session, faction, now, zone, last[keyOf$1(faction)] ?? now),
571
+ result: RESULT$1,
572
+ maxCalls: 3
573
+ });
574
+ applyStrategy(job, session, faction, strategy, now);
575
+ acted.push({
576
+ faction: faction.name,
577
+ summary: strategy.summary
578
+ });
579
+ }
580
+ return { acted };
581
+ } };
582
+ }
583
+ //#endregion
268
584
  //#region src/host/authoring/author-agent.ts
269
585
  function authorTools(job, work, mode, limits) {
270
586
  const link = {
@@ -510,6 +826,8 @@ function worldAuthor(deps) {
510
826
  const result = await runChild({
511
827
  reasoningEffort: job.store.settings().reasoning.children,
512
828
  sampling: childSampling(job.store.settings(), "authoring"),
829
+ ...childModel(job.store.settings(), "authoring"),
830
+ trace: childTrace(job.store, "authoring", "world author"),
513
831
  parent,
514
832
  signal,
515
833
  persona: promptFor(parent, "world/author", job.store.settings().prompts.language),
@@ -547,14 +865,17 @@ function worldAuthor(deps) {
547
865
  };
548
866
  const parent = parentOf(job.chat);
549
867
  const { authoring } = job.store.settings();
868
+ const work = { created: [] };
550
869
  const result = await runChild({
551
870
  reasoningEffort: job.store.settings().reasoning.children,
552
871
  sampling: childSampling(job.store.settings(), "authoring"),
872
+ ...childModel(job.store.settings(), "authoring"),
873
+ trace: childTrace(job.store, "authoring", "world consolidation"),
553
874
  parent,
554
875
  signal,
555
876
  persona: promptFor(parent, "world/consolidate", job.store.settings().prompts.language),
556
877
  prompt: consolidationPrompt(job),
557
- tools: authorTools(job, { created: [] }, "consolidate", authoring),
878
+ tools: authorTools(job, work, "consolidate", authoring),
558
879
  result: CONSOLIDATE_RESULT,
559
880
  beforeSubmit: (value) => {
560
881
  if (!value.complete) return void 0;
@@ -585,7 +906,8 @@ function fireTriggers(session, input) {
585
906
  round,
586
907
  now,
587
908
  zone,
588
- maxFires: settings.triggers.maxFires
909
+ maxFires: settings.triggers.maxFires,
910
+ judged: verdictReader(session)
589
911
  });
590
912
  for (const failure of run.failed) problem(`the trigger "${failure.trigger.key}" could not fire and is given up: ${failure.problem}`);
591
913
  const names = new Map(session.characters.list().map((character) => [character.id, character.name]));
@@ -680,6 +1002,35 @@ function noteStore(session, settings, clock) {
680
1002
  };
681
1003
  }
682
1004
  //#endregion
1005
+ //#region src/host/orchestration/observation.ts
1006
+ /** What a character takes in where it stands and of what it carries: the place, the ways out and what they lead to, what lies in the open, what it holds. */
1007
+ function observeSurroundings(session, characterId, turn) {
1008
+ const placement = session.placements.get("character", characterId);
1009
+ if (placement !== void 0) {
1010
+ session.knowledge.learn(characterId, "location", placement.locationId, turn, true);
1011
+ for (const exit of session.locations.exitsFrom(placement.locationId)) {
1012
+ session.knowledge.learn(characterId, "exit", exit.id, turn, true);
1013
+ session.knowledge.learn(characterId, "location", exit.toId, turn);
1014
+ }
1015
+ for (const { item } of session.items.contents({
1016
+ kind: "location",
1017
+ id: placement.locationId
1018
+ })) if (!item.hidden) session.knowledge.learn(characterId, "item", item.id, turn, true);
1019
+ }
1020
+ for (const { item } of session.items.contents({
1021
+ kind: "character",
1022
+ id: characterId
1023
+ })) session.knowledge.learn(characterId, "item", item.id, turn, true);
1024
+ }
1025
+ /**
1026
+ * The player's character is never asked to act, so nothing else shows it its surroundings: it takes them in when a turn begins, which is
1027
+ * how it comes to know the way back from where it went.
1028
+ */
1029
+ function observeAsPlayer(session, turn) {
1030
+ const player = session.characters.list().find((character) => character.control === "player");
1031
+ if (player !== void 0) observeSurroundings(session, player.id, turn);
1032
+ }
1033
+ //#endregion
683
1034
  //#region src/host/clock/agenda.ts
684
1035
  const CURSOR = "agenda.cursor";
685
1036
  const ASKED = "agenda.asked";
@@ -1018,23 +1369,9 @@ function carriedBy(session, characterId) {
1018
1369
  });
1019
1370
  }
1020
1371
  function knowledgeOf(session, characterId, turn, visibleCharacters) {
1372
+ observeSurroundings(session, characterId, turn);
1021
1373
  const placement = session.placements.get("character", characterId);
1022
- if (placement !== void 0) {
1023
- session.knowledge.learn(characterId, "location", placement.locationId, turn, true);
1024
- for (const exit of session.locations.exitsFrom(placement.locationId)) {
1025
- session.knowledge.learn(characterId, "exit", exit.id, turn, true);
1026
- session.knowledge.learn(characterId, "location", exit.toId, turn);
1027
- }
1028
- for (const { item } of session.items.contents({
1029
- kind: "location",
1030
- id: placement.locationId
1031
- })) if (!item.hidden) session.knowledge.learn(characterId, "item", item.id, turn, true);
1032
- }
1033
1374
  for (const otherId of visibleCharacters ?? (placement === void 0 ? [] : session.placements.at(placement.locationId, "character").map((other) => other.entityId))) if (otherId !== characterId && session.relationships.get(characterId, otherId) === void 0) session.relationships.upsert(characterId, otherId, { label: "acquaintance" }, turn);
1034
- for (const { item } of session.items.contents({
1035
- kind: "character",
1036
- id: characterId
1037
- })) session.knowledge.learn(characterId, "item", item.id, turn, true);
1038
1375
  const locations = session.knowledge.list(characterId, "location").flatMap((entry) => {
1039
1376
  const place = session.locations.get(entry.subjectId);
1040
1377
  return place === void 0 ? [] : [`${place.name} (${locationKey(place)})`];
@@ -1233,7 +1570,10 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
1233
1570
  text: (id, variables) => prompt(settings().prompts.language, id, variables),
1234
1571
  rules: () => rulesOf(worldRules(session), settings().rules.own),
1235
1572
  time: (turn) => readTime(session, settings().clock, turn, wall()),
1236
- beginTurn: (turn) => startTurn(session, settings().clock, turn, wall()),
1573
+ beginTurn: (turn) => {
1574
+ observeAsPlayer(session, turn);
1575
+ return startTurn(session, settings().clock, turn, wall());
1576
+ },
1237
1577
  endRound: (turn, round, stated, minimum) => passRound(session, settings().clock, turn, round, wall(), stated, minimum),
1238
1578
  skipTime: (turn, round, request) => skipAhead(session, settings().clock, turn, round, wall(), request),
1239
1579
  checkVariableChanges: (changes) => changes.flatMap((spec) => {
@@ -1272,6 +1612,9 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
1272
1612
  addNote: (kind, turn, lines) => {
1273
1613
  addToNote(session, kind, turn, lines);
1274
1614
  },
1615
+ recordActivity: (entry) => {
1616
+ recordActivity(session, entry);
1617
+ },
1275
1618
  notes: () => readNotes(session),
1276
1619
  clearNotes: () => {
1277
1620
  clearNotes(session);
@@ -1342,6 +1685,25 @@ function ownerOf(agent, turn) {
1342
1685
  turn
1343
1686
  };
1344
1687
  }
1688
+ /** Where the withdrawal of an agent's preview tool is kept: on the agent, so that a reloaded plugin still finds what its earlier self registered. */
1689
+ const PREVIEW_SHOWN = Symbol.for("dsh-agentic-roleplay.preview-tool");
1690
+ /** Registers the preview tool on the agent of a chat that shows one, once, and withdraws it when the setting is turned off. */
1691
+ function previewToggle(tool) {
1692
+ return (agent, enabled) => {
1693
+ const holder = agent;
1694
+ const withdraw = holder[PREVIEW_SHOWN];
1695
+ if (enabled && withdraw === void 0) try {
1696
+ holder[PREVIEW_SHOWN] = agent.ctx.tools.register(tool);
1697
+ } catch (error) {
1698
+ if (!(error instanceof Error) || !error.message.includes("already registered")) throw error;
1699
+ holder[PREVIEW_SHOWN] = () => void 0;
1700
+ }
1701
+ else if (!enabled && withdraw !== void 0) {
1702
+ delete holder[PREVIEW_SHOWN];
1703
+ withdraw();
1704
+ }
1705
+ };
1706
+ }
1345
1707
  /**
1346
1708
  * The listeners of a roleplay preset. Preset listeners are shared by every chat
1347
1709
  * that uses the preset and also hear the agents that chat spawns, so each one
@@ -1349,15 +1711,7 @@ function ownerOf(agent, turn) {
1349
1711
  */
1350
1712
  function installHooks(ctx, deps) {
1351
1713
  const { engine, boundaries, stores, timelines, previewTool } = deps;
1352
- const shown = /* @__PURE__ */ new WeakMap();
1353
- const showPreviewTool = (agent, enabled) => {
1354
- const withdraw = shown.get(agent);
1355
- if (enabled && withdraw === void 0) shown.set(agent, agent.ctx.tools.register(previewTool));
1356
- else if (!enabled && withdraw !== void 0) {
1357
- shown.delete(agent);
1358
- withdraw();
1359
- }
1360
- };
1714
+ const showPreviewTool = previewToggle(previewTool);
1361
1715
  ctx.on("session/event", (session, event) => {
1362
1716
  if (event.type !== "turn/end" || session.header.origin === "subagent" || roleplaySessionOf(session.id) === void 0) return;
1363
1717
  timelines.ended(session.id, session, event.seq);
@@ -1583,10 +1937,13 @@ function characterRunner(deps) {
1583
1937
  parent: deps.parent,
1584
1938
  signal,
1585
1939
  sampling: childSampling(deps.store.settings(), "characters"),
1940
+ ...childModel(deps.store.settings(), "characters"),
1941
+ trace: childTrace(deps.store, "characters", request.member.character.name),
1586
1942
  reasoningEffort: deps.store.settings().reasoning.children,
1587
1943
  persona: brief.persona,
1588
1944
  prompt: brief.prompt,
1589
1945
  tools,
1946
+ maxCalls: deps.store.settings().memory.lookupCalls,
1590
1947
  result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA
1591
1948
  }));
1592
1949
  };
@@ -1708,6 +2065,8 @@ async function authorPlot(parent, store, turn, signal) {
1708
2065
  parent,
1709
2066
  signal,
1710
2067
  sampling: childSampling(store.settings(), "authoring"),
2068
+ ...childModel(store.settings(), "authoring"),
2069
+ trace: childTrace(store, "authoring", "plot author"),
1711
2070
  persona: promptFor(parent, "roleplay/plot-author", store.settings().prompts.language),
1712
2071
  reasoningEffort: store.settings().reasoning.children,
1713
2072
  result: RESULT,
@@ -2608,12 +2967,87 @@ function rerankMemories(deps) {
2608
2967
  };
2609
2968
  }
2610
2969
  //#endregion
2970
+ //#region src/host/orchestration/after-turn.ts
2971
+ /** Something made up that has waited this many turns is fitted into the world even if few are waiting. */
2972
+ const STALE_AFTER_TURNS = 4;
2973
+ const messageOf = (error) => error instanceof Error ? error.message : String(error);
2974
+ /**
2975
+ * The background work that follows a delivered turn and writes to the story, none of which the turn waits for: fitting in what was made
2976
+ * up, the decisions of organisations, and the judging of the statements triggers wait on. Each runs one at a time per chat, within the
2977
+ * limits of the chat's settings, and a failure is reported and leaves the story as it was.
2978
+ */
2979
+ var AfterTurnJobs = class {
2980
+ deps;
2981
+ consolidating = /* @__PURE__ */ new Set();
2982
+ strategizing = /* @__PURE__ */ new Set();
2983
+ judging = /* @__PURE__ */ new Set();
2984
+ constructor(deps) {
2985
+ this.deps = deps;
2986
+ }
2987
+ start(owner, cancel) {
2988
+ this.consolidate(owner, cancel);
2989
+ this.strategize(owner, cancel);
2990
+ this.judge(owner, cancel);
2991
+ }
2992
+ /** Fit what was made up into the rest of the world, when enough of it is waiting or some has waited long. */
2993
+ consolidate(owner, cancel) {
2994
+ const store = this.deps.stores(owner.chat);
2995
+ if (store === void 0 || this.consolidating.has(owner.chat)) return;
2996
+ const { authoring } = store.settings();
2997
+ const pending = store.story.consolidation.pending();
2998
+ if (!authoring.enabled || pending.length === 0) return;
2999
+ if (pending.length < authoring.consolidateAfter && !pending.some((item) => owner.turn - item.createdTurn >= STALE_AFTER_TURNS)) return;
3000
+ this.consolidating.add(owner.chat);
3001
+ this.deps.track(owner.chat, this.deps.boundaries().author.consolidate({
3002
+ chat: owner.chat,
3003
+ turn: owner.turn,
3004
+ store
3005
+ }, cancel).then(() => {
3006
+ this.deps.written(owner.chat);
3007
+ }).catch((error) => {
3008
+ if (!cancel.aborted) this.deps.problem(`made-up characters and places were not fitted into the world: ${messageOf(error)}`);
3009
+ }).finally(() => {
3010
+ this.consolidating.delete(owner.chat);
3011
+ }));
3012
+ }
3013
+ /** The organisations whose time has come decide what they do; the strategist holds the limits. */
3014
+ strategize(owner, cancel) {
3015
+ const store = this.deps.stores(owner.chat);
3016
+ if (store === void 0 || this.strategizing.has(owner.chat) || store.settings().factions.perTurn === 0) return;
3017
+ this.strategizing.add(owner.chat);
3018
+ this.deps.track(owner.chat, this.deps.boundaries().strategist.strategize({
3019
+ chat: owner.chat,
3020
+ turn: owner.turn,
3021
+ store
3022
+ }, cancel).then((report) => {
3023
+ if (report.acted.length > 0) this.deps.written(owner.chat);
3024
+ }).catch((error) => {
3025
+ if (!cancel.aborted) this.deps.problem(`organisations were not asked what they do: ${messageOf(error)}`);
3026
+ }).finally(() => {
3027
+ this.strategizing.delete(owner.chat);
3028
+ }));
3029
+ }
3030
+ /** The statements that triggers wait on are judged; a trigger fires from the verdict at the next look. */
3031
+ judge(owner, cancel) {
3032
+ const store = this.deps.stores(owner.chat);
3033
+ if (store === void 0 || this.judging.has(owner.chat) || !store.settings().triggers.enabled || store.settings().triggers.judgedPerTurn === 0) return;
3034
+ this.judging.add(owner.chat);
3035
+ this.deps.track(owner.chat, this.deps.boundaries().judge.judge({
3036
+ chat: owner.chat,
3037
+ turn: owner.turn,
3038
+ store
3039
+ }, cancel).catch((error) => {
3040
+ if (!cancel.aborted) this.deps.problem(`the statements triggers wait on were not judged: ${messageOf(error)}`);
3041
+ }).finally(() => {
3042
+ this.judging.delete(owner.chat);
3043
+ }));
3044
+ }
3045
+ };
3046
+ //#endregion
2611
3047
  //#region src/host/orchestration/turn-engine.ts
2612
3048
  const MAX_OBJECTIONS = 3;
2613
3049
  /** The most a single round may be said to take: a day. A longer time passing is skipped with `advanceTime`. */
2614
3050
  const MAX_ROUND_SECONDS = 86400;
2615
- /** Something made up that has waited this many turns is fitted into the world even if few are waiting. */
2616
- const STALE_AFTER_TURNS = 4;
2617
3051
  /** The game master is asked to correct its output this many times before it is corrected for it. */
2618
3052
  const MAX_REFUSALS = 2;
2619
3053
  /** The runs of the record keeper that may fail one after another before the rounds waiting for it are given up, so that they cannot pile up for ever. */
@@ -2640,8 +3074,7 @@ var TurnEngine = class {
2640
3074
  objections = /* @__PURE__ */ new Map();
2641
3075
  /** What runs in the background of each chat and writes to its story, other than the records: fitting in what was made up, and the characters away. */
2642
3076
  working = /* @__PURE__ */ new Map();
2643
- /** Chats whose made-up characters and places are being fitted into the world now: one run at a time. */
2644
- consolidating = /* @__PURE__ */ new Set();
3077
+ afterTurn;
2645
3078
  /** Chats whose characters away from the player are being asked about what fell due: one run at a time. */
2646
3079
  offstage = /* @__PURE__ */ new Set();
2647
3080
  constructor(boundaries, stores, problem = () => void 0, written = () => void 0) {
@@ -2649,6 +3082,19 @@ var TurnEngine = class {
2649
3082
  this.stores = stores;
2650
3083
  this.problem = problem;
2651
3084
  this.written = written;
3085
+ this.afterTurn = new AfterTurnJobs({
3086
+ boundaries: () => this.boundaries(),
3087
+ stores: (chat) => this.stores(chat),
3088
+ track: (chat, job) => {
3089
+ this.track(chat, job);
3090
+ },
3091
+ problem: (message) => {
3092
+ this.problem(message);
3093
+ },
3094
+ written: (chat) => {
3095
+ this.written(chat);
3096
+ }
3097
+ });
2652
3098
  }
2653
3099
  /**
2654
3100
  * The turn is an out-of-character command of the player: nobody is asked to act and no preview is shown. The game master rules on
@@ -3047,30 +3493,6 @@ var TurnEngine = class {
3047
3493
  return this.stores(owner.chat)?.story.consolidation.pending().length ?? 0;
3048
3494
  }
3049
3495
  /**
3050
- * Fit what was made up into the rest of the world in the background, when enough of it is waiting or some
3051
- * has waited long: the turn does not wait for it, and a failed run leaves everything queued for the next.
3052
- */
3053
- consolidateIfDue(owner, state) {
3054
- const store = this.stores(owner.chat);
3055
- if (store === void 0 || this.consolidating.has(owner.chat)) return;
3056
- const { authoring } = store.settings();
3057
- const pending = store.story.consolidation.pending();
3058
- if (!authoring.enabled || pending.length === 0) return;
3059
- if (pending.length < authoring.consolidateAfter && !pending.some((item) => owner.turn - item.createdTurn >= STALE_AFTER_TURNS)) return;
3060
- this.consolidating.add(owner.chat);
3061
- this.track(owner.chat, this.boundaries().author.consolidate({
3062
- chat: owner.chat,
3063
- turn: owner.turn,
3064
- store
3065
- }, state.cancel.signal).then(() => {
3066
- this.written(owner.chat);
3067
- }).catch((error) => {
3068
- if (!state.cancel.signal.aborted) this.problem(`made-up characters and places were not fitted into the world: ${error instanceof Error ? error.message : String(error)}`);
3069
- }).finally(() => {
3070
- this.consolidating.delete(owner.chat);
3071
- }));
3072
- }
3073
- /**
3074
3496
  * After the turn, in the background: characters away from the player's character, for whom something fell due (a commitment whose
3075
3497
  * time has come, a deadline that passed), are asked what they do about it, as many as the chat allows. What they decide is applied
3076
3498
  * (their activity, and a move to where the commitment was when they mean to keep it) and recorded as a round only they perceive;
@@ -3091,7 +3513,7 @@ var TurnEngine = class {
3091
3513
  }));
3092
3514
  }
3093
3515
  async runOffScene(owner, state, store, due, limit, run) {
3094
- const { summary, perCharacter } = store.settings().offstage;
3516
+ const { summary, perCharacter, joint } = store.settings().offstage;
3095
3517
  let budget = limit;
3096
3518
  const acted = /* @__PURE__ */ new Map();
3097
3519
  for (const item of due) {
@@ -3101,18 +3523,22 @@ var TurnEngine = class {
3101
3523
  if (keys.length === 0) continue;
3102
3524
  budget -= keys.length;
3103
3525
  for (const key of keys) acted.set(key, (acted.get(key) ?? 0) + 1);
3104
- const asked = {
3105
- ...state,
3106
- situation: item.text,
3107
- history: [],
3108
- recalled: /* @__PURE__ */ new Map()
3109
- };
3110
- delete asked.first;
3111
- delete asked.second;
3112
- const attempt = await this.runAttempt(owner, 1, keys, cast, asked, run, state.cancel.signal, summary);
3113
- if (attempt.reports.length === 0) continue;
3526
+ const reports = [];
3527
+ for (const group of joint ? keys.map((key) => [key]) : [keys]) {
3528
+ const attending = reports.filter((report) => report.commitment !== "low").map((report) => `${report.name} has decided: ${report.intent}${report.utterance === void 0 ? "" : `, saying "${report.utterance}"`}.`);
3529
+ const asked = {
3530
+ ...state,
3531
+ situation: attending.length === 0 ? item.text : `${item.text}\n${attending.join("\n")}`,
3532
+ history: [],
3533
+ recalled: /* @__PURE__ */ new Map()
3534
+ };
3535
+ delete asked.first;
3536
+ delete asked.second;
3537
+ reports.push(...(await this.runAttempt(owner, 1, group, cast, asked, run, state.cancel.signal, summary)).reports);
3538
+ }
3539
+ if (reports.length === 0) continue;
3114
3540
  const where = item.place;
3115
- const moves = new Map(attempt.reports.flatMap((report) => {
3541
+ const moves = new Map(reports.flatMap((report) => {
3116
3542
  if (report.commitment === "low" || where === void 0) return [];
3117
3543
  const check = store.checkMove(report.character, {
3118
3544
  location: where,
@@ -3120,7 +3546,7 @@ var TurnEngine = class {
3120
3546
  });
3121
3547
  return check.ok ? [[report.character, check]] : [];
3122
3548
  }));
3123
- store.commit(attempt.reports.flatMap((report) => {
3549
+ store.commit(reports.flatMap((report) => {
3124
3550
  const member = cast.find((candidate) => candidate.key === report.character);
3125
3551
  const move = moves.get(report.character);
3126
3552
  return member === void 0 ? [] : [{
@@ -3141,7 +3567,7 @@ var TurnEngine = class {
3141
3567
  to: time.now,
3142
3568
  zone: time.zone
3143
3569
  },
3144
- entries: attempt.reports.map((report) => {
3570
+ entries: reports.map((report) => {
3145
3571
  const at = cast.find((candidate) => candidate.key === report.character)?.place?.location;
3146
3572
  const move = moves.get(report.character);
3147
3573
  return {
@@ -3163,7 +3589,7 @@ var TurnEngine = class {
3163
3589
  store.markHandled([item.key]);
3164
3590
  this.write(owner, state);
3165
3591
  if (summary && this.states.get(owner.chat) === state) {
3166
- const lines = attempt.reports.flatMap((report) => report.account === void 0 ? [] : [report.account]);
3592
+ const lines = reports.flatMap((report) => report.account === void 0 ? [] : [report.account]);
3167
3593
  store.addNote("away", owner.turn, lines);
3168
3594
  }
3169
3595
  }
@@ -3741,7 +4167,7 @@ var TurnEngine = class {
3741
4167
  this.suggestAfter(owner, state, output);
3742
4168
  this.startDueWrite(owner, state);
3743
4169
  this.delivered.set(owner.chat, state);
3744
- this.consolidateIfDue(owner, state);
4170
+ this.afterTurn.start(owner, state.cancel.signal);
3745
4171
  if (run !== void 0) this.offSceneIfDue(owner, state, run);
3746
4172
  return output;
3747
4173
  }
@@ -4025,6 +4451,8 @@ function apply(ctx) {
4025
4451
  })), "roleplay: rerank memories");
4026
4452
  });
4027
4453
  ctx.effect(() => ctx.roleplayOrchestration.replace({ committer: recordKeeper({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: record keeper");
4454
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ judge: triggerJudge({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: trigger judge");
4455
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ strategist: factionStrategist({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: faction strategist");
4028
4456
  ctx.effect(() => ctx.roleplayOrchestration.replace({ author: worldAuthor({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: world author");
4029
4457
  ctx.effect(() => ctx.roleplayOrchestration.replace({ suggester: suggestionWriter({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: suggestions");
4030
4458
  ctx.effect(() => ctx.roleplayState.bind((agentSessionId) => {