@serene-pub/sdk 0.6.0-pr-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +17 -0
  3. package/README.md +368 -0
  4. package/dist/actions.d.ts +572 -0
  5. package/dist/actions.js +829 -0
  6. package/dist/annexFields.d.ts +234 -0
  7. package/dist/annexFields.js +413 -0
  8. package/dist/announce.d.ts +464 -0
  9. package/dist/announce.js +426 -0
  10. package/dist/attributes.d.ts +670 -0
  11. package/dist/attributes.js +904 -0
  12. package/dist/bands.d.ts +125 -0
  13. package/dist/bands.js +256 -0
  14. package/dist/builder.d.ts +683 -0
  15. package/dist/builder.js +677 -0
  16. package/dist/candidates.d.ts +109 -0
  17. package/dist/candidates.js +118 -0
  18. package/dist/capabilities.d.ts +744 -0
  19. package/dist/capabilities.js +679 -0
  20. package/dist/channels.d.ts +106 -0
  21. package/dist/channels.js +129 -0
  22. package/dist/clauses.d.ts +40 -0
  23. package/dist/clauses.js +43 -0
  24. package/dist/component.d.ts +33 -0
  25. package/dist/component.js +27 -0
  26. package/dist/componentBuild.d.ts +48 -0
  27. package/dist/componentBuild.js +84 -0
  28. package/dist/componentClient.d.ts +100 -0
  29. package/dist/componentClient.js +13 -0
  30. package/dist/componentImports.d.ts +51 -0
  31. package/dist/componentImports.js +106 -0
  32. package/dist/componentModule.d.ts +8 -0
  33. package/dist/componentModule.js +270 -0
  34. package/dist/componentWire.d.ts +130 -0
  35. package/dist/componentWire.js +280 -0
  36. package/dist/config.d.ts +295 -0
  37. package/dist/config.js +231 -0
  38. package/dist/connections.d.ts +89 -0
  39. package/dist/connections.js +131 -0
  40. package/dist/declarations.d.ts +290 -0
  41. package/dist/declarations.js +794 -0
  42. package/dist/descriptors.d.ts +1774 -0
  43. package/dist/descriptors.js +1329 -0
  44. package/dist/dev.d.ts +136 -0
  45. package/dist/dev.js +161 -0
  46. package/dist/document.d.ts +202 -0
  47. package/dist/document.js +312 -0
  48. package/dist/engines.d.ts +117 -0
  49. package/dist/engines.js +203 -0
  50. package/dist/eventMapLaws.d.ts +63 -0
  51. package/dist/eventMapLaws.js +128 -0
  52. package/dist/events.d.ts +554 -0
  53. package/dist/events.js +633 -0
  54. package/dist/executor.d.ts +771 -0
  55. package/dist/executor.js +1829 -0
  56. package/dist/extension.d.ts +448 -0
  57. package/dist/extension.js +315 -0
  58. package/dist/facets.d.ts +53 -0
  59. package/dist/facets.js +60 -0
  60. package/dist/foldedSections.d.ts +74 -0
  61. package/dist/foldedSections.js +161 -0
  62. package/dist/genres.d.ts +507 -0
  63. package/dist/genres.js +633 -0
  64. package/dist/guardedConnection.d.ts +138 -0
  65. package/dist/guardedConnection.js +341 -0
  66. package/dist/handlebarsReach.d.ts +122 -0
  67. package/dist/handlebarsReach.js +222 -0
  68. package/dist/hash.d.ts +146 -0
  69. package/dist/hash.js +166 -0
  70. package/dist/hookGrants.d.ts +47 -0
  71. package/dist/hookGrants.js +68 -0
  72. package/dist/hooks.d.ts +290 -0
  73. package/dist/hooks.js +113 -0
  74. package/dist/hostElements.d.ts +447 -0
  75. package/dist/hostElements.js +702 -0
  76. package/dist/i18n.d.ts +94 -0
  77. package/dist/i18n.js +123 -0
  78. package/dist/identity.d.ts +93 -0
  79. package/dist/identity.js +135 -0
  80. package/dist/index.d.ts +85 -0
  81. package/dist/index.js +176 -0
  82. package/dist/layout.d.ts +194 -0
  83. package/dist/layout.js +40 -0
  84. package/dist/media.d.ts +202 -0
  85. package/dist/media.js +70 -0
  86. package/dist/messageBlocks.d.ts +487 -0
  87. package/dist/messageBlocks.js +683 -0
  88. package/dist/migration.d.ts +128 -0
  89. package/dist/migration.js +261 -0
  90. package/dist/names.d.ts +78 -0
  91. package/dist/names.js +136 -0
  92. package/dist/nodeInput.d.ts +399 -0
  93. package/dist/nodeInput.js +178 -0
  94. package/dist/participants.d.ts +291 -0
  95. package/dist/participants.js +252 -0
  96. package/dist/personGate.d.ts +62 -0
  97. package/dist/personGate.js +77 -0
  98. package/dist/pick.d.ts +84 -0
  99. package/dist/pick.js +103 -0
  100. package/dist/pluginHarness.d.ts +235 -0
  101. package/dist/pluginHarness.js +558 -0
  102. package/dist/pluginPermissions.d.ts +25 -0
  103. package/dist/pluginPermissions.js +97 -0
  104. package/dist/pluginRuleRef.d.ts +13 -0
  105. package/dist/pluginRuleRef.js +10 -0
  106. package/dist/predicates.d.ts +182 -0
  107. package/dist/predicates.js +249 -0
  108. package/dist/preview.d.ts +120 -0
  109. package/dist/preview.js +82 -0
  110. package/dist/promptBlocks.d.ts +130 -0
  111. package/dist/promptBlocks.js +197 -0
  112. package/dist/rankingDecisions.d.ts +60 -0
  113. package/dist/rankingDecisions.js +48 -0
  114. package/dist/receipt.d.ts +313 -0
  115. package/dist/receipt.js +60 -0
  116. package/dist/receiverRules.d.ts +24 -0
  117. package/dist/receiverRules.js +94 -0
  118. package/dist/refs.d.ts +117 -0
  119. package/dist/refs.js +137 -0
  120. package/dist/registry.d.ts +230 -0
  121. package/dist/registry.js +273 -0
  122. package/dist/review.d.ts +108 -0
  123. package/dist/review.js +97 -0
  124. package/dist/sampling.d.ts +152 -0
  125. package/dist/sampling.js +712 -0
  126. package/dist/scope.d.ts +65 -0
  127. package/dist/scope.js +128 -0
  128. package/dist/scripts.d.ts +243 -0
  129. package/dist/scripts.js +326 -0
  130. package/dist/sessionLayout.d.ts +339 -0
  131. package/dist/sessionLayout.js +503 -0
  132. package/dist/sessionSettings.d.ts +70 -0
  133. package/dist/sessionSettings.js +2 -0
  134. package/dist/settings.d.ts +501 -0
  135. package/dist/settings.js +604 -0
  136. package/dist/settingsSlot.d.ts +108 -0
  137. package/dist/settingsSlot.js +166 -0
  138. package/dist/shapes.d.ts +373 -0
  139. package/dist/shapes.js +408 -0
  140. package/dist/sheets.d.ts +165 -0
  141. package/dist/sheets.js +251 -0
  142. package/dist/statShapes.d.ts +96 -0
  143. package/dist/statShapes.js +112 -0
  144. package/dist/status.d.ts +103 -0
  145. package/dist/status.js +125 -0
  146. package/dist/storage.d.ts +145 -0
  147. package/dist/storage.js +33 -0
  148. package/dist/storyTime.d.ts +308 -0
  149. package/dist/storyTime.js +560 -0
  150. package/dist/surfaces.d.ts +501 -0
  151. package/dist/surfaces.js +292 -0
  152. package/dist/template.d.ts +312 -0
  153. package/dist/template.js +554 -0
  154. package/dist/templateCheck.d.ts +60 -0
  155. package/dist/templateCheck.js +516 -0
  156. package/dist/templateFit.d.ts +157 -0
  157. package/dist/templateFit.js +349 -0
  158. package/dist/templateIds.d.ts +138 -0
  159. package/dist/templateIds.js +144 -0
  160. package/dist/templateScopeAt.d.ts +131 -0
  161. package/dist/templateScopeAt.js +354 -0
  162. package/dist/testing.d.ts +177 -0
  163. package/dist/testing.js +383 -0
  164. package/dist/tokenizers.d.ts +113 -0
  165. package/dist/tokenizers.js +184 -0
  166. package/dist/turnLock.d.ts +96 -0
  167. package/dist/turnLock.js +79 -0
  168. package/dist/turnOrder.d.ts +143 -0
  169. package/dist/turnOrder.js +128 -0
  170. package/dist/validate.d.ts +74 -0
  171. package/dist/validate.js +1399 -0
  172. package/dist/values.d.ts +212 -0
  173. package/dist/values.js +390 -0
  174. package/dist/variables.d.ts +493 -0
  175. package/dist/variables.js +662 -0
  176. package/dist/verdicts.d.ts +275 -0
  177. package/dist/verdicts.js +348 -0
  178. package/dist/widgetDecls.d.ts +88 -0
  179. package/dist/widgetDecls.js +119 -0
  180. package/dist/widgets.d.ts +1527 -0
  181. package/dist/widgets.js +208 -0
  182. package/dist/wire.d.ts +126 -0
  183. package/dist/wire.js +140 -0
  184. package/dist/worldinfo.d.ts +150 -0
  185. package/dist/worldinfo.js +212 -0
  186. package/host-elements.d.ts +914 -0
  187. package/package.json +67 -0
package/dist/genres.js ADDED
@@ -0,0 +1,633 @@
1
+ import { widgetRef } from './widgetDecls.js';
2
+ import { drawnWidgetIds, layoutWidgetIds, widgetOfInstance } from './sessionLayout.js';
3
+ import { assertChannelDecls, assertMessageVerbFloors, assertSessionWrites, assertTurnControls, channelDecls, widgetDeclsFindings, } from './descriptors.js';
4
+ import { i18nFindings, localeMapOf } from './i18n.js';
5
+ import { eventById, notADeclaredEvent } from './events.js';
6
+ import { settingsSchemaFindings } from './settings.js';
7
+ import { getAttributeSlot } from './attributes.js';
8
+ import { refuseUnlessIdentical } from './hash.js';
9
+ import { isActionIdentity } from './identity.js';
10
+ import { enabledWhenFindings, normalizeEnabledWhen, } from './predicates.js';
11
+ /** `owner:genre/name` — lowercase, digits, hyphens, dots in the owner. */
12
+ const GENRE_ID = /^[a-z0-9]+(?:[.-][a-z0-9]+)*:genre\/[a-z0-9]+(?:-[a-z0-9]+)*$/;
13
+ /** @experimental */
14
+ export function assertGenreId(id) {
15
+ if (!GENRE_ID.test(id))
16
+ throw new Error(`'${id}' is not a valid genre id. Use 'owner:genre/name' — 'core:genre/chat', ` +
17
+ `'acme.rp:genre/mystery'. The id is an address sessions hold for their ` +
18
+ `lifetime; the display name lives in the declaration.`);
19
+ }
20
+ /**
21
+ * The core session events (24 §5), as **event ids** — `core:event/<name>@1`.
22
+ *
23
+ * Constants so the core vocabulary is typo-proof. Since R-4 (ruled 2026-09-15,
24
+ * landed 2026-09-16) these ARE `CORE_EVENTS` entries (`events.ts`): one
25
+ * registry, and a genre's event surface, a preset's `bindings` map and a spec's
26
+ * inlet lock are all keyed by these ids. The bare names (`session-created`)
27
+ * were the keys until the fold; a host migrates its stored keys once.
28
+ * @public
29
+ */
30
+ export const sessionEvents = Object.freeze({
31
+ /** The create slot — required; exactly one pipeline per genre declares it. */
32
+ sessionCreated: 'core:event/session-created@1',
33
+ /** The primary turn. A swipe is this pipeline re-run, not a new event. */
34
+ messageRespond: 'core:event/message-respond@1',
35
+ /** Arbitrary buttons/triggers — the existing functions surface (19 §3). */
36
+ sessionAction: 'core:event/session-action@1',
37
+ /** A character or persona joined; payload carries the kind. */
38
+ memberAdded: 'core:event/member-added@1',
39
+ /** A character or persona left; payload carries the kind. */
40
+ memberRemoved: 'core:event/member-removed@1',
41
+ /**
42
+ * A form in a message was addressed to a participant the AI portrays
43
+ * (R-15 *Forms*; U5d). Optional in every genre's surface: a genre that
44
+ * binds nothing leaves such a form waiting, as it would for a person.
45
+ */
46
+ formAddressed: 'core:event/form-addressed@1',
47
+ // ── Turn order as event-driven state (PLAN-turn-order §4.1, 2026-09-21) ──
48
+ // The events a genre may bind its turn-order spec to. A genre that
49
+ // binds the spec lists every event it binds it to, all optional (`{}`).
50
+ /** A row that is not generating landed — a send, a greeting, a finished or stopped reply. */
51
+ messageCompleted: 'core:event/message-completed@1',
52
+ /** A person rewrote a settled message. */
53
+ messageEdited: 'core:event/message-edited@1',
54
+ /** A message was deleted. */
55
+ messageDeleted: 'core:event/message-deleted@1',
56
+ /** A message was hidden from the prompt, or shown again. */
57
+ messageHidden: 'core:event/message-hidden@1',
58
+ /** A line's shown sprite changed — a picker's choice or a person's (DESIGN-sprites). */
59
+ spriteShown: 'core:event/sprite-shown@1',
60
+ /** A seated participant's row changed — active, position, visibility or portrayal. */
61
+ castChanged: 'core:event/cast-changed@1',
62
+ /** `sessions:update` landed — name, scenario, lorebook, genre fields, preset, channels, tags. */
63
+ sessionUpdated: 'core:event/session-updated@1',
64
+ /** A session was branched at a message into a new session; recorded on the branch. */
65
+ sessionBranched: 'core:event/session-branched@1',
66
+ /**
67
+ * A pipeline's annex entry changed — "my state changed". Caused by
68
+ * `core:outlet/set-session-annex@1`; the payload names the owner.
69
+ */
70
+ annexChanged: 'core:event/annex-changed@1',
71
+ /**
72
+ * `metadata.turnOrder` was written. **For typing only**: core-internal,
73
+ * read by the auto-advance listener and the `sessions:turnOrder` push;
74
+ * `genre()` refuses it in `events`, so no preset can bind it.
75
+ */
76
+ turnOrderChanged: 'core:event/turn-order-changed@1',
77
+ });
78
+ /**
79
+ * Why no genre may list, and no spec may lock, `turn-order-changed`
80
+ * (PLAN-turn-order §4.1): the turn-order write's own event is core-internal.
81
+ * One sentence for `genre()`, the builder's `.inlet()` and the package pass.
82
+ * @experimental
83
+ */
84
+ export const TURN_ORDER_CHANGED_IS_INTERNAL = `'${sessionEvents.turnOrderChanged}' is core-internal — the auto-advance listener and the ` +
85
+ `turn-order push read it, and a pipeline bound to it would recompute the order it was told ` +
86
+ `about. Bind '${sessionEvents.messageCompleted}' and the other session events instead.`;
87
+ /** Does this genre let its sessions track attributes beyond its own? Unstated is `'deny'`. @experimental */
88
+ export const genreAllowsCustomAttributes = (g) => (typeof g === 'string' ? registry.get(g) : g)?.customAttributes === 'allow';
89
+ /**
90
+ * The name a line nobody claims is shown and prompted under when its genre
91
+ * declares no fallback envoy (`EnvoyDecl.fallback`) — display text (R-20), read
92
+ * in the viewer's language. The host's last resort, so no line is ever
93
+ * attributed to "Unknown" (ruled 2026-09-26). The same word the host already
94
+ * gives narration with no narrator name.
95
+ * @experimental
96
+ */
97
+ export const UNCLAIMED_LINE_NAME = Object.freeze({ en: 'Narrator' });
98
+ /** An envoy's key: a lowercase kebab token. Dots are reserved for an action's namespace. @experimental */
99
+ export const ENVOY_KEY = /^[a-z][a-z0-9-]*$/;
100
+ /** An envoy's image: an `http(s)://` URL or a `data:image/…` URI — an `<img>` source, nothing else. @experimental */
101
+ export const ENVOY_IMAGE = /^(?:https?:\/\/\S+|data:image\/[a-z0-9.+-]+(?:;[^,]*)?,.+)$/i;
102
+ const ENVOY_SPEAKS = new Set(['in-turn', 'on-action']);
103
+ /**
104
+ * Every fault in one envoy declaration, as sentences (the teaching-error
105
+ * pattern, 15 §1.3). Empty when it is sound. `owner` says which of the two
106
+ * declaring places this is, because an action's envoy has one rule of its own:
107
+ * it may only be `on-action`.
108
+ * @internal
109
+ */
110
+ export function envoyFindings(raw, at, owner = 'genre') {
111
+ const out = [];
112
+ if (!raw || typeof raw !== 'object')
113
+ return [`${at}: an envoy is an object — got ${typeof raw}`];
114
+ const e = raw;
115
+ const where = `${at}[${typeof e.key === 'string' ? e.key : '?'}]`;
116
+ if (typeof e.key !== 'string' || !ENVOY_KEY.test(e.key))
117
+ out.push(`${where}: 'key' is required — a lowercase kebab token (${ENVOY_KEY.source}); ` +
118
+ `an action's envoy is namespaced by the host, never by the key`);
119
+ out.push(...i18nFindings(e.name, `${where}.name`, { required: true }));
120
+ out.push(...i18nFindings(e.description, `${where}.description`));
121
+ if (e.image !== undefined && (typeof e.image !== 'string' || !ENVOY_IMAGE.test(e.image)))
122
+ out.push(`${where}: 'image' is an http(s):// URL or a data:image/… URI — an <img> source and nothing else`);
123
+ if (e.prompts !== undefined) {
124
+ if (!e.prompts || typeof e.prompts !== 'object')
125
+ out.push(`${where}: 'prompts' is { systemPrompt?, postHistoryInstructions? }`);
126
+ else
127
+ for (const [k, v] of Object.entries(e.prompts))
128
+ if (typeof v !== 'string')
129
+ out.push(`${where}: prompts.${k} is a string — the authored text`);
130
+ }
131
+ if (e.default !== undefined && typeof e.default !== 'boolean')
132
+ out.push(`${where}: 'default' is a boolean`);
133
+ if (e.fallback !== undefined) {
134
+ if (typeof e.fallback !== 'boolean')
135
+ out.push(`${where}: 'fallback' is a boolean`);
136
+ else if (owner === 'action' && e.fallback)
137
+ out.push(`${where}: an action's envoy cannot be the fallback — it speaks for its action only; ` +
138
+ `declare the fallback on the genre's envoys`);
139
+ }
140
+ if (e.greeting !== undefined) {
141
+ const g = e.greeting;
142
+ if (owner === 'action')
143
+ out.push(`${where}: an action's envoy cannot declare a greeting — it speaks for its action ` +
144
+ `only; declare the greeting on the genre's envoy (R6)`);
145
+ else if (!g || typeof g !== 'object' || Array.isArray(g))
146
+ out.push(`${where}: 'greeting' is { text, channel? } — the line this envoy opens a new session with`);
147
+ else {
148
+ out.push(...i18nFindings(g.text, `${where}.greeting.text`, { required: true }));
149
+ if (g.channel !== undefined && (typeof g.channel !== 'string' || !g.channel.trim()))
150
+ out.push(`${where}: greeting.channel is a channel slug the genre declares — 'main' when absent`);
151
+ }
152
+ }
153
+ if (e.speaks !== undefined) {
154
+ if (!ENVOY_SPEAKS.has(e.speaks))
155
+ out.push(`${where}: 'speaks' is 'in-turn' or 'on-action' (R-21 (6))`);
156
+ else if (owner === 'action' && e.speaks !== 'on-action')
157
+ out.push(`${where}: an action's envoy speaks 'on-action' only — it is the speaker the ` +
158
+ `action's results post as, never a turn-taking candidate (R-21 (6))`);
159
+ }
160
+ return out;
161
+ }
162
+ /**
163
+ * The findings on a genre's whole list: each entry's, plus unique keys, at
164
+ * most one default, and — given the genre's `channels` (slugs, `main`
165
+ * included; R6) — a greeting on a channel the genre does not declare.
166
+ * @internal
167
+ */
168
+ export function envoysFindings(raw, at = 'envoys', channels) {
169
+ if (raw === undefined)
170
+ return [];
171
+ if (!Array.isArray(raw))
172
+ return [`${at}: a genre's envoys are an array`];
173
+ const out = [];
174
+ const keys = new Map();
175
+ let defaults = 0;
176
+ const fallbacks = [];
177
+ raw.forEach((e, i) => {
178
+ out.push(...envoyFindings(e, at, 'genre'));
179
+ const key = e?.key;
180
+ if (typeof key === 'string')
181
+ keys.set(key, (keys.get(key) ?? 0) + 1);
182
+ if (e?.default === true)
183
+ defaults++;
184
+ if (e?.fallback === true)
185
+ fallbacks.push(typeof key === 'string' ? key : '?');
186
+ const lands = e?.greeting?.channel;
187
+ if (channels && typeof lands === 'string' && lands.trim() && !channels.includes(lands.trim()))
188
+ out.push(`${at}[${typeof key === 'string' ? key : '?'}]: greeting.channel '${lands}' is not a channel ` +
189
+ `this genre declares — it declares ${channels.map((c) => `'${c}'`).join(', ')} (R6)`);
190
+ void i;
191
+ });
192
+ if (fallbacks.length > 1)
193
+ out.push(`${at}: ${fallbacks.map((k) => `'${k}'`).join(', ')} are all 'fallback: true' — a line nobody ` +
194
+ `claims posts as one envoy; mark one`);
195
+ for (const [key, n] of keys)
196
+ if (n > 1)
197
+ out.push(`${at}: the key '${key}' is declared ${n} times — an envoy's key is unique within its genre`);
198
+ if (defaults > 1)
199
+ out.push(`${at}: ${defaults} envoys are 'default: true' — at most one is seated with no choice; ` +
200
+ `the rest are offered`);
201
+ return out;
202
+ }
203
+ /** One envoy in its document form: `speaks` stated, nothing else added. @experimental */
204
+ export function normalizeEnvoy(raw, speaks) {
205
+ return Object.freeze({ ...raw, speaks });
206
+ }
207
+ /**
208
+ * A genre's enabled-when defaults, as findings: keyed by an action identity
209
+ * (`<spec>#<key>`, or `core#<verb>`), each value a predicate or a list judged
210
+ * by `enabledWhenFindings`. Empty when sound or absent.
211
+ * @experimental
212
+ */
213
+ export function genreEnabledWhenFindings(raw, at = 'enabledWhen') {
214
+ if (raw === undefined)
215
+ return [];
216
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
217
+ return [
218
+ `${at}: a genre's enabled-when defaults are an object keyed by action identity — ` +
219
+ `{ 'core:spec/look#look': { on: 'state.world.location', truthy: true, reason: { en: '…' } } }`,
220
+ ];
221
+ const out = [];
222
+ for (const [id, decl] of Object.entries(raw)) {
223
+ if (!isActionIdentity(id))
224
+ out.push(`${at}: a default is keyed by the identity of the action it applies to — ` +
225
+ `'<spec slug>#<key>', or 'core#<verb>' for a message verb — got '${id}'`);
226
+ out.push(...enabledWhenFindings(decl, `${at}[${id}]`));
227
+ }
228
+ return out;
229
+ }
230
+ function assertEnabledWhen(decl, genreId) {
231
+ if (!decl)
232
+ return undefined;
233
+ const findings = genreEnabledWhenFindings(decl, `${genreId}.enabledWhen`);
234
+ if (findings.length)
235
+ throw new Error(findings.join('\n'));
236
+ const out = {};
237
+ for (const [fn, v] of Object.entries(decl))
238
+ out[fn] = Object.freeze(normalizeEnabledWhen(v));
239
+ return Object.freeze(out);
240
+ }
241
+ /**
242
+ * Every display string a genre carries (R-20): `name` (required) and
243
+ * `description`; the shape's `fields` schema and its `panels[]` titles; and
244
+ * the `label` / `description` of every slot and sheet it brings. The slots and
245
+ * sheets passed their own doors already; they are read again here because a
246
+ * genre is the declaration a session is created under, and a picker card that
247
+ * lists a slot with no label is this genre's defect to hear about.
248
+ * @experimental
249
+ */
250
+ export function genreDisplayTextFindings(props, at) {
251
+ const out = [];
252
+ out.push(...i18nFindings(props.name, `${at}.name`, { required: true }));
253
+ out.push(...i18nFindings(props.description, `${at}.description`));
254
+ if (props.shape) {
255
+ out.push(...settingsSchemaFindings(props.shape.fields, `${at}.shape.fields`));
256
+ out.push(...widgetDeclsFindings(props.shape.panels, `${at}.shape.panels`));
257
+ }
258
+ for (const slot of props.slots ?? []) {
259
+ out.push(...i18nFindings(slot.label, `${at}.slots[${slot.id}].label`));
260
+ out.push(...i18nFindings(slot.description, `${at}.slots[${slot.id}].description`));
261
+ }
262
+ for (const sheet of props.sheets ?? []) {
263
+ out.push(...i18nFindings(sheet.label, `${at}.sheets[${sheet.id}].label`, { required: true }));
264
+ out.push(...i18nFindings(sheet.description, `${at}.sheets[${sheet.id}].description`));
265
+ }
266
+ return out;
267
+ }
268
+ function assertDisplayText(props, genreId) {
269
+ const findings = genreDisplayTextFindings(props, genreId);
270
+ if (findings.length)
271
+ throw new Error(findings.join('\n'));
272
+ }
273
+ /**
274
+ * `GenreProps.playerLabel` (R4), checked and normalised: display text with an
275
+ * `en` (R-20), as a frozen locale map — and refused for a genre where a
276
+ * persona always names the person's line (`shape.personas.min ≥ 1`), because
277
+ * nothing there would ever carry it.
278
+ */
279
+ function assertPlayerLabel(props, genreId) {
280
+ if (props.playerLabel === undefined)
281
+ return undefined;
282
+ const findings = i18nFindings(props.playerLabel, `${genreId}.playerLabel`);
283
+ if (findings.length)
284
+ throw new Error(findings.join('\n'));
285
+ if ((props.shape?.personas?.min ?? 0) >= 1)
286
+ throw new Error(`${genreId}.playerLabel: this genre requires a persona (shape.personas.min ≥ 1), so a persona ` +
287
+ `always names the person's line and no line would ever carry the label — drop playerLabel, ` +
288
+ `or let the genre run without a persona`);
289
+ return Object.freeze({ ...localeMapOf(props.playerLabel) });
290
+ }
291
+ function assertEnvoys(envoys, genreId, shape) {
292
+ if (!envoys)
293
+ return [];
294
+ const findings = envoysFindings(envoys, `${genreId}.envoys`, channelDecls(shape).map((c) => c.slug));
295
+ if (findings.length)
296
+ throw new Error(findings.join('\n'));
297
+ return envoys.map((e) => normalizeEnvoy(e, e.speaks ?? 'in-turn'));
298
+ }
299
+ /** Core's conversation widget — the primary widget a genre must replace if it withholds it. @internal */
300
+ export const CONVERSATION_WIDGET_ID = 'messages';
301
+ /** `omitWidgets` read down to ids, and `layouts` checked (R71). */
302
+ function assertGenreWidgets(props, id) {
303
+ const problems = [];
304
+ const omitWidgets = [];
305
+ for (const w of props.omitWidgets ?? []) {
306
+ if (typeof w === 'string') {
307
+ problems.push(`${id} omitWidgets: '${w}' is a string — name the widget value (coreWidgets.x, or the package's widget)`);
308
+ continue;
309
+ }
310
+ try {
311
+ omitWidgets.push(widgetRef(w));
312
+ }
313
+ catch (e) {
314
+ problems.push(`${id} omitWidgets: ${e.message}`);
315
+ }
316
+ }
317
+ const layouts = [...(props.layouts ?? [])];
318
+ // The first is the genre's default, and the instance seeds a genre's
319
+ // default by its slug.
320
+ if (layouts.length && layouts[0].slug !== 'default')
321
+ problems.push(`${id} layouts: the first is the genre's default — give it slug 'default' (it is '${layouts[0].slug}')`);
322
+ const slugs = new Set();
323
+ for (const l of layouts) {
324
+ if (slugs.has(l.slug))
325
+ problems.push(`${id} layouts: two layouts are '${l.slug}' — a slug names one`);
326
+ slugs.add(l.slug);
327
+ // By widget, not by instance: `messages#sanctum` places the conversation.
328
+ for (const w of layoutWidgetIds(l.preset))
329
+ if (omitWidgets.includes(widgetOfInstance(w)))
330
+ problems.push(`${id} layout '${l.slug}' places '${w}', which the genre omits`);
331
+ }
332
+ // The primary floor: a session always draws its primary widget. A genre
333
+ // that withholds the conversation says what stands in its place — its
334
+ // package's `role: 'primary'` widget — in the layout it ships first, in any
335
+ // zone (placement is free). Which widget that is, the widget's declaration
336
+ // says, and a genre holds only ids: so this asks that the layout draws
337
+ // something, and the package pass (`genreLayoutFindings`, run by
338
+ // `defineExtension` and the packager) that what it draws is primary.
339
+ if (omitWidgets.includes(CONVERSATION_WIDGET_ID)) {
340
+ const first = layouts[0];
341
+ if (!first || !drawnWidgetIds(first.preset).length)
342
+ problems.push(`${id} omits the conversation — ship a layout (layouts: [layout({ … })]) that places ` +
343
+ `the widget that takes its place (its role: 'primary' widget), in any zone`);
344
+ }
345
+ if (problems.length)
346
+ throw new Error(problems.join('\n'));
347
+ return { omitWidgets: [...new Set(omitWidgets)], layouts };
348
+ }
349
+ /**
350
+ * Declare a genre. The id is stated in full, under your plugin's slug
351
+ * (`acme.dice:genre/table`), and the genre value is what everything else
352
+ * references.
353
+ * @public
354
+ */
355
+ export function genre(id, props) {
356
+ assertGenreId(id);
357
+ // The floors (R-15): a genre that switches off stop, branch or edit is
358
+ // refused here, at the declaration, on the same terms as an inlet's shape.
359
+ assertMessageVerbFloors(props.shape, id);
360
+ // The writes (R-B) and the channel declarations (R-C): refused here too,
361
+ // on the same terms and for the same reason — a `writes.lore: 'no'` or a
362
+ // channel declared `role: 'prose'` is an authoring mistake, not a value to
363
+ // degrade at the write site where nobody is reading.
364
+ assertSessionWrites(props.shape, id);
365
+ assertTurnControls(props.shape, id);
366
+ assertChannelDecls(props.shape, id);
367
+ const events = { ...(props.events ?? {}) };
368
+ // The turn-order write's own event is core-internal (PLAN-turn-order
369
+ // §4.1): the recompute must not be able to answer itself, so no genre
370
+ // may list it and no preset can ever bind it. Refused here, at the
371
+ // declaration, where the author is.
372
+ if (sessionEvents.turnOrderChanged in events)
373
+ throw new Error(`${id} lists it in its events: ${TURN_ORDER_CHANGED_IS_INTERNAL}`);
374
+ // A genre lists core's events. A package's event joins a genre's surface
375
+ // through the package entry, which also says who may record it — one
376
+ // place, so a genre cannot list an event with no scope.
377
+ for (const event of Object.keys(events)) {
378
+ if (!eventById(event))
379
+ throw new Error(`${id}: ${notADeclaredEvent(event)}`);
380
+ if (!event.startsWith('core:'))
381
+ throw new Error(`${id} lists '${event}', a package's event — add it to the genre from defineExtension({ events: ` +
382
+ `[{ event, genre, recordedBy }] }), which also says who may record it`);
383
+ }
384
+ // Every genre has the create slot, stated or not — stating it merely
385
+ // confirms; omitting it must not produce a genre nothing can instantiate.
386
+ events[sessionEvents.sessionCreated] = {
387
+ ...(events[sessionEvents.sessionCreated] ?? {}),
388
+ required: true,
389
+ };
390
+ // The envoys (R-18): refused here, at the declaration, on the same terms
391
+ // as the floors — a duplicate key, two defaults or a name with no `en`
392
+ // is an authoring mistake, not a row to degrade.
393
+ // The display text (R-20, U5i): the card's name and subtitle, the shape's
394
+ // fields and panels, and every slot's and sheet's label — refused here on
395
+ // the same terms as the floors. A blank name is a card with no face.
396
+ assertDisplayText(props, id);
397
+ const envoys = assertEnvoys(props.envoys, id, props.shape);
398
+ // The enabled-when defaults (R-15, U5e): refused here on the same terms —
399
+ // a path that is a port reference or a predicate with no reason is an
400
+ // authoring mistake, not a button to grey with no sentence.
401
+ const enabledWhen = assertEnabledWhen(props.enabledWhen, id);
402
+ const { omitWidgets, layouts } = assertGenreWidgets(props, id);
403
+ if (props.customAttributes !== undefined && props.customAttributes !== 'allow' && props.customAttributes !== 'deny')
404
+ throw new Error(`${id}.customAttributes: 'allow' or 'deny' — not ${JSON.stringify(props.customAttributes)}`);
405
+ const playerLabel = assertPlayerLabel(props, id);
406
+ const decl = Object.freeze({
407
+ id,
408
+ name: props.name,
409
+ family: props.family,
410
+ description: props.description,
411
+ shape: props.shape,
412
+ events: Object.freeze(events),
413
+ slots: props.slots ? Object.freeze([...props.slots]) : undefined,
414
+ sheets: props.sheets ? Object.freeze([...props.sheets]) : undefined,
415
+ // Absent unless allowed, so a genre that denies (or says nothing) hashes as it did.
416
+ ...(props.customAttributes === 'allow' ? { customAttributes: 'allow' } : {}),
417
+ ...(envoys.length ? { envoys: Object.freeze(envoys) } : {}),
418
+ // R4: absent when unstated, so a genre that says nothing hashes as it did.
419
+ ...(playerLabel ? { playerLabel } : {}),
420
+ ...(enabledWhen && Object.keys(enabledWhen).length ? { enabledWhen } : {}),
421
+ // The pinned settings (§4.13): copied when stated, frozen like the
422
+ // rest, absent otherwise — so an unpinned genre hashes as it did.
423
+ ...(props.settings && Object.keys(props.settings).length
424
+ ? { settings: Object.freeze({ ...props.settings }) }
425
+ : {}),
426
+ // R71: absent when unstated, so a genre that says nothing hashes as it did.
427
+ ...(omitWidgets.length ? { omitWidgets: Object.freeze(omitWidgets) } : {}),
428
+ ...(layouts.length ? { layouts: Object.freeze(layouts) } : {}),
429
+ });
430
+ const existing = registry.get(id);
431
+ if (existing)
432
+ refuseUnlessIdentical(existing, decl, `duplicate genre id: ${id}`, GENRE_DISPLAY_KEYS);
433
+ registry.set(id, decl);
434
+ return decl;
435
+ }
436
+ /**
437
+ * Declared genres, by id.
438
+ *
439
+ * ⚠ **Registered, not merely returned**, and the reason is `slots`. A genre
440
+ * carries the attribute slots it brings, and the only party that can answer
441
+ * "does THIS session have health?" is the genre the session was created under —
442
+ * the declarations registry is global, so a reader that walked it would put a
443
+ * health bar on every chat session on the instance, which is the one thing the
444
+ * stats design says a newcomer must never see. A session holds a genre id;
445
+ * this is what turns that id back into the list.
446
+ *
447
+ * Stored as a fact about the running code, like every other registry here: an
448
+ * identical re-declaration is a no-op so a dev-server reload does not throw,
449
+ * and a *different* declaration under a claimed id throws with both hashes
450
+ * named.
451
+ */
452
+ const registry = new Map();
453
+ /** Display text stripped from the comparison — see `SLOT_DISPLAY_KEYS`. */
454
+ const GENRE_DISPLAY_KEYS = { display: ['name', 'description'] };
455
+ /** @internal */
456
+ export const getGenre = (id) => registry.get(id);
457
+ /** @experimental */
458
+ export const genres = () => [...registry.values()];
459
+ /** @experimental */
460
+ export function _clearGenres() {
461
+ registry.clear();
462
+ }
463
+ /**
464
+ * Register a genre from a package's **stored manifest** — the declaration
465
+ * `genre()` already built and `serene-pub build` serialised, which the host
466
+ * reads back because it never evaluates a plugin's code in-process.
467
+ *
468
+ * Not `genre()`: that is the authoring door and takes values (widget refs,
469
+ * `EnabledWhenDecl`), where a manifest holds their compiled form (widget ids,
470
+ * normalised predicates) — re-running the authoring checks over it would
471
+ * refuse the very shape they produced. What is checked here is what a stored
472
+ * row can still get wrong: the id grammar, the `core:` namespace, and that the
473
+ * owner segment is the declaring package's. A present entry is **replaced**,
474
+ * like a stored slot: the manifest is the one author, and an upgraded package
475
+ * re-registering is that author, not a second party.
476
+ * @internal
477
+ */
478
+ export function _registerPackageGenre(packageId, raw) {
479
+ const id = typeof raw?.id === 'string' ? raw.id : '';
480
+ assertGenreId(id);
481
+ if (id.startsWith('core:'))
482
+ throw new Error(`package '${packageId}' may not declare '${id}': the 'core:' namespace is reserved.`);
483
+ if (id.slice(0, id.indexOf(':')) !== packageId)
484
+ throw new Error(`genre '${id}' is not under '${packageId}' — a package declares only its own genres`);
485
+ if (!raw.name || typeof raw.family !== 'string')
486
+ throw new Error(`genre '${id}' has no name or family — not a genre declaration`);
487
+ const events = { ...(raw.events ?? {}) };
488
+ events[sessionEvents.sessionCreated] = { ...(events[sessionEvents.sessionCreated] ?? {}), required: true };
489
+ const decl = Object.freeze({
490
+ ...raw,
491
+ events: Object.freeze(events),
492
+ ...(raw.slots ? { slots: Object.freeze([...raw.slots]) } : {}),
493
+ ...(raw.sheets ? { sheets: Object.freeze([...raw.sheets]) } : {}),
494
+ });
495
+ registry.set(id, decl);
496
+ return decl;
497
+ }
498
+ /**
499
+ * Withdraw a package's genre, so a disabled or uninstalled plugin's genre stops
500
+ * resolving and an upgraded package may declare it again, differently. The
501
+ * host's to call when it reconciles plugin genres. `core:` genres are never
502
+ * withdrawn: they arrive and leave with the build.
503
+ * @internal
504
+ */
505
+ export function _withdrawGenre(id) {
506
+ if (id.startsWith('core:'))
507
+ return false;
508
+ return registry.delete(id);
509
+ }
510
+ /**
511
+ * The attribute slots a session of this genre carries — its sheets' and its own
512
+ * loose list, as one vocabulary.
513
+ *
514
+ * Sheets first, in the order the genre names them and each in its own order,
515
+ * then whatever the genre lists loose that no sheet already brought. Deduped by
516
+ * id, and the *first* mention is what fixes a slot's position: order here is
517
+ * not decoration — it is what a panel draws, what a state block renders, and
518
+ * what rules run in — so the union preserves it rather than sorting it.
519
+ *
520
+ * An id this build does not declare answers with an empty list rather than
521
+ * with every slot in the registry: an unknown genre is a genre whose vocabulary
522
+ * this install cannot state, and guessing it is how a stat appears where the
523
+ * author never put one. A sheet entry naming a slot this build no longer
524
+ * declares is skipped on the same terms. Values already stored against such a
525
+ * session are untouched — they are read as opaque data, which is the standing
526
+ * "never refuse, fall back and say so" rule for a stale binding.
527
+ * @experimental
528
+ */
529
+ export const genreSlots = (id) => {
530
+ const g = registry.get(id);
531
+ if (!g)
532
+ return [];
533
+ const out = [];
534
+ const seen = new Set();
535
+ const take = (decl) => {
536
+ if (!decl || seen.has(decl.id))
537
+ return;
538
+ seen.add(decl.id);
539
+ out.push(decl);
540
+ };
541
+ for (const sheet of g.sheets ?? [])
542
+ for (const entry of sheet.slots)
543
+ take(getAttributeSlot(entry.id));
544
+ for (const decl of g.slots ?? [])
545
+ take(decl);
546
+ return out;
547
+ };
548
+ /**
549
+ * The sheets a genre brings, by id or by declaration — empty for a genre this
550
+ * build does not declare, on the same "never guess" terms as `genreSlots`.
551
+ *
552
+ * The declarations and not just their slots, because `required`, `default` and
553
+ * the per-slot `config` are what session creation and the panels read, and
554
+ * `genreSlots` has deliberately flattened those away.
555
+ * @internal
556
+ */
557
+ export const genreSheets = (g) => (typeof g === 'string' ? registry.get(g)?.sheets : g.sheets) ?? [];
558
+ /**
559
+ * The envoys a genre declares, by id — empty for a genre this build does not
560
+ * declare, on the same "never guess" terms as `genreSlots`.
561
+ * @experimental
562
+ */
563
+ export const genreEnvoys = (id) => registry.get(id)?.envoys ?? [];
564
+ /**
565
+ * The genre's fallback envoy (`EnvoyDecl.fallback`) — the speaker a line
566
+ * nobody claims posts as — or undefined when it declares none.
567
+ * @experimental
568
+ */
569
+ export const genreFallbackEnvoy = (g) => (typeof g === 'string' ? registry.get(g)?.envoys : g.envoys)?.find((e) => e.fallback === true);
570
+ /** One of a genre's envoys by key, or undefined. @experimental */
571
+ export const genreEnvoy = (g, key) => (typeof g === 'string' ? registry.get(g)?.envoys : g.envoys)?.find((e) => e.key === key);
572
+ /**
573
+ * The genre's enabled-when default for one function, by id or declaration —
574
+ * empty for a genre this build does not declare or a function it says
575
+ * nothing about, on the same "never guess" terms as `genreSlots`.
576
+ * @internal
577
+ */
578
+ export const genreEnabledWhen = (g, fn) => (typeof g === 'string' ? registry.get(g)?.enabledWhen : g.enabledWhen)?.[fn] ?? [];
579
+ /** A genre reference as it lands in documents: always the id. Takes a `GenreDecl`, a `use()` ref or an id. @experimental */
580
+ export const genreIdOf = (g) => {
581
+ const id = typeof g === 'string' ? g : g.id;
582
+ assertGenreId(id);
583
+ return id;
584
+ };
585
+ /**
586
+ * The configurable surface of one envoy, as a slot declaration (R-18 (2)).
587
+ *
588
+ * An envoy is not a node and has no registry row to carry a declaration —
589
+ * so the SDK declares its slot from the two facts the genre does carry, its
590
+ * `prompts` defaults and its name, the way `clauseSettingsSlotFor` declares
591
+ * a gather clause's mode. A host renders it through the same reader a node's
592
+ * slot goes through, at the address `envoy:<key>` (`envoyConfigKey`), with
593
+ * the genre's text as the author default: an admin's edit is a deviation
594
+ * above it, and clearing the edit is the genre's text again.
595
+ *
596
+ * `parameters`, not `prompts`, and the reason is what each kind means to a
597
+ * panel: a `prompts` slot is a **reference** to a swappable prompt row, and
598
+ * an envoy's instructions are not a row anybody swaps — they are the genre's
599
+ * words, tuned in place. The slot is still *named* `prompts`, because that
600
+ * is the name the reading node's own slot has and the name `slot.prompts({
601
+ * envoy })` resolves at; the fields are that node's fields.
602
+ * @internal
603
+ */
604
+ export function envoyPromptsSlotFor(envoy) {
605
+ return {
606
+ kind: 'parameters',
607
+ facet: 'prompts',
608
+ quick: true,
609
+ description: {
610
+ en: 'The written instructions this envoy speaks under. The genre ships them; edit them here to change how it answers.',
611
+ },
612
+ schema: {
613
+ systemPrompt: {
614
+ type: 'text',
615
+ quick: true,
616
+ default: envoy.prompts?.systemPrompt ?? '',
617
+ label: { en: 'System prompt' },
618
+ description: {
619
+ en: "Who the envoy is and how it should answer — the reply's instructions, in the envoy's own words.",
620
+ },
621
+ },
622
+ postHistoryInstructions: {
623
+ type: 'text',
624
+ default: envoy.prompts?.postHistoryInstructions ?? '',
625
+ label: { en: 'Post-history instructions' },
626
+ description: {
627
+ en: 'Instructions placed after the conversation, just before the envoy answers. Empty unless the genre or you put something here.',
628
+ },
629
+ },
630
+ },
631
+ };
632
+ }
633
+ //# sourceMappingURL=genres.js.map