create-marcapony-app 0.3.7 → 0.4.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.
package/README.md CHANGED
@@ -30,6 +30,7 @@ up and build on it.
30
30
  | `booking` | Signed-in customers see, book and cancel their appointments | Customer portal |
31
31
  | `shop` | Products, a cart and a checkout that sends the buyer to pay | Your site |
32
32
  | `team-tool` | Your team approves, rejects and completes the day's reservations | Dashboard |
33
+ | `character` | A character from your business that chats with visitors | Your site |
33
34
 
34
35
  Each template's `README.md` says which placement, data access, scopes and
35
36
  permissions to choose when you create the app under **My Apps** in the
package/dist/index.d.ts CHANGED
@@ -11,6 +11,9 @@ export declare const TEMPLATES: readonly [{
11
11
  }, {
12
12
  readonly name: "team-tool";
13
13
  readonly summary: "Your team approves and updates today's reservations";
14
+ }, {
15
+ readonly name: "character";
16
+ readonly summary: "A character from your business that chats with visitors";
14
17
  }];
15
18
  export type TemplateName = (typeof TEMPLATES)[number]['name'];
16
19
  export declare const DEFAULT_TEMPLATE: TemplateName;
package/dist/index.js CHANGED
@@ -18,6 +18,7 @@ export const TEMPLATES = [
18
18
  { name: 'booking', summary: 'Customers book and cancel appointments in the portal' },
19
19
  { name: 'shop', summary: 'Products, a cart and checkout with a payment link' },
20
20
  { name: 'team-tool', summary: "Your team approves and updates today's reservations" },
21
+ { name: 'character', summary: 'A character from your business that chats with visitors' },
21
22
  ];
22
23
  export const DEFAULT_TEMPLATE = 'blank';
23
24
  const BASE_DIR = 'base';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-marcapony-app",
3
- "version": "0.3.7",
3
+ "version": "0.4.1",
4
4
  "description": "Scaffold a Marcapony app \u2014 a Worker backed by the Marcapony API, ready for `marcapony app link` and `marcapony app deploy`",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE.md",
@@ -14,7 +14,7 @@
14
14
  },
15
15
  "dependencies": {
16
16
  "hono": "^4.13.0",
17
- "marcapony-sdk": "^0.7.0",
17
+ "marcapony-sdk": "^0.9.0",
18
18
  "react": "^19.3.0",
19
19
  "react-dom": "^19.3.0"
20
20
  },
@@ -0,0 +1,78 @@
1
+ # Marcapony app: character
2
+
3
+ A character from your business that chats with visitors: a barista who
4
+ recommends a drink, a guide who answers questions about a tour, a shopkeeper in
5
+ a game. The page shows the character's greeting and starter questions and
6
+ streams its answers as they are written.
7
+
8
+ ## Set up in the dashboard
9
+
10
+ 1. Create the character under **Characters** in the dashboard, switch it on
11
+ for apps and give it a daily budget. A character answers apps only with a
12
+ daily budget, and this app has its own daily budget for characters too.
13
+ 2. Create the app under **My Apps** with:
14
+ - **Placement:** public (`"placement": "public"`)
15
+ - **Data access:** visitor. Characters only read what the business has
16
+ published, so they work with any data access; choose the narrowest.
17
+ - **Scopes:** none to choose. Granting the character to the app (next
18
+ step) adds `personas:chat`.
19
+ - **Permissions:** none
20
+ 3. Grant the character to this app in the character's settings ("Apps that can
21
+ use this character"). That adds the `personas:chat` scope to the app's keys
22
+ and gives the app its `MARCAPONY_APP_SECRET`, which signs the visitor
23
+ cookie.
24
+ 4. Set the character's slug as the environment setting `PERSONA_SLUG`, with
25
+ the Marcapony CLI the project pins (`marcapony app env set PERSONA_SLUG`).
26
+ For `bun run dev`, add `PERSONA_SLUG=<slug>` to `.env.local` as well.
27
+
28
+ Characters in apps need a package that includes them.
29
+
30
+ ## Routes
31
+
32
+ | Route | What it does |
33
+ | ------------------------------------------------- | ---------------------------------------------------- |
34
+ | `GET /api/health` | Answers `{ "ok": true }` |
35
+ | `GET /api/character` | The character: name, description, greeting, starter questions |
36
+ | `POST /api/chat/<slug>/conversations` | Starts a conversation and sets the visitor cookie |
37
+ | `POST /api/chat/<slug>/conversations/:id/messages` | Sends `{ text, history }` and streams the answer |
38
+ | `POST /api/chat/<slug>/conversations/:id/reports` | Reports an answer: `{ messageId, reason }` |
39
+
40
+ The `/api/chat/*` routes are `personasHandler` from `marcapony-sdk`. It gives
41
+ every visitor an anonymous id in the `mp_eu` cookie (HttpOnly, Secure, one
42
+ year), so the per-visitor limits apply, and it stores nothing: the browser
43
+ keeps the conversation's signed history in `sessionStorage` and sends it with
44
+ each message, so a new tab starts a new conversation. When Marcapony no longer
45
+ accepts the saved history, the page starts a new conversation and sends the
46
+ message there.
47
+
48
+ ## What to change first
49
+
50
+ 1. The chat panel in `src/ui/App.tsx`: the character's avatar
51
+ (`avatarUrl`), your styles, and what happens when it is resting.
52
+ 2. Before a public launch, add a bot check: create a Turnstile widget for the
53
+ app's address and set `TURNSTILE_SITE_KEY` (a setting) and
54
+ `TURNSTILE_SECRET_KEY` (`marcapony app env set TURNSTILE_SECRET_KEY --secret`).
55
+ Visitors then pass a check before their first message and after every 10
56
+ messages; the interface already shows the widget when it is asked for.
57
+ 3. Your privacy notice: you are the data controller for your visitors, their
58
+ anonymous ids and everything they type to the character.
59
+
60
+ ## Develop and publish
61
+
62
+ Requires [Bun](https://bun.sh).
63
+
64
+ ```sh
65
+ bun install
66
+ bun run link # paste the connection code from the app's page; writes .env.local and AGENTS.md
67
+ bun run dev # interface and /api routes on your machine
68
+ bun run deploy # build and publish; prints the address
69
+ ```
70
+
71
+ `.env.local` holds the app key. Never commit it, and never send it to the
72
+ browser: the interface calls this app's own `/api` routes, and only those talk
73
+ to Marcapony. Locally there is no `MARCAPONY_APP_SECRET`, so the server signs
74
+ the cookie with a fixed development value; deployed, it refuses to run without
75
+ the real one.
76
+
77
+ While the app is in test mode, the character answers on a cheaper model,
78
+ nothing is charged and the app has 50 test messages a day.
@@ -0,0 +1,16 @@
1
+ {
2
+ "$schema": "./node_modules/marcapony/manifest.schema.json",
3
+ "manifest": 2,
4
+ "build": "bun run build",
5
+ "server": "dist/server/index.js",
6
+ "public": {
7
+ "dir": "dist/client"
8
+ },
9
+ "routes": {
10
+ "server": ["/api/*"],
11
+ "notFound": "spa"
12
+ },
13
+ "runtime": "2026-10",
14
+ "ignore": ["coverage/", "*.log"],
15
+ "placement": "public"
16
+ }
@@ -0,0 +1,72 @@
1
+ import { Hono } from 'hono'
2
+ import { personasHandler } from 'marcapony-sdk'
3
+ import { errorResponse, marcaponyFromEnv, type MarcaponyBindings } from './marcapony'
4
+
5
+ /**
6
+ * A character from the business that chats with visitors. The browser talks
7
+ * to this app's own `/api/chat/*` routes and never sees the app key;
8
+ * `personasHandler` forwards each message to the character and streams the
9
+ * answer back.
10
+ */
11
+ interface Bindings extends MarcaponyBindings {
12
+ /**
13
+ * Signs the visitor cookie. Marcapony sets it once a character is granted
14
+ * to this app, and it stays the same across deploys.
15
+ */
16
+ MARCAPONY_APP_SECRET?: string
17
+ /** The slug of the character to talk to, as an environment setting. */
18
+ PERSONA_SLUG?: string
19
+ /** Optional: your own Turnstile widget, to check visitors before they chat. */
20
+ TURNSTILE_SITE_KEY?: string
21
+ TURNSTILE_SECRET_KEY?: string
22
+ }
23
+
24
+ const app = new Hono<{ Bindings: Bindings }>()
25
+
26
+ /** Locally there is no app secret; a fixed value keeps the cookie working in `bun run dev`. */
27
+ const LOCAL_SECRET = 'local-development-only-not-a-real-app-secret'
28
+
29
+ function appSecret(env: Bindings): string {
30
+ if (env.MARCAPONY_APP_SECRET) return env.MARCAPONY_APP_SECRET
31
+ // The platform sets MARCAPONY_APP_ID on every deploy, so its absence means local dev.
32
+ if (!env.MARCAPONY_APP_ID) return LOCAL_SECRET
33
+ throw new Error(
34
+ 'MARCAPONY_APP_SECRET is missing. Grant a character to this app in the dashboard, then deploy again.',
35
+ )
36
+ }
37
+
38
+ function personaSlug(env: Bindings): string {
39
+ if (!env.PERSONA_SLUG) {
40
+ throw new Error(
41
+ 'PERSONA_SLUG is not set. Set it to the slug of the character this app talks to.',
42
+ )
43
+ }
44
+ return env.PERSONA_SLUG
45
+ }
46
+
47
+ app.get('/api/health', (c) => c.json({ ok: true }))
48
+
49
+ /** The character the interface shows: name, greeting and starter questions. */
50
+ app.get('/api/character', async (c) => {
51
+ const mp = marcaponyFromEnv(c.env)
52
+ return c.json(await mp.personas.get(personaSlug(c.env)))
53
+ })
54
+
55
+ app.all('/api/chat/*', (c) => {
56
+ const turnstile =
57
+ c.env.TURNSTILE_SITE_KEY && c.env.TURNSTILE_SECRET_KEY
58
+ ? { siteKey: c.env.TURNSTILE_SITE_KEY, secretKey: c.env.TURNSTILE_SECRET_KEY }
59
+ : undefined
60
+ const chat = personasHandler(marcaponyFromEnv(c.env), {
61
+ secret: appSecret(c.env),
62
+ basePath: '/api/chat',
63
+ // Only this app's own character can be addressed from the browser.
64
+ personas: [personaSlug(c.env)],
65
+ turnstile,
66
+ })
67
+ return chat(c.req.raw)
68
+ })
69
+
70
+ app.onError((err) => errorResponse(err))
71
+
72
+ export default app
@@ -0,0 +1,361 @@
1
+ import { useEffect, useRef, useState } from 'react'
2
+ import { api, errorMessage } from './api'
3
+
4
+ interface Character {
5
+ slug: string
6
+ name: string
7
+ description: string
8
+ avatarUrl: string | null
9
+ greeting: string
10
+ starterQuestions: string[]
11
+ available: boolean
12
+ }
13
+
14
+ /** A signed entry of the conversation. Kept as it came back and sent back unchanged. */
15
+ interface HistoryEntry {
16
+ role: 'user' | 'assistant'
17
+ text: string
18
+ messageId: string
19
+ signature: string
20
+ }
21
+
22
+ interface Line {
23
+ role: 'user' | 'assistant'
24
+ text: string
25
+ /** The answer's id, for reporting it. */
26
+ messageId?: string
27
+ }
28
+
29
+ interface Saved {
30
+ conversationId: string | null
31
+ history: HistoryEntry[]
32
+ lines: Line[]
33
+ }
34
+
35
+ /** One conversation per browser tab: it ends when the tab is closed. */
36
+ const STORAGE_KEY = 'character-chat'
37
+
38
+ function load(): Saved {
39
+ try {
40
+ const parsed = JSON.parse(sessionStorage.getItem(STORAGE_KEY) ?? 'null') as Saved | null
41
+ if (parsed && Array.isArray(parsed.history) && Array.isArray(parsed.lines)) return parsed
42
+ } catch {
43
+ // A broken entry starts a new conversation.
44
+ }
45
+ return { conversationId: null, history: [], lines: [] }
46
+ }
47
+
48
+ /** What the server answers when it cannot take the message. */
49
+ class ChatError extends Error {
50
+ constructor(
51
+ readonly code: string,
52
+ message: string,
53
+ readonly turnstileSiteKey?: string,
54
+ ) {
55
+ super(message)
56
+ }
57
+ }
58
+
59
+ /**
60
+ * The saved conversation cannot go on (it reached its message limit, or it no
61
+ * longer exists), but a new one works right away.
62
+ */
63
+ const CONVERSATION_ENDED = new Set(['conversation_limit_reached', 'not_found'])
64
+
65
+ /** Shown instead of the raw error when the character cannot answer for now. */
66
+ function friendly(err: unknown): string {
67
+ if (err instanceof ChatError) {
68
+ if (err.code === 'persona_unavailable' || err.code === 'feature_paused') {
69
+ return 'The character is resting right now. Try again later.'
70
+ }
71
+ if (CONVERSATION_ENDED.has(err.code)) {
72
+ return 'This conversation has ended. Your next message starts a new one.'
73
+ }
74
+ if (err.code.endsWith('_cap') || err.code.endsWith('_reached')) {
75
+ return 'The character has talked enough for today. Come back tomorrow.'
76
+ }
77
+ if (err.code === 'rate_limited') return 'Too many messages at once. Wait a moment.'
78
+ }
79
+ return errorMessage(err)
80
+ }
81
+
82
+ declare global {
83
+ interface Window {
84
+ turnstile?: {
85
+ render: (
86
+ element: HTMLElement,
87
+ options: { sitekey: string; callback: (token: string) => void },
88
+ ) => string
89
+ remove: (id: string) => void
90
+ }
91
+ }
92
+ }
93
+
94
+ /** Shows the Turnstile widget and resolves with its token. */
95
+ async function turnstileToken(siteKey: string, element: HTMLElement): Promise<string> {
96
+ if (!window.turnstile) {
97
+ await new Promise<void>((resolve, reject) => {
98
+ const script = document.createElement('script')
99
+ script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'
100
+ script.onload = () => resolve()
101
+ script.onerror = () => reject(new Error('The visitor check could not load'))
102
+ document.head.appendChild(script)
103
+ })
104
+ }
105
+ return new Promise((resolve) => {
106
+ const id = window.turnstile!.render(element, {
107
+ sitekey: siteKey,
108
+ callback: (token) => {
109
+ window.turnstile!.remove(id)
110
+ resolve(token)
111
+ },
112
+ })
113
+ })
114
+ }
115
+
116
+ export function App() {
117
+ const [character, setCharacter] = useState<Character | null>(null)
118
+ const [saved, setSaved] = useState<Saved>(load)
119
+ const [draft, setDraft] = useState('')
120
+ // The answer being written, shown below the finished lines.
121
+ const [partial, setPartial] = useState<string | null>(null)
122
+ const [busy, setBusy] = useState(false)
123
+ const [error, setError] = useState<string | null>(null)
124
+ const [checking, setChecking] = useState(false)
125
+ const widget = useRef<HTMLDivElement>(null)
126
+
127
+ useEffect(() => {
128
+ api<Character>('/api/character')
129
+ .then(setCharacter)
130
+ .catch((err: unknown) => setError(errorMessage(err)))
131
+ }, [])
132
+
133
+ useEffect(() => {
134
+ sessionStorage.setItem(STORAGE_KEY, JSON.stringify(saved))
135
+ }, [saved])
136
+
137
+ const base = character ? `/api/chat/${encodeURIComponent(character.slug)}` : ''
138
+
139
+ /** The saved conversation, or a new one when there is none or `fresh` is set. */
140
+ async function conversationId(fresh = false): Promise<string> {
141
+ if (saved.conversationId && !fresh) return saved.conversationId
142
+ // No locale: the character answers in the account's default language, the
143
+ // same one /api/character shows. A locale the site does not serve is refused.
144
+ const started = await api<{ conversationId: string }>(`${base}/conversations`, { body: {} })
145
+ setSaved((previous) => ({ ...previous, conversationId: started.conversationId }))
146
+ return started.conversationId
147
+ }
148
+
149
+ /** Sends one message and reads the streamed answer. */
150
+ async function stream(
151
+ id: string,
152
+ text: string,
153
+ history: HistoryEntry[],
154
+ token?: string,
155
+ ): Promise<void> {
156
+ const response = await fetch(`${base}/conversations/${id}/messages`, {
157
+ method: 'POST',
158
+ headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream' },
159
+ body: JSON.stringify({ text, history, turnstileToken: token }),
160
+ })
161
+ if (!response.ok || !response.body) {
162
+ const body = (await response.json().catch(() => ({}))) as {
163
+ code?: string
164
+ error?: string
165
+ turnstileSiteKey?: string
166
+ }
167
+ throw new ChatError(
168
+ body.code ?? 'server_error',
169
+ body.error ?? `Request failed with status ${response.status}`,
170
+ body.turnstileSiteKey,
171
+ )
172
+ }
173
+
174
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader()
175
+ let buffer = ''
176
+ let answer = ''
177
+ for (;;) {
178
+ const { done, value } = await reader.read()
179
+ if (done) break
180
+ buffer += value
181
+ const frames = buffer.split('\n\n')
182
+ buffer = frames.pop() ?? ''
183
+ for (const frame of frames) {
184
+ if (!frame.startsWith('data: ')) continue
185
+ const event = JSON.parse(frame.slice('data: '.length)) as Record<string, unknown>
186
+ if (event.type === 'message_start') {
187
+ answer = ''
188
+ setPartial('')
189
+ } else if (event.type === 'text') {
190
+ answer += String(event.content)
191
+ setPartial(answer)
192
+ } else if (event.type === 'retract') {
193
+ // The safety check withdrew what was shown; a replacement follows.
194
+ answer = ''
195
+ setPartial('')
196
+ } else if (event.type === 'error') {
197
+ throw new ChatError(String(event.code), String(event.error))
198
+ } else if (event.type === 'done') {
199
+ const finished = answer
200
+ setSaved((previous) => ({
201
+ ...previous,
202
+ history: event.history as HistoryEntry[],
203
+ lines: [
204
+ ...previous.lines,
205
+ { role: 'assistant', text: finished, messageId: String(event.messageId) },
206
+ ],
207
+ }))
208
+ }
209
+ }
210
+ }
211
+ }
212
+
213
+ async function send(text: string) {
214
+ const trimmed = text.trim()
215
+ if (!trimmed || !character || busy) return
216
+ setBusy(true)
217
+ setError(null)
218
+ setDraft('')
219
+ setSaved((previous) => ({
220
+ ...previous,
221
+ lines: [...previous.lines, { role: 'user', text: trimmed }],
222
+ }))
223
+ /** One message to one conversation, with the visitor check when it is due. */
224
+ async function attempt(id: string, history: HistoryEntry[]): Promise<void> {
225
+ try {
226
+ await stream(id, trimmed, history)
227
+ } catch (err) {
228
+ // A visitor check is due: show the widget, then send once more with its token.
229
+ if (!(err instanceof ChatError && err.code === 'verification_required')) throw err
230
+ if (!err.turnstileSiteKey || !widget.current) throw err
231
+ setChecking(true)
232
+ const token = await turnstileToken(err.turnstileSiteKey, widget.current).finally(() =>
233
+ setChecking(false),
234
+ )
235
+ await stream(id, trimmed, history, token)
236
+ }
237
+ }
238
+
239
+ try {
240
+ try {
241
+ await attempt(await conversationId(), saved.history)
242
+ } catch (err) {
243
+ if (!(err instanceof ChatError && err.code === 'invalid_history')) throw err
244
+ // The saved history no longer fits this conversation (a lost tab, an
245
+ // older page): start a new conversation and send the message there.
246
+ setSaved((previous) => ({ ...previous, conversationId: null, history: [] }))
247
+ await attempt(await conversationId(true), [])
248
+ }
249
+ } catch (err) {
250
+ if (err instanceof ChatError && CONVERSATION_ENDED.has(err.code)) {
251
+ // Forget the ended conversation; the next message starts a new one.
252
+ setSaved((previous) => ({ ...previous, conversationId: null, history: [] }))
253
+ }
254
+ setError(friendly(err))
255
+ } finally {
256
+ setPartial(null)
257
+ setBusy(false)
258
+ }
259
+ }
260
+
261
+ async function report(messageId: string) {
262
+ if (!saved.conversationId) return
263
+ try {
264
+ await api(`${base}/conversations/${saved.conversationId}/reports`, {
265
+ body: { messageId, reason: 'unsafe' },
266
+ })
267
+ setError('Thank you. The message was reported to the business.')
268
+ } catch (err) {
269
+ setError(errorMessage(err))
270
+ }
271
+ }
272
+
273
+ function restart() {
274
+ setSaved({ conversationId: null, history: [], lines: [] })
275
+ setError(null)
276
+ }
277
+
278
+ if (!character) {
279
+ return <main>{error ? <p className="error">{error}</p> : <p>Loading…</p>}</main>
280
+ }
281
+
282
+ return (
283
+ <main>
284
+ <h1>{character.name}</h1>
285
+ {character.description ? <p className="muted">{character.description}</p> : null}
286
+ {!character.available ? (
287
+ <p className="notice">The character is resting right now. Try again later.</p>
288
+ ) : null}
289
+
290
+ <ul className="rows">
291
+ {character.greeting ? (
292
+ <li>
293
+ <span>{character.greeting}</span>
294
+ </li>
295
+ ) : null}
296
+ {saved.lines.map((line, i) => (
297
+ <li key={`${i}-${line.role}`}>
298
+ <span className={line.role === 'user' ? 'muted' : undefined}>
299
+ {line.role === 'user' ? 'You: ' : ''}
300
+ {line.text}
301
+ </span>
302
+ {line.messageId ? (
303
+ <button type="button" onClick={() => void report(line.messageId!)}>
304
+ Report
305
+ </button>
306
+ ) : null}
307
+ </li>
308
+ ))}
309
+ {partial !== null ? (
310
+ <li>
311
+ <span>{partial || '…'}</span>
312
+ </li>
313
+ ) : null}
314
+ </ul>
315
+
316
+ {saved.lines.length === 0 && character.starterQuestions.length > 0 ? (
317
+ <p className="actions">
318
+ {character.starterQuestions.map((question) => (
319
+ <button
320
+ key={question}
321
+ type="button"
322
+ disabled={busy}
323
+ onClick={() => void send(question)}
324
+ >
325
+ {question}
326
+ </button>
327
+ ))}
328
+ </p>
329
+ ) : null}
330
+
331
+ <div ref={widget} />
332
+ {checking ? <p className="muted">One moment: a quick check that you are not a bot.</p> : null}
333
+ {error ? <p className="error">{error}</p> : null}
334
+
335
+ <form
336
+ onSubmit={(event) => {
337
+ event.preventDefault()
338
+ void send(draft)
339
+ }}
340
+ >
341
+ <label>
342
+ Message
343
+ <textarea
344
+ value={draft}
345
+ maxLength={2000}
346
+ rows={3}
347
+ onChange={(event) => setDraft(event.target.value)}
348
+ />
349
+ </label>
350
+ <p className="actions">
351
+ <button type="submit" disabled={busy || !character.available || !draft.trim()}>
352
+ {busy ? 'Writing…' : 'Send'}
353
+ </button>
354
+ <button type="button" disabled={busy} onClick={restart}>
355
+ New conversation
356
+ </button>
357
+ </p>
358
+ </form>
359
+ </main>
360
+ )
361
+ }