@proveanything/smartlinks 2.1.18 → 2.1.19

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 (53) hide show
  1. package/dist/adminViews.d.ts +19 -0
  2. package/dist/adminViews.js +16 -0
  3. package/dist/api/ai.d.ts +15 -5
  4. package/dist/api/ai.js +15 -9
  5. package/dist/api/aiGuide.d.ts +108 -0
  6. package/dist/api/aiGuide.js +161 -0
  7. package/dist/api/appObjects.d.ts +21 -0
  8. package/dist/api/appObjects.js +33 -1
  9. package/dist/api/authKit.d.ts +37 -1
  10. package/dist/api/authKit.js +51 -0
  11. package/dist/docs/API_SUMMARY.md +509 -40
  12. package/dist/docs/admin-lists-and-pickers.md +140 -0
  13. package/dist/docs/admin-views.md +22 -0
  14. package/dist/docs/app-data-storage.md +277 -276
  15. package/dist/docs/auth-kit.md +872 -741
  16. package/dist/docs/comms.md +686 -644
  17. package/dist/docs/customer-guide.md +70 -0
  18. package/dist/docs/headless-providers.md +112 -112
  19. package/dist/docs/server-functions.md +69 -1
  20. package/dist/docs/ui-utils.md +123 -121
  21. package/dist/docs/user-groups.md +175 -168
  22. package/dist/headless.js +38 -2
  23. package/dist/http.js +4 -0
  24. package/dist/index.d.ts +2 -2
  25. package/dist/live.d.ts +80 -0
  26. package/dist/live.js +315 -0
  27. package/dist/openapi.yaml +888 -34
  28. package/dist/testing/index.d.ts +22 -0
  29. package/dist/testing/index.js +31 -0
  30. package/dist/types/appManifest.d.ts +214 -1
  31. package/dist/types/appOptions.d.ts +32 -0
  32. package/dist/types/appOptions.js +3 -0
  33. package/dist/types/authKit.d.ts +193 -4
  34. package/dist/types/comms.d.ts +41 -2
  35. package/dist/types/headless.d.ts +49 -1
  36. package/dist/types/iframeResponder.d.ts +1 -1
  37. package/dist/types/index.d.ts +1 -0
  38. package/dist/types/index.js +1 -0
  39. package/docs/API_SUMMARY.md +509 -40
  40. package/docs/admin-lists-and-pickers.md +140 -0
  41. package/docs/admin-views.md +22 -0
  42. package/docs/app-data-storage.md +277 -276
  43. package/docs/auth-kit.md +872 -741
  44. package/docs/comms.md +686 -644
  45. package/docs/customer-guide.md +70 -0
  46. package/docs/headless-providers.md +112 -112
  47. package/docs/server-functions.md +69 -1
  48. package/docs/ui-utils.md +123 -121
  49. package/docs/user-groups.md +175 -168
  50. package/openapi.yaml +888 -34
  51. package/package.json +1 -1
  52. package/scripts/doctor.mjs +454 -428
  53. package/scripts/lib/keyed-app-data.mjs +21 -0
@@ -0,0 +1,70 @@
1
+ # The customer guide
2
+
3
+ A business's assistant for its visitors, in Portal and the Hub, by voice or by text. It knows the business
4
+ (a brief written for visitors), where the visitor is (the product, the item scanned, the app on screen) and
5
+ what that screen says, and it can open another app for them. The business switches it on and shapes it in
6
+ Studio (Configure → Guide). Design: prove `server/docs/design/customer-assistant.md`.
7
+
8
+ Everything that shapes the guide — its instructions, voice, tools and limits — is fixed by SmartLinks when a
9
+ conversation starts. A page only says where the visitor is and what is on their screen.
10
+
11
+ ---
12
+
13
+ ## For a host (Portal, the Hub, a custom site)
14
+
15
+ ```ts
16
+ import * as SL from '@proveanything/smartlinks'
17
+
18
+ const info = await SL.ai.guide.get(collectionId, 'portal') // { enabled, name, modes, suggestions, handoff }
19
+ if (!info.enabled) return
20
+
21
+ const chat = await SL.ai.guide.start(collectionId, {
22
+ surface: 'portal', // or 'hub'
23
+ mode: info.modes.start, // 'voice' or 'text'
24
+ productId, proofId,
25
+ apps: [{ id: 'recipes', title: 'Recipes' }], // the apps on the visitor's page: their pages come from the deep-link registry
26
+ where: { appId: 'recipes', path: '/method' }, // where the visitor is now
27
+ screen: await SL.ai.content.request({ frame: appIframe.contentWindow }),
28
+ showApp: (appId) => openApp(appId),
29
+ openPage: ({ appId, path, params }) => openApp(appId, path, params), // a page the guide chose (look_in → open_page)
30
+ goTo: (productId) => openProduct(productId), // another product it found (find → go_to)
31
+ onShow: (card) => showFound(card), // what find found, rows with goTo
32
+ offerPerson: (handoff) => showContact(handoff),
33
+ onState: setState, // idle | connecting | listening | hearing | thinking | speaking | paused | error
34
+ onCaption: setCaption, // what it is saying or writing, as it goes
35
+ onError: setError,
36
+ })
37
+
38
+ chat.pause(); chat.resume(); chat.stop()
39
+ chat.send('What is it made of?') // text mode (works in voice mode too)
40
+ chat.note('The visitor is now on Dishwasher DW-60 (product id p9), in Manual at /troubleshooting.') // where they are; it doesn't answer
41
+ ```
42
+
43
+ The guide knows the pages around the visitor from SmartLinks' deep-link registry (`linkable` in each app's
44
+ manifest, and each app's config `linkable` per collection and per product; see deep-link-discovery.md).
45
+ Register your pages there and the guide can open them by name.
46
+
47
+ - Voice needs the microphone; ask for it on a tap (browsers require it).
48
+ - A signed-in visitor (Auth Kit bearer on the SDK) owns their conversation; otherwise it is anonymous.
49
+ - The guide's `read_screen` tool asks the app on screen what it shows (below). Pass `readScreen` to answer
50
+ it yourself.
51
+ - Limits per visitor and per business are set in Studio; a refusal comes back as `GUIDE_LIMIT` (429).
52
+
53
+ ## For an app: say what your screen shows
54
+
55
+ ```ts
56
+ useEffect(() => SL.ai.content.provide(() => ({
57
+ appId: 'pages',
58
+ title: page.title,
59
+ content: page.text, // plain words: the exhibit, the recipe, what this form is for
60
+ })), [page])
61
+ ```
62
+
63
+ `provide` works the same in an iframe (the host asks by message) and as a direct component. Return what a
64
+ person reading the screen would take in, not markup. Without it, a host may fall back to the page's text.
65
+
66
+ ## Your own live conversation
67
+
68
+ `SL.ai.live.start({ endpoints: { mint, tool, event }, mode, screenTools, … })` is the client the guide and the
69
+ Studio assistant use: WebRTC straight to the realtime service with a key your server minted, tools split
70
+ between the page (`screenTools`) and your server (`endpoints.tool`). See `src/live.ts`.
@@ -1,112 +1,112 @@
1
- # Headless providers: declaring an app's content for other sites
2
-
3
- A **headless provider** is an app whose content other sites and apps may use: an FAQ app, a media gallery, content pages, a blog. The site renders the content its own way. The business keeps editing it in the provider's own admin, inside SmartLinks. A site never builds an editor for provider content.
4
-
5
- To become a provider, an app declares two blocks in `app.manifest.json`:
6
- - **`data`**: its data types, meaning how each is stored, its fields, examples and read recipes;
7
- - **`headless`**: the opt-in, meaning its purpose, categories, which types a site renders, where the owner edits it, and rendering guidance.
8
-
9
- Site builders (the Forge agent included) read these declarations to decide "install the FAQ app and use its content" instead of inventing their own.
10
-
11
- ## The `data` block
12
-
13
- ```jsonc
14
- "data": {
15
- "schemaVersion": "1.0.0", // semver of THIS contract; a major = a breaking change
16
- "types": {
17
- "<app>.<thing>": { // lowercase, dot-separated, e.g. "faq.item"
18
- "description": "What one item is, in a sentence.",
19
- "storage": { "kind": "record", "recordType": "<the recordType the app writes>" },
20
- "visibility": "public", // the visibility items normally have: public | owner | admin
21
- "anchors": ["product"], // optional: what items can be attached to
22
- "fields": {
23
- "<key>": {
24
- "type": "string", // see field types
25
- "label": "Question",
26
- "required": true,
27
- "localized": true, // translated per language (text types only)
28
- "public": true, // readable by anonymous visitors
29
- "zone": "data" // data (default) | owner | admin
30
- }
31
- },
32
- "listing": { "sort": ["order"], "filters": ["category"] },
33
- "examples": [ { "<key>": "realistic value" } ],
34
- "read": { // optional: defaults to the standard calls for the storage
35
- "list": "SL.app.records.list(collectionId, appId, { recordType: '...', limit: 50 })",
36
- "get": "SL.app.records.get(collectionId, appId, recordId)",
37
- "notes": "anything a site must know, e.g. 'sort by order, then title'"
38
- }
39
- }
40
- }
41
- }
42
- ```
43
-
44
- **Storage kinds:**
45
-
46
- | `storage.kind` | The app keeps items in | Read with |
47
- |---|---|---|
48
- | `record` (+ `recordType`) | App records: the usual home for content | `SL.app.records.list / get`, filtered by `recordType` |
49
- | `case` | App cases: requests that get resolved | `SL.app.cases.list / get` |
50
- | `thread` | App threads: discussions, Q&A, reviews | `SL.app.threads.list / get` |
51
- | `config` (+ optional `key`) | App configuration: settings, small fixed lists | `SL.appConfiguration.getConfig({ collectionId, appId })` |
52
-
53
- **What the read calls return.** This is fixed by the storage kind, so a provider never needs to describe it, and site builders get it from the checker and `forge-cms describe`:
54
-
55
- - **`record`, `case`, `thread`:** `list` returns `{ data: Item[], pagination: { total, limit, offset, hasMore } }`.
56
- - The items are in **`response.data`**, never `response.items` or `response.records`.
57
- - Each item's declared fields are in **`item.data`** (e.g. `record.data.question`). `id`, `status`, `productId` and the dates are top-level.
58
- - Page with `offset` / `limit` while `pagination.hasMore`. `get` returns one item.
59
- - **`config`:** the configuration object. Items are in `config.<key>` when the type names a `key`.
60
-
61
- Products, contacts and proofs are platform data. Reference them with `ref` fields (`"to": "product"`); never redeclare them.
62
-
63
- **Field types:** `string`, `text`, `richtext` (HTML), `markdown`, `number`, `boolean`, `date` (YYYY-MM-DD), `datetime`, `enum` (+ `options`), `url`, `image` and `file` (a URL or `{ url, ... }`), `ref` and `ref[]` (+ `to`: a declared type id, or `product` / `contact` / `proof`), `string[]`, `json` (avoid where a typed field fits).
64
-
65
- **Zones and what's public.** App records, cases and threads have three JSONB zones: `data`, `owner` and `admin`. Only `data` can be public, and only when the item's visibility is `public`. Mark each field a visitor may read with `"public": true`. Internal fields (notes, moderation flags) are `zone: "admin"` and never public.
66
-
67
- **Examples** are the item's `data` JSON exactly as the app writes it, with realistic content, not lorem ipsum.
68
-
69
- ## The `headless` block
70
-
71
- ```jsonc
72
- "headless": {
73
- "purpose": "What content this holds and when a site should use it instead of building its own.",
74
- "categories": ["faq"], // faq | media | pages | articles | catalog | events | locations
75
- // | people | reviews | documents | forms | other
76
- "primaryTypes": ["faq.item"], // the types a site renders; others are supporting (e.g. categories)
77
- "editedIn": { "label": "FAQ → Questions", "adminPath": "#/questions" },
78
- "render": {
79
- "guidance": "Group by category; questions expand to show answers.",
80
- "seo": ["faqPage"] // SL.seo.schema helpers a site should use
81
- }
82
- }
83
- ```
84
-
85
- A primary type must be readable by visitors: public visibility, at least one public field, and at least one example.
86
-
87
- ## Checking a declaration
88
-
89
- - **In Forge:** `forge-headless check` validates it against the app's real public data on its test collection. `forge-headless register` validates it and records it in Forge, which makes the app a provider that site builds can find.
90
- - **Anywhere else:**
91
- - `npx smartlinks-headless [appDir] [--collection <id> --app <appId>]`;
92
- - or `SL.headless.validate(manifest, { samples })` in code.
93
-
94
- Errors block. Warnings are worth fixing, and the most useful one is *real data has "x" but it isn't declared*.
95
-
96
- ## Adding a headless mode to an existing app (procedure)
97
-
98
- 1. **Find what the app stores.** Search the source for its writes and reads:
99
- - `SL.app.records.create / upsert / bulkUpsert` (note each `recordType`);
100
- - `SL.app.cases`, `SL.app.threads`;
101
- - `appConfiguration.setConfig` / data items.
102
-
103
- Each distinct `recordType` (or config key) the business edits is a candidate type.
104
- 2. **Find the fields.** Read the admin forms and the TypeScript types for what each item holds. Note which zone each field is written to.
105
- 3. **Decide what's public.** Content a visitor sees is public. Notes, flags and anything personal are not, and move to `zone: "admin"` if the app keeps them in `data`.
106
- 4. **Write the `data` block:** a type per content thing, its storage, fields, listing, and one or two realistic examples taken from the app's real data.
107
- 5. **Write the `headless` block:** purpose, categories, primary types, where it's edited (the admin screen's name and route), and render and SEO guidance.
108
- 6. **Check against real data** (`forge-headless check`). Declare any real fields you missed, or confirm they're internal.
109
- 7. **Register** (`forge-headless register`) once it's valid.
110
- 8. **Keep the data contract stable.** Adding fields or types is a minor bump of `schemaVersion`; renaming or removing them is a major one.
111
-
112
- Don't change how the app stores data just to declare it. The declaration describes what already exists. If something must change (say, an internal field sitting in the public `data` zone), make that a separate, deliberate change.
1
+ # Headless providers: declaring an app's content for other sites
2
+
3
+ A **headless provider** is an app whose content other sites and apps may use: an FAQ app, a media gallery, content pages, a blog. The site renders the content its own way. The business keeps editing it in the provider's own admin, inside SmartLinks. A site never builds an editor for provider content.
4
+
5
+ To become a provider, an app declares two blocks in `app.manifest.json`:
6
+ - **`data`**: its data types, meaning how each is stored, its fields, examples and read recipes;
7
+ - **`headless`**: the opt-in, meaning its purpose, categories, which types a site renders, where the owner edits it, and rendering guidance.
8
+
9
+ Site builders (the Forge agent included) read these declarations to decide "install the FAQ app and use its content" instead of inventing their own.
10
+
11
+ ## The `data` block
12
+
13
+ ```jsonc
14
+ "data": {
15
+ "schemaVersion": "1.0.0", // semver of THIS contract; a major = a breaking change
16
+ "types": {
17
+ "<app>.<thing>": { // lowercase, dot-separated, e.g. "faq.item"
18
+ "description": "What one item is, in a sentence.",
19
+ "storage": { "kind": "record", "recordType": "<the recordType the app writes>" },
20
+ "visibility": "public", // the visibility items normally have: public | owner | admin
21
+ "anchors": ["product"], // optional: what items can be attached to
22
+ "fields": {
23
+ "<key>": {
24
+ "type": "string", // see field types
25
+ "label": "Question",
26
+ "required": true,
27
+ "localized": true, // translated per language (text types only)
28
+ "public": true, // readable by anonymous visitors
29
+ "zone": "data" // data (default) | owner | admin
30
+ }
31
+ },
32
+ "listing": { "sort": ["order"], "filters": ["category"] },
33
+ "examples": [ { "<key>": "realistic value" } ],
34
+ "read": { // optional: defaults to the standard calls for the storage
35
+ "list": "SL.app.records.list(collectionId, appId, { recordType: '...', limit: 50 })",
36
+ "get": "SL.app.records.get(collectionId, appId, recordId)",
37
+ "notes": "anything a site must know, e.g. 'sort by order, then title'"
38
+ }
39
+ }
40
+ }
41
+ }
42
+ ```
43
+
44
+ **Storage kinds:**
45
+
46
+ | `storage.kind` | The app keeps items in | Read with |
47
+ |---|---|---|
48
+ | `record` (+ `recordType`) | App records: the usual home for content | `SL.app.records.list / get`, filtered by `recordType` |
49
+ | `case` | App cases: requests that get resolved | `SL.app.cases.list / get` |
50
+ | `thread` | App threads: discussions, Q&A, reviews | `SL.app.threads.list / get` |
51
+ | `config` (+ optional `key`) | App configuration: settings, small fixed lists | `SL.appConfiguration.getConfig({ collectionId, appId })` |
52
+
53
+ **What the read calls return.** This is fixed by the storage kind, so a provider never needs to describe it, and site builders get it from the checker and `forge-cms describe`:
54
+
55
+ - **`record`, `case`, `thread`:** `list` returns `{ data: Item[], pagination: { total, limit, offset, hasMore } }`.
56
+ - The items are in **`response.data`**, never `response.items` or `response.records`.
57
+ - Each item's declared fields are in **`item.data`** (e.g. `record.data.question`). `id`, `status`, `productId` and the dates are top-level.
58
+ - Page with `offset` / `limit` while `pagination.hasMore`. `get` returns one item.
59
+ - **`config`:** the configuration object. Items are in `config.<key>` when the type names a `key`.
60
+
61
+ Products, contacts and proofs are platform data. Reference them with `ref` fields (`"to": "product"`); never redeclare them.
62
+
63
+ **Field types:** `string`, `text`, `richtext` (HTML), `markdown`, `number`, `boolean`, `date` (YYYY-MM-DD), `datetime`, `enum` (+ `options` fixed by the app, or `list`: a value list the admin edits, see admin-lists-and-pickers.md), `url`, `image` and `file` (a URL or `{ url, ... }`), `ref` and `ref[]` (+ `to`: a declared type id, or `product` / `contact` / `proof`), `string[]`, `json` (avoid where a typed field fits).
64
+
65
+ **Zones and what's public.** App records, cases and threads have three JSONB zones: `data`, `owner` and `admin`. Only `data` can be public, and only when the item's visibility is `public`. Mark each field a visitor may read with `"public": true`. Internal fields (notes, moderation flags) are `zone: "admin"` and never public.
66
+
67
+ **Examples** are the item's `data` JSON exactly as the app writes it, with realistic content, not lorem ipsum.
68
+
69
+ ## The `headless` block
70
+
71
+ ```jsonc
72
+ "headless": {
73
+ "purpose": "What content this holds and when a site should use it instead of building its own.",
74
+ "categories": ["faq"], // faq | media | pages | articles | catalog | events | locations
75
+ // | people | reviews | documents | forms | other
76
+ "primaryTypes": ["faq.item"], // the types a site renders; others are supporting (e.g. categories)
77
+ "editedIn": { "label": "FAQ → Questions", "adminPath": "#/questions" },
78
+ "render": {
79
+ "guidance": "Group by category; questions expand to show answers.",
80
+ "seo": ["faqPage"] // SL.seo.schema helpers a site should use
81
+ }
82
+ }
83
+ ```
84
+
85
+ A primary type must be readable by visitors: public visibility, at least one public field, and at least one example.
86
+
87
+ ## Checking a declaration
88
+
89
+ - **In Forge:** `forge-headless check` validates it against the app's real public data on its test collection. `forge-headless register` validates it and records it in Forge, which makes the app a provider that site builds can find.
90
+ - **Anywhere else:**
91
+ - `npx smartlinks-headless [appDir] [--collection <id> --app <appId>]`;
92
+ - or `SL.headless.validate(manifest, { samples })` in code.
93
+
94
+ Errors block. Warnings are worth fixing, and the most useful one is *real data has "x" but it isn't declared*.
95
+
96
+ ## Adding a headless mode to an existing app (procedure)
97
+
98
+ 1. **Find what the app stores.** Search the source for its writes and reads:
99
+ - `SL.app.records.create / upsert / bulkUpsert` (note each `recordType`);
100
+ - `SL.app.cases`, `SL.app.threads`;
101
+ - `appConfiguration.setConfig` / data items.
102
+
103
+ Each distinct `recordType` (or config key) the business edits is a candidate type.
104
+ 2. **Find the fields.** Read the admin forms and the TypeScript types for what each item holds. Note which zone each field is written to.
105
+ 3. **Decide what's public.** Content a visitor sees is public. Notes, flags and anything personal are not, and move to `zone: "admin"` if the app keeps them in `data`.
106
+ 4. **Write the `data` block:** a type per content thing, its storage, fields, listing, and one or two realistic examples taken from the app's real data.
107
+ 5. **Write the `headless` block:** purpose, categories, primary types, where it's edited (the admin screen's name and route), and render and SEO guidance.
108
+ 6. **Check against real data** (`forge-headless check`). Declare any real fields you missed, or confirm they're internal.
109
+ 7. **Register** (`forge-headless register`) once it's valid.
110
+ 8. **Keep the data contract stable.** Adding fields or types is a minor bump of `schemaVersion`; renaming or removing them is a major one.
111
+
112
+ Don't change how the app stores data just to declare it. The declaration describes what already exists. If something must change (say, an internal field sitting in the public `data` zone), make that a separate, deliberate change.
@@ -539,6 +539,7 @@ Prefer the platform primitives above over a dependency; when you do need one, pi
539
539
  | Check a tapped tag is real | `ctx.sl.tags.resolve(proofId)` → `{ id, claimSetId, code }` or `null` | `sl:tags:read` |
540
540
  | Put a visitor's details on a contact | `ctx.sl.contacts.upsert({ email, firstName, … })` → `{ contactId, created }` (fills empty fields only) | `sl:contacts:write` |
541
541
  | Record "they did X" | `ctx.sl.interactions.record({ interactionId, contactId, outcome, metadata })` | `sl:interactions:write` |
542
+ | Message one person: a confirmation, a reminder, a cancellation, an update | `ctx.sl.messages.send({ to: 'caller' \| contactId, templateId \| message: { subject, body }, about: { type, id, view?, params? } })` → `{ ok, channel }` or `{ ok: false, reason }` — their preferred channel, their opt-outs respected, logged with your app and what it's about; see [comms.md](comms.md#messaging-one-person-from-an-app) | `sl:messages:write` |
542
543
  | Land a loyalty / CRM provider's view of a person (member id, tier, points, tags, external ids) | `ctx.sl.members.apply({ identity, contact?, loyalty?, tags?, externalIds? }, { provider })` → `{ contactId, op }` — matches by id, external id, email or phone; profile fields fill-empty only; see [connectors.md](connectors.md#loyalty-and-crm-connectors) | `sl:members:write` |
543
544
  | Invoke a connector's action — redeem, enrol, issue a coupon, raise a ticket — with the connector's credentials | `ctx.sl.connectors.call('acme-loyalty', 'redeem', { rewardId })` → the action's result; `ctx.sl.connectors.actions(appId)` lists them; see [connectors.md](connectors.md#actions-provider-operations-on-demand) | `sl:connectors:write` |
544
545
  | Ask "is this person gold or above?" without holding their member record | `ctx.sl.entitlements.check('tier>=gold')` → `{ allowed, basis, asOf, attributes }` for the signed-in caller (or `{ identity, token, fallback }`); see [entitlements.md](entitlements.md) | `sl:entitlements:read` |
@@ -768,7 +769,7 @@ overlaps, idempotency, holds): `ctx.memory.bookings`.
768
769
  model, no agent loop. Declare each tool as a capability: `tools:pdf.create`, or `tools:pdf.*` for the
769
770
  whole family. Open to functions: `pdf.create`, `pdf.merge`, `pdf.fill`, `pdf.inspect`, `pdf.render`,
770
771
  `pdf.decodeBarcodes`, `pdf.inspectGraphics`, `pdf.preflight`, `pdf.printReady`, `pdf.edit`,
771
- `image.transform` (arguments as in [ai.md](ai.md)).
772
+ `image.transform`, `image.ocr`, and `pdf.extract` (a PDF + a JSON schema → its fields; it calls a model, so it is refused when the collection's AI budget is used up) (arguments as in [ai.md](ai.md)). A site's server code may use them too.
772
773
 
773
774
  - **Identity:** the call runs as the function's collection, whatever the caller. An anonymous caller
774
775
  holding only your own key gets the same result; the work is attributed and billed to the collection.
@@ -812,6 +813,73 @@ export async function printLabel(ctx, event) {
812
813
  - **Verify:** `pdf.decodeBarcodes` on a `signedUrl` reads the codes back deterministically, so you can
813
814
  confirm the digits before answering.
814
815
 
816
+ ## Files — `ctx.sl.assets`
817
+
818
+ The collection's assets are its lasting files: a record per file, kept as long as the asset is. Server
819
+ code reads them (a PDF to parse, a photo to check) and saves what it makes (a job sheet, a label, a
820
+ report) as assets of its own app. Declare `sl:assets:read` or `sl:assets:write`, with **collection
821
+ authority** (an asset belongs to the collection, not to a visitor).
822
+
823
+ ```ts
824
+ // capabilities: ["sl:assets:write", "tools:pdf.create"], authority: "collection"
825
+ const pdf = await ctx.sl.tools.run('pdf.create', { format: 'A4', html, return: 'base64' })
826
+ const sheet = await ctx.sl.assets.create({
827
+ name: `Job ${job.ref}.pdf`, contentType: 'application/pdf', base64: pdf.base64,
828
+ labels: ['job-sheet'], metadata: { workOrderId: job.id },
829
+ })
830
+ // later: the bytes back
831
+ const { base64, contentType } = await ctx.sl.assets.read(sheet.id)
832
+ ```
833
+
834
+ - **Reads see every asset** in the collection: `get`, `list({ productId?, proofId?, appId?, labels? })`,
835
+ `read(id)` (base64, or `{ as: 'text' }`).
836
+ - **Writes act on this app's own assets only.** `create` stamps the asset with your app;
837
+ `replace(id, file)` keeps the old file as a version (same id, same `assetUrl`); `update(id, { name,
838
+ labels, metadata })`; `remove(id)`. Changing another app's asset is refused (`NOT_YOURS`).
839
+ - **Size.** `read`, `create` and `replace` carry the file as base64, so up to **7 MB**. Bigger files go
840
+ straight to storage, never through SmartLinks:
841
+
842
+ ```ts
843
+ // capabilities add: "network:storage.googleapis.com"
844
+ const { uploadId, sessionUrl } = await ctx.sl.assets.startUpload({ name: 'line-3.mp4', contentType: 'video/mp4' })
845
+ await ctx.fetch(sessionUrl, { method: 'PUT', body: bytes }) // one request, or chunks with Content-Range
846
+ const video = await ctx.sl.assets.finishUpload(uploadId)
847
+ ```
848
+
849
+ To read a large file, fetch its `url` (declare the CDN host, `network:cdn.smartlinks.app`).
850
+ - **Who can open the file.** An asset's file is served from the CDN under an unguessable address, as
851
+ every asset is. Keep the address to the people who should have it.
852
+
853
+ ## AI — `ctx.sl.ai`
854
+
855
+ `ctx.sl.ai.generate({ prompt, system?, files?, schema?, quality? })` asks a model. `files` are PDFs,
856
+ photos or text (`{ assetId }`, `{ base64, contentType }` or `{ text }`); with a `schema` (JSON
857
+ Schema) the answer is parsed into `data`. Declare `sl:ai:write`; any authority may use it.
858
+
859
+ ```ts
860
+ // capabilities: ["sl:ai:write", "sl:assets:read"], authority: "collection"
861
+ const { data } = await ctx.sl.ai.generate({
862
+ prompt: 'Read this sales order.',
863
+ files: [{ assetId }],
864
+ schema: { type: 'object', properties: { salesOrderNumber: { type: 'string' }, lines: { type: 'array', items: { type: 'object', properties: { code: { type: 'string' }, qty: { type: 'number' } } } } } },
865
+ })
866
+ ```
867
+
868
+ - **Budget, enforced.** Every call is recorded and priced against the collection and your app. When the
869
+ collection's monthly AI budget or credits are used up, the call throws `AI_BUDGET_EXCEEDED` /
870
+ `AI_CREDITS_EXHAUSTED` (402) before anything is spent. Catch it and tell the person plainly.
871
+ - **Quality.** `'fast'` (the default) is quick and cheap; `'best'` thinks harder and costs more.
872
+ - **Limits.** Up to 10 files and 7 MB in all; 5 calls a second per collection (bursts wait).
873
+ - **Failure.** `AI_BAD_JSON` (502) when the answer wasn't JSON of the shape asked for: try again, or ask
874
+ for less at once.
875
+
876
+ ### Uploaded files on a site
877
+
878
+ In a site's own functions, a file posted to the function arrives intact: `event.rawBytes` holds the
879
+ exact bytes of any request, and a multipart form's files are in `event.files` as
880
+ `[{ field, filename, contentType, size, base64 }]` (its text fields in `event.body`). `base64` goes
881
+ straight into `ctx.sl.assets.create` or `ctx.sl.ai.generate`.
882
+
815
883
  ### Making an email attachment
816
884
 
817
885
  A flow step can attach a file your function makes: `"attach": [{ "function": "receiptPdf" }]` in a