@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
@@ -1,14 +1,14 @@
1
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";
2
+ import { $t as findPanel, A as ROLES, At as subfolders, B as yesAt, C as settleExtracted, Cn as DEFAULT_SLOTS, D as classifyItems, E as buildRoster, F as askYesNo, Ft as IMPORT_FOLDER, H as parseWorldFile, K as parseOpeningParts, M as isLeftOut, Mt as itemise, N as kindOfRole, O as findEntity, Ot as LORE_DIR, Pt as withPlayer, Qt as pauseOf, R as noAt, Rt as PICTURE_FILE, S as pruneRelationships, Sn as WEEKDAY_NAMES, T as snapPassage, U as MAX_OPENING_CHARS, Ut as InvalidEditProblems, V as WORLD_FILE_NAME, Vt as readImportFolder, X as startQuestionsToFile, Xt as IMPORT_COMMAND, Zt as importRequestOf, _ as mergeExtracted, _n as CHARACTER_FILE_NAME, a as characterDocument, b as pruneLoreSubjects, c as extractCharacters, cn as parseLoreFile, d as extractStyle, dn as ITEM_FILE_NAME, en as splitPanels, fn as SLOTS_FILE_NAME, g as loreDocuments, gn as parseFactionFile, h as inert, hn as FACTION_FILE_NAME, i as asWritten, in as loadVariables, j as ROLE_TABLE, jt as cleanText, k as KINDS, kt as loadLore, l as extractFactions, ln as LOCATION_FILE_NAME, m as extractVariables, mn as parseSlotsFile, o as emptyExtracted, on as variableProblems, p as extractThings, pn as parseItemFile, q as partsText, r as addLore, rn as VARIABLES_FILE_NAME, s as extractBackground, sn as LORE_FILE_NAME, t as SerialQueue, tn as dialectOf, u as extractPlaces, un as parseLocationFile, v as pruneKnowledge, vn as parseCharacterFile, w as sourcesFor, x as pruneMembers, y as pruneLinks, yn as guarded, zt as openingText } from "./serial-xcAG57p_.js";
3
+ import { p as parseSwitchboard } from "./narration-CUZIXzab.js";
4
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";
5
+ import { $ as copyWorldPrompts, G as readDocument$1, J as formatIssue, K as errorMessage, 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 Reader, rt as promptProblem, t as externalToolLimit, xt as COMPARISONS, z as loadPlots } from "./hooks-CnxV2uEh.js";
6
+ import { t as trimCharacters } from "./text-KnqhN_Zv.js";
7
+ import { C as mapLimit, D as uniqueKey, E as trOf, S as NoEmbeddingService, T as slug, _ as MEDIA_TYPES, c as imageExtensionOf, l as libraryHashes, m as referenceImagePath, s as addToLibraryOnce, t as addCardLink, w as norm, y as writeImageFileMetadata } from "./gallery-CT5uj50b.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";
11
- import { mkdtemp, readFile, readdir, rename, rm, stat } from "node:fs/promises";
11
+ import { access, mkdtemp, readFile, readdir, rename, rm, stat } from "node:fs/promises";
12
12
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
13
13
  import { inflateSync } from "node:zlib";
14
14
  import { defineTool } from "@deepseek-ai/dsh-tools";
@@ -262,6 +262,338 @@ function readCard(file, name) {
262
262
  }
263
263
  /** Whether a file looks like a PNG, so that its picture can be kept. */
264
264
  const isPng = (file) => file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE);
265
+ // src/host/import/structure.ts
266
+ /** The most example lines the character keeps. */
267
+ const MAX_EXAMPLES = 8;
268
+ /** The summary is the start of the description: a sentence or two. */
269
+ const SUMMARY_CHARS = 280;
270
+ /** A line an example speaks through: a short name, a colon, and what the character says. */
271
+ function spoken(line) {
272
+ const colon = line.indexOf(":");
273
+ if (colon < 1 || colon > 100) return void 0;
274
+ return {
275
+ name: line.slice(0, colon),
276
+ utterance: line.slice(colon + 1).trimStart()
277
+ };
278
+ }
279
+ /** The lines of the example messages that the character speaks, as written; the markers of the tool that wrote them are taken out. */
280
+ function exampleLines(text, name) {
281
+ const lines = cleanText(text, name).split("\n").map((line) => line.trim()).filter((line) => line !== "");
282
+ if (!lines.some((line) => spoken(line) !== void 0)) return lines.slice(0, MAX_EXAMPLES);
283
+ const names = new Set([name, name.split(/\s+/)[0] ?? ""].map((part) => part.toLocaleLowerCase()));
284
+ return lines.flatMap((line) => {
285
+ const match = spoken(line);
286
+ if (match === void 0 || !names.has(match.name.trim().toLocaleLowerCase())) return [];
287
+ return match.utterance === "" ? [] : [match.utterance];
288
+ }).slice(0, MAX_EXAMPLES);
289
+ }
290
+ /**
291
+ * What a card holds, laid out without a model: the card's own character from its description, personality and examples, its lorebook entries as lore in its own words (for the game master only,
292
+ * as nothing has read what they say), and its instructions as the narration style, word for word. No place, faction, thing or other person is found: those take a reader.
293
+ */
294
+ function structureOnly(card, items, _choices) {
295
+ const taken = /* @__PURE__ */ new Set();
296
+ const roster = [{
297
+ kind: "character",
298
+ key: uniqueKey(slug(card.name, "character"), taken),
299
+ name: card.name,
300
+ aliases: [],
301
+ player: false
302
+ }];
303
+ const target = [{
304
+ name: card.name,
305
+ kind: "character"
306
+ }];
307
+ const classified = {};
308
+ for (const item of items) if (item.id.startsWith("field:description") || item.id.startsWith("field:personality")) classified[item.id] = {
309
+ roles: ["character"],
310
+ targets: target
311
+ };
312
+ else if (item.id.startsWith("field:example")) classified[item.id] = {
313
+ roles: ["speech"],
314
+ targets: target
315
+ };
316
+ else if (item.id.startsWith("field:")) classified[item.id] = {
317
+ roles: ["scenario"],
318
+ targets: []
319
+ };
320
+ else classified[item.id] = {
321
+ roles: ["world"],
322
+ targets: []
323
+ };
324
+ const extracted = emptyExtracted();
325
+ const description = cleanText(card.description, card.name);
326
+ const built = characterDocument(roster[0], {
327
+ tier: "principal",
328
+ kind: "person",
329
+ summary: description.slice(0, SUMMARY_CHARS).trim(),
330
+ personality: cleanText(card.personality, card.name),
331
+ background: description,
332
+ speech: {
333
+ style: "",
334
+ examples: exampleLines(card.messageExample, card.name)
335
+ }
336
+ }, roster);
337
+ extracted.characters.push(built.document);
338
+ extracted.notes.push(...built.notes);
339
+ for (const item of items.filter((entry) => entry.id.startsWith("entry:"))) for (const entry of loreDocuments(asWritten(item), roster, taken)) addLore(extracted.lore, {
340
+ ...entry.document,
341
+ scope: "listed"
342
+ });
343
+ const instructions = [card.systemPrompt, card.postHistoryInstructions].map((text) => cleanText(text, card.name)).filter((text) => text !== "");
344
+ if (instructions.length > 0) extracted.prompts.push({
345
+ id: "roleplay/style",
346
+ text: inert(instructions.join("\n\n"))
347
+ });
348
+ extracted.notes.push("imported without a model: only the card's own character, its lorebook and its instructions were carried over");
349
+ return {
350
+ classified,
351
+ roster,
352
+ extracted
353
+ };
354
+ }
355
+ // src/host/import/survey-edit.ts
356
+ /** Every reason a set of changes cannot be applied: none of them is. */
357
+ var SurveyEditError = class extends Error {
358
+ problems;
359
+ constructor(problems) {
360
+ super(problems.join("; "));
361
+ this.problems = problems;
362
+ }
363
+ };
364
+ const MAX_NAME = 100;
365
+ const MAX_ALIASES = 20;
366
+ const MAX_TARGETS = 10;
367
+ const PLAYER_WORDS = /^(the |a )?(player|user|you|reader|玩家|用户|你)$/i;
368
+ const clone = (value) => JSON.parse(JSON.stringify(value));
369
+ function nameProblem(name) {
370
+ if (typeof name !== "string" || name.trim() === "") return "a name is needed";
371
+ if (name.trim().length > MAX_NAME) return `a name is at most ${MAX_NAME} characters`;
372
+ if (PLAYER_WORDS.test(name.trim()) || /\[PLAYER\]|\{\{\s*user\s*\}\}/i.test(name)) return "the player is never listed as an entity";
373
+ }
374
+ function lookup$1(roster, who, problems) {
375
+ if (typeof who !== "string" || who.trim() === "") {
376
+ problems.push("an entity is needed");
377
+ return;
378
+ }
379
+ const found = roster.find((entity) => entity.key === who.trim()) ?? findEntity(roster, who);
380
+ if (found === void 0) problems.push(`there is no entity "${who}" (see import_survey_show)`);
381
+ return found;
382
+ }
383
+ /** Whether a target of a piece names this entity. */
384
+ const names$2 = (entity) => new Set([entity.name, ...entity.aliases].map(norm));
385
+ /** Applies every change, or none: the survey as it stands is not touched, and what comes back is a new one. */
386
+ function editSurvey(before, edits, pieces) {
387
+ const survey = clone(before);
388
+ const problems = [];
389
+ const done = [];
390
+ const retarget = (from, to) => {
391
+ for (const piece of Object.values(survey.classified)) {
392
+ const targets = [];
393
+ for (const target of piece.targets) {
394
+ if (!from.has(norm(target.name))) {
395
+ targets.push(target);
396
+ continue;
397
+ }
398
+ if (to !== void 0 && !targets.some((other) => norm(other.name) === norm(to.name))) targets.push(to);
399
+ }
400
+ piece.targets = targets;
401
+ }
402
+ };
403
+ edits.forEach((edit, index) => {
404
+ const at = `change ${index + 1}`;
405
+ const fail = (message) => {
406
+ problems.push(`${at}: ${message}`);
407
+ };
408
+ switch (edit.op) {
409
+ case "rename": {
410
+ const inner = [];
411
+ const entity = lookup$1(survey.roster, edit.entity, inner);
412
+ const bad = nameProblem(edit.name);
413
+ if (bad !== void 0) inner.push(bad);
414
+ else if (entity !== void 0 && survey.roster.some((other) => other !== entity && names$2(other).has(norm(edit.name)))) inner.push(`"${edit.name}" is already the name of another entity: merge them instead`);
415
+ inner.forEach(fail);
416
+ if (entity === void 0 || inner.length > 0) return;
417
+ const old = names$2(entity);
418
+ const was = entity.name;
419
+ entity.name = edit.name.trim();
420
+ if (!entity.aliases.some((alias) => norm(alias) === norm(was)) && norm(was) !== norm(entity.name)) entity.aliases.push(was);
421
+ retarget(old, {
422
+ name: entity.name,
423
+ kind: entity.kind
424
+ });
425
+ done.push(`renamed ${was} to ${entity.name}`);
426
+ return;
427
+ }
428
+ case "merge": {
429
+ const inner = [];
430
+ const entity = lookup$1(survey.roster, edit.entity, inner);
431
+ const into = lookup$1(survey.roster, edit.into, inner);
432
+ if (entity !== void 0 && into !== void 0 && entity === into) inner.push("an entity cannot be merged into itself");
433
+ if (entity !== void 0 && into !== void 0 && entity.kind !== into.kind) inner.push(`${entity.name} is a ${entity.kind} and ${into.name} is a ${into.kind}: change the kind first`);
434
+ inner.forEach(fail);
435
+ if (entity === void 0 || into === void 0 || inner.length > 0) return;
436
+ for (const alias of [entity.name, ...entity.aliases]) if (!names$2(into).has(norm(alias))) into.aliases.push(alias);
437
+ into.aliases = into.aliases.slice(0, MAX_ALIASES);
438
+ if (entity.player) into.player = true;
439
+ for (const other of survey.roster) if (other.parent !== void 0 && norm(other.parent) === norm(entity.name)) other.parent = into.name;
440
+ retarget(names$2(entity), {
441
+ name: into.name,
442
+ kind: into.kind
443
+ });
444
+ survey.roster = survey.roster.filter((other) => other !== entity);
445
+ done.push(`merged ${entity.name} into ${into.name}`);
446
+ return;
447
+ }
448
+ case "kind": {
449
+ const inner = [];
450
+ const entity = lookup$1(survey.roster, edit.entity, inner);
451
+ if (!KINDS.includes(edit.kind)) inner.push(`a kind is one of ${KINDS.join(", ")}`);
452
+ inner.forEach(fail);
453
+ if (entity === void 0 || inner.length > 0 || entity.kind === edit.kind) return;
454
+ const old = entity.kind;
455
+ entity.kind = edit.kind;
456
+ if (edit.kind !== "place") delete entity.parent;
457
+ if (edit.kind !== "character") entity.player = false;
458
+ retarget(names$2(entity), {
459
+ name: entity.name,
460
+ kind: entity.kind
461
+ });
462
+ done.push(`${entity.name} is a ${edit.kind}, not a ${old}`);
463
+ return;
464
+ }
465
+ case "alias": {
466
+ const inner = [];
467
+ const entity = lookup$1(survey.roster, edit.entity, inner);
468
+ for (const alias of edit.add ?? []) {
469
+ const bad = nameProblem(alias);
470
+ if (bad !== void 0) inner.push(`alias "${alias}": ${bad}`);
471
+ else if (survey.roster.some((other) => other !== entity && names$2(other).has(norm(alias)))) inner.push(`"${alias}" already names another entity: merge them instead`);
472
+ }
473
+ inner.forEach(fail);
474
+ if (entity === void 0 || inner.length > 0) return;
475
+ for (const alias of edit.add ?? []) if (!names$2(entity).has(norm(alias))) entity.aliases.push(alias.trim());
476
+ const drop = new Set((edit.remove ?? []).map(norm));
477
+ entity.aliases = entity.aliases.filter((alias) => !drop.has(norm(alias))).slice(0, MAX_ALIASES);
478
+ done.push(`aliases of ${entity.name}: ${entity.aliases.join(", ") || "none"}`);
479
+ return;
480
+ }
481
+ case "player": {
482
+ const inner = [];
483
+ const entity = lookup$1(survey.roster, edit.entity, inner);
484
+ if (entity !== void 0 && entity.kind !== "character") inner.push(`${entity.name} is a ${entity.kind}: only a character can be played`);
485
+ inner.forEach(fail);
486
+ if (entity === void 0 || inner.length > 0) return;
487
+ for (const other of survey.roster) other.player = other === entity;
488
+ done.push(`${entity.name} is the character the player plays`);
489
+ return;
490
+ }
491
+ case "add": {
492
+ const bad = nameProblem(edit.name);
493
+ if (bad !== void 0) return fail(bad);
494
+ if (!KINDS.includes(edit.kind)) return fail(`a kind is one of ${KINDS.join(", ")}`);
495
+ if (survey.roster.some((other) => names$2(other).has(norm(edit.name)))) return fail(`"${edit.name}" is already in the survey`);
496
+ const aliases = (edit.aliases ?? []).map((alias) => alias.trim()).filter((alias) => alias !== "");
497
+ const badAlias = aliases.map(nameProblem).find((problem) => problem !== void 0);
498
+ if (badAlias !== void 0) return fail(`alias: ${badAlias}`);
499
+ survey.roster.push({
500
+ kind: edit.kind,
501
+ key: uniqueKey(slug(edit.name, edit.kind), new Set(survey.roster.map((other) => other.key))),
502
+ name: edit.name.trim(),
503
+ aliases: aliases.slice(0, MAX_ALIASES),
504
+ player: false
505
+ });
506
+ done.push(`added ${edit.kind} ${edit.name.trim()}; it is written from the pieces whose targets name it (see the piece change)`);
507
+ return;
508
+ }
509
+ case "remove": {
510
+ const inner = [];
511
+ const entity = lookup$1(survey.roster, edit.entity, inner);
512
+ inner.forEach(fail);
513
+ if (entity === void 0) return;
514
+ retarget(names$2(entity), void 0);
515
+ survey.roster = survey.roster.filter((other) => other !== entity);
516
+ done.push(`removed ${entity.name}`);
517
+ return;
518
+ }
519
+ case "piece": {
520
+ const piece = typeof edit.piece === "string" ? survey.classified[edit.piece] : void 0;
521
+ if (piece === void 0 || !pieces.has(edit.piece)) return fail(`there is no piece "${String(edit.piece)}" (see import_survey_show)`);
522
+ if (edit.roles === void 0 && edit.targets === void 0) return fail("give the roles, the targets or both");
523
+ if (edit.roles !== void 0) {
524
+ if (edit.roles.length === 0 || edit.roles.length > 3) return fail("a piece has one to three roles");
525
+ const unknown = edit.roles.filter((role) => !ROLES.includes(role));
526
+ if (unknown.length > 0) return fail(`unknown roles ${unknown.join(", ")}; a role is one of ${ROLES.join(", ")}`);
527
+ }
528
+ if (edit.targets !== void 0) {
529
+ if (edit.targets.length > MAX_TARGETS) return fail(`a piece names at most ${MAX_TARGETS} targets`);
530
+ const bad = edit.targets.map((target) => nameProblem(target.name) ?? ([...KINDS, "other"].includes(target.kind) ? void 0 : `a target's kind is one of ${[...KINDS, "other"].join(", ")}`)).find((problem) => problem !== void 0);
531
+ if (bad !== void 0) return fail(bad);
532
+ }
533
+ if (edit.roles !== void 0) piece.roles = [...new Set(edit.roles)];
534
+ if (edit.targets !== void 0) piece.targets = edit.targets.map((target) => ({
535
+ name: target.name.trim(),
536
+ kind: target.kind
537
+ }));
538
+ done.push(`${edit.piece}: ${piece.roles.join(", ")} about ${piece.targets.map((target) => target.name).join(", ") || "nobody"}`);
539
+ return;
540
+ }
541
+ default: fail(`unknown change "${String(edit.op)}"; it is one of rename, merge, kind, alias, player, add, remove, piece`);
542
+ }
543
+ });
544
+ if (problems.length > 0) throw new SurveyEditError(problems);
545
+ if (survey.roster.filter((entity) => entity.player).length > 1) throw new SurveyEditError(["more than one entity is marked as the character the player plays"]);
546
+ return {
547
+ survey,
548
+ done
549
+ };
550
+ }
551
+ const SHOWN_PIECES = 12;
552
+ /** What the survey found, for the person to check: every entity with the pieces it is written from, and what looks doubtful. */
553
+ function describeSurvey(survey, items) {
554
+ const entities = survey.roster.map((entity) => {
555
+ const sources = sourcesFor(entity, items, survey.classified);
556
+ return {
557
+ key: entity.key,
558
+ name: entity.name,
559
+ kind: entity.kind,
560
+ ...entity.aliases.length === 0 ? {} : { aliases: entity.aliases },
561
+ ...entity.player ? { playedByThePlayer: true } : {},
562
+ ...entity.parent === void 0 ? {} : { in: entity.parent },
563
+ pieces: sources.slice(0, SHOWN_PIECES).map((item) => item.id),
564
+ ...sources.length > SHOWN_PIECES ? { morePieces: sources.length - SHOWN_PIECES } : {}
565
+ };
566
+ });
567
+ const unsure = [];
568
+ if (survey.roster.some((entity) => entity.kind === "character") && !survey.roster.some((entity) => entity.player)) unsure.push("no character is marked as the one the player plays (set it with a player change when the card has one)");
569
+ for (const entity of survey.roster) if (sourcesFor(entity, items, survey.classified).length === 0) unsure.push(`${entity.name} (${entity.kind}) has no piece that is about it`);
570
+ for (const item of items) {
571
+ const piece = survey.classified[item.id];
572
+ if (piece === void 0) continue;
573
+ if (piece.roles.some((role) => kindOfRole(role) !== void 0) && piece.targets.length === 0) unsure.push(`${item.id} is about ${piece.roles[0]} but names nobody`);
574
+ else if (piece.targets.length >= 5) unsure.push(`${item.id} names ${piece.targets.length} targets: is it about all of them`);
575
+ }
576
+ const pieceRoles = {};
577
+ for (const item of items) {
578
+ const role = survey.classified[item.id]?.roles[0];
579
+ if (role !== void 0) pieceRoles[role] = (pieceRoles[role] ?? 0) + 1;
580
+ }
581
+ return {
582
+ entities,
583
+ unsure,
584
+ pieceRoles
585
+ };
586
+ }
587
+ /** The pieces of the card with what the survey made of each. */
588
+ function describePieces(survey, items) {
589
+ return items.map((item) => ({
590
+ piece: item.id,
591
+ label: item.label,
592
+ characters: item.text.length,
593
+ roles: survey.classified[item.id]?.roles ?? [],
594
+ about: (survey.classified[item.id]?.targets ?? []).map((target) => `${target.name} (${target.kind})`)
595
+ }));
596
+ }
265
597
  // src/host/triggers/load.ts
266
598
  const TRIGGERS_FILE_NAME = "triggers.json";
267
599
  /** Read `triggers.json`: a list of what the world does by itself when something comes true (docs/world-format.md). */
@@ -576,96 +908,213 @@ async function extractCasting(ctx, card, passages) {
576
908
  };
577
909
  }
578
910
  }
579
- // src/host/import/structure.ts
580
- /** The most example lines the character keeps. */
581
- const MAX_EXAMPLES = 8;
582
- /** The summary is the start of the description: a sentence or two. */
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
- };
911
+ // src/host/import/stages.ts
912
+ /** The parts of the build, in the order they are best run: what the world is made of (places first, because characters start in them), then how it is told. */
913
+ const STAGES = [
914
+ "places",
915
+ "characters",
916
+ "factions",
917
+ "things",
918
+ "background",
919
+ "style",
920
+ "variables",
921
+ "casting"
922
+ ];
923
+ /** The stages a stage reads the result of. Only the casting passages travel between stages; every other job reads the survey. */
924
+ const STAGE_NEEDS = {
925
+ places: [],
926
+ characters: [],
927
+ factions: [],
928
+ things: [],
929
+ background: [],
930
+ style: [],
931
+ variables: [],
932
+ casting: ["background"]
933
+ };
934
+ const isStage = (value) => typeof value === "string" && STAGES.includes(value);
935
+ const folder$1 = (world) => join(world, IMPORT_FOLDER);
936
+ const STAGES_FOLDER = "stages";
937
+ const REVISION = "survey-revision.json";
938
+ async function readJson$2(file) {
939
+ try {
940
+ return JSON.parse(await readFile(file, "utf8"));
941
+ } catch (error) {
942
+ if (error.code === "ENOENT") return void 0;
943
+ throw error;
944
+ }
592
945
  }
593
- /** The lines of the example messages that the character speaks, as written; the markers of the tool that wrote them are taken out. */
594
- function exampleLines(text, name) {
595
- const lines = cleanText(text, name).split("\n").map((line) => line.trim()).filter((line) => line !== "");
596
- if (!lines.some((line) => spoken(line) !== void 0)) return lines.slice(0, MAX_EXAMPLES);
597
- const names = new Set([name, name.split(/\s+/)[0] ?? ""].map((part) => part.toLocaleLowerCase()));
598
- return lines.flatMap((line) => {
599
- const match = spoken(line);
600
- if (match === void 0 || !names.has(match.name.trim().toLocaleLowerCase())) return [];
601
- return match.utterance === "" ? [] : [match.utterance];
602
- }).slice(0, MAX_EXAMPLES);
946
+ const stageFile = (world, stage) => join(folder$1(world), STAGES_FOLDER, `${stage}.json`);
947
+ const readStage = (world, stage) => readJson$2(stageFile(world, stage));
948
+ const writeStage = (world, record) => atomicWriteJson(stageFile(world, record.stage), record, { createDirectory: true });
949
+ /** Forgets what every stage wrote: a new survey starts the build over. */
950
+ async function clearStages(world) {
951
+ await rm(join(folder$1(world), STAGES_FOLDER), {
952
+ recursive: true,
953
+ force: true
954
+ });
603
955
  }
604
- /**
605
- * What a card holds, laid out without a model: the card's own character from its description, personality and examples, its lorebook entries as lore in its own words (for the game master only,
606
- * as nothing has read what they say), and its instructions as the narration style, word for word. No place, faction, thing or other person is found: those take a reader.
607
- */
608
- function structureOnly(card, items, _choices) {
609
- const taken = /* @__PURE__ */ new Set();
610
- const roster = [{
611
- kind: "character",
612
- key: uniqueKey(slug(card.name, "character"), taken),
613
- name: card.name,
614
- aliases: [],
615
- player: false
616
- }];
617
- const target = [{
618
- name: card.name,
619
- kind: "character"
620
- }];
621
- const classified = {};
622
- for (const item of items) if (item.id.startsWith("field:description") || item.id.startsWith("field:personality")) classified[item.id] = {
623
- roles: ["character"],
624
- targets: target
625
- };
626
- else if (item.id.startsWith("field:example")) classified[item.id] = {
627
- roles: ["speech"],
628
- targets: target
956
+ /** The survey's revision and whether the person (or their assistant) changed it after the model made it. */
957
+ async function readRevision(world) {
958
+ return await readJson$2(join(folder$1(world), REVISION)) ?? {
959
+ revision: 0,
960
+ edited: false
629
961
  };
630
- else if (item.id.startsWith("field:")) classified[item.id] = {
631
- roles: ["scenario"],
632
- targets: []
633
- };
634
- else classified[item.id] = {
635
- roles: ["world"],
636
- targets: []
637
- };
638
- const extracted = emptyExtracted();
639
- const description = cleanText(card.description, card.name);
640
- const built = characterDocument(roster[0], {
641
- tier: "principal",
642
- kind: "person",
643
- summary: description.slice(0, SUMMARY_CHARS).trim(),
644
- personality: cleanText(card.personality, card.name),
645
- background: description,
646
- speech: {
647
- style: "",
648
- examples: exampleLines(card.messageExample, card.name)
649
- }
650
- }, roster);
651
- extracted.characters.push(built.document);
652
- extracted.notes.push(...built.notes);
653
- for (const item of items.filter((entry) => entry.id.startsWith("entry:"))) for (const entry of loreDocuments(asWritten(item), roster, taken)) addLore(extracted.lore, {
654
- ...entry.document,
655
- scope: "listed"
656
- });
657
- const instructions = [card.systemPrompt, card.postHistoryInstructions].map((text) => cleanText(text, card.name)).filter((text) => text !== "");
658
- if (instructions.length > 0) extracted.prompts.push({
659
- id: "roleplay/style",
660
- text: inert(instructions.join("\n\n"))
962
+ }
963
+ /** The survey was changed by hand: the stages that read the one before are stale. */
964
+ async function surveyEdited(world) {
965
+ const { revision } = await readRevision(world);
966
+ await atomicWriteJson(join(folder$1(world), REVISION), {
967
+ revision: revision + 1,
968
+ edited: true
969
+ }, { createDirectory: true });
970
+ return revision + 1;
971
+ }
972
+ /** A survey made by the model starts as it made it. */
973
+ async function surveyMade(world) {
974
+ const { revision } = await readRevision(world);
975
+ await atomicWriteJson(join(folder$1(world), REVISION), {
976
+ revision: revision + 1,
977
+ edited: false
978
+ }, { createDirectory: true });
979
+ }
980
+ const GROUPS = [
981
+ "characters",
982
+ "locations",
983
+ "factions",
984
+ "items",
985
+ "lore",
986
+ "prompts",
987
+ "rules",
988
+ "variables",
989
+ "commands",
990
+ "triggers"
991
+ ];
992
+ const COUNT_NAMES = {
993
+ characters: "characters",
994
+ locations: "places",
995
+ factions: "factions",
996
+ items: "things",
997
+ lore: "lore",
998
+ prompts: "prompts",
999
+ rules: "rules",
1000
+ variables: "variables",
1001
+ commands: "commands",
1002
+ triggers: "triggers"
1003
+ };
1004
+ /** How many of each kind of document a stage's result holds, leaving out the kinds it has none of. */
1005
+ function countsOf(extracted) {
1006
+ const counts = {};
1007
+ for (const group of GROUPS) {
1008
+ const length = extracted[group]?.length ?? 0;
1009
+ if (length > 0) counts[COUNT_NAMES[group]] = length;
1010
+ }
1011
+ return counts;
1012
+ }
1013
+ /** What every stage has done, and which of the stages that ran have to run again. */
1014
+ async function statusOf(world) {
1015
+ const { revision } = await readRevision(world);
1016
+ const records = /* @__PURE__ */ new Map();
1017
+ for (const stage of STAGES) {
1018
+ const record = await readStage(world, stage);
1019
+ if (record !== void 0) records.set(stage, record);
1020
+ }
1021
+ return STAGES.map((stage) => {
1022
+ const record = records.get(stage);
1023
+ if (record === void 0) return {
1024
+ stage,
1025
+ state: "todo",
1026
+ counts: {},
1027
+ notes: 0
1028
+ };
1029
+ const changed = STAGE_NEEDS[stage].find((need) => record.needs?.[need] !== records.get(need)?.at);
1030
+ const why = record.revision === revision ? changed === void 0 ? void 0 : `${changed} was run again after it` : "the survey was changed after it";
1031
+ return {
1032
+ stage,
1033
+ state: why === void 0 ? "done" : "stale",
1034
+ at: record.at,
1035
+ ...record.guidance === void 0 ? {} : { guidance: record.guidance },
1036
+ counts: countsOf(record.extracted),
1037
+ notes: record.extracted.notes?.length ?? 0,
1038
+ ...why === void 0 ? {} : { why }
1039
+ };
661
1040
  });
662
- extracted.notes.push("imported without a model: only the card's own character, its lorebook and its instructions were carried over");
1041
+ }
1042
+ /** Whether every stage has run on the survey as it is now: the world can be written. */
1043
+ const complete = (status) => status.every((entry) => entry.state === "done");
1044
+ /** The documents of every stage that has run, as one extraction, with what no stage can do alone settled. */
1045
+ async function mergedStages(world, items, classified, roster) {
1046
+ const parts = [];
1047
+ for (const stage of STAGES) {
1048
+ const record = await readStage(world, stage);
1049
+ if (record !== void 0) parts.push(record.extracted);
1050
+ }
1051
+ const merged = mergeExtracted(parts);
1052
+ merged.derived = merged.derived.filter((entry) => !(entry.kind === "command" && entry.name === ""));
1053
+ return settleExtracted(merged, items, classified, roster);
1054
+ }
1055
+ /** A context whose jobs carry the person's note for the step: it is part of each job's prompt, so a job asked again with another note is a new job. */
1056
+ function withGuidance(ctx, guidance) {
1057
+ if (guidance === void 0 || guidance.trim() === "") return ctx;
1058
+ const note = `${trOf(ctx)("A note from the person importing the card, for this step. Follow it where the card allows; it never overrides the rules above:")}\n${guidance.trim()}`;
663
1059
  return {
664
- classified,
665
- roster,
666
- extracted
1060
+ ...ctx,
1061
+ run: (job) => ctx.run({
1062
+ ...job,
1063
+ prompt: `${job.prompt}\n\n${note}`
1064
+ })
667
1065
  };
668
1066
  }
1067
+ /** Makes the documents of one stage. */
1068
+ async function produce(stage, ctx, input) {
1069
+ const { card, items, classified, roster } = input;
1070
+ const written = items.filter((item) => !isLeftOut(classified[item.id]));
1071
+ switch (stage) {
1072
+ case "places": return await extractPlaces(ctx, card, written, classified, roster);
1073
+ case "characters": return await extractCharacters(ctx, card, written, classified, roster);
1074
+ case "factions": return await extractFactions(ctx, card, written, classified, roster);
1075
+ case "things": return await extractThings(ctx, card, written, classified, roster);
1076
+ case "background": return await extractBackground(ctx, card, written, classified, roster);
1077
+ case "style": {
1078
+ const style = await extractStyle(ctx, card, items, classified);
1079
+ return {
1080
+ ...emptyExtracted(),
1081
+ prompts: style.prompts,
1082
+ rules: style.rules,
1083
+ notes: style.notes,
1084
+ derived: style.derived
1085
+ };
1086
+ }
1087
+ case "variables": {
1088
+ const tracked = await extractVariables(ctx, card, items, classified, roster);
1089
+ return {
1090
+ ...emptyExtracted(),
1091
+ variables: tracked.variables,
1092
+ notes: tracked.notes,
1093
+ derived: tracked.derived
1094
+ };
1095
+ }
1096
+ case "casting": {
1097
+ const cast = await extractCasting(ctx, card, input.background?.casting ?? []);
1098
+ const from = (input.background?.derived ?? []).filter((entry) => entry.kind === "command" && entry.name === "").flatMap((entry) => entry.pieces);
1099
+ const named = (document) => typeof document["name"] === "string" && document["name"] !== "" ? document["name"] : typeof document["id"] === "string" ? document["id"] : typeof document["key"] === "string" ? document["key"] : "unnamed";
1100
+ return {
1101
+ ...emptyExtracted(),
1102
+ commands: cast.commands,
1103
+ triggers: cast.triggers,
1104
+ notes: cast.notes,
1105
+ derived: [...cast.commands.map((document) => ({
1106
+ kind: "command",
1107
+ name: named(document),
1108
+ pieces: from
1109
+ })), ...cast.triggers.map((document) => ({
1110
+ kind: "trigger",
1111
+ name: named(document),
1112
+ pieces: from
1113
+ }))]
1114
+ };
1115
+ }
1116
+ }
1117
+ }
669
1118
  // src/host/import/outcomes.ts
670
1119
  /**
671
1120
  * What became of one piece of a card: `carried` is kept word for word (an opening), `converted` made characters, places, things or other entries of the world, `guidance`
@@ -799,6 +1248,11 @@ function cardPieces(card, choices) {
799
1248
  }))
800
1249
  ];
801
1250
  }
1251
+ /** The ids of the pieces of the card that hold an address; none for one found only in scripts or other settings of the card. */
1252
+ function pieceFinder(card, choices) {
1253
+ const pieces = cardPieces(card, choices);
1254
+ return (url) => pieces.filter((piece) => piece.text.includes(url)).map((piece) => piece.id);
1255
+ }
802
1256
  async function optional(file) {
803
1257
  try {
804
1258
  return JSON.parse(await readFile(file, "utf8"));
@@ -1250,6 +1704,10 @@ function mendParts(source, parts, speakers) {
1250
1704
  const mended = [];
1251
1705
  let at = 0;
1252
1706
  for (const part of parts) {
1707
+ if (part.type === "image") {
1708
+ mended.push(part);
1709
+ continue;
1710
+ }
1253
1711
  const found = source.indexOf(part.text, at);
1254
1712
  if (found < 0) return [...parts];
1255
1713
  const gap = unquoted(source.slice(at, found));
@@ -3156,8 +3614,13 @@ async function fetchPictures(world, urls, deps = {}) {
3156
3614
  });
3157
3615
  return;
3158
3616
  }
3159
- const { path, added: isNew } = await addToLibraryOnce(world, reply.body, fileNameOf(url), hashes);
3617
+ const link = {
3618
+ url: address,
3619
+ pieces: deps.piecesOf?.(address) ?? []
3620
+ };
3621
+ const { path, added: isNew } = await addToLibraryOnce(world, reply.body, fileNameOf(url), hashes, link);
3160
3622
  if (!isNew) {
3623
+ await addCardLink(world, path, link).catch(() => void 0);
3161
3624
  skipped.push({
3162
3625
  url: address,
3163
3626
  reason: "a copy of another picture",
@@ -4868,7 +5331,7 @@ const FIDELITY_SCHEMA = {
4868
5331
  /** Why the comparison cannot be used: a quote that is not in the text it is said to come from is a guess, not a finding. */
4869
5332
  function comparisonProblem(value, source, document) {
4870
5333
  if (value.dropped.length > MAX_REPORTED || value.invented.length > MAX_REPORTED) return `report at most ${MAX_REPORTED} of each`;
4871
- const missing = (list, text) => list.some((entry) => entry.fact.trim() === "" || !squashed(text).includes(squashed(entry.quote)) || squashed(entry.quote) === "");
5334
+ const missing = (list, text) => list.some((entry) => entry.fact.trim() === "" || snapPassage(entry.quote, text) === void 0);
4872
5335
  if (missing(value.dropped, source)) return "the quote of every dropped fact must be a passage of the source, exactly as it is written there";
4873
5336
  if (missing(value.invented, document)) return "the quote of every invented fact must be a passage of the document, exactly as it is written there";
4874
5337
  }
@@ -5442,6 +5905,22 @@ const about = {
5442
5905
  where: "world.json",
5443
5906
  message: "the world has no opening, so a story starts with \"The story begins.\""
5444
5907
  });
5908
+ const shown = [...(info.openingParts ?? []).map((part) => ({
5909
+ where: "opening_message",
5910
+ part
5911
+ })), ...info.alternateOpenings.flatMap((entry, index) => (entry.parts ?? []).map((part) => ({
5912
+ where: `alternate_openings[${index}]`,
5913
+ part
5914
+ })))];
5915
+ for (const { where, part } of shown) {
5916
+ if (part.type !== "image") continue;
5917
+ if (await access(join(input.world.directory, "images", part.path)).then(() => false, () => true)) found.push({
5918
+ severity: "error",
5919
+ code: "opening-picture-missing",
5920
+ where,
5921
+ message: `the opening shows "${part.path}", which is not in the world's images, so no story can start with it`
5922
+ });
5923
+ }
5445
5924
  return foundBy("quality-world", found);
5446
5925
  }
5447
5926
  };
@@ -5761,7 +6240,11 @@ const fetching = /* @__PURE__ */ new Map();
5761
6240
  * Starts fetching the pictures the card points to, next to the work of the agents, once per import; a later call gets the same run or its saved result.
5762
6241
  * A failure is a report of its own: pictures never stop an import.
5763
6242
  */
5764
- function ensurePictures(world, urls) {
6243
+ /** The addresses to download pictures from: none when the person turned downloading off. */
6244
+ function picturesToFetch(card, choices) {
6245
+ return choices.fetchPictures === false ? [] : card.urls ?? [];
6246
+ }
6247
+ function ensurePictures(world, urls, piecesOf) {
5765
6248
  const running = fetching.get(world);
5766
6249
  if (running !== void 0) return running;
5767
6250
  const run = (async () => {
@@ -5770,7 +6253,7 @@ function ensurePictures(world, urls) {
5770
6253
  } catch (error) {
5771
6254
  if (error.code !== "ENOENT") throw error;
5772
6255
  }
5773
- const report = await fetchPictures(world, urls).catch((error) => ({
6256
+ const report = await fetchPictures(world, urls, { piecesOf }).catch((error) => ({
5774
6257
  found: 0,
5775
6258
  added: [],
5776
6259
  skipped: [{
@@ -5865,8 +6348,8 @@ async function survey(ctx, world) {
5865
6348
  "surveyed",
5866
6349
  "built"
5867
6350
  ], "the survey");
5868
- const { card, items } = await load(world);
5869
- ensurePictures(world, card.urls ?? []);
6351
+ const { card, items, choices } = await load(world);
6352
+ ensurePictures(world, picturesToFetch(card, choices), pieceFinder(card, choices));
5870
6353
  const { classified, failures, decided } = await classifyItems(ctx, card, items);
5871
6354
  if (items.length > 0 && failures.length >= items.length && decided === 0) throw new Error(`no piece of the card could be read, so nothing was imported: ${failures[0]}`);
5872
6355
  const { roster, failure } = await buildRoster(ctx, card, items.filter((item) => !isLeftOut(classified[item.id])), classified);
@@ -5874,6 +6357,8 @@ async function survey(ctx, world) {
5874
6357
  await writeJson(join(folder(world), CLASSIFICATION), classified);
5875
6358
  await writeJson(join(folder(world), ROSTER), roster);
5876
6359
  await rm(join(folder(world), EXTRACTED), { force: true });
6360
+ await clearStages(world);
6361
+ await surveyMade(world);
5877
6362
  await writeJson(join(folder(world), STATE), { phase: "surveyed" });
5878
6363
  const roles = {};
5879
6364
  for (const item of items) {
@@ -5899,45 +6384,259 @@ async function survey(ctx, world) {
5899
6384
  ]
5900
6385
  };
5901
6386
  }
5902
- /** Second step: write every character, place, faction, thing and background entry from the pieces that are about it. */
5903
- async function build(ctx, world) {
5904
- await need(world, ["surveyed", "built"], "the build");
5905
- const { card, items } = await load(world);
5906
- ensurePictures(world, card.urls ?? []);
6387
+ const REPORT_NAMES = 40;
6388
+ const REPORT_NOTES = 20;
6389
+ const nameOf = (document) => String(document["name"] ?? document["id"] ?? document["key"] ?? "");
6390
+ async function stageReport(world, stage) {
6391
+ const status = await statusOf(world);
6392
+ const record = await readStage(world, stage);
6393
+ const extracted = record?.extracted ?? {};
6394
+ const written = [...[
6395
+ extracted.locations,
6396
+ extracted.characters,
6397
+ extracted.factions,
6398
+ extracted.items,
6399
+ extracted.lore,
6400
+ extracted.variables,
6401
+ extracted.commands,
6402
+ extracted.triggers
6403
+ ].flatMap((group) => group ?? []).map(nameOf), ...(extracted.prompts ?? []).map((prompt) => prompt.id)].filter((name) => name !== "");
6404
+ const notes = extracted.notes ?? [];
6405
+ return {
6406
+ stage,
6407
+ counts: status.find((each) => each.stage === stage).counts,
6408
+ written: written.slice(0, REPORT_NAMES),
6409
+ notes: notes.slice(0, REPORT_NOTES),
6410
+ notesTotal: notes.length,
6411
+ ...record?.guidance === void 0 ? {} : { guidance: record.guidance },
6412
+ left: status.filter((each) => each.state === "todo").map((each) => each.stage),
6413
+ stale: status.filter((each) => each.state === "stale").map((each) => each.stage),
6414
+ complete: complete(status)
6415
+ };
6416
+ }
6417
+ /** What every stage has done: which are done, which are still to run and which have to run again. */
6418
+ async function importStatus(world) {
6419
+ const stages = await statusOf(world);
6420
+ return {
6421
+ phase: await importPhase(world),
6422
+ stages,
6423
+ complete: complete(stages)
6424
+ };
6425
+ }
6426
+ const running = /* @__PURE__ */ new Set();
6427
+ /**
6428
+ * Writes one stage's documents from the survey as it is now (an answered job is not asked again; with `guidance` the jobs are new ones), keeps them in `.import/stages/`, and makes the whole extraction
6429
+ * from every stage that has run. When every stage has run on the current survey the import is `built` and can be written as a world.
6430
+ */
6431
+ async function runStage(ctx, world, stage, guidance) {
6432
+ await need(world, ["surveyed", "built"], `the stage "${stage}"`);
6433
+ const key = `${world}:${stage}`;
6434
+ if (running.has(key)) throw new ImportStateError(`the stage "${stage}" is already running`);
6435
+ const status = await statusOf(world);
6436
+ for (const needed of STAGE_NEEDS[stage]) {
6437
+ const dependency = status.find((entry) => entry.stage === needed);
6438
+ if (dependency?.state !== "done") throw new ImportStateError(`the stage "${stage}" needs the stage "${needed}" first${dependency?.state === "stale" ? ", and that stage is stale" : ""}`);
6439
+ }
6440
+ running.add(key);
6441
+ try {
6442
+ const { card, items, choices } = await load(world);
6443
+ ensurePictures(world, picturesToFetch(card, choices), pieceFinder(card, choices));
6444
+ const classified = await readJson(join(folder(world), CLASSIFICATION));
6445
+ const roster = await readJson(join(folder(world), ROSTER));
6446
+ const background = STAGE_NEEDS[stage].includes("background") ? (await readStage(world, "background"))?.extracted : void 0;
6447
+ const extracted = await produce(stage, withGuidance(ctx, guidance), {
6448
+ card,
6449
+ items,
6450
+ classified,
6451
+ roster,
6452
+ background
6453
+ });
6454
+ if (ctx.cancelled?.() === true) throw new Error(`the stage "${stage}" was stopped before it was done, so what it made is not kept`);
6455
+ const { revision } = await readRevision(world);
6456
+ const needs = Object.fromEntries(await Promise.all(STAGE_NEEDS[stage].map(async (needed) => [needed, (await readStage(world, needed)).at])));
6457
+ await writeStage(world, {
6458
+ stage,
6459
+ at: (/* @__PURE__ */ new Date()).toISOString(),
6460
+ revision,
6461
+ ...STAGE_NEEDS[stage].length === 0 ? {} : { needs },
6462
+ ...guidance === void 0 || guidance.trim() === "" ? {} : { guidance: guidance.trim() },
6463
+ extracted
6464
+ });
6465
+ await settleBuild(world);
6466
+ return await stageReport(world, stage);
6467
+ } finally {
6468
+ running.delete(key);
6469
+ }
6470
+ }
6471
+ /** The extraction of every stage that has run is kept as one; the import is `built` when they all have run on the survey as it is. */
6472
+ async function settleBuild(world) {
6473
+ const { items } = await load(world);
5907
6474
  const classified = await readJson(join(folder(world), CLASSIFICATION));
5908
6475
  const roster = await readJson(join(folder(world), ROSTER));
5909
- const extracted = await extractEntities(ctx, card, items.filter((item) => !isLeftOut(classified[item.id])), classified, roster);
5910
- const style = await extractStyle(ctx, card, items, classified);
5911
- extracted.prompts.push(...style.prompts);
5912
- extracted.rules.push(...style.rules);
5913
- extracted.notes.push(...style.notes);
5914
- extracted.derived.push(...style.derived);
5915
- const tracked = await extractVariables(ctx, card, items, classified, roster);
5916
- extracted.variables.push(...tracked.variables);
5917
- extracted.notes.push(...tracked.notes);
5918
- extracted.derived.push(...tracked.derived);
5919
- const cast = await extractCasting(ctx, card, extracted.casting);
5920
- extracted.commands.push(...cast.commands);
5921
- extracted.triggers.push(...cast.triggers);
5922
- extracted.notes.push(...cast.notes);
5923
- const castFrom = extracted.derived.filter((entry) => entry.kind === "command" && entry.name === "").flatMap((entry) => entry.pieces);
5924
- extracted.derived = extracted.derived.filter((entry) => !(entry.kind === "command" && entry.name === ""));
5925
- const named = (document) => typeof document["name"] === "string" && document["name"] !== "" ? document["name"] : typeof document["id"] === "string" ? document["id"] : typeof document["key"] === "string" ? document["key"] : "unnamed";
5926
- extracted.derived.push(...cast.commands.map((document) => ({
5927
- kind: "command",
5928
- name: named(document),
5929
- pieces: castFrom
5930
- })), ...cast.triggers.map((document) => ({
5931
- kind: "trigger",
5932
- name: named(document),
5933
- pieces: castFrom
5934
- })));
5935
- if (ctx.cancelled?.() === true) throw new Error("the build was stopped before it was done, so what it made is not kept");
6476
+ const merged = await mergedStages(world, items.filter((item) => !isLeftOut(classified[item.id])), classified, roster);
5936
6477
  await rename(join(folder(world), EXTRACTED), join(folder(world), PREVIOUS_EXTRACTED)).catch((error) => {
5937
6478
  if (error.code !== "ENOENT") throw error;
5938
6479
  });
5939
- await writeJson(join(folder(world), EXTRACTED), extracted);
5940
- await writeJson(join(folder(world), STATE), { phase: "built" });
6480
+ await writeJson(join(folder(world), EXTRACTED), merged);
6481
+ await writeJson(join(folder(world), STATE), { phase: complete(await statusOf(world)) ? "built" : "surveyed" });
6482
+ }
6483
+ const SURVEY_PAGE = 60;
6484
+ /** The survey as it stands: its entities with the pieces each is written from, or its pieces with what each was taken to be, a page at a time. */
6485
+ async function showSurvey(world, what, offset = 0) {
6486
+ await need(world, ["surveyed", "built"], "showing the survey");
6487
+ const { items } = await load(world);
6488
+ const survey = {
6489
+ classified: await readJson(join(folder(world), CLASSIFICATION)),
6490
+ roster: await readJson(join(folder(world), ROSTER))
6491
+ };
6492
+ const { revision, edited } = await readRevision(world);
6493
+ const described = describeSurvey(survey, items);
6494
+ const list = what === "entities" ? described.entities : describePieces(survey, items);
6495
+ const page = list.slice(Math.max(0, offset), Math.max(0, offset) + SURVEY_PAGE);
6496
+ const left = list.length - Math.max(0, offset) - page.length;
6497
+ return {
6498
+ revision,
6499
+ edited,
6500
+ roles: described.pieceRoles,
6501
+ [what]: page,
6502
+ unsure: described.unsure.slice(0, 40),
6503
+ ...left > 0 ? { more: left } : {}
6504
+ };
6505
+ }
6506
+ /** Changes the survey as the person asks (all changes or none). The stages that read the survey before are stale from now on, and the import is no longer ready to be written. */
6507
+ async function changeSurvey(world, edits) {
6508
+ await need(world, ["surveyed", "built"], "changing the survey");
6509
+ const { items } = await load(world);
6510
+ const { survey, done } = editSurvey({
6511
+ classified: await readJson(join(folder(world), CLASSIFICATION)),
6512
+ roster: await readJson(join(folder(world), ROSTER))
6513
+ }, edits, new Set(items.map((item) => item.id)));
6514
+ await writeJson(join(folder(world), CLASSIFICATION), survey.classified);
6515
+ await writeJson(join(folder(world), ROSTER), survey.roster);
6516
+ await surveyEdited(world);
6517
+ await writeJson(join(folder(world), STATE), { phase: "surveyed" });
6518
+ return {
6519
+ done,
6520
+ stale: (await statusOf(world)).filter((entry) => entry.state === "stale").map((entry) => entry.stage)
6521
+ };
6522
+ }
6523
+ const STAGE_KIND = {
6524
+ places: "place",
6525
+ characters: "character",
6526
+ factions: "faction",
6527
+ things: "thing"
6528
+ };
6529
+ const STAGE_GROUP = {
6530
+ places: "locations",
6531
+ characters: "characters",
6532
+ factions: "factions",
6533
+ things: "items"
6534
+ };
6535
+ /** What a stage left out, without a model: the entities of its kind that have no document, and the notes the run made. */
6536
+ async function auditStage(world, stage) {
6537
+ await need(world, ["surveyed", "built"], "the audit");
6538
+ const record = await readStage(world, stage);
6539
+ const status = (await statusOf(world)).find((entry) => entry.stage === stage);
6540
+ if (record === void 0) return {
6541
+ stage,
6542
+ state: "not run yet",
6543
+ missing: [],
6544
+ notes: []
6545
+ };
6546
+ const kind = STAGE_KIND[stage];
6547
+ const roster = await readJson(join(folder(world), ROSTER));
6548
+ const made = new Set((record.extracted[STAGE_GROUP[stage] ?? "items"] ?? []).map((document) => String(document["id"] ?? "")));
6549
+ const missing = kind === void 0 ? [] : roster.filter((entity) => entity.kind === kind && !made.has(entity.key)).map((entity) => entity.name);
6550
+ return {
6551
+ stage,
6552
+ state: status.state === "stale" ? `stale: ${status.why ?? ""}` : status.state,
6553
+ missing,
6554
+ notes: (record.extracted.notes ?? []).slice(0, 40)
6555
+ };
6556
+ }
6557
+ /** One staged document in full, or the list of what a stage staged. */
6558
+ async function showStaged(world, stage, name) {
6559
+ await need(world, ["surveyed", "built"], "showing a stage");
6560
+ const record = await readStage(world, stage);
6561
+ if (record === void 0) throw new ImportStateError(`the stage "${stage}" has not run yet`);
6562
+ const extracted = record.extracted;
6563
+ const all = [
6564
+ ...(extracted.locations ?? []).map((document) => ({
6565
+ group: "place",
6566
+ document
6567
+ })),
6568
+ ...(extracted.characters ?? []).map((document) => ({
6569
+ group: "character",
6570
+ document
6571
+ })),
6572
+ ...(extracted.factions ?? []).map((document) => ({
6573
+ group: "faction",
6574
+ document
6575
+ })),
6576
+ ...(extracted.items ?? []).map((document) => ({
6577
+ group: "thing",
6578
+ document
6579
+ })),
6580
+ ...(extracted.lore ?? []).map((document) => ({
6581
+ group: "lore",
6582
+ document
6583
+ })),
6584
+ ...(extracted.variables ?? []).map((document) => ({
6585
+ group: "variable",
6586
+ document
6587
+ })),
6588
+ ...(extracted.commands ?? []).map((document) => ({
6589
+ group: "command",
6590
+ document
6591
+ })),
6592
+ ...(extracted.triggers ?? []).map((document) => ({
6593
+ group: "trigger",
6594
+ document
6595
+ })),
6596
+ ...(extracted.prompts ?? []).map((prompt) => ({
6597
+ group: "prompt",
6598
+ document: {
6599
+ id: prompt.id,
6600
+ text: prompt.text
6601
+ }
6602
+ })),
6603
+ ...(extracted.rules ?? []).map((rule, index) => ({
6604
+ group: "rule",
6605
+ document: {
6606
+ id: `rule-${index + 1}`,
6607
+ text: rule
6608
+ }
6609
+ }))
6610
+ ];
6611
+ const label = (document) => String(document["name"] ?? document["id"] ?? document["key"] ?? "");
6612
+ if (name === void 0) return {
6613
+ stage,
6614
+ documents: all.map((entry) => ({
6615
+ kind: entry.group,
6616
+ name: label(entry.document),
6617
+ characters: JSON.stringify(entry.document).length
6618
+ }))
6619
+ };
6620
+ const wanted = name.normalize("NFKC").toLowerCase().trim();
6621
+ const found = all.find((entry) => [label(entry.document), String(entry.document["id"] ?? "")].some((candidate) => candidate.normalize("NFKC").toLowerCase().trim() === wanted));
6622
+ if (found === void 0) throw new ImportStateError(`the stage "${stage}" staged nothing called "${name}": list what it staged by leaving the name out`);
6623
+ return {
6624
+ stage,
6625
+ kind: found.group,
6626
+ document: found.document
6627
+ };
6628
+ }
6629
+ /** Second step, all stages at once: write every character, place, faction, thing and background entry from the pieces that are about it. */
6630
+ async function build(ctx, world) {
6631
+ await need(world, ["surveyed", "built"], "the build");
6632
+ for (const stage of STAGES) {
6633
+ ctx.say(`stage: ${stage}`);
6634
+ await runStage(ctx, world, stage);
6635
+ }
6636
+ const extracted = {
6637
+ ...emptyExtracted(),
6638
+ ...await readJson(join(folder(world), EXTRACTED))
6639
+ };
5941
6640
  return {
5942
6641
  characters: extracted.characters.length,
5943
6642
  places: extracted.locations.length,
@@ -5959,7 +6658,7 @@ async function finish(ctx, world) {
5959
6658
  ...emptyExtracted(),
5960
6659
  ...await readJson(join(folder(world), EXTRACTED)).catch(() => ({}))
5961
6660
  };
5962
- const pictures = await ensurePictures(world, card.urls ?? []);
6661
+ const pictures = await ensurePictures(world, picturesToFetch(card, choices), pieceFinder(card, choices));
5963
6662
  const result = await finishImport(ctx, {
5964
6663
  directory: world,
5965
6664
  card,
@@ -6002,7 +6701,7 @@ async function structureImport(world, language) {
6002
6701
  await need(world, ["ready"], "the import without a model");
6003
6702
  const { card, choices, items, picture } = await load(world);
6004
6703
  const { classified, roster, extracted } = structureOnly(card, items, choices);
6005
- const pictures = await ensurePictures(world, card.urls ?? []);
6704
+ const pictures = await ensurePictures(world, picturesToFetch(card, choices), pieceFinder(card, choices));
6006
6705
  const result = await finishImport({
6007
6706
  noModel: true,
6008
6707
  run: () => Promise.reject(/* @__PURE__ */ new Error("this import has no model")),
@@ -6116,6 +6815,12 @@ const residencyOf = (agent) => agent.ctx.get("roleplayOrchestration")?.residency
6116
6815
  const SURVEY_TOOL = "import_survey";
6117
6816
  const BUILD_TOOL = "import_build";
6118
6817
  const FINISH_TOOL = "import_finish";
6818
+ const STATUS_TOOL = "import_status";
6819
+ const STAGE_TOOL = "import_stage";
6820
+ const SHOW_TOOL = "import_show";
6821
+ const AUDIT_TOOL = "import_audit";
6822
+ const SURVEY_SHOW_TOOL = "import_survey_show";
6823
+ const SURVEY_EDIT_TOOL = "import_survey_edit";
6119
6824
  /** How many times a turn that has not finished the import is sent back to it. */
6120
6825
  const MAX_OBJECTIONS = 3;
6121
6826
  /** How often a turn that left the world unable to start is sent back to mend it: each round can show a part of the world that was hidden behind the last one. */
@@ -6242,11 +6947,29 @@ async function worldOf(worlds, exec) {
6242
6947
  const toolNames = {
6243
6948
  survey: SURVEY_TOOL,
6244
6949
  build: BUILD_TOOL,
6245
- finish: FINISH_TOOL
6950
+ finish: FINISH_TOOL,
6951
+ status: STATUS_TOOL,
6952
+ stage: STAGE_TOOL,
6953
+ show: SHOW_TOOL,
6954
+ audit: AUDIT_TOOL,
6955
+ surveyShow: SURVEY_SHOW_TOOL,
6956
+ surveyEdit: SURVEY_EDIT_TOOL,
6957
+ stages: STAGES.join(", ")
6246
6958
  };
6959
+ /** Where the assistant stops in the import of the card waiting in a world: the person's choice, or the default for the card's size. */
6960
+ async function pauseFor(directory) {
6961
+ try {
6962
+ const { card, choices } = await readImportFolder(join(directory, IMPORT_FOLDER));
6963
+ return pauseOf(choices, card.book?.entries.length ?? 0);
6964
+ } catch (error) {
6965
+ if (error.code === "ENOENT") return "never";
6966
+ throw error;
6967
+ }
6968
+ }
6247
6969
  /** The three steps of an import, as tools of the authoring chat. They do their work in agents of their own, one narrow job each. */
6248
6970
  function importTools(worlds, settings, prompting) {
6249
6971
  const builds = /* @__PURE__ */ new Map();
6972
+ const stageRuns = /* @__PURE__ */ new Map();
6250
6973
  /** Runs one step for the world of the calling chat; what the model should do next is told in the result, in the person's language. */
6251
6974
  const step = async (exec, work, next, fresh = false) => {
6252
6975
  const world = await worldOf(worlds, exec);
@@ -6272,7 +6995,8 @@ function importTools(worlds, settings, prompting) {
6272
6995
  isConcurrencySafe: () => false,
6273
6996
  async execute(args, exec) {
6274
6997
  checkedCard(args);
6275
- return await step(exec, survey, (text) => text("import/next-survey"), true);
6998
+ const pause = await pauseFor((await worldOf(worlds, exec)).directory);
6999
+ return await step(exec, survey, (text) => text(pause === "never" ? "import/next-survey" : "import/next-survey-paused"), true);
6276
7000
  }
6277
7001
  }),
6278
7002
  defineTool({
@@ -6295,6 +7019,248 @@ function importTools(worlds, settings, prompting) {
6295
7019
  return await step(exec, build, (text) => text("import/next-build"));
6296
7020
  }
6297
7021
  }),
7022
+ defineTool({
7023
+ name: STATUS_TOOL,
7024
+ description: "Where the import of the card stands: the phase, every stage with whether it is done, still to do or stale (the survey changed after it ran), what each wrote, the person's note it was given, and whether the world can be written. Cheap; call it at the start of a turn and whenever you are unsure.",
7025
+ parameters: { card: cardParameter },
7026
+ output: output((value) => JSON.stringify(value, null, 1)),
7027
+ isConcurrencySafe: () => true,
7028
+ async execute(args, exec) {
7029
+ checkedCard(args);
7030
+ const { directory } = await worldOf(worlds, exec);
7031
+ return json({
7032
+ ...await importStatus(directory),
7033
+ pause: await pauseFor(directory)
7034
+ });
7035
+ }
7036
+ }),
7037
+ defineTool({
7038
+ name: SURVEY_SHOW_TOOL,
7039
+ description: "The survey as it stands: its entities (characters, places, organisations, things) with the pieces of the card each is written from, who the player plays, and what looks doubtful; or, with what \"pieces\", every piece with what it was taken to be and whom or what it is about. A page at a time.",
7040
+ parameters: {
7041
+ card: cardParameter,
7042
+ what: {
7043
+ type: "string",
7044
+ enum: ["entities", "pieces"],
7045
+ description: "What to list (default entities)."
7046
+ },
7047
+ offset: {
7048
+ type: "number",
7049
+ description: "Where to start in the list (default 0)."
7050
+ }
7051
+ },
7052
+ output: output((value) => JSON.stringify(value, null, 1)),
7053
+ isConcurrencySafe: () => true,
7054
+ async execute(args, exec) {
7055
+ checkedCard(args);
7056
+ const { directory } = await worldOf(worlds, exec);
7057
+ const offset = typeof args.offset === "number" && Number.isFinite(args.offset) ? Math.max(0, Math.floor(args.offset)) : 0;
7058
+ return json(await showSurvey(directory, args.what === "pieces" ? "pieces" : "entities", offset));
7059
+ }
7060
+ }),
7061
+ defineTool({
7062
+ name: SURVEY_EDIT_TOOL,
7063
+ description: "Corrects the survey when the person says it is wrong, all changes or none: rename an entity, merge two (the second becomes an alias of the first), change its kind, add or remove aliases, say which character the player plays, add or remove an entity, or set what a piece is (its roles) and whom it is about (its targets). The stages that already ran on the old survey become stale and are run again. Entities are named by key, name or alias.",
7064
+ parameters: {
7065
+ card: cardParameter,
7066
+ edits: {
7067
+ type: "array",
7068
+ required: true,
7069
+ description: "The changes, in order.",
7070
+ items: {
7071
+ type: "object",
7072
+ additionalProperties: false,
7073
+ properties: {
7074
+ op: {
7075
+ type: "string",
7076
+ required: true,
7077
+ enum: [
7078
+ "rename",
7079
+ "merge",
7080
+ "kind",
7081
+ "alias",
7082
+ "player",
7083
+ "add",
7084
+ "remove",
7085
+ "piece"
7086
+ ],
7087
+ description: "What to change."
7088
+ },
7089
+ entity: {
7090
+ type: "string",
7091
+ description: "The entity (rename, merge, kind, alias, player, remove)."
7092
+ },
7093
+ name: {
7094
+ type: "string",
7095
+ description: "The new name (rename, add)."
7096
+ },
7097
+ into: {
7098
+ type: "string",
7099
+ description: "The entity that stays (merge)."
7100
+ },
7101
+ kind: {
7102
+ type: "string",
7103
+ enum: [
7104
+ "character",
7105
+ "place",
7106
+ "faction",
7107
+ "thing"
7108
+ ],
7109
+ description: "The kind (kind, add)."
7110
+ },
7111
+ add: {
7112
+ type: "array",
7113
+ items: { type: "string" },
7114
+ description: "Aliases to add (alias)."
7115
+ },
7116
+ remove: {
7117
+ type: "array",
7118
+ items: { type: "string" },
7119
+ description: "Aliases to remove (alias)."
7120
+ },
7121
+ aliases: {
7122
+ type: "array",
7123
+ items: { type: "string" },
7124
+ description: "Aliases of the new entity (add)."
7125
+ },
7126
+ piece: {
7127
+ type: "string",
7128
+ description: "A piece id from import_survey_show (piece)."
7129
+ },
7130
+ roles: {
7131
+ type: "array",
7132
+ items: { type: "string" },
7133
+ description: "What the piece is, the most important first, one to three: character, player, speech, place, faction, thing, world, scenario, instruction, generator, template, irrelevant (piece)."
7134
+ },
7135
+ targets: {
7136
+ type: "array",
7137
+ items: {
7138
+ type: "object",
7139
+ additionalProperties: false,
7140
+ properties: {
7141
+ name: {
7142
+ type: "string",
7143
+ required: true
7144
+ },
7145
+ kind: {
7146
+ type: "string",
7147
+ required: true,
7148
+ enum: [
7149
+ "character",
7150
+ "place",
7151
+ "faction",
7152
+ "thing",
7153
+ "other"
7154
+ ]
7155
+ }
7156
+ }
7157
+ },
7158
+ description: "Whom or what the piece is about; replaces the list it has (piece)."
7159
+ }
7160
+ }
7161
+ }
7162
+ }
7163
+ },
7164
+ output: output((value) => JSON.stringify(value, null, 1)),
7165
+ isConcurrencySafe: () => false,
7166
+ async execute(args, exec) {
7167
+ checkedCard(args);
7168
+ const { directory } = await worldOf(worlds, exec);
7169
+ if (!Array.isArray(args.edits) || args.edits.length === 0) throw new Error("give at least one change in edits");
7170
+ try {
7171
+ return json(await changeSurvey(directory, args.edits));
7172
+ } catch (error) {
7173
+ if (error instanceof SurveyEditError) throw new Error(`nothing was changed:\n${error.problems.map((problem) => `- ${problem}`).join("\n")}`);
7174
+ throw error;
7175
+ }
7176
+ }
7177
+ }),
7178
+ defineTool({
7179
+ name: STAGE_TOOL,
7180
+ description: `Writes one part of the world from the survey, in agents of their own, and keeps it staged (the world itself is written by ${FINISH_TOOL}). The stages are ${STAGES.join(", ")}, best run in that order. It takes minutes. It reports what it wrote, what failed or was left out and why, and what is left. Run again, it asks only for what did not finish; a stage whose survey changed is run again in full. The person's note for the stage goes in guidance.`,
7181
+ parameters: {
7182
+ card: cardParameter,
7183
+ stage: {
7184
+ type: "string",
7185
+ required: true,
7186
+ enum: [...STAGES],
7187
+ description: "The part to write."
7188
+ },
7189
+ guidance: {
7190
+ type: "string",
7191
+ description: "What the person asked for this stage, in their words (\"be mindful that ...\"). Part of every job of the stage; leave it out when they said nothing."
7192
+ }
7193
+ },
7194
+ output: output((value) => JSON.stringify(value, null, 1)),
7195
+ isConcurrencySafe: () => false,
7196
+ async execute(args, exec) {
7197
+ checkedCard(args);
7198
+ const stage = args.stage;
7199
+ if (!isStage(stage)) throw new Error(`stage is one of ${STAGES.join(", ")}`);
7200
+ const chat = exec.agent?.session.id ?? "";
7201
+ const turn = exec.agent === void 0 ? 0 : currentTurn(exec.agent);
7202
+ const key = `${chat}:${stage}`;
7203
+ const seen = stageRuns.get(key);
7204
+ const count = seen?.turn === turn ? seen.count + 1 : 1;
7205
+ if (count > MAX_BUILDS_PER_TURN) throw new Error(`the stage "${stage}" has already run ${MAX_BUILDS_PER_TURN} times in this turn: do not run it again, tell the person what is wrong and stop`);
7206
+ stageRuns.set(key, {
7207
+ turn,
7208
+ count
7209
+ });
7210
+ const guidance = typeof args.guidance === "string" ? args.guidance : void 0;
7211
+ return await step(exec, async (ctx, directory) => ({
7212
+ ...await runStage(ctx, directory, stage, guidance),
7213
+ pause: await pauseFor(directory)
7214
+ }), (text, result) => nextAfterStage(text, result));
7215
+ }
7216
+ }),
7217
+ defineTool({
7218
+ name: SHOW_TOOL,
7219
+ description: "What a stage staged: without a name, the list of its documents; with a name (or id), that document in full, as it will be written into the world. Use it to answer the person who wants to see a character, a place or a rule before the world is written.",
7220
+ parameters: {
7221
+ card: cardParameter,
7222
+ stage: {
7223
+ type: "string",
7224
+ required: true,
7225
+ enum: [...STAGES],
7226
+ description: "The stage."
7227
+ },
7228
+ name: {
7229
+ type: "string",
7230
+ description: "The name or id of one document."
7231
+ }
7232
+ },
7233
+ output: output((value) => JSON.stringify(value, null, 1)),
7234
+ isConcurrencySafe: () => true,
7235
+ async execute(args, exec) {
7236
+ checkedCard(args);
7237
+ const stage = args.stage;
7238
+ if (!isStage(stage)) throw new Error(`stage is one of ${STAGES.join(", ")}`);
7239
+ const { directory } = await worldOf(worlds, exec);
7240
+ return json(await showStaged(directory, stage, typeof args.name === "string" && args.name.trim() !== "" ? args.name : void 0));
7241
+ }
7242
+ }),
7243
+ defineTool({
7244
+ name: AUDIT_TOOL,
7245
+ description: "What a stage left out, worked out without a model: the entities of its kind that have no staged document, and the notes its run made. Then compare with the card (card_read) when the person asks whether something was lost.",
7246
+ parameters: {
7247
+ card: cardParameter,
7248
+ stage: {
7249
+ type: "string",
7250
+ required: true,
7251
+ enum: [...STAGES],
7252
+ description: "The stage."
7253
+ }
7254
+ },
7255
+ output: output((value) => JSON.stringify(value, null, 1)),
7256
+ isConcurrencySafe: () => true,
7257
+ async execute(args, exec) {
7258
+ checkedCard(args);
7259
+ const stage = args.stage;
7260
+ if (!isStage(stage)) throw new Error(`stage is one of ${STAGES.join(", ")}`);
7261
+ return json(await auditStage((await worldOf(worlds, exec)).directory, stage));
7262
+ }
7263
+ }),
6298
7264
  defineTool({
6299
7265
  name: FINISH_TOOL,
6300
7266
  description: "Step 3 of importing a character card: write the world together with its description, tags, opening and cover, check whether a story can start from it, and report what was imported. A world that still has problems is kept as a repairable draft. Run after the build.",
@@ -6308,14 +7274,33 @@ function importTools(worlds, settings, prompting) {
6308
7274
  })
6309
7275
  ];
6310
7276
  }
7277
+ /** What to do after a stage: go on to the next one, or stop and report, as the pause of the import says. */
7278
+ function nextAfterStage(text, report) {
7279
+ const todo = STAGES.filter((stage) => report.left.includes(stage) || report.stale.includes(stage));
7280
+ if (report.pause === "stages") return text("import/next-stage-paused", { left: todo.length === 0 ? `nothing: the next step is ${FINISH_TOOL}, which writes the world` : todo.join(", ") });
7281
+ return text("import/next-stage-go", {
7282
+ next: report.complete ? FINISH_TOOL : `${STAGE_TOOL} with stage "${todo[0]}"`,
7283
+ card: CARD
7284
+ });
7285
+ }
7286
+ /** Whether the import may hand the turn back after a completed step. A survey-only pause is spent once any stage has started. */
7287
+ const pausesAfterStep = (pause, stages) => pause === "stages" || pause === "survey" && stages.every((stage) => stage.state === "todo");
6311
7288
  /** The procedure of an import turn, told to the chat in place of what it does for any other message. */
6312
- function importNotice(phase, text) {
7289
+ function importNotice(phase, text, pause = "never") {
6313
7290
  if (phase === void 0) return text("import/notice-missing");
6314
7291
  if (phase === "repair") return text("import/notice-repair");
6315
- return text("import/notice", {
7292
+ const done = phase === "done" ? text("import/notice-done") : "";
7293
+ if (pause === "never" || phase === "done") return text("import/notice", {
6316
7294
  card: CARD,
6317
7295
  phase,
6318
- done: phase === "done" ? text("import/notice-done") : ""
7296
+ done
7297
+ });
7298
+ return text("import/notice-staged", {
7299
+ card: CARD,
7300
+ phase,
7301
+ done,
7302
+ pause,
7303
+ policy: text(pause === "survey" ? "import/pause-survey" : "import/pause-stages")
6319
7304
  });
6320
7305
  }
6321
7306
  /** The text of an import's prompts for a world: in the language of its authoring chat, with the names of the import tools filled in. */
@@ -6404,6 +7389,15 @@ function importHooks(ctx, worlds, prompting, state) {
6404
7389
  imports.delete(chat);
6405
7390
  return;
6406
7391
  }
7392
+ if ((phase === "surveyed" || phase === "built") && record !== void 0) {
7393
+ const pause = await pauseFor(record.directory);
7394
+ const stages = pause === "survey" ? (await importStatus(record.directory)).stages : [];
7395
+ if (pausesAfterStep(pause, stages)) {
7396
+ imports.delete(chat);
7397
+ objections.delete(chat);
7398
+ return;
7399
+ }
7400
+ }
6407
7401
  const told = objections.get(chat) ?? 0;
6408
7402
  if (told >= MAX_OBJECTIONS) {
6409
7403
  imports.delete(chat);
@@ -6453,7 +7447,7 @@ async function beginImport(deps, chat, request) {
6453
7447
  deps.state.repairs.delete(chat);
6454
7448
  }
6455
7449
  if (phase === "repair") await startRepair(record.directory);
6456
- const notice = importNotice(phase, deps.text(worldId));
7450
+ const notice = importNotice(phase, deps.text(worldId), await pauseFor(record.directory));
6457
7451
  return {
6458
7452
  ok: true,
6459
7453
  message: request.trim() === "" ? notice : `${notice}\n\n${request.trim()}`
@@ -6500,6 +7494,6 @@ function limitAuthoringAgents(ctx, kindOf) {
6500
7494
  return await next();
6501
7495
  });
6502
7496
  }
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 };
7497
+ export { checkWorld as $, authoredWorldOf as $t, loadWorldParts as A, lettersOf$1 as At, localChanges as B, commandVariable 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, ImportCardError as Gt, writeOrigin as H, parseCommandsFile as Ht, writeSnapshot as I, entitiesByPiece as It, guardedLookup as J, pictureOf as Jt, candidateUrls as K, cardFormat as Kt, describeChanges as L, pieceFinder 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, DICE_RESULTS as Qt, hashWorld as R, readSource as Rt, addressChanges as S, DICE_FILE_NAME as St, matchPieces as T, CALENDAR_FILE_NAME as Tt, CatalogueError as U, TRIGGERS_FILE_NAME as Ut, readOrigin as V, loadCommands as Vt, addressKey as W, loadTriggers as Wt, vetUrl as X, DICE_COMPARISONS as Xt, mergeReports as Y, readCard as Yt, cardCharacter as Z, DICE_READINGS 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, authoringChatSessionId as en, 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, isPng 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, COMMANDS_FILE_NAME as zt };
6504
7498
 
6505
- //# sourceMappingURL=authoring-tools-BpkpGMSO.js.map
7499
+ //# sourceMappingURL=authoring-tools-CKV1UnN7.js.map