briyah 2.0.6 → 2.0.7

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 (40) hide show
  1. package/README.md +105 -0
  2. package/data/packs/dnd5e/pack.json +7 -1
  3. package/dist-sdk/server/src/ai/agent.d.ts +27 -0
  4. package/dist-sdk/server/src/ai/agent.js +54 -13
  5. package/dist-sdk/server/src/app/user-service-factory.js +3 -0
  6. package/dist-sdk/server/src/app.controller.d.ts +7 -1
  7. package/dist-sdk/server/src/app.controller.js +55 -0
  8. package/dist-sdk/server/src/app.service.d.ts +114 -2
  9. package/dist-sdk/server/src/app.service.js +181 -4
  10. package/dist-sdk/server/src/documents/document-conversion.d.ts +70 -0
  11. package/dist-sdk/server/src/documents/document-conversion.js +341 -0
  12. package/dist-sdk/server/src/documents/library/chunking.d.ts +65 -0
  13. package/dist-sdk/server/src/documents/library/chunking.js +263 -0
  14. package/dist-sdk/server/src/documents/library/document-guide.builder.d.ts +2 -0
  15. package/dist-sdk/server/src/documents/library/document-guide.builder.js +58 -0
  16. package/dist-sdk/server/src/documents/library/document-registry.d.ts +22 -0
  17. package/dist-sdk/server/src/documents/library/document-registry.js +44 -0
  18. package/dist-sdk/server/src/documents/library/document.types.d.ts +108 -0
  19. package/dist-sdk/server/src/documents/library/document.types.js +20 -0
  20. package/dist-sdk/server/src/documents/library/embedding.d.ts +57 -0
  21. package/dist-sdk/server/src/documents/library/embedding.js +151 -0
  22. package/dist-sdk/server/src/packs/pack-manifest.d.ts +46 -0
  23. package/dist-sdk/server/src/packs/pack-manifest.js +46 -1
  24. package/dist-sdk/server/src/room/artifact-store.service.js +44 -11
  25. package/dist-sdk/server/src/room/artifact.d.ts +8 -0
  26. package/dist-sdk/server/src/room/room.js +7 -1
  27. package/dist-sdk/server/src/rpg/rpg-roster.d.ts +70 -29
  28. package/dist-sdk/server/src/rpg/rpg-roster.js +152 -41
  29. package/dist-sdk/server/src/rpg/rpg.service.d.ts +66 -29
  30. package/dist-sdk/server/src/rpg/rpg.service.js +140 -65
  31. package/dist-sdk/server/src/sdk/index.d.ts +12 -2
  32. package/dist-sdk/server/src/sdk/index.js +27 -1
  33. package/dist-sdk/server/src/tools/core/document.tools.d.ts +39 -0
  34. package/dist-sdk/server/src/tools/core/document.tools.js +391 -0
  35. package/dist-sdk/server/src/tools/core/index.js +2 -1
  36. package/dist-sdk/server/src/tools/native-tool.types.d.ts +37 -0
  37. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +23 -2
  38. package/dist-sdk/server/src/tools/tool-execution.service.js +30 -6
  39. package/dist-sdk/shared/types/app.types.d.ts +39 -5
  40. package/package.json +172 -167
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ /**
3
+ * Turning text into vectors for semantic search.
4
+ *
5
+ * Anthropic publishes no embeddings endpoint, so this defaults to OpenAI's
6
+ * `text-embedding-3-small`. The provider sits behind {@link EmbeddingProvider} so
7
+ * a host can supply another, and so tests never reach a network.
8
+ *
9
+ * The dimension is the one number a host has to agree with: it is baked into the
10
+ * vector column of whatever database stores the result, and a model that returns
11
+ * a different length would fail every insert — or worse, succeed against a column
12
+ * declared without one. So {@link EMBEDDING_DIMENSIONS} is exported for the host's
13
+ * migration to use, and every response is checked against what was asked for.
14
+ */
15
+ var __importDefault = (this && this.__importDefault) || function (mod) {
16
+ return (mod && mod.__esModule) ? mod : { "default": mod };
17
+ };
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.EMBEDDING_DIMENSIONS = exports.DEFAULT_EMBEDDING_MODEL = void 0;
20
+ exports.embedTexts = embedTexts;
21
+ const openai_1 = __importDefault(require("openai"));
22
+ const model_prices_1 = require("../../ai/model_prices");
23
+ const logger_1 = require("../../common/logger");
24
+ /** The default model. Override with `EMBEDDING_MODEL` or per call. */
25
+ exports.DEFAULT_EMBEDDING_MODEL = 'text-embedding-3-small';
26
+ /**
27
+ * The vector length a host's schema should declare. `text-embedding-3-small`
28
+ * produces 1536 natively. Override with `EMBEDDING_DIMENSIONS` only together with
29
+ * a migration — the column and the model have to change as one.
30
+ */
31
+ exports.EMBEDDING_DIMENSIONS = 1536;
32
+ /**
33
+ * OpenAI allows 2,048 inputs and 300,000 tokens per request. The token bound is
34
+ * the one that bites: 2,048 chunks of 1,800 characters is roughly a million
35
+ * tokens. Batches are sized by an estimate that errs high.
36
+ */
37
+ const MAX_INPUTS_PER_REQUEST = 2_048;
38
+ const MAX_ESTIMATED_TOKENS_PER_REQUEST = 200_000;
39
+ /**
40
+ * One input's hard ceiling is 8,191 tokens. Text past this is cut rather than
41
+ * failing the batch — a passage that long is not a passage, and the first part of
42
+ * it is still a good vector for what it is about.
43
+ */
44
+ const MAX_CHARS_PER_INPUT = 24_000;
45
+ /** Characters per token, pessimistically: dense tables and numbers tokenize poorly. */
46
+ const CHARS_PER_TOKEN_ESTIMATE = 3;
47
+ /**
48
+ * Embeds texts in as few requests as the provider's limits allow.
49
+ *
50
+ * @throws If the provider is unavailable, or returns vectors of the wrong length
51
+ */
52
+ async function embedTexts(texts, options = {}) {
53
+ const model = options.model || process.env.EMBEDDING_MODEL || exports.DEFAULT_EMBEDDING_MODEL;
54
+ const dimensions = options.dimensions || Number(process.env.EMBEDDING_DIMENSIONS) || exports.EMBEDDING_DIMENSIONS;
55
+ const provider = options.provider ?? openAiProvider();
56
+ const progress = options.onProgress ?? (() => undefined);
57
+ const inputs = texts.map((text) => (text || ' ').slice(0, MAX_CHARS_PER_INPUT));
58
+ const batches = batch(inputs);
59
+ const vectors = [];
60
+ let tokens = 0;
61
+ for (let i = 0; i < batches.length; i++) {
62
+ const result = await provider.embed(batches[i], model, dimensions);
63
+ if (result.vectors.length !== batches[i].length) {
64
+ throw new Error(`The embedding provider returned ${result.vectors.length} vectors for ${batches[i].length} inputs.`);
65
+ }
66
+ const wrong = result.vectors.find((vector) => vector.length !== dimensions);
67
+ if (wrong) {
68
+ throw new Error(`The embedding model "${model}" returned vectors of length ${wrong.length}, not ${dimensions}. ` +
69
+ 'The model and the database column have to agree; change them together.');
70
+ }
71
+ vectors.push(...result.vectors);
72
+ tokens += result.tokens;
73
+ if (batches.length > 1) {
74
+ progress(`Embedded batch ${i + 1} of ${batches.length}.`);
75
+ }
76
+ }
77
+ return { vectors, model, dimensions, tokens, cost: tokens * pricePerToken(model) };
78
+ }
79
+ /**
80
+ * The model's price per input token, or zero when it cannot be found. Accounting
81
+ * failing is logged, never fatal: the vectors are already paid for, and throwing
82
+ * them away over a missing price file would only mean paying for them twice.
83
+ */
84
+ function pricePerToken(model) {
85
+ try {
86
+ return (0, model_prices_1.resolveModelInfo)(model)?.input_cost_per_token ?? 0;
87
+ }
88
+ catch (error) {
89
+ logger_1.logger.warn(`No price for embedding model "${model}"; recording its cost as zero. ${error.message}`);
90
+ return 0;
91
+ }
92
+ }
93
+ /** Groups inputs so no request passes either of the provider's limits. */
94
+ function batch(inputs) {
95
+ const batches = [];
96
+ let current = [];
97
+ let estimate = 0;
98
+ for (const input of inputs) {
99
+ const tokens = Math.ceil(input.length / CHARS_PER_TOKEN_ESTIMATE);
100
+ if (current.length && (current.length >= MAX_INPUTS_PER_REQUEST || estimate + tokens > MAX_ESTIMATED_TOKENS_PER_REQUEST)) {
101
+ batches.push(current);
102
+ current = [];
103
+ estimate = 0;
104
+ }
105
+ current.push(input);
106
+ estimate += tokens;
107
+ }
108
+ if (current.length) {
109
+ batches.push(current);
110
+ }
111
+ return batches;
112
+ }
113
+ let defaultProvider = null;
114
+ /** OpenAI, constructed on first use so a host that never embeds needs no key. */
115
+ function openAiProvider() {
116
+ if (defaultProvider) {
117
+ return defaultProvider;
118
+ }
119
+ const apiKey = process.env.OPENAI_API_KEY;
120
+ if (!apiKey) {
121
+ throw new Error('Embedding needs OPENAI_API_KEY, or an EmbeddingProvider passed in the options.');
122
+ }
123
+ const client = new openai_1.default({
124
+ apiKey,
125
+ maxRetries: 4,
126
+ timeout: 120_000,
127
+ ...(process.env.OPENAI_ORGANIZATION_ID && { organization: process.env.OPENAI_ORGANIZATION_ID }),
128
+ });
129
+ defaultProvider = {
130
+ async embed(texts, model, dimensions) {
131
+ // Sent only to shorten a model's native vectors: a model that cannot
132
+ // shorten them rejects the parameter even when it matches.
133
+ let native;
134
+ try {
135
+ native = (0, model_prices_1.resolveModelInfo)(model)?.output_vector_size;
136
+ }
137
+ catch {
138
+ native = undefined; // no price table: send nothing, take the model's own size
139
+ }
140
+ const response = await client.embeddings.create({
141
+ model,
142
+ input: texts,
143
+ ...(native && native !== dimensions ? { dimensions } : {}),
144
+ });
145
+ // The API documents `index`; order by it rather than trusting array order.
146
+ const ordered = [...response.data].sort((a, b) => a.index - b.index);
147
+ return { vectors: ordered.map((item) => item.embedding), tokens: response.usage?.total_tokens ?? 0 };
148
+ },
149
+ };
150
+ return defaultProvider;
151
+ }
@@ -19,6 +19,10 @@
19
19
  * copy of a directory listing drifts from it — which is the mistake
20
20
  * `prompt-folders.spec.ts` exists to catch in the D&D prompts.
21
21
  *
22
+ * {@link PackTable} is the exception, and it is one because it declares a *choice*
23
+ * rather than a listing: a pack ships several room templates and nothing on disk
24
+ * says which of them the RPG page should build.
25
+ *
22
26
  * `pack.json` is optional. A directory holding only `artifacts/manifest.json` is
23
27
  * still a pack, titled after itself.
24
28
  */
@@ -51,7 +55,47 @@ export interface PackManifest {
51
55
  * never an auto-enable, never a block.
52
56
  */
53
57
  requiresPacks?: string[];
58
+ /** What the RPG page builds from this pack. Absent means it is not a game pack. */
59
+ table?: PackTable;
60
+ }
61
+ /**
62
+ * How a pack is played from the RPG page.
63
+ *
64
+ * The RPG page exists to reduce a table to two decisions — who is playing and how
65
+ * good the models are — so it needs one room template to build and one agent
66
+ * template to seat a party from. A pack ships several of each and nothing on disk
67
+ * distinguishes them: `rooms/table.json` and `rooms/campaign.json` are both real
68
+ * D&D tables, and only one of them is the one to build when the party is chosen
69
+ * separately. So this is declared, and everything a declaration would duplicate —
70
+ * the prompt folder a seat comes from, which crew agents are expensive, what the
71
+ * seats are called — is derived from the templates it names.
72
+ *
73
+ * A pack without one is not offered, which is every pack but a game.
74
+ */
75
+ export interface PackTable {
76
+ /**
77
+ * The room template to build: the crew, and **no player seats**.
78
+ *
79
+ * Player-less because the RPG page seats the party itself, one agent at a time,
80
+ * so each AI player can have its own model and its own personality. A template
81
+ * that seats a player would have the party arrive twice.
82
+ */
83
+ room: string;
84
+ /** The agent template one seat is created from, and the roster discriminator. */
85
+ playerAgent: string;
86
+ /** What one player is called: `Player`, `Student`. Defaults to `Player`. */
87
+ playerNoun: string;
88
+ /** How many the table seats. Defaults to {@link MAX_TABLE_SEATS}. */
89
+ maxPlayers: number;
54
90
  }
91
+ /**
92
+ * The most seats a pack may ask for.
93
+ *
94
+ * Not a technical limit — the room does not care. But every player is another agent
95
+ * perceiving every message, and a pack asking for forty has made a mistake rather
96
+ * than a choice.
97
+ */
98
+ export declare const MAX_TABLE_SEATS = 12;
55
99
  /**
56
100
  * One agent a pack ships, as a reference to a prompt folder plus overrides.
57
101
  *
@@ -146,6 +190,8 @@ export interface LoadedPack {
146
190
  /** Tool names the pack's grants and manifest between them ask for. */
147
191
  requiresTools: string[];
148
192
  requiresPacks: string[];
193
+ /** How the RPG page plays it, when the pack says. Absent for a pack that is not a game. */
194
+ table?: PackTable;
149
195
  }
150
196
  export type PackOrigin = 'host' | 'user';
151
197
  /**
@@ -20,6 +20,10 @@
20
20
  * copy of a directory listing drifts from it — which is the mistake
21
21
  * `prompt-folders.spec.ts` exists to catch in the D&D prompts.
22
22
  *
23
+ * {@link PackTable} is the exception, and it is one because it declares a *choice*
24
+ * rather than a listing: a pack ships several room templates and nothing on disk
25
+ * says which of them the RPG page should build.
26
+ *
23
27
  * `pack.json` is optional. A directory holding only `artifacts/manifest.json` is
24
28
  * still a pack, titled after itself.
25
29
  */
@@ -57,7 +61,7 @@ var __importStar = (this && this.__importStar) || (function () {
57
61
  };
58
62
  })();
59
63
  Object.defineProperty(exports, "__esModule", { value: true });
60
- exports.PACK_SUBDIR = void 0;
64
+ exports.MAX_TABLE_SEATS = exports.PACK_SUBDIR = void 0;
61
65
  exports.readPack = readPack;
62
66
  exports.roomAgentKey = roomAgentKey;
63
67
  const fs = __importStar(require("fs"));
@@ -71,6 +75,14 @@ exports.PACK_SUBDIR = {
71
75
  agents: 'agents',
72
76
  rooms: 'rooms',
73
77
  };
78
+ /**
79
+ * The most seats a pack may ask for.
80
+ *
81
+ * Not a technical limit — the room does not care. But every player is another agent
82
+ * perceiving every message, and a pack asking for forty has made a mistake rather
83
+ * than a choice.
84
+ */
85
+ exports.MAX_TABLE_SEATS = 12;
74
86
  /**
75
87
  * Reads a pack directory.
76
88
  *
@@ -93,6 +105,7 @@ function readPack(dir, name, origin) {
93
105
  return null;
94
106
  }
95
107
  const manifest = readManifest(dir, name);
108
+ const table = manifest?.table ? validateTable(manifest.table, dir) : null;
96
109
  const agents = readTemplates(dir, exports.PACK_SUBDIR.agents, validateAgentTemplate);
97
110
  const rooms = readTemplates(dir, exports.PACK_SUBDIR.rooms, validateRoomTemplate);
98
111
  const promptFolders = subdirectoriesOf(path.join(dir, exports.PACK_SUBDIR.prompts));
@@ -108,6 +121,7 @@ function readPack(dir, name, origin) {
108
121
  rooms,
109
122
  requiresTools: deriveRequiredTools(dir, promptFolders, agents, manifest),
110
123
  requiresPacks: (manifest?.requiresPacks ?? []).filter(prompt_resolver_1.isValidPackName),
124
+ ...(table && { table }),
111
125
  };
112
126
  }
113
127
  /**
@@ -233,6 +247,37 @@ function sanitizeOverrides(overrides, file) {
233
247
  }
234
248
  return clean;
235
249
  }
250
+ /**
251
+ * Reads the `table` block, or drops it with a warning.
252
+ *
253
+ * Dropped rather than thrown, as a malformed template is: a `table` a host mistyped
254
+ * costs them the pack's row in the RPG page's game picker, not the whole pack. The
255
+ * keys it names are resolved where they are used, so a `room` that does not exist
256
+ * is caught with the rest of the roster rather than twice.
257
+ */
258
+ function validateTable(value, dir) {
259
+ const where = `${dir}/pack.json`;
260
+ if (!value || typeof value !== 'object') {
261
+ logger_1.logger.warn(`Ignoring "table" in ${where}: expected a JSON object`);
262
+ return null;
263
+ }
264
+ if (!isValidKey(value.room) || !isValidKey(value.playerAgent)) {
265
+ logger_1.logger.warn(`Ignoring "table" in ${where}: "room" and "playerAgent" must both name a template`);
266
+ return null;
267
+ }
268
+ const noun = typeof value.playerNoun === 'string' ? value.playerNoun.trim() : '';
269
+ const seats = Number(value.maxPlayers);
270
+ const seatable = Number.isInteger(seats) && seats >= 1 && seats <= exports.MAX_TABLE_SEATS;
271
+ if (value.maxPlayers !== undefined && !seatable) {
272
+ logger_1.logger.warn(`Seating ${exports.MAX_TABLE_SEATS} at ${where}'s table: "maxPlayers" must be 1 to ${exports.MAX_TABLE_SEATS}`);
273
+ }
274
+ return {
275
+ room: value.room,
276
+ playerAgent: value.playerAgent,
277
+ playerNoun: noun || 'Player',
278
+ maxPlayers: seatable ? seats : exports.MAX_TABLE_SEATS,
279
+ };
280
+ }
236
281
  function validateRoomTemplate(value, file) {
237
282
  if (!value || typeof value !== 'object') {
238
283
  logger_1.logger.warn(`Ignoring ${file}: expected a JSON object`);
@@ -233,21 +233,47 @@ let ArtifactStoreService = class ArtifactStoreService {
233
233
  else {
234
234
  viewers = [creator]; // Missing viewers line defaults to creator only
235
235
  }
236
- // An optional `# transient: true` follows the viewers line. Older files
237
- // have no such line and load as cached artifacts, which is what they were.
238
- let bodyStart = 3;
236
+ // Optional headers follow the viewers line, each written only when set:
237
+ // `# transient:`, `# created:`, `# updated:`. Older files have none of
238
+ // them and load as they always did. The loop stops at the blank line that
239
+ // separates headers from the body, so a body opening with a markdown
240
+ // heading is never mistaken for one.
241
+ let index = viewersLine.startsWith('# viewers: ') ? 3 : 2;
239
242
  let transient = false;
240
- if (lines[3] && lines[3].startsWith('# transient: ')) {
241
- transient = lines[3].substring('# transient: '.length).trim() === 'true';
242
- bodyStart = 4;
243
+ let createdAt;
244
+ let updatedAt;
245
+ for (; index < lines.length; index++) {
246
+ const header = lines[index].match(/^# (transient|created|updated): (.*)$/);
247
+ if (!header) {
248
+ break;
249
+ }
250
+ const value = header[2].trim();
251
+ if (header[1] === 'transient') {
252
+ transient = value === 'true';
253
+ }
254
+ else if (header[1] === 'created') {
255
+ createdAt = value;
256
+ }
257
+ else {
258
+ updatedAt = value;
259
+ }
260
+ }
261
+ // formatArtifactFile separates the headers from the body with exactly one
262
+ // blank line, so skip exactly one. Leaving it in prepended a newline to
263
+ // the body on every load — a body grew by a line each time it was loaded
264
+ // and saved again, and anything fingerprinting bodies saw it change.
265
+ if (index < lines.length && lines[index].trim() === '') {
266
+ index++;
243
267
  }
244
- const body = lines.slice(bodyStart).join('\n');
268
+ const body = lines.slice(index).join('\n');
245
269
  return {
246
270
  name,
247
271
  creator,
248
272
  body,
249
273
  viewers,
250
274
  ...(transient && { transient }),
275
+ ...(createdAt && { createdAt }),
276
+ ...(updatedAt && { updatedAt }),
251
277
  };
252
278
  }
253
279
  /**
@@ -257,12 +283,19 @@ let ArtifactStoreService = class ArtifactStoreService {
257
283
  const viewersStr = artifact.viewers && artifact.viewers.length > 0
258
284
  ? artifact.viewers.join(', ')
259
285
  : artifact.creator; // Default to creator if no viewers specified
260
- // The transient line is written only when set, so an ordinary artifact's
261
- // file is byte-identical to what earlier versions produced.
262
- const transientLine = artifact.transient ? '\n# transient: true' : '';
286
+ // Optional headers are written only when set, so an artifact that uses
287
+ // none of them produces the same file earlier versions did.
288
+ const optional = [
289
+ artifact.transient ? '# transient: true' : null,
290
+ artifact.createdAt ? `# created: ${artifact.createdAt}` : null,
291
+ artifact.updatedAt ? `# updated: ${artifact.updatedAt}` : null,
292
+ ]
293
+ .filter((line) => line !== null)
294
+ .map((line) => `\n${line}`)
295
+ .join('');
263
296
  return `# name: ${artifact.name}
264
297
  # creator: ${artifact.creator}
265
- # viewers: ${viewersStr}${transientLine}
298
+ # viewers: ${viewersStr}${optional}
266
299
 
267
300
  ${artifact.body}`;
268
301
  }
@@ -22,4 +22,12 @@ export interface Artifact {
22
22
  * artifact that is large and stable is cheaper left cached.
23
23
  */
24
24
  transient?: boolean;
25
+ /**
26
+ * When the artifact was first published, as an ISO string. Absent on
27
+ * artifacts saved before timestamps existed — nothing invents one for them,
28
+ * since a made-up creation date is worse than an honest blank.
29
+ */
30
+ createdAt?: string;
31
+ /** When the artifact was last written, as an ISO string. */
32
+ updatedAt?: string;
25
33
  }
@@ -1487,7 +1487,7 @@ class Room {
1487
1487
  async executeToolForAgent(agent, message) {
1488
1488
  const toolName = message.name;
1489
1489
  const result = this.toolExecutionService
1490
- ? await this.toolExecutionService.runForAgent(toolName, message.content, agent.toolNames || [], this.currentToolContext, this.buildToolRoomAccess(agent), this.buildToolIllustration(agent))
1490
+ ? await this.toolExecutionService.runForAgent(toolName, message.content, agent.toolNames || [], this.currentToolContext, this.buildToolRoomAccess(agent), this.buildToolIllustration(agent), agent.id)
1491
1491
  : { ok: false, error: 'Tool execution is not available in this room' };
1492
1492
  const argsPreview = Room.previewForToolLog(message.content || '', Room.TOOL_LOG_ARGS_PREVIEW);
1493
1493
  const statusText = 'error' in result ? `error: ${result.error}` : Room.describeToolResult(result.result);
@@ -1896,6 +1896,7 @@ Recent Message: ${message.getContent()}
1896
1896
  // Check if an artifact with this name already exists
1897
1897
  const existingIndex = this.artifacts.findIndex((a) => a.name === name);
1898
1898
  let returnedArtifact;
1899
+ const now = new Date().toISOString();
1899
1900
  if (existingIndex >= 0) {
1900
1901
  // Update existing artifact
1901
1902
  this.artifacts[existingIndex].body = body;
@@ -1906,6 +1907,9 @@ Recent Message: ${message.getContent()}
1906
1907
  if (transient !== undefined) {
1907
1908
  this.artifacts[existingIndex].transient = transient;
1908
1909
  }
1910
+ // createdAt is left alone — including when it is absent, on an
1911
+ // artifact saved before timestamps existed.
1912
+ this.artifacts[existingIndex].updatedAt = now;
1909
1913
  returnedArtifact = this.artifacts[existingIndex];
1910
1914
  }
1911
1915
  else {
@@ -1916,6 +1920,8 @@ Recent Message: ${message.getContent()}
1916
1920
  body,
1917
1921
  viewers: viewers.length > 0 ? viewers : [creator], // If no viewers specified, only creator can see
1918
1922
  ...(transient !== undefined && { transient }),
1923
+ createdAt: now,
1924
+ updatedAt: now,
1919
1925
  };
1920
1926
  this.artifacts.push(newArtifact);
1921
1927
  returnedArtifact = newArtifact;
@@ -1,45 +1,86 @@
1
1
  /**
2
- * What a campaign's party may be, decided before anything is created.
2
+ * What a table is, and what a party may be.
3
3
  *
4
- * Pure on purpose: no filesystem, no Nest, no `AppService`. Every rule here is one
5
- * the room would otherwise enforce badly or late, and the whole point is to refuse a
6
- * party the room could not route while refusing costs nothing.
4
+ * A table is one installed pack's `table` block — see {@link PackTable} — resolved
5
+ * against the templates it names. That resolution is the whole of this module: the
6
+ * pack declares which room to build and which agent template is a seat, and
7
+ * everything else the RPG page needs is derived from those two, so a pack never says
8
+ * the same thing twice. The prompt folder comes from the seat template; the crew and
9
+ * which of them are expensive come from the room template; the seat placeholders come
10
+ * from the pack's noun.
11
+ *
12
+ * No filesystem and no Nest: a {@link LoadedPack} arrives already read, and every rule
13
+ * about the shape of a party is one the room would otherwise enforce badly or late.
14
+ * The point of refusing here is that refusing costs nothing.
15
+ */
16
+ import { PromptFolderDefaults, RpgPackOption, RpgPlayerRequest } from '../../../shared/types/app.types';
17
+ import { LoadedPack } from '../packs/pack-manifest';
18
+ /** One pack's table, resolved: everything needed to build one and to describe it. */
19
+ export interface RpgTable {
20
+ /** The pack supplying the rules. */
21
+ pack: string;
22
+ title: string;
23
+ description?: string;
24
+ /** The pack's player-less room template — the crew, and no seats. */
25
+ roomKey: string;
26
+ /** The agent template a seat is filed under, and the roster discriminator. */
27
+ playerAgentKey: string;
28
+ /** The prompt folder a seat is created from, pack-qualified. */
29
+ playerFolder: string;
30
+ /** What the seat template asks for, under the settings the RPG page decides itself. */
31
+ playerOverrides: Partial<PromptFolderDefaults>;
32
+ /** What one player is called: `Player`, `Student`. */
33
+ playerNoun: string;
34
+ /** The seats a party is created under, in order. Its length is the capacity. */
35
+ seatNames: string[];
36
+ /** Crew labels the quality tier's own model runs. */
37
+ primaryRoles: string[];
38
+ /** Crew labels that run on the tier's economy model. */
39
+ economyRoles: string[];
40
+ }
41
+ /**
42
+ * The seats a table of this size offers.
43
+ *
44
+ * Generated rather than listed, so a pack can ask for any number of seats without a
45
+ * matching list of names having to exist. Unique by construction, which is what the
46
+ * room needs: two agents in one room may not share a nickname, and a nickname is
47
+ * derived from the name.
48
+ *
49
+ * @param noun What one player is called
50
+ * @param count How many seats
51
+ * @returns The placeholders, in seating order
7
52
  */
8
- import { RpgPlayerRequest } from '../../../shared/types/app.types';
9
- /** The pack a campaign is built from. */
10
- export declare const RPG_PACK = "dnd5e";
11
- /** The pack's player-less room template — the crew, and no seats. */
12
- export declare const RPG_ROOM_KEY = "campaign";
13
- /** The prompt folder every player is created from, pack-qualified. */
14
- export declare const RPG_PLAYER_FOLDER = "dnd5e:dnd_player";
15
- /** The pack agent template a player is filed under, and the roster discriminator. */
16
- export declare const RPG_PLAYER_AGENT_KEY = "player";
53
+ export declare function seatNames(noun: string, count: number): string[];
17
54
  /**
18
- * How many players one table seats.
55
+ * Resolves a pack's declared table.
19
56
  *
20
- * Not a technical limit — the room does not care. Six is a table, and every player
21
- * beyond it is another agent perceiving every message.
57
+ * @param pack A pack, already read
58
+ * @returns The table, or null when the pack declares none, or names a template it does
59
+ * not ship, or points at a room that already seats a player. Null is the ordinary
60
+ * case — every pack that is not a game is one — so only the misconfigurations warn.
22
61
  */
23
- export declare const RPG_MAX_PLAYERS = 6;
62
+ export declare function resolveRpgTable(pack: LoadedPack): RpgTable | null;
63
+ /** A table as the client is offered one: the labels, and none of the keys. */
64
+ export declare function toRpgPackOption(table: RpgTable, isDefault: boolean): RpgPackOption;
24
65
  /**
25
- * The names a party is seated under, in order.
66
+ * The table to preselect: the one named by DEFAULT_RPG_PACK, else the first.
67
+ *
68
+ * Mirrors `pickDefaultEntry`, down to warning about a name that is not installed
69
+ * rather than offering nothing — a host who mistyped the variable should still get a
70
+ * working dialog.
26
71
  *
27
- * A seat is a placeholder, not a character. Players choose a character during
28
- * character creation and are renamed to it then — which is the only point at which
29
- * they know what the classes and races on offer are. Generated here rather than
30
- * asked for, so they are unique by construction and nothing has to be refused.
72
+ * @param tables Every table this deployment offers, in the order they are listed
73
+ * @returns The one to preselect, or null when the deployment ships no game pack
31
74
  */
32
- export declare const RPG_SEAT_NAMES: readonly ["Player One", "Player Two", "Player Three", "Player Four", "Player Five", "Player Six"];
75
+ export declare function pickDefaultTable(tables: RpgTable[]): RpgTable | null;
33
76
  /**
34
77
  * Refuses a party the room could not seat, before a single agent exists.
35
78
  *
36
- * Much smaller than it was. It used to police character names — length, punctuation,
37
- * collisions with the crew and with each other — because the party was named here.
38
- * Now the party is seated under {@link RPG_SEAT_NAMES} and named in the game, so the
39
- * only collision left is one a player invents at the table, and
40
- * `Room.renameAgent` refuses that where it happens.
79
+ * Every message uses the pack's own noun, because "a table seats 4 students" is a rule
80
+ * of the game the user chose rather than a limit of the software.
41
81
  *
42
82
  * @param players The requested party, in seating order
83
+ * @param table The table they are being seated at
43
84
  * @throws {ValidationError} Naming the offending seat and why
44
85
  */
45
- export declare function assertSeatable(players: RpgPlayerRequest[] | undefined): void;
86
+ export declare function assertSeatable(players: RpgPlayerRequest[] | undefined, table: RpgTable): void;