@seriousgaming/sdk-tools 1.3.0 → 1.5.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.
- package/dist/cli.js +4055 -2646
- package/dist/client.js +807 -172
- package/dist/core/session-host.d.ts +4 -2
- package/dist/core/settings-locks.d.ts +27 -2
- package/dist/dev/console/assets/{index-DEV8N0na.js → index-BVF8exas.js} +22 -22
- package/dist/dev/console/index.html +1 -1
- package/dist/dev/public-origins.d.ts +61 -0
- package/dist/dev/routes.d.ts +4 -0
- package/dist/dev/shell.d.ts +32 -4
- package/dist/dev/view/batch.d.ts +7 -1
- package/dist/docs/ai-agents.md +5 -0
- package/dist/docs/api/index.md +1 -1
- package/dist/docs/api/sdk-tools-client.md +1 -0
- package/dist/docs/api/sdk.md +79 -2
- package/dist/docs/changelog-0.x.md +2 -2
- package/dist/docs/changelog.md +62 -4
- package/dist/docs/cli-and-dev-server.md +58 -0
- package/dist/docs/cli-error-codes.md +39 -36
- package/dist/docs/cli-reference.md +68 -21
- package/dist/docs/concepts/terminology.md +1 -1
- package/dist/docs/environment-variables.md +10 -5
- package/dist/docs/guides/ai-facilitation.md +2 -0
- package/dist/docs/guides/capabilities.md +4 -0
- package/dist/docs/guides/designing-a-game.md +2 -0
- package/dist/docs/guides/designing-screens.md +133 -0
- package/dist/docs/guides/endpoints.md +4 -2
- package/dist/docs/guides/engine-testing.md +6 -2
- package/dist/docs/guides/engine.md +2 -0
- package/dist/docs/guides/file-handling.md +116 -22
- package/dist/docs/guides/games.md +3 -1
- package/dist/docs/guides/global-settings.md +2 -0
- package/dist/docs/guides/guide.md +2 -0
- package/dist/docs/guides/hooks.md +2 -0
- package/dist/docs/guides/index.md +9 -0
- package/dist/docs/guides/internationalization.md +2 -0
- package/dist/docs/guides/llm-integration.md +5 -3
- package/dist/docs/guides/multi-team-games.md +3 -1
- package/dist/docs/guides/patterns.md +2 -0
- package/dist/docs/guides/presentation.md +1 -1
- package/dist/docs/guides/production-constraints.md +2 -0
- package/dist/docs/guides/scenario-editor.md +3 -1
- package/dist/docs/guides/scenarios.md +15 -3
- package/dist/docs/guides/session-game-flow.md +365 -0
- package/dist/docs/guides/session-hooks.md +205 -0
- package/dist/docs/guides/session.md +27 -565
- package/dist/docs/guides/settings.md +64 -2
- package/dist/docs/guides/setup.md +3 -1
- package/dist/docs/guides/speech-generation.md +2 -0
- package/dist/docs/guides/starter-game.md +61 -21
- package/dist/docs/guides/testing.md +2 -0
- package/dist/docs/guides/tick-controller.md +3 -1
- package/dist/docs/guides/type-safety.md +2 -0
- package/dist/docs/guides/ui-files-and-llms.md +328 -0
- package/dist/docs/guides/ui-participants.md +281 -0
- package/dist/docs/guides/ui-styling.md +263 -0
- package/dist/docs/guides/ui-ticks.md +247 -0
- package/dist/docs/guides/ui.md +11 -1092
- package/dist/docs/guides/upgrading.md +2 -0
- package/dist/docs/guides/validators.md +64 -4
- package/dist/docs/guides/waiting-room.md +1 -1
- package/dist/docs/index.md +2 -1
- package/dist/docs/page-index.md +145 -0
- package/dist/docs/recipes/adapt-a-game-for-walkthroughs.md +1 -1
- package/dist/docs/recipes/adapt-ui-for-observers.md +1 -1
- package/dist/docs/recipes/create-presentation.md +11 -0
- package/dist/docs/recipes/create-scenario-editor.md +1 -0
- package/dist/docs/recipes/create-session-ui.md +2 -1
- package/dist/docs/recipes/create-setup.md +1 -0
- package/dist/docs/recipes/create-user-interface.md +1 -0
- package/dist/docs/recipes/create-waiting-room-ui.md +1 -0
- package/dist/docs/recipes/design-state-for-concurrent-writes.md +1 -1
- package/dist/docs/recipes/fix-duplicate-packages.md +2 -2
- package/dist/docs/recipes/index.md +3 -0
- package/dist/docs/recipes/screenshot-a-surface.md +80 -0
- package/dist/docs/recipes/test-a-multi-role-game.md +1 -1
- package/dist/docs/recipes/upload-and-display-files.md +7 -7
- package/dist/docs/recipes/use-request-tick.md +2 -2
- package/dist/docs/recipes/validate-scenarios.md +4 -1
- package/dist/execution/config-resolver.d.ts +4 -1
- package/dist/execution/endpoint-runner.d.ts +6 -0
- package/dist/execution/logic-calls.d.ts +7 -2
- package/dist/execution/scenario-gates.d.ts +21 -1
- package/dist/guide/settings.d.ts +1 -1
- package/dist/host.js +64 -2
- package/dist/runtime/manifest-version.d.ts +1 -1
- package/dist/runtime.js +7 -2
- package/dist/storage/asset-resolver.d.ts +24 -1
- package/dist/storage/blob-store.d.ts +7 -0
- package/dist/templates/package/CLAUDE.md.template +14 -5
- package/dist/templates/package/DESIGN.md.liquid +39 -7
- package/dist/templates/package/README.md.liquid +1 -1
- package/dist/templates/package/claude/rules/workflow-create-user-interface.md +1 -1
- package/dist/templates/package/pnpm-workspace.yaml.template +13 -0
- package/dist/templates/starter-game/capabilities/pacing/capability.sdk.json +18 -0
- package/dist/templates/starter-game/package.json +2 -0
- package/dist/templates/starter-game/presentation/defaults.ts +52 -0
- package/dist/templates/starter-game/presentation/index.html +20 -0
- package/dist/templates/starter-game/presentation/presentation.sdk.json +10 -0
- package/dist/templates/starter-game/presentation/src/App.tsx +55 -0
- package/dist/templates/starter-game/presentation/src/Band.tsx +40 -0
- package/dist/templates/starter-game/presentation/src/Slides.tsx +415 -0
- package/dist/templates/starter-game/presentation/src/WeatherIcon.tsx +21 -0
- package/dist/templates/starter-game/presentation/src/i18n.ts +88 -0
- package/dist/templates/starter-game/presentation/src/main.tsx +15 -0
- package/dist/templates/starter-game/presentation/src/stalls.test.ts +196 -0
- package/dist/templates/starter-game/presentation/src/stalls.ts +199 -0
- package/dist/templates/starter-game/presentation/types.ts +94 -0
- package/dist/templates/starter-game/seriousgaming.sdk.json +2 -1
- package/dist/templates/starter-game/session/defaults.ts +6 -0
- package/dist/templates/starter-game/session/index.html +1 -1
- package/dist/templates/starter-game/session/session.sdk.json +2 -2
- package/dist/templates/starter-game/session/src/App.test.tsx +436 -115
- package/dist/templates/starter-game/session/src/App.tsx +372 -222
- package/dist/templates/starter-game/session/src/JoinCodes.tsx +184 -0
- package/dist/templates/starter-game/session/src/ManagePanel.tsx +188 -0
- package/dist/templates/starter-game/session/src/Results.tsx +340 -0
- package/dist/templates/starter-game/session/src/SessionBar.tsx +179 -0
- package/dist/templates/starter-game/session/src/SessionPanels.tsx +105 -0
- package/dist/templates/starter-game/session/src/SidePanel.tsx +89 -0
- package/dist/templates/starter-game/session/src/StallCard.tsx +253 -0
- package/dist/templates/starter-game/session/src/TopBar.tsx +36 -0
- package/dist/templates/starter-game/session/src/i18n.ts +91 -24
- package/dist/templates/starter-game/session/src/status.ts +28 -0
- package/dist/templates/starter-game/session/types.ts +8 -2
- package/dist/templates/starter-game/shared/Awning.tsx +31 -0
- package/dist/templates/starter-game/shared/HostLogo.test.tsx +38 -0
- package/dist/templates/starter-game/shared/HostLogo.tsx +48 -0
- package/dist/templates/starter-game/shared/StallIcons.tsx +83 -0
- package/dist/templates/starter-game/shared/days.ts +11 -0
- package/dist/templates/starter-game/shared/format.test.ts +13 -0
- package/dist/templates/starter-game/{ui/src → shared}/format.ts +1 -1
- package/dist/templates/starter-game/testing/e2e/game.spec.ts +42 -8
- package/dist/templates/starter-game/ui/defaults.ts +3 -0
- package/dist/templates/starter-game/ui/src/App.test.tsx +197 -29
- package/dist/templates/starter-game/ui/src/App.tsx +176 -99
- package/dist/templates/starter-game/ui/src/DayBar.test.tsx +50 -7
- package/dist/templates/starter-game/ui/src/DayBar.tsx +96 -38
- package/dist/templates/starter-game/ui/src/DaysTable.tsx +69 -0
- package/dist/templates/starter-game/ui/src/FirstDay.tsx +37 -0
- package/dist/templates/starter-game/ui/src/Header.tsx +257 -0
- package/dist/templates/starter-game/ui/src/Lesson.tsx +63 -0
- package/dist/templates/starter-game/ui/src/MakeRow.tsx +98 -71
- package/dist/templates/starter-game/ui/src/Notices.tsx +59 -0
- package/dist/templates/starter-game/ui/src/PastDay.tsx +88 -0
- package/dist/templates/starter-game/ui/src/Section.tsx +26 -26
- package/dist/templates/starter-game/ui/src/ThemeToggle.tsx +25 -11
- package/dist/templates/starter-game/ui/src/TodayPanel.test.tsx +37 -33
- package/dist/templates/starter-game/ui/src/TodayPanel.tsx +66 -52
- package/dist/templates/starter-game/ui/src/WeatherCard.tsx +47 -0
- package/dist/templates/starter-game/ui/src/WeekOver.tsx +145 -0
- package/dist/templates/starter-game/ui/src/YesterdayPanel.tsx +65 -114
- package/dist/templates/starter-game/ui/src/days.ts +58 -0
- package/dist/templates/starter-game/ui/src/i18n.ts +86 -32
- package/dist/templates/starter-game/ui/src/test-helpers.ts +1 -0
- package/dist/templates/starter-game/ui/src/theme.ts +8 -8
- package/dist/templates/starter-game/ui/types.ts +6 -0
- package/dist/templates/starter-game/ui/ui.sdk.json +1 -1
- package/dist/templates/starter-game/validators/daylimit/defaults.ts +13 -0
- package/dist/templates/starter-game/validators/daylimit/logic/logic.test.ts +20 -0
- package/dist/templates/starter-game/validators/daylimit/logic/logic.ts +23 -0
- package/dist/templates/starter-game/validators/daylimit/types.ts +23 -0
- package/dist/templates/starter-game/validators/daylimit/validator.sdk.json +10 -0
- package/dist/templates/starter-game/waiting_room/src/App.test.tsx +83 -5
- package/dist/templates/starter-game/waiting_room/src/App.tsx +262 -119
- package/dist/templates/starter-game/waiting_room/src/i18n.ts +8 -4
- package/dist/utils/error-codes.d.ts +12 -0
- package/dist/utils/local-refs.d.ts +40 -0
- package/dist/utils/schema-members.d.ts +19 -0
- package/package.json +11 -4
- package/dist/templates/starter-game/session/src/Section.tsx +0 -37
- package/dist/templates/starter-game/session/src/TeamDoor.tsx +0 -96
- package/dist/templates/starter-game/session/src/format.ts +0 -8
- package/dist/templates/starter-game/ui/src/HistoryPanel.test.tsx +0 -74
- package/dist/templates/starter-game/ui/src/HistoryPanel.tsx +0 -120
- package/dist/templates/starter-game/ui/src/HostLogo.test.tsx +0 -25
- package/dist/templates/starter-game/ui/src/HostLogo.tsx +0 -38
|
@@ -6,6 +6,8 @@ This guide covers declaring them, reading them from logic and surfaces, overridi
|
|
|
6
6
|
|
|
7
7
|
Not to be confused with [global settings](./global-settings.md), the file in your home directory that holds API keys for every project.
|
|
8
8
|
|
|
9
|
+
**Keywords:** settings, parameters, settingsSchema, defaults, read settings, override settings, configure, scenario settings, locked settings, game settings, hidden values, sdk configure
|
|
10
|
+
|
|
9
11
|
## Overview
|
|
10
12
|
|
|
11
13
|
A settings resource is a schema and nothing else. It lives at `settings/<identifier>/settings.sdk.json`, and a package may hold any number of them, as it does capabilities.
|
|
@@ -62,7 +64,7 @@ Run `pnpm run sdk new settings` with no JSON to be prompted for each property in
|
|
|
62
64
|
}
|
|
63
65
|
```
|
|
64
66
|
|
|
65
|
-
`settingsSchema` is a full JSON Schema Draft 7 object. Two rules are stricter than for a capability's `variablesSchema`:
|
|
67
|
+
`settingsSchema` is a full JSON Schema Draft 7 object, as every schema a game writes is, read the same way whatever `$schema` it names. Two features of later drafts also work: `$defs` beside `definitions`, and keywords written beside a `$ref` (see [Reuse a shape](#reuse-a-shape-or-nest-it-to-any-depth)). Two rules are stricter than for a capability's `variablesSchema`:
|
|
66
68
|
|
|
67
69
|
- Every property needs a `default`. `new settings`, `update settings` and `sdk build` all refuse a property without one
|
|
68
70
|
- Every default must fit its own schema, at any depth. `sdk build` refuses a string default on a number property, a default outside its range or `enum`, and an object default missing a key its own `required` lists, naming the settings resource and the path. The generated `Settings` type comes from the schema, so the compiler cannot catch a default that disagrees with it
|
|
@@ -70,6 +72,43 @@ Run `pnpm run sdk new settings` with no JSON to be prompted for each property in
|
|
|
70
72
|
|
|
71
73
|
A `required` inside an object-valued property is allowed. It holds the property's `default` to its keys, never a scenario or a setup change: those are partial at every depth, so a scenario or a setup UI may set one key of the object and leave the rest to the layer beneath. An array is the exception: it replaces the one beneath whole, so each item an override supplies must be complete.
|
|
72
74
|
|
|
75
|
+
### Reuse a shape, or nest it to any depth
|
|
76
|
+
|
|
77
|
+
Declare a shape once under `$defs` (or `definitions`) and use it with a `$ref`. A shape may contain itself, which is how recursive data, such as a running order whose items hold items or a rule whose branches are rules, is checked to every depth rather than left as a bare object below the first level:
|
|
78
|
+
|
|
79
|
+
```json
|
|
80
|
+
"settingsSchema": {
|
|
81
|
+
"type": "object",
|
|
82
|
+
"properties": {
|
|
83
|
+
"Agenda": {
|
|
84
|
+
"title": "Agenda",
|
|
85
|
+
"$ref": "#/$defs/agendaItem",
|
|
86
|
+
"default": { "title": "Workshop", "children": [] }
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
"$defs": {
|
|
90
|
+
"agendaItem": {
|
|
91
|
+
"type": "object",
|
|
92
|
+
"properties": {
|
|
93
|
+
"title": { "type": "string" },
|
|
94
|
+
"children": { "type": "array", "items": { "$ref": "#/$defs/agendaItem" } }
|
|
95
|
+
},
|
|
96
|
+
"required": ["title", "children"],
|
|
97
|
+
"additionalProperties": false
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
"additionalProperties": false
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
- **A reference stays inside its own schema.** It names a part of the settings resource that holds it, as `#/$defs/<name>`. The build refuses one that names nothing, another file, a URL or another resource's schema, pointing at it
|
|
105
|
+
- **Write the `default` beside the `$ref`.** Keywords beside a reference apply with it, so the property's `default`, `title` and `description` go there, and so does a constraint for this use alone, such as a `maximum`
|
|
106
|
+
- **Every check follows it.** The defaults, scenarios, setup and scenario editor writes, [file settings](#settings-that-hold-a-file), [locks](#lock-a-setting) and [guide conditions](./guide.md) all reach through a reference, at every depth
|
|
107
|
+
- **Each use keeps its own rule.** Where the shape is an object setting, a scenario may set one key of it and leave the rest; where it is an array's item, each item must be complete
|
|
108
|
+
- **The generated types name it.** `Agenda` is typed `AgendaItem`, one interface whose `children` are `AgendaItem[]`, exported from `types.ts` for your own code. When two resources a file reads both define the same name, the second is prefixed with its identifier (`EngineRule`)
|
|
109
|
+
|
|
110
|
+
A capability's `variablesSchema` takes `$defs` and `$ref` the same way.
|
|
111
|
+
|
|
73
112
|
### Describe every setting
|
|
74
113
|
|
|
75
114
|
A settings schema is read by more than the build. A hosted runtime's generic settings form, a [scenario editor](./scenario-editor.md), and an AI agent authoring a scenario for your released game all work from it, and an agent can edit a game with no editor UI at all if the schema says what each value means. Give every property:
|
|
@@ -112,6 +151,8 @@ Some values are part of the game's design rather than something to tune: a const
|
|
|
112
151
|
- **Nothing can change a locked value.** The build refuses a scenario that sets it, with `SETTINGS_LOCKED` pointing at the value, even when it sets the same value as your default. A setup screen or scenario editor that changes it is refused as `denied`, with a message naming the setting (`"engine.LowProductionThreshold" is read-only`), and none of that write applies
|
|
113
152
|
- **Sending it back unchanged is fine.** An editor that spreads the settings it was given sends the locked value back as it was, and only what changed is applied, so spreading is still safe
|
|
114
153
|
- **Locking an object locks everything in it.** `readOnly` on an object-valued property fixes every key inside it, at any depth
|
|
154
|
+
- **Lock named properties, or a whole list or map.** A list's items and a map's entries come and go as scenarios add and remove them, so there is no single value of yours for a lock inside one to keep. The build refuses `readOnly` beneath `items`, `additionalProperties` or `patternProperties`; put it on the list or map itself instead
|
|
155
|
+
- **A lock reached through a `$ref` counts.** `readOnly` on a shape under `$defs` locks every named property that uses it (see [Reuse a shape, or nest it to any depth](#reuse-a-shape-or-nest-it-to-any-depth))
|
|
115
156
|
- **Saving a scenario leaves locked values out.** The dev console's Save writes every other setting and drops the locked ones, so the scenario still builds
|
|
116
157
|
- **Editors are not sent the schema.** A setup screen or scenario editor receives the values, not the schema, so show a locked field as read-only yourself, as the factory example's scenario editor does
|
|
117
158
|
- **Adding a lock is a scenario-format change.** A custom scenario saved before the lock may hold a value for it, so bump `scenarioFormat` when you lock a setting a released version left open (see [Scenario format: when to bump it](./scenarios.md#scenario-format-when-to-bump-it))
|
|
@@ -136,6 +177,27 @@ A setting can hold a file, such as a client's logo or a briefing document. Mark
|
|
|
136
177
|
- **The build checks your files.** Every file a package scenario or a default names must be shipped, within `maxBytes`, and of a type `accept` lists, judged from its extension. A `blob:` reference in a package scenario fails the build: it is an upload, which no package can carry
|
|
137
178
|
- **Every write is checked against it.** A setup screen, the scenario editor or an agent sets a file by uploading it first and writing the `blob:` reference it gets back. A reference to a file nobody uploaded, or one too large or of the wrong type, is refused as `denied`, naming the setting. So is anything that is not a reference, a `data:` URI or a URL included
|
|
138
179
|
- **It tells an agent what to upload.** A schema alone says only that the value is a string; `blob` says it is a PNG of up to 512 KB
|
|
180
|
+
- **A map can hold a file per key.** Put `blob` on a map's `additionalProperties` (or a `patternProperties` schema), and every entry is a file setting of its own, checked and named by its key (`brand.Cast.ada`, see [How a setting is named](#how-a-setting-is-named)). A file per language is one such map (see [A file per language](./file-handling.md#a-file-per-language))
|
|
181
|
+
|
|
182
|
+
### How a setting is named
|
|
183
|
+
|
|
184
|
+
A refusal, a lock's message, a `Scenario` gate's problem and a guide's `:setting` all name one value by its setting path: the settings identifier, then each key down to the value.
|
|
185
|
+
|
|
186
|
+
```text
|
|
187
|
+
ui.MinPrice
|
|
188
|
+
brand.Cast.ada.portrait
|
|
189
|
+
engine.Rounds.0.Price
|
|
190
|
+
brand.Cast["a.b"].portrait
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
A plain key, one that is not empty and holds no `.`, `[`, `]`, `"` or space, follows a dot, and so does a list's position. Any other key, such as a map entry named `a.b`, goes in brackets as a JSON string, so the path reads back one way only. Build and read paths with `settingPath` and `parseSettingPath` from `@seriousgaming/sdk` rather than joining keys yourself:
|
|
194
|
+
|
|
195
|
+
```typescript
|
|
196
|
+
import { parseSettingPath, settingPath } from '@seriousgaming/sdk';
|
|
197
|
+
|
|
198
|
+
settingPath('brand', 'Cast', 'a.b', 'portrait'); // 'brand.Cast["a.b"].portrait'
|
|
199
|
+
parseSettingPath('brand.Cast["a.b"].portrait'); // { identifier: 'brand', keys: ['Cast', 'a.b', 'portrait'] }
|
|
200
|
+
```
|
|
139
201
|
|
|
140
202
|
### How to divide settings
|
|
141
203
|
|
|
@@ -402,7 +464,7 @@ Options:
|
|
|
402
464
|
Every override source is validated against the `settingsSchema` of the settings resource it names, scenario overrides and session overrides alike. Neither has to name every property, but both are refused for:
|
|
403
465
|
|
|
404
466
|
- A key naming no settings resource the package declares
|
|
405
|
-
- A property the schema does not declare, such as a misspelling
|
|
467
|
+
- A property the schema does not declare, such as a misspelling. An object that lists `properties` and says nothing else of its keys refuses any key it does not list, whether or not it sets `additionalProperties: false`. A bare `{ "type": "object" }`, or an object with `patternProperties`, an `additionalProperties` schema or `allOf`/`anyOf`/`oneOf`, takes whatever its schema admits, so an object meant to hold any keys, such as a map of triggers, is written that way
|
|
406
468
|
- A value of the wrong type, or outside a `minimum`, `maximum` or `enum`
|
|
407
469
|
- A value the schema locks with `readOnly` (see [Lock a setting](#lock-a-setting))
|
|
408
470
|
|
|
@@ -4,6 +4,8 @@ The `setup` slot holds the small form a facilitator fills in when they create a
|
|
|
4
4
|
|
|
5
5
|
This guide covers creating one, building its form, and how it behaves in the dev server.
|
|
6
6
|
|
|
7
|
+
**Keywords:** setup screen, setup form, session creation, configures, per-session settings, number of rounds, requestPlay, start play, facilitator form
|
|
8
|
+
|
|
7
9
|
## What setup is
|
|
8
10
|
|
|
9
11
|
A game holds at most one setup screen, at `setup/`. It is a slot, like `session` or `waiting_room`, so it carries no name of its own: the slot is its identifier.
|
|
@@ -143,7 +145,7 @@ An endpoint called from setup sees `caller.role` as `'facilitator'`.
|
|
|
143
145
|
Setup is embedded in the host's page, not a page of its own:
|
|
144
146
|
|
|
145
147
|
- **Leave the ground to the host.** Do not paint a page background. MUI's `CssBaseline` paints the body, so override it with `<GlobalStyles styles={{ body: { backgroundColor: 'transparent' } }} />`
|
|
146
|
-
- **
|
|
148
|
+
- **Avoid dialogs with a backdrop.** A modal inside an iframe darkens only the frame, not the host's bar above it. Use a side panel, a confirmation beside the button that asked, or full screen
|
|
147
149
|
- **Do not reproduce host chrome.** The language picker, the theme control, and the Play action live outside your iframe
|
|
148
150
|
|
|
149
151
|
The [session UI guide](./session.md#rendering-inside-the-host) covers the same ground in more detail.
|
|
@@ -6,6 +6,8 @@ The SDK exposes a provider-agnostic text-to-speech callback, `generateSpeech`. E
|
|
|
6
6
|
|
|
7
7
|
The dev server ships with one provider adapter (ElevenLabs). Additional providers (OpenAI, Google Cloud, Azure, AWS Polly) will land behind a future `TTS_PROVIDER` env var without breaking changes to game code.
|
|
8
8
|
|
|
9
|
+
**Keywords:** speech, text-to-speech, TTS, generateSpeech, voice, voice presets, audio, ElevenLabs, ELEVENLABS_API_KEY, narration
|
|
10
|
+
|
|
9
11
|
## Overview
|
|
10
12
|
|
|
11
13
|
`generateSpeech` accepts either a bare string or a request object, mirroring `generateText`:
|
|
@@ -13,7 +13,8 @@ Most of the starter game is ordinary, but four decisions in it are the ones a fi
|
|
|
13
13
|
- **State keyed so participants cannot overwrite each other.** `plan.Make` is keyed by menu item, and a hook puts each participant in charge of one item, so two people changing two numbers write two different keys
|
|
14
14
|
- **A validator on the one thing they share.** Two changes can each fit while the merged plan busts the stall's capacity. No shape of state prevents that, so `validators/capacity` checks the merged result
|
|
15
15
|
- **Every write awaited.** The game UI reports a refused write to the participant who made it, instead of showing a decision the game never received
|
|
16
|
-
- **Teams run their own days.** The game is in independent mode: each team opens its stall when it is ready
|
|
16
|
+
- **Teams run their own days.** The game is in independent mode: each team opens its stall when it is ready. The facilitator does not run the day; they hold the room at a day with a limit a validator enforces, watch, and can undo
|
|
17
|
+
- **Screens designed for where they are used.** Each screen leads with its one decision, works at phone size, uses the host's colours and an icon set rather than drawn icons, and asks 'are you sure?' beside the button rather than in a dialog. See [Designing screens](./designing-screens.md)
|
|
17
18
|
|
|
18
19
|
[Design state for concurrent writes](../recipes/design-state-for-concurrent-writes.md) explains the first two in full.
|
|
19
20
|
|
|
@@ -35,13 +36,14 @@ See [Shaping games](./games.md).
|
|
|
35
36
|
|
|
36
37
|
Each directory is one capability, a named slice of the game's state with a JSON Schema for its variables. There is no logic here.
|
|
37
38
|
|
|
38
|
-
| Capability | Holds
|
|
39
|
-
| ---------- |
|
|
40
|
-
| `plan` | How many of each item to make today, keyed by item. The one capability participants write
|
|
41
|
-
| `weather` | Today's forecast and roughly how many people will want each item
|
|
42
|
-
| `results` | What happened yesterday, item by item, and the money: takings, spending, profit, and the running total in the jar
|
|
43
|
-
| `roles` | Which item each participant looks after, keyed by participant id
|
|
44
|
-
| `briefing` | A note from the facilitator shown on every team's screen. `shared` scope, so there is one value for the whole session
|
|
39
|
+
| Capability | Holds |
|
|
40
|
+
| ---------- | --------------------------------------------------------------------------------------------------------------------------------- |
|
|
41
|
+
| `plan` | How many of each item to make today, keyed by item. The one capability participants write |
|
|
42
|
+
| `weather` | Today's forecast and roughly how many people will want each item |
|
|
43
|
+
| `results` | What happened yesterday, item by item, and the money: takings, spending, profit, and the running total in the jar |
|
|
44
|
+
| `roles` | Which item each participant looks after, keyed by participant id |
|
|
45
|
+
| `briefing` | A note from the facilitator shown on every team's screen. `shared` scope, so there is one value for the whole session |
|
|
46
|
+
| `pacing` | `LastOpenDay`, the last day a stall may open. `shared` scope, written only by the facilitator's screen; the default opens all ten |
|
|
45
47
|
|
|
46
48
|
See [Capabilities](./capabilities.md).
|
|
47
49
|
|
|
@@ -56,7 +58,7 @@ Each directory is one settings resource: read-only parameters, every one with a
|
|
|
56
58
|
| `menu` | `Capacity` (120) and the `Menu`, each item's name, cost, and price | The engine, every surface, the hook, and the validator |
|
|
57
59
|
| `engine` | `UsualDemand` for each item, `SunnyPull`, `RainyPull`, and `Variation`. Only the engine reads it, so no participant's browser ever holds the demand | The engine |
|
|
58
60
|
| `ui` | `Step` and `CurrencySymbol` | The game UI |
|
|
59
|
-
| `session` | `ShowJoinLinks` and `CurrencySymbol` | The session UI
|
|
61
|
+
| `session` | `ShowJoinLinks` and `CurrencySymbol` | The session UI and the presentation |
|
|
60
62
|
|
|
61
63
|
See [Settings](./settings.md).
|
|
62
64
|
|
|
@@ -84,39 +86,77 @@ See [Hooks](./hooks.md).
|
|
|
84
86
|
|
|
85
87
|
A validator that sees every change a UI makes to the plan before it is applied. It reads the `menu` settings, and refuses a plan that asks for more than the stall's capacity, a negative or fractional count, or an item not on the menu. It never changes state; it only says no, with a message the game UI shows.
|
|
86
88
|
|
|
89
|
+
### `validators/daylimit/`
|
|
90
|
+
|
|
91
|
+
A validator with a `RequestTick` gate and no `UpdateData`. It refuses a stall's request to open a day after `pacing.LastOpenDay`, so the facilitator's hold is enforced on the server rather than only by a disabled button. Only a participant's request reaches it; the facilitator's own actions are never held.
|
|
92
|
+
|
|
87
93
|
See [Validators](./validators.md).
|
|
88
94
|
|
|
89
95
|
## User interfaces
|
|
90
96
|
|
|
91
|
-
Each is a small React app built with Vite
|
|
97
|
+
Each is a small React app built with Vite, with its own `index.html`, `src/main.tsx` (the SDK wrapper, locale, and right-to-left set-up), and `src/i18n.ts` (every string on the screen). The three screens people use are built with MUI and add `src/theme.ts` (`createSurfaceTheme` over the host's theme, with Work Sans as the font); the presentation is built with the SDK's deck library instead.
|
|
98
|
+
|
|
99
|
+
### `shared/`
|
|
100
|
+
|
|
101
|
+
Code every screen uses, imported by relative path. It is not a slot, so the build and the scaffold treat it as ordinary source.
|
|
102
|
+
|
|
103
|
+
- `Awning.tsx`: the scalloped edge under each top bar, in the host's primary colour. It is the game's one drawn motif; everything else comes from the icon set
|
|
104
|
+
- `HostLogo.tsx`: the host's logo, with the variant chosen for the coloured bar, or nothing when the host sends none
|
|
105
|
+
- `StallIcons.tsx`: the Material icon and tint for each menu item and each kind of weather
|
|
106
|
+
- `format.ts`: money from pence, and counts. `days.ts`: the length of the week, read from the manifest's `maxTicks`
|
|
92
107
|
|
|
93
108
|
### `ui/`
|
|
94
109
|
|
|
95
|
-
The game UI: what each participant sees.
|
|
110
|
+
The game UI: what each participant sees. It leads with today's decision and keeps the button that opens the stall in a bar at the bottom of the layout, never floating over it.
|
|
96
111
|
|
|
97
|
-
- `src/App.tsx`: the layout
|
|
98
|
-
- `src/
|
|
99
|
-
- `src/
|
|
100
|
-
- `src/
|
|
101
|
-
- `src/
|
|
102
|
-
- `src/writes.ts`: one mutation reporter every write goes through
|
|
103
|
-
- `src/menu.ts`, `src/
|
|
104
|
-
- `ui.sdk.json`: reads every capability it shows, writes only `plan`, and reads the `ui` settings (`Step` and `CurrencySymbol`)
|
|
112
|
+
- `src/App.tsx`: the layout and the state it is in: before day 1 (`src/FirstDay.tsx`), mid-week, looking back at a past day (`src/PastDay.tsx`), and the week over (`src/WeekOver.tsx`)
|
|
113
|
+
- `src/Header.tsx`: the stall's name, the item the participant looks after, and a timeline of the days, where a day already played opens that day
|
|
114
|
+
- `src/WeatherCard.tsx`, `src/TodayPanel.tsx` and `src/MakeRow.tsx`: today's forecast and the controls for the plan, one row per item, with the participant's own item marked
|
|
115
|
+
- `src/DayBar.tsx`: the bottom bar. **Open the stall for day N** calls `requestTick`; when the facilitator's limit holds the stall it is disabled and says so
|
|
116
|
+
- `src/YesterdayPanel.tsx`, `src/Lesson.tsx` and `src/DaysTable.tsx`: yesterday as one profit figure and one lesson, and every day so far. Earlier days come from the host with `usePastState`, so nothing in context grows as the days go by (see [Review a past day in a UI](../recipes/review-a-past-day.md))
|
|
117
|
+
- `src/Notices.tsx` and `src/writes.ts`: the facilitator's notice, and the one mutation reporter every write goes through, so a refusal reaches the person who made it
|
|
118
|
+
- `src/menu.ts`, `src/days.ts`, `src/Section.tsx`, `src/ThemeToggle.tsx`: menu ordering, day helpers, the card layout, and a light or dark switch
|
|
119
|
+
- `ui.sdk.json`: reads every capability it shows, `pacing` included, writes only `plan`, and reads the `ui` settings (`Step` and `CurrencySymbol`)
|
|
105
120
|
|
|
106
121
|
See [Building user interfaces](./ui.md).
|
|
107
122
|
|
|
108
123
|
### `session/`
|
|
109
124
|
|
|
110
|
-
The session UI: the facilitator's whole screen, which the dev server shows at `/` as the console. It
|
|
125
|
+
The session UI: the facilitator's whole screen, which the dev server shows at `/` as the console. It follows what most facilitator screens need, and leaves out what only some games do:
|
|
126
|
+
|
|
127
|
+
- `src/SessionBar.tsx`: one line across the top. The day limit, which writes `pacing.LastOpenDay`, the waiting room, and the facilitator guide and slides when the host offers them
|
|
128
|
+
- `src/StallCard.tsx` and `src/status.ts`: a card per stall with the day it is on, who is connected, what is in the jar, and links to observe it or copy its join link
|
|
129
|
+
- `src/ManagePanel.tsx` and `src/SidePanel.tsx`: a panel beside the cards, with no backdrop, to rename a stall, move a person, or undo a day, confirmed in place
|
|
130
|
+
- `src/Results.tsx`: the room's averages and range above a sortable table, any day played so far, and full screen for the projector
|
|
131
|
+
- `src/JoinCodes.tsx`: each stall's join link in large type, one stall at a time, for the room to read
|
|
132
|
+
- `src/SessionPanels.tsx`: the notice to the room (the shared `briefing`) and starting the session again
|
|
133
|
+
|
|
134
|
+
`ShowJoinLinks`, in the `session` settings it reads, turns the per-team join and observe links off.
|
|
111
135
|
|
|
112
136
|
See [Building session UIs](./session.md).
|
|
113
137
|
|
|
114
138
|
### `waiting_room/`
|
|
115
139
|
|
|
116
|
-
The screen participants see while the session is held. It tells a held start ('
|
|
140
|
+
The screen participants see while the session is held. It tells a held start ('Your stall opens soon') from a pause part-way through, shows who is on the team, lets the team name its stall, and copies the join link for anyone else joining.
|
|
117
141
|
|
|
118
142
|
See [Building waiting room UIs](./waiting-room.md).
|
|
119
143
|
|
|
144
|
+
### `presentation/`
|
|
145
|
+
|
|
146
|
+
The facilitator's slide deck, which they project for the room. It is read-only, and it renders with or without a session, so a facilitator can rehearse it or export it before the day.
|
|
147
|
+
|
|
148
|
+
- `src/Slides.tsx`: a title slide, one slide a day with the forecast and how the room did the day before, and a results slide for the room. The projector shows the room, never a stall by name: each stall's figures are in the speaker notes
|
|
149
|
+
- `src/stalls.ts`: the room's figures, kept apart from the slides so `src/stalls.test.ts` can test them without a deck. The stalls run their own days, so a day's figures count only the stalls that have played it, read through `usePastState`
|
|
150
|
+
- `src/Band.tsx` and `src/WeatherIcon.tsx`: the awning and the weather icon in the deck's own colours, since a deck has no MUI theme
|
|
151
|
+
- `src/App.tsx`: the `Deck`, with the host's theme as its colours, and opening on the day the room has reached
|
|
152
|
+
- `presentation.sdk.json`: reads `plan`, `weather` and `results`, and the `session` settings for the currency symbol
|
|
153
|
+
|
|
154
|
+
The dev server shows it at `/presentation`, and at `/presentation?preview` with no session.
|
|
155
|
+
|
|
156
|
+
See [Building presentations](./presentation.md).
|
|
157
|
+
|
|
158
|
+
The starter has no `setup/` or `scenario_editor/`, to keep it a quick first read. `examples/factory` in the SDK repository has both, and [Building setup screens](./setup.md) and [Building scenario editors](./scenario-editor.md) cover them.
|
|
159
|
+
|
|
120
160
|
## Content
|
|
121
161
|
|
|
122
162
|
### `scenarios/`
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
Test your engine's logic and your user interfaces, so a broken rule or a broken screen fails on your machine rather than in front of a room.
|
|
4
4
|
|
|
5
|
+
**Keywords:** testing, unit tests, UI tests, Vitest, React Testing Library, renderUserInterface, createMock, test Run, test Init, Playwright, jsdom, test hooks
|
|
6
|
+
|
|
5
7
|
## Testing engine logic
|
|
6
8
|
|
|
7
9
|
### Starting from the generated defaults
|
|
@@ -4,6 +4,8 @@ A tick controller makes ticks happen on their own, on a schedule your logic deci
|
|
|
4
4
|
|
|
5
5
|
This guide explains the model, then is the reference for writing one.
|
|
6
6
|
|
|
7
|
+
**Keywords:** tick controller, timer, automatic ticks, interval, schedule, timed rounds, nextTickAt, game completion, complete, enabled, pause, extend a tick, cron
|
|
8
|
+
|
|
7
9
|
## The model
|
|
8
10
|
|
|
9
11
|
By default, ticks are manual: a participant or facilitator presses a control, or a command is sent, to advance the game. That suits a game that moves one decision at a time. Some games need time to move on its own, or at a pace that depends on what is happening in the simulation. Some also need to end when a goal is met rather than after a fixed number of ticks.
|
|
@@ -410,7 +412,7 @@ pnpm run sdk timer extend 120 # two more minutes (the CLI takes second
|
|
|
410
412
|
pnpm run sdk timer resume --team 2 # one team, in an independent game
|
|
411
413
|
```
|
|
412
414
|
|
|
413
|
-
The current schedule, a [`TimerState`](../api/sdk-ui.md#timerstate) with every duration and timestamp in milliseconds, is pushed to every game UI. UIs subscribe with `useUserInterfaceTimer` and render their own countdown or progress bar. See [Displaying the tick timer](./ui.md#displaying-the-tick-timer) in the user interfaces guide.
|
|
415
|
+
The current schedule, a [`TimerState`](../api/sdk-ui.md#timerstate) with every duration and timestamp in milliseconds, is pushed to every game UI. UIs subscribe with `useUserInterfaceTimer` and render their own countdown or progress bar. See [Displaying the tick timer](./ui-ticks.md#displaying-the-tick-timer) in the user interfaces guide.
|
|
414
416
|
|
|
415
417
|
## Testing without waiting
|
|
416
418
|
|
|
@@ -4,6 +4,8 @@ The SDK generates TypeScript types from your schemas, so a misspelt variable fai
|
|
|
4
4
|
|
|
5
5
|
This guide covers the rules that keep that guarantee, and the shortcuts that quietly break it.
|
|
6
6
|
|
|
7
|
+
**Keywords:** type safety, TypeScript, generated types, types.ts, sdk generate, any, type casts, JSON Schema types, schema constraints, strict types
|
|
8
|
+
|
|
7
9
|
## Core principle
|
|
8
10
|
|
|
9
11
|
The Serious Gaming SDK uses TypeScript and JSON Schema to provide **end-to-end type safety**. When you define a capability's `variablesSchema` or a settings resource's `settingsSchema`, the SDK generates precise TypeScript types. Shortcuts and workarounds (using `any`, string-based JSON, etc.) break this guarantee and lead to runtime errors.
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
# Files and LLMs in user interfaces
|
|
2
|
+
|
|
3
|
+
How a game UI links to static assets, uploads and shows files, reads an asset's contents, and reaches an LLM through an endpoint to build a chat.
|
|
4
|
+
|
|
5
|
+
It is part of [Building user interfaces](./ui.md), which covers creating the surface and reading and writing context.
|
|
6
|
+
|
|
7
|
+
**Keywords:** static assets, assetUrl, file upload, uploadFile, blob, read asset, LLM, generateText, chat UI, callEndpoint, EndpointError, markdown
|
|
8
|
+
|
|
9
|
+
## Linking to static assets
|
|
10
|
+
|
|
11
|
+
User interfaces run inside an iframe served at a nested path (e.g.,
|
|
12
|
+
`/user-interfaces/ui/`). Because of this, **absolute URLs
|
|
13
|
+
like `/my-file.pdf` will not resolve to your assets**: they escape the iframe
|
|
14
|
+
and hit the shell app's origin instead.
|
|
15
|
+
|
|
16
|
+
Always use **relative paths** when linking to files in your UI's directory:
|
|
17
|
+
|
|
18
|
+
```typescript
|
|
19
|
+
// Wrong: escapes the iframe, loads the shell app's index.html
|
|
20
|
+
window.open('/Briefing.pdf');
|
|
21
|
+
|
|
22
|
+
// Correct: resolves relative to your UI's index.html
|
|
23
|
+
window.open('./Briefing.pdf');
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
This applies to any reference from your UI code to static files: `<a href>`,
|
|
27
|
+
`<img src>`, `<embed src>`, `window.open()`, `fetch()`, etc. The same rule
|
|
28
|
+
holds in both the dev server and production builds.
|
|
29
|
+
|
|
30
|
+
In production your UI also runs under a strict content security policy: every
|
|
31
|
+
asset must be bundled into your build (no external CDNs, no Google Fonts, no
|
|
32
|
+
blob-URL workers), and outbound network calls go through an engine, an endpoint,
|
|
33
|
+
or a host capability. The dev server mirrors this policy, so violations
|
|
34
|
+
surface locally. See [Production security constraints](./production-constraints.md)
|
|
35
|
+
for the full policy and the do's and don'ts.
|
|
36
|
+
|
|
37
|
+
**Where to put static files:** Place them in your UI's directory alongside
|
|
38
|
+
`index.html` (or in a subdirectory). For the default scaffold structure, that
|
|
39
|
+
means inside `ui/`:
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
ui/
|
|
43
|
+
├── index.html
|
|
44
|
+
├── Briefing.pdf ← ./Briefing.pdf
|
|
45
|
+
├── public/
|
|
46
|
+
│ └── logo.png ← ./public/logo.png
|
|
47
|
+
└── src/
|
|
48
|
+
└── App.tsx
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## File uploads
|
|
52
|
+
|
|
53
|
+
User interfaces can upload files (PDFs, images, CSV, etc.) using the `uploadBlob` callback and display them using `getAssetUrl`. Uploaded files and scenario-bundled files share a single asset reference scheme (see [Asset references](../guides/file-handling.md#asset-references) for the full picture).
|
|
54
|
+
|
|
55
|
+
### Uploading a file
|
|
56
|
+
|
|
57
|
+
```typescript
|
|
58
|
+
import { useUserInterfaceCallbacks, useUserInterfaceData } from '@seriousgaming/sdk/ui';
|
|
59
|
+
import type { Context, Settings } from '../types';
|
|
60
|
+
|
|
61
|
+
function DocumentUpload() {
|
|
62
|
+
const callbacks = useUserInterfaceCallbacks();
|
|
63
|
+
const { setData } = useUserInterfaceData<Context, Settings>();
|
|
64
|
+
const [isUploading, setIsUploading] = useState(false);
|
|
65
|
+
|
|
66
|
+
const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
67
|
+
const file = e.target.files?.[0];
|
|
68
|
+
if (!file || !callbacks.uploadBlob) return;
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
setIsUploading(true);
|
|
72
|
+
const reference = await callbacks.uploadBlob(file);
|
|
73
|
+
setData({ 'upload': { DocumentRef: reference } });
|
|
74
|
+
} finally {
|
|
75
|
+
setIsUploading(false);
|
|
76
|
+
e.target.value = '';
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
return (
|
|
81
|
+
<input type="file" accept=".pdf,.csv,.txt" onChange={handleUpload} disabled={isUploading} />
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
The capability holding the reference must be listed in the UI's `writes`. The maximum file size is **20 MB**.
|
|
87
|
+
|
|
88
|
+
### Displaying a file
|
|
89
|
+
|
|
90
|
+
Use `useAssetUrl` to get a URL suitable for `<img>`, `<embed>`, or `<video>`. It resolves uploaded blobs and scenario-bundled assets alike, and returns `undefined` for an absent reference, so there is nothing to guard:
|
|
91
|
+
|
|
92
|
+
```typescript
|
|
93
|
+
import { useAssetUrl } from '@seriousgaming/sdk/ui';
|
|
94
|
+
|
|
95
|
+
function DocumentViewer() {
|
|
96
|
+
const { data } = useUserInterfaceData<Context, Settings>();
|
|
97
|
+
const src = useAssetUrl(data.upload?.DocumentRef);
|
|
98
|
+
if (!src) return null;
|
|
99
|
+
|
|
100
|
+
return (
|
|
101
|
+
<embed
|
|
102
|
+
src={src}
|
|
103
|
+
type="application/pdf"
|
|
104
|
+
style={{ width: '100%', height: '500px', border: 'none' }}
|
|
105
|
+
/>
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
The capability holding the reference must be listed in the UI's `reads`. `useAssetUrl` works on every surface; the `getAssetUrl` callback does the same job outside a component.
|
|
111
|
+
|
|
112
|
+
For the full reference, including engine access via `readAsset`, blob scopes, CLI upload, and supported file types, see [File handling](./file-handling.md).
|
|
113
|
+
|
|
114
|
+
## Reading an asset's contents
|
|
115
|
+
|
|
116
|
+
To render what is in a file rather than link to it, such as a briefing, a JSON table of scenario prose, or a CSV, use `useAsset`. It fetches the asset, reads the body `as` `'json'`, `'text'` or `'blob'`, and returns `{ data, error, loading }`:
|
|
117
|
+
|
|
118
|
+
```tsx
|
|
119
|
+
import { useAsset } from '@seriousgaming/sdk/ui';
|
|
120
|
+
|
|
121
|
+
function Briefing() {
|
|
122
|
+
const { data, error, loading } = useAsset('shared:briefing/briefing.md', { as: 'text' });
|
|
123
|
+
if (loading) return <Spinner />;
|
|
124
|
+
if (error) return <Alert>{error.message}</Alert>;
|
|
125
|
+
return <Markdown>{data}</Markdown>;
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
It prefers a copy in the surface's locale, held in a directory named for the locale just before the file name, and falls back to the reference as given. In `fr-CA`, `shared:briefing/briefing.md` tries `shared:briefing/fr-CA/briefing.md`, then `shared:briefing/fr/briefing.md`, then `shared:briefing/briefing.md` (a locale with a script, such as `zh-Hant-TW`, tries `zh-Hant` before `zh`):
|
|
130
|
+
|
|
131
|
+
```
|
|
132
|
+
shared-assets/
|
|
133
|
+
briefing/
|
|
134
|
+
briefing.md ← the untranslated text, and the fallback
|
|
135
|
+
fr/briefing.md
|
|
136
|
+
ar/briefing.md
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Pass `locale` to look in a different one, or `locale: false` to read the reference alone. A `blob:` reference is always read as given. The hook refetches when the reference or the locale changes, so it follows a mid-session language switch, and an answer to a reference that has since changed is discarded. For JSON, give the type: `useAsset<Briefing>(reference, { as: 'json' })`.
|
|
140
|
+
|
|
141
|
+
## Using LLMs in user interfaces
|
|
142
|
+
|
|
143
|
+
User interfaces cannot call `generateText` (or `extractText` or `generateSpeech`) directly. A UI reaches these services through an [endpoint](./endpoints.md): the endpoint wraps the callback and runs server-side, and the UI invokes it through `callbacks.endpoints['<endpoint-id>']`. This keeps credential-holding calls off the untrusted iframe. To create one, follow [Create an endpoint](../recipes/create-endpoint.md). See [Call an endpoint from a UI](../recipes/call-endpoint-from-ui.md) and the [LLM integration guide](llm-integration.md) for the full pattern.
|
|
144
|
+
|
|
145
|
+
### The endpoint
|
|
146
|
+
|
|
147
|
+
The endpoint bundle declares `"uses": ["generateText"]` and runs the LLM call:
|
|
148
|
+
|
|
149
|
+
```typescript
|
|
150
|
+
// endpoints/chat/logic/logic.ts
|
|
151
|
+
import { getText } from '@seriousgaming/sdk';
|
|
152
|
+
import type { Handler } from '../types';
|
|
153
|
+
|
|
154
|
+
export const Handle: Handler = async ({ request, callbacks }) => {
|
|
155
|
+
const response = await callbacks.generateText({
|
|
156
|
+
messages: request.messages,
|
|
157
|
+
systemPrompt:
|
|
158
|
+
request.systemPrompt ?? 'You are a helpful business advisor. Provide concise guidance.',
|
|
159
|
+
});
|
|
160
|
+
return { reply: getText(response) };
|
|
161
|
+
};
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
The UI bundle declares the endpoint in its `endpoints` array. A UI bundle has no `uses` field, and the build refuses one.
|
|
165
|
+
|
|
166
|
+
```json
|
|
167
|
+
{
|
|
168
|
+
"definition": {
|
|
169
|
+
"endpoints": ["chat"]
|
|
170
|
+
},
|
|
171
|
+
"rootDirectory": ".",
|
|
172
|
+
"ui": { "entrypoint": "index.html" }
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### Calling the endpoint from a component
|
|
177
|
+
|
|
178
|
+
Access `callbacks.endpoints` with the `useUserInterfaceCallbacks` hook. Persist the conversation in a capability so it survives across ticks:
|
|
179
|
+
|
|
180
|
+
```tsx
|
|
181
|
+
import { useState } from 'react';
|
|
182
|
+
import { useUserInterfaceCallbacks, useUserInterfaceData } from '@seriousgaming/sdk/ui';
|
|
183
|
+
import type { Context, Settings } from '../types';
|
|
184
|
+
import type { Callbacks } from '../types';
|
|
185
|
+
|
|
186
|
+
function ChatAssistant() {
|
|
187
|
+
const { data, setData } = useUserInterfaceData<Context, Settings>();
|
|
188
|
+
const callbacks = useUserInterfaceCallbacks() as Callbacks;
|
|
189
|
+
const [isLoading, setIsLoading] = useState(false);
|
|
190
|
+
|
|
191
|
+
const messages = data.chathistory.Messages;
|
|
192
|
+
|
|
193
|
+
const handleSendMessage = async (userMessage: string) => {
|
|
194
|
+
if (!userMessage.trim()) return;
|
|
195
|
+
setIsLoading(true);
|
|
196
|
+
try {
|
|
197
|
+
const newMessages = [...messages, { role: 'user' as const, content: userMessage }];
|
|
198
|
+
const { reply } = await callbacks.endpoints['chat']({
|
|
199
|
+
messages: newMessages,
|
|
200
|
+
});
|
|
201
|
+
await setData({
|
|
202
|
+
chathistory: {
|
|
203
|
+
Messages: [...newMessages, { role: 'assistant' as const, content: reply }],
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
} finally {
|
|
207
|
+
setIsLoading(false);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
return (
|
|
212
|
+
<div>
|
|
213
|
+
{messages.map((msg, idx) => (
|
|
214
|
+
<div key={idx} className={msg.role}>
|
|
215
|
+
{msg.content}
|
|
216
|
+
</div>
|
|
217
|
+
))}
|
|
218
|
+
<input
|
|
219
|
+
type="text"
|
|
220
|
+
placeholder="Type your message..."
|
|
221
|
+
onKeyPress={(e) => {
|
|
222
|
+
if (e.key === 'Enter' && !isLoading) {
|
|
223
|
+
handleSendMessage(e.currentTarget.value);
|
|
224
|
+
e.currentTarget.value = '';
|
|
225
|
+
}
|
|
226
|
+
}}
|
|
227
|
+
disabled={isLoading}
|
|
228
|
+
/>
|
|
229
|
+
{isLoading && <p>Loading...</p>}
|
|
230
|
+
</div>
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### Localising prompts
|
|
236
|
+
|
|
237
|
+
Translate the system prompt in the UI with i18n and pass it to the endpoint in the request. The endpoint forwards it to `generateText`:
|
|
238
|
+
|
|
239
|
+
```tsx
|
|
240
|
+
import { useTranslation } from 'react-i18next';
|
|
241
|
+
|
|
242
|
+
const { t } = useTranslation();
|
|
243
|
+
const { reply } = await callbacks.endpoints['chat']({
|
|
244
|
+
messages: newMessages,
|
|
245
|
+
systemPrompt: t('chatSystemPrompt'),
|
|
246
|
+
});
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
Update `src/i18n.ts`:
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
const resources = {
|
|
253
|
+
en: {
|
|
254
|
+
translation: {
|
|
255
|
+
chatSystemPrompt: 'You are a helpful assistant for a business game.',
|
|
256
|
+
askForAdvice: 'Ask for advice...',
|
|
257
|
+
},
|
|
258
|
+
},
|
|
259
|
+
es: {
|
|
260
|
+
translation: {
|
|
261
|
+
chatSystemPrompt: 'Eres un asistente útil para un juego de simulación empresarial.',
|
|
262
|
+
askForAdvice: 'Pedir consejo...',
|
|
263
|
+
},
|
|
264
|
+
},
|
|
265
|
+
};
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
### Markdown rendering in chat
|
|
269
|
+
|
|
270
|
+
Render markdown replies with `react-markdown`:
|
|
271
|
+
|
|
272
|
+
```typescript
|
|
273
|
+
import { useUserInterfaceCallbacks } from '@seriousgaming/sdk/ui';
|
|
274
|
+
import ReactMarkdown from 'react-markdown';
|
|
275
|
+
import { Box, styled } from '@mui/material';
|
|
276
|
+
|
|
277
|
+
const StyledMarkdown = styled(Box)(({ theme }) => ({
|
|
278
|
+
'& code': {
|
|
279
|
+
backgroundColor: theme.palette.action.hover,
|
|
280
|
+
padding: '2px 6px',
|
|
281
|
+
borderRadius: '4px',
|
|
282
|
+
fontFamily: 'monospace'
|
|
283
|
+
},
|
|
284
|
+
'& pre': {
|
|
285
|
+
backgroundColor: theme.palette.action.hover,
|
|
286
|
+
padding: theme.spacing(1),
|
|
287
|
+
borderRadius: '4px',
|
|
288
|
+
overflow: 'auto'
|
|
289
|
+
}
|
|
290
|
+
}));
|
|
291
|
+
|
|
292
|
+
function ChatMessage({ content }: { content: string }) {
|
|
293
|
+
return (
|
|
294
|
+
<StyledMarkdown>
|
|
295
|
+
<ReactMarkdown>{content}</ReactMarkdown>
|
|
296
|
+
</StyledMarkdown>
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
### Error handling
|
|
302
|
+
|
|
303
|
+
A failed endpoint call rejects with an `EndpointError`, the endpoint counterpart of `MutationError`. `error.kind` (shorthand for `error.outcome.kind`) says why: the [`MutationOutcome` kinds](./ui-ticks.md#awaiting-state-changes), plus `invalid-request` (the request failed `requestSchema` and the handler never ran), `handler-error` (the handler threw or overran its time limit) and `invalid-response` (it returned something its declaration forbids). `error.applied` lists the endpoint's effects that had already landed, and `error.failedStep` names the one that failed, so you can tell a call that changed nothing from one that saved its write and then failed on an action:
|
|
304
|
+
|
|
305
|
+
```typescript
|
|
306
|
+
import { EndpointError } from '@seriousgaming/sdk/ui';
|
|
307
|
+
|
|
308
|
+
try {
|
|
309
|
+
const { reply } = await callbacks.endpoints['chat']({ messages });
|
|
310
|
+
setResponse(reply);
|
|
311
|
+
} catch (error) {
|
|
312
|
+
if (error instanceof EndpointError && error.kind === 'handler-error') {
|
|
313
|
+
setError(t('chatUnavailable'));
|
|
314
|
+
} else {
|
|
315
|
+
setError(error instanceof Error ? error.message : String(error));
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
An empty `applied` means nothing changed. As with a mutation, never retry an endpoint call automatically: a `conflict` means a person may try again. See [Call an endpoint from a UI](../recipes/call-endpoint-from-ui.md#steps) for every kind.
|
|
321
|
+
|
|
322
|
+
### Putting a chat UI together
|
|
323
|
+
|
|
324
|
+
The sections above are the parts of a complete chat surface. Beyond them, a chat that feels finished usually adds:
|
|
325
|
+
|
|
326
|
+
- Message history kept in the component's state, or in a capability when it must survive a reload, and sent with each call
|
|
327
|
+
- A loading state while the call is in flight, with the send button disabled
|
|
328
|
+
- Scrolling to the latest message when one arrives
|