@softr/sdk 0.0.89-alpha.4 → 0.0.90-ai.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/action.d.ts +34 -1
- package/dist/action.js +12 -1
- package/dist/auth/platform.js +1 -1
- package/dist/core/ai.d.ts +79 -0
- package/dist/core/ai.js +64 -0
- package/dist/core/file-upload.js +3 -2
- package/dist/core/workflow.js +5 -4
- package/dist/datasource/record.js +1 -1
- package/dist/fetch.js +63 -1
- package/dist/formatting.d.ts +3 -3
- package/dist/index.d.ts +3 -4
- package/dist/index.js +2 -4
- package/dist/locale-settings.js +1 -1
- package/dist/mcp.js +4 -8
- package/dist/package.js +1 -1
- package/dist/pwa.d.ts +2 -2
- package/dist/pwa.js +2 -2
- package/dist/server.d.ts +2 -1
- package/dist/server.js +2 -1
- package/package.json +1 -1
- package/skills/softr-sdk/SKILL.md +13 -8
- package/skills/softr-sdk/ai/SKILL.md +168 -0
- package/skills/softr-sdk/auth/SKILL.md +1 -1
- package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
- package/skills/softr-sdk/current-user/SKILL.md +1 -1
- package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
- package/skills/softr-sdk/formatting/SKILL.md +1 -1
- package/skills/softr-sdk/integrations/SKILL.md +8 -4
- package/skills/softr-sdk/mcp/SKILL.md +1 -1
- package/skills/softr-sdk/pwa/SKILL.md +1 -1
- package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
- package/skills/softr-sdk/record-queries/SKILL.md +1 -1
- package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
- package/skills/softr-sdk/routes-and-visibility/SKILL.md +1 -1
- package/skills/softr-sdk/workflows/SKILL.md +1 -1
- package/dist/agent/agent-fns.d.ts +0 -30
- package/dist/agent/agent-fns.js +0 -215
- package/dist/agent/use-agent-chat.d.ts +0 -106
- package/dist/agent/use-agent-chat.js +0 -486
- package/skills/softr-sdk/agent-chat/SKILL.md +0 -124
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: ai
|
|
3
|
+
description: >-
|
|
4
|
+
Run an AI model from the app on Softr's own keys, billed to the workspace's
|
|
5
|
+
AI credits, with nothing to connect: defineAiAction from @softr/sdk declares
|
|
6
|
+
the action with the catalog model it runs on and its permissions;
|
|
7
|
+
ai.generate from @softr/sdk/server runs it with a system text, a prompt, an
|
|
8
|
+
optional JSON schema for an answer that is data, and optional files;
|
|
9
|
+
ai.stream runs it for an answer the user watches being written. Load this
|
|
10
|
+
for a summary, an extraction, a classification, a draft, or a chat the app
|
|
11
|
+
asks a model for, before you decide whether a feature runs on Softr AI
|
|
12
|
+
or on the user's own account, and before you change the model it runs on.
|
|
13
|
+
metadata:
|
|
14
|
+
type: sub-skill
|
|
15
|
+
library: softr-sdk
|
|
16
|
+
library_version: 0.0.79-alpha.0
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
**Boundary.** `ai` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineAiAction` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
20
|
+
|
|
21
|
+
# AI
|
|
22
|
+
|
|
23
|
+
An app asks a model through an AI action. Softr runs the call on its own provider keys and bills the workspace's AI credits, so there is no key to ask the user for and nothing to connect. This is the default for every AI feature of the app's own — a summary of a record, fields extracted from a document, a classification, a draft, a chat. The other path is the user's own provider account, through a connected integration: the `integrations` sub-skill. An app can hold both: each feature carries its own choice in its code.
|
|
24
|
+
|
|
25
|
+
## Decide who runs it first
|
|
26
|
+
|
|
27
|
+
Never choose silently between Softr AI and the user's own account. Decide for each AI feature, before you write its code, in this order:
|
|
28
|
+
|
|
29
|
+
1. The user said who runs it: follow it. "My OpenAI key" or "our Anthropic account", with exactly one integration of that type in `integration_list`: use that one, without asking. A new key of a provider they named — they asked for a new one, or the workspace holds none of that type — is one `requestinput` of type `integration` for that type: its card connects one. A connected key runs the feature; a skipped request means Softr AI, and you say so. Several keys of that type, or "my own key" with no provider: ask (step 4). A provider or a model named without "my" or "our" ("use Claude", "summarise with GPT") is a model preference on Softr AI, not a reason to ask.
|
|
30
|
+
2. The app already has AI features: follow the choice they made, and say so in one line.
|
|
31
|
+
3. `integration_list` shows no `OPEN_AI`, `ANTHROPIC_AI` or `GEMINI_AI` integration: use Softr AI, and say so in one line. Call the tool; do not assume the answer.
|
|
32
|
+
4. Otherwise ask with one `requestinput` of type `aiProvider`. Its card lists every key the workspace holds and every provider to connect, unfiltered. The answer is Softr AI, or the integration with its id and type: follow it, even when it is another provider than the one the user named. A declined request means Softr AI: use it, and say so in one line.
|
|
33
|
+
|
|
34
|
+
Never ask who runs a feature, or which key, with the `question` tool: its free-text answer invites the user to type a key into the chat.
|
|
35
|
+
|
|
36
|
+
Ask at most once per turn. A turn that builds several AI features sends one request, and its `feature` names every one of them in the user's words: "Deal summary and lead tagging". It holds the names only, never the provider, the key or how the feature runs, because the card asks exactly that: "Product chat", not "Product chat, using an OpenAI key".
|
|
37
|
+
|
|
38
|
+
An own-account answer leaves this skill: the call goes through `defineIntegration`, as the `integrations` sub-skill describes.
|
|
39
|
+
|
|
40
|
+
## Choose the model
|
|
41
|
+
|
|
42
|
+
The model is chosen when the app is built and frozen in its code. Before you declare an action, read Softr's catalog with the `ai_list_models` tool: the most recent models of each provider. Each entry carries the `id` the action names, the `provider`, `bestFor`, what to pick it for, `reads`, what it reads beside text, and `reasoning`, whether it thinks before it answers. (`providerModelId` is for the own-account path of the `integrations` sub-skill, never for `defineAiAction`.)
|
|
43
|
+
|
|
44
|
+
- by default — a chat, an assistant, a summary, a briefing, a draft: a mid-tier model, `anthropic`'s newest one between its cheapest and strongest. When the user named another provider, that provider's mid-tier model;
|
|
45
|
+
- an extraction or a classification: the cheapest model whose `reads` covers what it is given — an image or a PDF needs `IMAGE`;
|
|
46
|
+
- the strongest model listed only when the user asks for more quality.
|
|
47
|
+
|
|
48
|
+
Copy the `id` exactly from the tool's answer. An id outside the catalog is refused when the action is saved, and a model spelled from memory, or taken from an example, never is in it.
|
|
49
|
+
|
|
50
|
+
## Changing it later
|
|
51
|
+
|
|
52
|
+
A model change asked in chat ("use a cheaper model", "try Gemini") edits the `model` of the feature's action, or, on the user's own account, the `providerModelId` its call sends. Read `ai_list_models` again and copy the new id. It never sends an `aiProvider` request. On the user's own account the new model is one of that account's provider: a model of another provider, or a switch to the user's own key, changes who runs it, so follow step 1 of the order above.
|
|
53
|
+
|
|
54
|
+
## Say it
|
|
55
|
+
|
|
56
|
+
The plan and the closing message give one line per AI feature built or changed: who runs it, its model, what it bills — Softr AI uses the workspace's AI credits, the user's own key is billed by its provider — and that the user can ask to switch the model or to use their own OpenAI, Anthropic or Gemini key. For example: "Deal summary runs on Softr AI with <the model> and uses your workspace's AI credits. Ask me to switch the model or to use your own OpenAI, Anthropic or Gemini key."
|
|
57
|
+
|
|
58
|
+
## Declare the action
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
const summarizeDeal = defineAiAction({
|
|
62
|
+
id: 'summarizeDeal',
|
|
63
|
+
model: '<an id from ai_list_models>',
|
|
64
|
+
permissions: { userGroupTypes: ['LOGGED_IN_USERS'] },
|
|
65
|
+
})
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Write the object inline in `defineAiAction`. Passing it through a variable widens the types.
|
|
69
|
+
|
|
70
|
+
**Every call spends the workspace's credits.** Keep the audience to `['LOGGED_IN_USERS']`, narrowed with `customGroups` where the feature is for some users only. Open an AI action to visitors only when a public page really needs it, and say so to the user: anyone on the internet can then bill the workspace.
|
|
71
|
+
|
|
72
|
+
Declare one action per feature — the summary and the extraction are two actions, each with its own `id`, its own model and its own audience.
|
|
73
|
+
|
|
74
|
+
## Core pattern: an answer the server reads
|
|
75
|
+
|
|
76
|
+
`ai.generate(action, init)` runs the action and answers when the model is done. `init` takes:
|
|
77
|
+
|
|
78
|
+
- `prompt` — what the model is asked, with the facts it is given. Required.
|
|
79
|
+
- `system` — what the model is and the rules it answers under.
|
|
80
|
+
- `schema` — a JSON schema the answer has to match. With it the model is asked for JSON only, and the answer comes back parsed in `json` as well as written in `text`.
|
|
81
|
+
- `files` — documents and images the model reads, each as `{ url, mimeType? }`: an `https` URL Softr may fetch, one of the app's own uploads as a rule.
|
|
82
|
+
- `maxOutputTokens` — a cap on the answer's length. Softr caps it further.
|
|
83
|
+
- `messages` — the earlier turns of a conversation, oldest first, each `{ role: 'user' | 'assistant', content }`. The prompt is the newest turn. Leave out for a one-shot call.
|
|
84
|
+
- `reasoning` — `'low'`, `'medium'` or `'high'`: how hard a reasoning model thinks before it answers. The catalog says which models reason; the others ignore it. Leave out for the provider's default.
|
|
85
|
+
- `temperature` — 0 to 1: how varied the answer is. `0` for an extraction or a classification, around `0.7` for a draft. Left out, the provider's default applies. A model whose provider no longer takes one, such as the Claude 5 models, ignores it.
|
|
86
|
+
|
|
87
|
+
The answer is `{ text, json, usage, model }`: `text` as the model wrote it, `json` parsed when a schema was given and the model kept to it, `null` otherwise.
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
const summarize = createServerFn({ method: 'POST' })
|
|
91
|
+
.validator(z.object({ recordId: z.string() }))
|
|
92
|
+
.handler(async ({ data }) => {
|
|
93
|
+
const deal = await ds.get(dealQuery, { id: data.recordId })
|
|
94
|
+
if (deal === null) throw new Error('This deal no longer exists')
|
|
95
|
+
const facts = [`Name: ${fieldText(deal.fields.name)}`, `Stage: ${fieldText(deal.fields.stage)}`].join('\n')
|
|
96
|
+
const answer = await ai.generate(summarizeDeal, {
|
|
97
|
+
system: 'You brief a sales team. Use only the facts given; say what is missing rather than invent it.',
|
|
98
|
+
prompt: facts,
|
|
99
|
+
maxOutputTokens: 800,
|
|
100
|
+
})
|
|
101
|
+
return answer.text
|
|
102
|
+
})
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Extraction: an answer that is data
|
|
106
|
+
|
|
107
|
+
A document dropped on the app, fields pulled out of it, a record created — the model reads the file and answers in the shape the record needs. Give it the schema and the file; validate the parsed answer before writing it, since a model may stray from the shape.
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
const InvoiceFields = z.object({ vendor: z.string(), total: z.number(), issuedOn: z.string() })
|
|
111
|
+
|
|
112
|
+
const extractInvoice = createServerFn({ method: 'POST' })
|
|
113
|
+
.validator(z.object({ fileUrl: z.string().url() }))
|
|
114
|
+
.handler(async ({ data }) => {
|
|
115
|
+
const answer = await ai.generate(readInvoice, {
|
|
116
|
+
system: 'Read the invoice and answer with its fields. Dates as YYYY-MM-DD, amounts as numbers.',
|
|
117
|
+
prompt: 'Extract the vendor, the total and the issue date.',
|
|
118
|
+
schema: {
|
|
119
|
+
type: 'object',
|
|
120
|
+
properties: { vendor: { type: 'string' }, total: { type: 'number' }, issuedOn: { type: 'string' } },
|
|
121
|
+
required: ['vendor', 'total', 'issuedOn'],
|
|
122
|
+
},
|
|
123
|
+
files: [{ url: data.fileUrl, mimeType: 'application/pdf' }],
|
|
124
|
+
})
|
|
125
|
+
const parsed = InvoiceFields.safeParse(answer.json)
|
|
126
|
+
if (!parsed.success) throw new Error('The invoice could not be read. Try a clearer scan.')
|
|
127
|
+
return ds.create(createInvoice, { data: parsed.data })
|
|
128
|
+
})
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
The file's URL comes from the app's own upload: load the Softr SDK `file-uploads` guidance for that half. `readInvoice` names a model whose `bestFor` reads PDF documents.
|
|
132
|
+
|
|
133
|
+
## Streaming: an answer the user watches being written
|
|
134
|
+
|
|
135
|
+
A chat, an assistant, a long draft shown as it is typed — never buffer these: the user would watch a blank panel until the last token. A chat box the user types into is always this case, never `ai.generate`. `ai.stream(action, init)` takes the same `init` and answers with a `Response` whose body is a stream of Server-Sent Events. Hand it to the browser from the server function, unchanged:
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
const draftReply = createServerFn({ method: 'POST' })
|
|
139
|
+
.validator(z.object({ prompt: z.string() }))
|
|
140
|
+
.handler(async ({ data }) => {
|
|
141
|
+
const res = await ai.stream(draftAction, { system: 'You write replies for a support team.', prompt: data.prompt })
|
|
142
|
+
return new Response(res.body, { headers: { 'Content-Type': 'text/event-stream' } })
|
|
143
|
+
})
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Each event is one JSON object on a `data:` line:
|
|
147
|
+
|
|
148
|
+
- `{ "text": "..." }` — the next piece of the answer; append it.
|
|
149
|
+
- `{ "done": true, "usage": { "inputTokens", "outputTokens" }, "model": "..." }` — the answer is complete.
|
|
150
|
+
- `{ "error": "..." }` — in place of `done`, when the call ended before its answer: show the message.
|
|
151
|
+
|
|
152
|
+
On the client, call the server function's URL with `fetch`, read `response.body` with a stream reader, split on blank lines, and parse the JSON after `data:`. A conversation sends its earlier turns in `messages`; the app keeps them, the model holds nothing between calls.
|
|
153
|
+
|
|
154
|
+
## Failure modes
|
|
155
|
+
|
|
156
|
+
**Calling from client code.** `ai` is server-only. Importing it into a component or calling it outside a `createServerFn` handler fails the build or has no request context to act on.
|
|
157
|
+
|
|
158
|
+
**Spelling a model id.** `model` is copied from `ai_list_models`, never written from memory. An id outside the catalog fails the save of the action, so the app cannot be published with it.
|
|
159
|
+
|
|
160
|
+
**No credits left.** `ai.generate` and `ai.stream` throw an `AiError` whose `status` is `402` when the workspace has no AI credits. Show its message to the user; the workspace owner tops the credits up in Softr. Any other refusal carries its status and reason the same way.
|
|
161
|
+
|
|
162
|
+
**Trusting `json` without checking it.** A model may stray from the schema; `json` is then `null`, or a shape close to the one asked. Validate it with `zod` before writing it to a record, and keep `text` as the fallback the user can read.
|
|
163
|
+
|
|
164
|
+
**Buffering a chat.** A chat built on `ai.generate` shows nothing until the whole reply is done, and the user reads "replies appear all at once" in your closing message. A chat streams.
|
|
165
|
+
|
|
166
|
+
**Reading a streamed body with `res.json()`.** The body of `ai.stream` is an event stream, not one JSON document. Return `res.body` in a `Response` or read it with a stream reader.
|
|
167
|
+
|
|
168
|
+
**Asking for the user's API key.** An AI feature of the app's own needs none. Only when the user chose their own provider account for the feature does the call go through a connected integration — load the `integrations` sub-skill then.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.89
|
|
12
|
+
library_version: 0.0.89
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `auth` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.89
|
|
12
|
+
library_version: 0.0.89
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler or a server-side route hook — importing it into a component fails the build. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -7,7 +7,7 @@ description: >-
|
|
|
7
7
|
metadata:
|
|
8
8
|
type: sub-skill
|
|
9
9
|
library: softr-sdk
|
|
10
|
-
library_version: 0.0.89
|
|
10
|
+
library_version: 0.0.89
|
|
11
11
|
---
|
|
12
12
|
|
|
13
13
|
**Boundary.** `upload` lives on `@softr/sdk/server` and runs inside server functions. `useFileUpload` and `FileItem` live on `@softr/sdk` and run in components. `FileAttachment` comes from `@softr/sdk` and can be imported anywhere.
|
|
@@ -7,7 +7,7 @@ description: >-
|
|
|
7
7
|
metadata:
|
|
8
8
|
type: sub-skill
|
|
9
9
|
library: softr-sdk
|
|
10
|
-
library_version: 0.0.89
|
|
10
|
+
library_version: 0.0.89
|
|
11
11
|
---
|
|
12
12
|
|
|
13
13
|
**Boundary.** `integration` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineIntegration` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -126,7 +126,11 @@ Do not add an `Authorization` key to `headers` — Softr injects the integration
|
|
|
126
126
|
|
|
127
127
|
## Calling an AI model
|
|
128
128
|
|
|
129
|
-
|
|
129
|
+
**This is the path for the user's own provider account only.** An AI feature of the app's own — a summary, an extraction, a chat — runs on Softr's keys through an AI action, with nothing to connect and no key to ask for: load the `ai` sub-skill for it. Call a model through an integration only when the user chose their own OpenAI, Anthropic or Gemini account for the feature, in the prompt or when asked, and had it connected.
|
|
130
|
+
|
|
131
|
+
**The model id comes from `ai_list_models`, never from memory.** Each entry of that list carries `providerModelId`, the id the provider's own API accepts, and `provider`: `anthropic` for an `ANTHROPIC_AI` integration, `openai` for `OPEN_AI`, `google_ai` for `GEMINI_AI`. Pick an entry of the integration's provider as the `ai` sub-skill's "Choose the model" says, and send its `providerModelId`. An id spelled from memory (`claude-3-5-…`, `gpt-4o`) names a model that no longer answers, and the error only shows up when the button is pressed.
|
|
132
|
+
|
|
133
|
+
An AI integration is called like any other. For `ANTHROPIC_AI`, the action is `POST` on `https://api.anthropic.com/v1/messages`, the request carries the `anthropic-version` header and a body of `model`, `max_tokens`, `system` and `messages`, and the answer's text is in `content[].text`:
|
|
130
134
|
|
|
131
135
|
```ts
|
|
132
136
|
const askClaude = defineIntegration({
|
|
@@ -141,7 +145,7 @@ const claude = integration.createFetcher(askClaude)
|
|
|
141
145
|
const res = await claude({
|
|
142
146
|
headers: { 'Content-Type': 'application/json', 'anthropic-version': '2023-06-01' },
|
|
143
147
|
body: JSON.stringify({
|
|
144
|
-
model: '
|
|
148
|
+
model: '<providerModelId of an anthropic entry of ai_list_models>',
|
|
145
149
|
max_tokens: 1024,
|
|
146
150
|
system: 'You write a short briefing for a sales team. Use only the facts given.',
|
|
147
151
|
messages: [{ role: 'user', content: facts }],
|
|
@@ -152,7 +156,7 @@ const body = (await res.json()) as { content: Array<{ type: string; text?: strin
|
|
|
152
156
|
const text = body.content.flatMap((block) => (block.type === 'text' && block.text ? [block.text] : [])).join('')
|
|
153
157
|
```
|
|
154
158
|
|
|
155
|
-
|
|
159
|
+
For `OPEN_AI`, the action is `POST` on `https://api.openai.com/v1/chat/completions` with a body of `model` and `messages` (the system text as the first message, role `system`); the answer's text is in `choices[0].message.content`. For `GEMINI_AI`, the action is `POST` on `https://generativelanguage.googleapis.com/v1beta/models/<providerModelId>:generateContent` with a body of `contents` (`[{ role: 'user', parts: [{ text }] }]`) and an optional `systemInstruction`; the answer's text is in `candidates[0].content.parts[].text`. Read the answer defensively: a refusal or an empty answer leaves the text out.
|
|
156
160
|
|
|
157
161
|
## Base URLs by integration type
|
|
158
162
|
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.89
|
|
12
|
+
library_version: 0.0.89
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `softrMcpMiddleware` lives on `@softr/sdk` and is registered once, in `src/start.ts`. The actions you hand it are the same `defineQuery` / `defineMutation` values the app's own pages use — declared wherever they already live, not duplicated for MCP.
|
|
@@ -8,7 +8,7 @@ description: >-
|
|
|
8
8
|
metadata:
|
|
9
9
|
type: sub-skill
|
|
10
10
|
library: softr-sdk
|
|
11
|
-
library_version: 0.0.89
|
|
11
|
+
library_version: 0.0.89
|
|
12
12
|
---
|
|
13
13
|
|
|
14
14
|
**Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineMutation` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.89
|
|
12
|
+
library_version: 0.0.89
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler or a server-side route hook — importing it into a component fails the build. The same holds for any helper that calls `ds`: declare it inside the handler. A function at module level that calls `ds` keeps the server-only import in the browser bundle, and every page stops loading until it moves. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.89
|
|
12
|
+
library_version: 0.0.89
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `definePage`, `pageHead`, the access functions and the error predicates come from `@softr/sdk` and work anywhere.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.89
|
|
12
|
+
library_version: 0.0.89
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `workflow` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineWorkflow` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
import * as _tanstack_react_start8 from "@tanstack/react-start";
|
|
3
|
-
|
|
4
|
-
//#region src/agent/agent-fns.d.ts
|
|
5
|
-
|
|
6
|
-
declare const agentSchema: z.ZodObject<{
|
|
7
|
-
id: z.ZodString;
|
|
8
|
-
title: z.ZodString;
|
|
9
|
-
avatar: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
10
|
-
thumbnail: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
11
|
-
}, z.core.$strip>;
|
|
12
|
-
/** An agent the visitor may chat with. */
|
|
13
|
-
type Agent = z.infer<typeof agentSchema>;
|
|
14
|
-
/**
|
|
15
|
-
* The agents the visitor may chat with in this app. The builder attaches them
|
|
16
|
-
* in Studio, and each one's visibility settings decide who sees it.
|
|
17
|
-
*/
|
|
18
|
-
declare const listAgents: _tanstack_react_start8.OptionalFetcher<undefined, undefined, Promise<{
|
|
19
|
-
id: string;
|
|
20
|
-
title: string;
|
|
21
|
-
avatar?: string | null | undefined;
|
|
22
|
-
thumbnail?: string | null | undefined;
|
|
23
|
-
}[]>>;
|
|
24
|
-
/** One past chat with an agent. `title` is null until the agent names the chat. */
|
|
25
|
-
type AgentChatSummary = {
|
|
26
|
-
id: string;
|
|
27
|
-
title: string | null;
|
|
28
|
-
};
|
|
29
|
-
//#endregion
|
|
30
|
-
export { Agent, AgentChatSummary, listAgents };
|
package/dist/agent/agent-fns.js
DELETED
|
@@ -1,215 +0,0 @@
|
|
|
1
|
-
import { assert } from "../assertions.js";
|
|
2
|
-
import { fetch } from "../fetch.js";
|
|
3
|
-
import { sessionConfig } from "../auth/config.js";
|
|
4
|
-
import { readSessionToken } from "../auth/session.js";
|
|
5
|
-
import { softrApiUrl } from "../softr-api.js";
|
|
6
|
-
import { describeFailure, refererHeader } from "../datasource/record.js";
|
|
7
|
-
import { z } from "zod";
|
|
8
|
-
import { createServerFn } from "@tanstack/react-start";
|
|
9
|
-
import { getRequest } from "@tanstack/react-start/server";
|
|
10
|
-
|
|
11
|
-
//#region src/agent/agent-fns.ts
|
|
12
|
-
const AGENTS_PRODUCTION = "https://agents-api.softr.io";
|
|
13
|
-
const PLATFORM_HOST = /^(platform-api|platform-preview-api|preview-api)(?=[.-])/;
|
|
14
|
-
/**
|
|
15
|
-
* Where the agents service is. It sits next to the platform API, so unless
|
|
16
|
-
* `SOFTR_AGENTS_API_URL` says otherwise, it's the platform's host with
|
|
17
|
-
* `agents-api` in place of the platform's name. Live and preview share one
|
|
18
|
-
* agents service.
|
|
19
|
-
*/
|
|
20
|
-
function agentsApiUrl() {
|
|
21
|
-
const explicit = process.env.SOFTR_AGENTS_API_URL;
|
|
22
|
-
if (explicit) return explicit.replace(/\/+$/, "");
|
|
23
|
-
if (!process.env.SOFTR_PLATFORM_API_URL) return AGENTS_PRODUCTION;
|
|
24
|
-
const platform = new URL(softrApiUrl("SOFTR_PLATFORM_API_URL"));
|
|
25
|
-
assert(PLATFORM_HOST.test(platform.hostname), () => `can't tell the agents API from ${platform.origin}, set SOFTR_AGENTS_API_URL`);
|
|
26
|
-
platform.hostname = platform.hostname.replace(PLATFORM_HOST, "agents-api");
|
|
27
|
-
return platform.origin;
|
|
28
|
-
}
|
|
29
|
-
function agentsFetch(path, init = {}) {
|
|
30
|
-
const token = readSessionToken();
|
|
31
|
-
return fetch(`${agentsApiUrl()}/v1/agents/${path}`, {
|
|
32
|
-
method: init.method ?? "GET",
|
|
33
|
-
signal: init.signal,
|
|
34
|
-
headers: {
|
|
35
|
-
"Content-Type": "application/json",
|
|
36
|
-
...token ? { Authorization: `Bearer ${token}` } : {},
|
|
37
|
-
"Softr-Application-ID": sessionConfig().applicationId,
|
|
38
|
-
...refererHeader(),
|
|
39
|
-
...init.headers
|
|
40
|
-
},
|
|
41
|
-
body: init.body === void 0 ? void 0 : JSON.stringify(init.body)
|
|
42
|
-
});
|
|
43
|
-
}
|
|
44
|
-
const chatSchema = z.object({
|
|
45
|
-
agentId: z.string().min(1),
|
|
46
|
-
message: z.string(),
|
|
47
|
-
sessionId: z.string().nullable(),
|
|
48
|
-
timezone: z.string(),
|
|
49
|
-
pageName: z.string(),
|
|
50
|
-
pageUrl: z.string(),
|
|
51
|
-
record: z.object({
|
|
52
|
-
id: z.string(),
|
|
53
|
-
fields: z.record(z.string(), z.unknown())
|
|
54
|
-
}).nullable()
|
|
55
|
-
});
|
|
56
|
-
/**
|
|
57
|
-
* Sends one message and streams the reply back as it comes, one JSON event per line.
|
|
58
|
-
*
|
|
59
|
-
* Takes FormData so the browser can call it with plain `fetch` and read the
|
|
60
|
-
* stream itself. A failed call passes the agents service's status and message on.
|
|
61
|
-
*/
|
|
62
|
-
const agentChatFn = createServerFn({ method: "POST" }).validator((data) => {
|
|
63
|
-
const payload = data.get("payload");
|
|
64
|
-
assert(typeof payload === "string", "agent chat: payload is required");
|
|
65
|
-
return chatSchema.parse(JSON.parse(payload));
|
|
66
|
-
}).handler(async ({ data }) => {
|
|
67
|
-
const upstream = await agentsFetch(`${encodeURIComponent(data.agentId)}/chat`, {
|
|
68
|
-
method: "POST",
|
|
69
|
-
signal: getRequest().signal,
|
|
70
|
-
headers: {
|
|
71
|
-
Accept: "application/x-ndjson",
|
|
72
|
-
"X-User-Timezone": data.timezone
|
|
73
|
-
},
|
|
74
|
-
body: {
|
|
75
|
-
message: data.message,
|
|
76
|
-
...data.sessionId ? { sessionId: data.sessionId } : {},
|
|
77
|
-
context: {
|
|
78
|
-
pageName: data.pageName,
|
|
79
|
-
pageUrl: data.pageUrl,
|
|
80
|
-
...data.record ? { currentRecord: { data: data.record } } : {}
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
});
|
|
84
|
-
return new Response(upstream.body, {
|
|
85
|
-
status: upstream.status,
|
|
86
|
-
headers: { "Content-Type": upstream.headers.get("Content-Type") ?? "application/x-ndjson" }
|
|
87
|
-
});
|
|
88
|
-
});
|
|
89
|
-
const agentSchema = z.object({
|
|
90
|
-
id: z.string(),
|
|
91
|
-
title: z.string(),
|
|
92
|
-
avatar: z.string().nullish(),
|
|
93
|
-
thumbnail: z.string().nullish()
|
|
94
|
-
});
|
|
95
|
-
/**
|
|
96
|
-
* The agents the visitor may chat with in this app. The builder attaches them
|
|
97
|
-
* in Studio, and each one's visibility settings decide who sees it.
|
|
98
|
-
*/
|
|
99
|
-
const listAgents = createServerFn({ method: "GET" }).handler(async () => {
|
|
100
|
-
const token = readSessionToken();
|
|
101
|
-
const res = await fetch(`${softrApiUrl("SOFTR_PLATFORM_API_URL")}/v1/vibe/applications/${sessionConfig().applicationId}/agents`, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
|
|
102
|
-
if (!res.ok) throw new Error(`Loading agents failed: ${await describeFailure(res)}`);
|
|
103
|
-
return z.array(agentSchema).parse(await res.json());
|
|
104
|
-
});
|
|
105
|
-
const listAgentChatsFn = createServerFn({ method: "POST" }).validator(z.object({ agentId: z.string().min(1) })).handler(async ({ data }) => {
|
|
106
|
-
const res = await agentsFetch(`${encodeURIComponent(data.agentId)}/sessions`);
|
|
107
|
-
if (!res.ok) throw new Error(`Loading chats failed: ${await describeFailure(res)}`);
|
|
108
|
-
return z.array(z.object({
|
|
109
|
-
id: z.string(),
|
|
110
|
-
title: z.string().nullable()
|
|
111
|
-
})).parse(await res.json());
|
|
112
|
-
});
|
|
113
|
-
const historySchema = z.object({
|
|
114
|
-
messages: z.array(z.object({
|
|
115
|
-
id: z.string(),
|
|
116
|
-
role: z.enum(["USER", "ASSISTANT"]),
|
|
117
|
-
content: z.string(),
|
|
118
|
-
createdAt: z.number()
|
|
119
|
-
})),
|
|
120
|
-
toolCalls: z.array(z.object({
|
|
121
|
-
id: z.string(),
|
|
122
|
-
messageId: z.string(),
|
|
123
|
-
toolName: z.string(),
|
|
124
|
-
input: z.string(),
|
|
125
|
-
createdAt: z.number(),
|
|
126
|
-
metadata: z.object({
|
|
127
|
-
innerThought: z.string().nullish(),
|
|
128
|
-
durationMs: z.number().nullish(),
|
|
129
|
-
failed: z.boolean().nullish()
|
|
130
|
-
})
|
|
131
|
-
}))
|
|
132
|
-
});
|
|
133
|
-
const CHAT_GONE = [
|
|
134
|
-
401,
|
|
135
|
-
403,
|
|
136
|
-
404,
|
|
137
|
-
410
|
|
138
|
-
];
|
|
139
|
-
/** What a past chat holds, or `null` when it's gone or belongs to someone else. */
|
|
140
|
-
const loadAgentChatFn = createServerFn({ method: "POST" }).validator(z.object({
|
|
141
|
-
agentId: z.string().min(1),
|
|
142
|
-
sessionId: z.string().min(1)
|
|
143
|
-
})).handler(async ({ data }) => {
|
|
144
|
-
const res = await agentsFetch(`${encodeURIComponent(data.agentId)}/sessions/${encodeURIComponent(data.sessionId)}`);
|
|
145
|
-
if (CHAT_GONE.includes(res.status)) return null;
|
|
146
|
-
if (!res.ok) throw new Error(`Loading the chat failed: ${await describeFailure(res)}`);
|
|
147
|
-
return historySchema.parse(await res.json());
|
|
148
|
-
});
|
|
149
|
-
/** Saves the visitor's answer. `false` when the chat is gone, see `loadAgentChatFn`. */
|
|
150
|
-
const decideAgentToolFn = createServerFn({ method: "POST" }).validator(z.object({
|
|
151
|
-
agentId: z.string().min(1),
|
|
152
|
-
sessionId: z.string().min(1),
|
|
153
|
-
toolCallId: z.string().min(1),
|
|
154
|
-
toolName: z.string().min(1),
|
|
155
|
-
decision: z.enum(["APPROVE", "REJECT"]),
|
|
156
|
-
scope: z.enum([
|
|
157
|
-
"ONCE",
|
|
158
|
-
"SESSION",
|
|
159
|
-
"USER"
|
|
160
|
-
])
|
|
161
|
-
})).handler(async ({ data: { agentId,...decision } }) => {
|
|
162
|
-
const res = await agentsFetch(`${encodeURIComponent(agentId)}/tool-permission-decisions`, {
|
|
163
|
-
method: "POST",
|
|
164
|
-
body: decision
|
|
165
|
-
});
|
|
166
|
-
if (CHAT_GONE.includes(res.status)) return false;
|
|
167
|
-
if (!res.ok) throw new Error(`Saving the answer failed: ${await describeFailure(res)}`);
|
|
168
|
-
return true;
|
|
169
|
-
});
|
|
170
|
-
const connectionSchema = z.object({
|
|
171
|
-
integration: z.string().min(1),
|
|
172
|
-
requestId: z.string().min(1)
|
|
173
|
-
});
|
|
174
|
-
function connectionUrl({ integration, requestId }, step) {
|
|
175
|
-
const { applicationId } = sessionConfig();
|
|
176
|
-
const provider = encodeURIComponent(integration.toLowerCase());
|
|
177
|
-
return `${`${softrApiUrl("SOFTR_DATASOURCE_API_URL")}/v1/datasource/applications/${applicationId}`}/integrations/${provider}/oauth/${step}?${new URLSearchParams({ requestId })}`;
|
|
178
|
-
}
|
|
179
|
-
/** The sign-in page to open in the popup. */
|
|
180
|
-
const startAgentConnectionFn = createServerFn({ method: "POST" }).validator(connectionSchema).handler(async ({ data }) => {
|
|
181
|
-
const token = readSessionToken();
|
|
182
|
-
const res = await fetch(connectionUrl(data, "register"), {
|
|
183
|
-
method: "POST",
|
|
184
|
-
headers: {
|
|
185
|
-
...token ? { Authorization: `Bearer ${token}` } : {},
|
|
186
|
-
...refererHeader()
|
|
187
|
-
}
|
|
188
|
-
});
|
|
189
|
-
if (!res.ok) throw new Error(`Starting the connection failed: ${await describeFailure(res)}`);
|
|
190
|
-
return z.object({ url: z.string() }).parse(await res.json()).url;
|
|
191
|
-
});
|
|
192
|
-
/** Waits a while for the visitor to finish signing in. `false` when they haven't yet. */
|
|
193
|
-
const awaitAgentConnectionFn = createServerFn({ method: "POST" }).validator(connectionSchema).handler(async ({ data }) => {
|
|
194
|
-
const res = await fetch(connectionUrl(data, "register-result"), { signal: getRequest().signal });
|
|
195
|
-
if (res.status === 503) return false;
|
|
196
|
-
if (!res.ok) throw new Error(`Connecting failed: ${await describeFailure(res)}`);
|
|
197
|
-
return true;
|
|
198
|
-
});
|
|
199
|
-
/** Tells the agent the account is connected. `false` when the chat is gone, see `loadAgentChatFn`. */
|
|
200
|
-
const finishAgentConnectionFn = createServerFn({ method: "POST" }).validator(z.object({
|
|
201
|
-
agentId: z.string().min(1),
|
|
202
|
-
sessionId: z.string().min(1),
|
|
203
|
-
toolCallId: z.string().min(1)
|
|
204
|
-
})).handler(async ({ data: { agentId,...completion } }) => {
|
|
205
|
-
const res = await agentsFetch(`${encodeURIComponent(agentId)}/integration-auth-completions`, {
|
|
206
|
-
method: "POST",
|
|
207
|
-
body: completion
|
|
208
|
-
});
|
|
209
|
-
if (CHAT_GONE.includes(res.status)) return false;
|
|
210
|
-
if (!res.ok) throw new Error(`Finishing the connection failed: ${await describeFailure(res)}`);
|
|
211
|
-
return true;
|
|
212
|
-
});
|
|
213
|
-
|
|
214
|
-
//#endregion
|
|
215
|
-
export { agentChatFn, awaitAgentConnectionFn, decideAgentToolFn, finishAgentConnectionFn, listAgentChatsFn, listAgents, loadAgentChatFn, startAgentConnectionFn };
|