@softr/sdk 0.0.87-alpha.5 → 0.0.88-signing.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/auth/platform.js +1 -1
- package/dist/core/file-upload.js +1 -1
- package/dist/core/workflow.js +1 -1
- package/dist/datasource/record.js +1 -1
- package/dist/default-error-overlay.d.ts +2 -2
- package/dist/fetch.js +61 -1
- package/dist/index.d.ts +1 -3
- package/dist/index.js +1 -3
- package/dist/locale-settings.js +1 -1
- package/dist/mcp.js +3 -5
- package/dist/package.js +1 -1
- package/dist/pwa.d.ts +2 -2
- package/dist/pwa.js +2 -2
- package/package.json +1 -1
- package/skills/softr-sdk/SKILL.md +1 -5
- 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 +1 -1
- 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 -172
- package/dist/agent/use-agent-chat.d.ts +0 -100
- package/dist/agent/use-agent-chat.js +0 -419
- package/skills/softr-sdk/agent-chat/SKILL.md +0 -122
package/dist/auth/platform.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { assert, panic } from "../assertions.js";
|
|
2
|
+
import { softrApiUrl } from "../softr-api.js";
|
|
2
3
|
import { fetch } from "../fetch.js";
|
|
3
4
|
import { permissionsSchema } from "./permissions.js";
|
|
4
|
-
import { softrApiUrl } from "../softr-api.js";
|
|
5
5
|
import { softrConfig } from "../softr-config.js";
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
|
package/dist/core/file-upload.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { softrApiUrl } from "../softr-api.js";
|
|
1
2
|
import { fetch } from "../fetch.js";
|
|
2
3
|
import { sessionConfig } from "../auth/config.js";
|
|
3
4
|
import { readSessionToken } from "../auth/session.js";
|
|
4
|
-
import { softrApiUrl } from "../softr-api.js";
|
|
5
5
|
import { randomUUID } from "node:crypto";
|
|
6
6
|
|
|
7
7
|
//#region src/core/file-upload.ts
|
package/dist/core/workflow.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { softrApiUrl } from "../softr-api.js";
|
|
1
2
|
import { fetch } from "../fetch.js";
|
|
2
3
|
import { sessionConfig } from "../auth/config.js";
|
|
3
4
|
import { readSessionToken } from "../auth/session.js";
|
|
4
|
-
import { softrApiUrl } from "../softr-api.js";
|
|
5
5
|
|
|
6
6
|
//#region src/core/workflow.ts
|
|
7
7
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { assert, panic } from "../assertions.js";
|
|
2
|
+
import { softrApiUrl } from "../softr-api.js";
|
|
2
3
|
import { fetch } from "../fetch.js";
|
|
3
4
|
import { readUserTimezone } from "../cookies.js";
|
|
4
5
|
import { readSessionToken } from "../auth/session.js";
|
|
5
|
-
import { softrApiUrl } from "../softr-api.js";
|
|
6
6
|
import { isDatasourceAction } from "../action.js";
|
|
7
7
|
import { buildFilterCriteria, buildOrderBy, dealiasFilterCriteria, dealiasOrderBy } from "./filter.js";
|
|
8
8
|
import { andAll, makeFieldSet, makeSortSet } from "./fields.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as react6 from "react";
|
|
2
2
|
|
|
3
3
|
//#region src/default-error-overlay.d.ts
|
|
4
4
|
type Props = {
|
|
@@ -8,6 +8,6 @@ type Props = {
|
|
|
8
8
|
declare function DefaultErrorOverlay({
|
|
9
9
|
error,
|
|
10
10
|
reset
|
|
11
|
-
}: Props):
|
|
11
|
+
}: Props): react6.JSX.Element;
|
|
12
12
|
//#endregion
|
|
13
13
|
export { DefaultErrorOverlay };
|
package/dist/fetch.js
CHANGED
|
@@ -1,9 +1,29 @@
|
|
|
1
|
+
import { version } from "./package.js";
|
|
2
|
+
import { assert, requireDefined } from "./assertions.js";
|
|
1
3
|
import { logger } from "./logger.js";
|
|
4
|
+
import { softrApiUrl } from "./softr-api.js";
|
|
2
5
|
|
|
3
6
|
//#region src/fetch.ts
|
|
4
7
|
const fetch = async (input, init) => {
|
|
5
|
-
if (process.env.NODE_ENV === "production") return globalThis.fetch(input, init);
|
|
6
8
|
const url = input instanceof Request ? input.url : String(input);
|
|
9
|
+
if ([
|
|
10
|
+
softrApiUrl("SOFTR_PLATFORM_API_URL"),
|
|
11
|
+
softrApiUrl("SOFTR_DATASOURCE_API_URL"),
|
|
12
|
+
softrApiUrl("SOFTR_WORKFLOWS_API_URL")
|
|
13
|
+
].some((base) => url.startsWith(`${base}/`))) {
|
|
14
|
+
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
|
|
15
|
+
headers.set("user-agent", `softr-sdk/${version}`);
|
|
16
|
+
init = {
|
|
17
|
+
...init,
|
|
18
|
+
headers
|
|
19
|
+
};
|
|
20
|
+
const signed = await sign(input, init);
|
|
21
|
+
if (signed) {
|
|
22
|
+
input = signed;
|
|
23
|
+
init = void 0;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
if (process.env.NODE_ENV === "production") return globalThis.fetch(input, init);
|
|
7
27
|
const method = init?.method ?? (input instanceof Request ? input.method : "GET");
|
|
8
28
|
const started = Date.now();
|
|
9
29
|
try {
|
|
@@ -16,6 +36,46 @@ const fetch = async (input, init) => {
|
|
|
16
36
|
throw error;
|
|
17
37
|
}
|
|
18
38
|
};
|
|
39
|
+
async function sign(input, init) {
|
|
40
|
+
const key = process.env.SOFTR_REQUEST_SIGNING_KEY;
|
|
41
|
+
const keyId = process.env.SOFTR_REQUEST_SIGNING_KEY_ID;
|
|
42
|
+
if (!key || !keyId) return void 0;
|
|
43
|
+
assert(/^[0-9a-f]{64}$/i.test(key), "SOFTR_REQUEST_SIGNING_KEY must be 64 hex characters");
|
|
44
|
+
assert(!/["\\]/.test(keyId), "SOFTR_REQUEST_SIGNING_KEY_ID must not contain quotes or backslashes");
|
|
45
|
+
const request = new Request(input, init);
|
|
46
|
+
const headers = new Headers(request.headers);
|
|
47
|
+
const { host, pathname, search } = new URL(request.url);
|
|
48
|
+
const derived = {
|
|
49
|
+
"@method": request.method,
|
|
50
|
+
"@authority": host,
|
|
51
|
+
"@path": pathname,
|
|
52
|
+
"@query": search || "?"
|
|
53
|
+
};
|
|
54
|
+
const fields = Object.keys(derived);
|
|
55
|
+
const body = request.body ? new Uint8Array(await request.arrayBuffer()) : void 0;
|
|
56
|
+
if (body) {
|
|
57
|
+
headers.set("content-digest", `sha-256=:${base64(await crypto.subtle.digest("SHA-256", body))}:`);
|
|
58
|
+
fields.push("content-type", "content-digest");
|
|
59
|
+
}
|
|
60
|
+
if (headers.has("authorization")) fields.push("authorization");
|
|
61
|
+
const created = Math.floor(Date.now() / 1e3);
|
|
62
|
+
const params = `(${fields.map((field) => `"${field}"`).join(" ")});created=${created};keyid="${keyId}";tag="softr-code-app"`;
|
|
63
|
+
const base = [...fields.map((field) => `"${field}": ${derived[field] ?? requireDefined(headers.get(field), field)}`), `"@signature-params": ${params}`].join("\n");
|
|
64
|
+
const hmacKey = await crypto.subtle.importKey("raw", Uint8Array.from(key.match(/../g) ?? [], (byte) => parseInt(byte, 16)), {
|
|
65
|
+
name: "HMAC",
|
|
66
|
+
hash: "SHA-256"
|
|
67
|
+
}, false, ["sign"]);
|
|
68
|
+
const signature = base64(await crypto.subtle.sign("HMAC", hmacKey, new TextEncoder().encode(base)));
|
|
69
|
+
headers.set("signature-input", `softr=${params}`);
|
|
70
|
+
headers.set("signature", `softr=:${signature}:`);
|
|
71
|
+
return new Request(request, {
|
|
72
|
+
headers,
|
|
73
|
+
body
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
function base64(bytes) {
|
|
77
|
+
return btoa(String.fromCharCode(...new Uint8Array(bytes)));
|
|
78
|
+
}
|
|
19
79
|
|
|
20
80
|
//#endregion
|
|
21
81
|
export { fetch };
|
package/dist/index.d.ts
CHANGED
|
@@ -16,7 +16,5 @@ import { useOverrides } from "./core/use-overrides.js";
|
|
|
16
16
|
import { useUserTimezone } from "./timezone.js";
|
|
17
17
|
import { PwaInstall, PwaPlatform, SoftrPwaHead, usePwaInstall } from "./pwa.js";
|
|
18
18
|
import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
19
|
-
import { Agent, AgentChatSummary, listAgents } from "./agent/agent-fns.js";
|
|
20
|
-
import { AgentBlock, AgentChat, AgentChatOptions, AgentMessage, AgentQuestion, AgentTodo, AgentToolCall, useAgentChat } from "./agent/use-agent-chat.js";
|
|
21
19
|
import { Audience } from "./route/audience.js";
|
|
22
|
-
export { type ActionPermissions,
|
|
20
|
+
export { type ActionPermissions, Audience, type AuthOptions, type AuthSettings, AuthSettingsProvider, type DateOptions, type DateParts, type DateSeparator, type DateValue, DefaultErrorOverlay, type FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Page, type PageSettings, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type User, type WeekDay, assertRouteAccess, checkAccess, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
|
package/dist/index.js
CHANGED
|
@@ -12,8 +12,6 @@ import { fieldShape, formatDuration, formatField, formatValue, registerSoftrFiel
|
|
|
12
12
|
import { useOverrides } from "./core/use-overrides.js";
|
|
13
13
|
import { useUserTimezone } from "./timezone.js";
|
|
14
14
|
import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
15
|
-
import { listAgents } from "./agent/agent-fns.js";
|
|
16
|
-
import { useAgentChat } from "./agent/use-agent-chat.js";
|
|
17
15
|
import { Audience } from "./route/audience.js";
|
|
18
16
|
|
|
19
|
-
export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError,
|
|
17
|
+
export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
|
package/dist/locale-settings.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { logger } from "./logger.js";
|
|
2
|
+
import { softrApiUrl } from "./softr-api.js";
|
|
2
3
|
import { fetch } from "./fetch.js";
|
|
3
4
|
import { readRequestCookies, serializeCookie, writeCookies } from "./cookies.js";
|
|
4
5
|
import { sessionConfig } from "./auth/config.js";
|
|
5
|
-
import { softrApiUrl } from "./softr-api.js";
|
|
6
6
|
import { localeSettingsSchema } from "./formatting.js";
|
|
7
7
|
import { getRequestProtocol } from "@tanstack/react-start/server";
|
|
8
8
|
|
package/dist/mcp.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { assert } from "./assertions.js";
|
|
2
|
+
import { softrApiUrl } from "./softr-api.js";
|
|
2
3
|
import { fetch } from "./fetch.js";
|
|
3
4
|
import { sessionConfig } from "./auth/config.js";
|
|
4
5
|
import { readSessionToken, withSessionToken } from "./auth/session.js";
|
|
5
|
-
import { softrApiUrl } from "./softr-api.js";
|
|
6
6
|
import { isDatasourceAction } from "./action.js";
|
|
7
7
|
import { softrConfig } from "./softr-config.js";
|
|
8
8
|
import { makePlatform } from "./auth/platform.js";
|
|
@@ -385,10 +385,8 @@ async function rpc(request, origin, actions) {
|
|
|
385
385
|
const token = bearerToken(request);
|
|
386
386
|
if (token === null) return unauthorized(origin);
|
|
387
387
|
const session = await platformSession(token);
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
else if (session.refused && await resolveUser(token) !== null) sessionToken = token;
|
|
391
|
-
else return session.refused ? unauthorized(origin) : unavailable();
|
|
388
|
+
if (!session.ok) return session.refused ? unauthorized(origin) : unavailable();
|
|
389
|
+
const { sessionToken } = session;
|
|
392
390
|
const body = await readJson(request);
|
|
393
391
|
const message = z.object({
|
|
394
392
|
id: z.union([z.string(), z.number()]).optional(),
|
package/dist/package.js
CHANGED
package/dist/pwa.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as react4 from "react";
|
|
2
2
|
import "@tanstack/react-start";
|
|
3
3
|
|
|
4
4
|
//#region src/pwa.d.ts
|
|
@@ -23,7 +23,7 @@ import "@tanstack/react-start";
|
|
|
23
23
|
* )
|
|
24
24
|
* }
|
|
25
25
|
*/
|
|
26
|
-
declare function SoftrPwaHead():
|
|
26
|
+
declare function SoftrPwaHead(): react4.FunctionComponentElement<react4.FragmentProps>;
|
|
27
27
|
type PwaPlatform = "ios" | "android" | "desktop";
|
|
28
28
|
type PwaInstall = {
|
|
29
29
|
available: false;
|
package/dist/pwa.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { logger } from "./logger.js";
|
|
2
|
+
import { softrApiUrl } from "./softr-api.js";
|
|
2
3
|
import { fetch } from "./fetch.js";
|
|
3
4
|
import { sessionConfig } from "./auth/config.js";
|
|
4
|
-
import { softrApiUrl } from "./softr-api.js";
|
|
5
5
|
import { z } from "zod";
|
|
6
6
|
import { Fragment, createElement, useEffect, useState } from "react";
|
|
7
7
|
import { createMiddleware } from "@tanstack/react-start";
|
|
@@ -125,7 +125,7 @@ function usePwaInstall() {
|
|
|
125
125
|
useEffect(() => {
|
|
126
126
|
if (window.matchMedia("(display-mode: standalone)").matches || "standalone" in navigator && navigator.standalone === true) return;
|
|
127
127
|
let cancelled = false;
|
|
128
|
-
fetch(INSTALL_PATH, { headers: { accept: "application/json" } }).then(async (response) => {
|
|
128
|
+
globalThis.fetch(INSTALL_PATH, { headers: { accept: "application/json" } }).then(async (response) => {
|
|
129
129
|
if (!response.ok) return;
|
|
130
130
|
const parsed = installSchema.safeParse(await response.json());
|
|
131
131
|
if (!parsed.success || cancelled) return;
|
package/package.json
CHANGED
|
@@ -8,7 +8,7 @@ description: >-
|
|
|
8
8
|
metadata:
|
|
9
9
|
type: core
|
|
10
10
|
library: softr-sdk
|
|
11
|
-
library_version: 0.0.
|
|
11
|
+
library_version: 0.0.88-signing.0
|
|
12
12
|
---
|
|
13
13
|
|
|
14
14
|
# Softr SDK core
|
|
@@ -48,7 +48,6 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
|
|
|
48
48
|
| Sign a visitor in, out, or up | [auth/SKILL.md](./auth/SKILL.md) |
|
|
49
49
|
| Call a connected third-party API (Slack, Stripe, Gmail, …) | [integrations/SKILL.md](./integrations/SKILL.md) |
|
|
50
50
|
| Open the app to AI assistants over MCP | [mcp/SKILL.md](./mcp/SKILL.md) |
|
|
51
|
-
| Let visitors chat with a Softr agent | [agent-chat/SKILL.md](./agent-chat/SKILL.md) |
|
|
52
51
|
| Let visitors install the app on their home screen | [pwa/SKILL.md](./pwa/SKILL.md) |
|
|
53
52
|
| Show a date, a time or a number | [formatting/SKILL.md](./formatting/SKILL.md) |
|
|
54
53
|
|
|
@@ -85,9 +84,6 @@ Calling a connected third-party API (Slack, Stripe, Gmail, Google Calendar, …)
|
|
|
85
84
|
Opening the app to an AI assistant over MCP?
|
|
86
85
|
load softr-sdk/mcp
|
|
87
86
|
|
|
88
|
-
Adding a chat with one of the app's Softr agents?
|
|
89
|
-
load softr-sdk/agent-chat
|
|
90
|
-
|
|
91
87
|
Adding an install button, or making the app installable?
|
|
92
88
|
load softr-sdk/pwa
|
|
93
89
|
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.
|
|
12
|
+
library_version: 0.0.88-signing.0
|
|
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.
|
|
12
|
+
library_version: 0.0.88-signing.0
|
|
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.
|
|
10
|
+
library_version: 0.0.88-signing.0
|
|
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.
|
|
10
|
+
library_version: 0.0.88-signing.0
|
|
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.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.
|
|
12
|
+
library_version: 0.0.88-signing.0
|
|
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.
|
|
11
|
+
library_version: 0.0.88-signing.0
|
|
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.
|
|
12
|
+
library_version: 0.0.88-signing.0
|
|
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.
|
|
@@ -8,7 +8,7 @@ description: >-
|
|
|
8
8
|
metadata:
|
|
9
9
|
type: sub-skill
|
|
10
10
|
library: softr-sdk
|
|
11
|
-
library_version: 0.0.
|
|
11
|
+
library_version: 0.0.88-signing.0
|
|
12
12
|
---
|
|
13
13
|
|
|
14
14
|
**Boundary.** `defineVisibility`, 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.
|
|
12
|
+
library_version: 0.0.88-signing.0
|
|
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_start7 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_start7.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,172 +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
|
-
|
|
171
|
-
//#endregion
|
|
172
|
-
export { agentChatFn, decideAgentToolFn, listAgentChatsFn, listAgents, loadAgentChatFn };
|
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
import { AgentChatSummary } from "./agent-fns.js";
|
|
2
|
-
|
|
3
|
-
//#region src/agent/use-agent-chat.d.ts
|
|
4
|
-
/** A step of the agent's work: a tool it calls, and where that call stands. */
|
|
5
|
-
type AgentToolCall = {
|
|
6
|
-
type: "tool";
|
|
7
|
-
id: string;
|
|
8
|
-
name: string;
|
|
9
|
-
/** The tool's input as the agent sent it, usually JSON. */
|
|
10
|
-
input?: string;
|
|
11
|
-
/**
|
|
12
|
-
* `awaiting-approval` waits for `approve` or `reject`. `awaiting-connection`
|
|
13
|
-
* needs the visitor to connect `integration` first, which code apps can't do yet.
|
|
14
|
-
*/
|
|
15
|
-
status: "running" | "done" | "failed" | "awaiting-approval" | "approved" | "rejected" | "awaiting-connection";
|
|
16
|
-
error?: string;
|
|
17
|
-
integration?: string;
|
|
18
|
-
/** Why the agent calls it, in its own words. */
|
|
19
|
-
thought?: string;
|
|
20
|
-
/** How long a finished call took. */
|
|
21
|
-
durationMs?: number;
|
|
22
|
-
};
|
|
23
|
-
type AgentTodo = {
|
|
24
|
-
content: string;
|
|
25
|
-
status: "pending" | "in_progress" | "completed";
|
|
26
|
-
};
|
|
27
|
-
type AgentQuestion = {
|
|
28
|
-
question: string;
|
|
29
|
-
header: string;
|
|
30
|
-
options: Array<{
|
|
31
|
-
label: string;
|
|
32
|
-
description: string;
|
|
33
|
-
}>;
|
|
34
|
-
multiSelect: boolean;
|
|
35
|
-
};
|
|
36
|
-
/** One piece of a message, in the order the agent produced it. */
|
|
37
|
-
type AgentBlock = {
|
|
38
|
-
type: "text";
|
|
39
|
-
text: string;
|
|
40
|
-
} | AgentToolCall
|
|
41
|
-
/** The agent's plan. It replaces itself as the agent works through it. */ | {
|
|
42
|
-
type: "todo";
|
|
43
|
-
todos: AgentTodo[];
|
|
44
|
-
}
|
|
45
|
-
/** The agent asks the visitor to pick. They answer by sending a message. */ | {
|
|
46
|
-
type: "question";
|
|
47
|
-
questions: AgentQuestion[];
|
|
48
|
-
} | {
|
|
49
|
-
type: "error";
|
|
50
|
-
message: string;
|
|
51
|
-
};
|
|
52
|
-
type AgentMessage = {
|
|
53
|
-
id: string;
|
|
54
|
-
role: "user" | "assistant";
|
|
55
|
-
blocks: AgentBlock[];
|
|
56
|
-
};
|
|
57
|
-
type AgentChat = {
|
|
58
|
-
/** The whole chat, oldest first. While the agent replies, its reply is the last one and grows. */
|
|
59
|
-
messages: AgentMessage[];
|
|
60
|
-
/** `thinking` until the first part of the reply arrives, `replying` until it ends. */
|
|
61
|
-
status: "idle" | "thinking" | "replying";
|
|
62
|
-
/** True while a past chat loads, including the one reopened on mount. */
|
|
63
|
-
loading: boolean;
|
|
64
|
-
/** Why the last request failed. Cleared by the next one. */
|
|
65
|
-
error: Error | null;
|
|
66
|
-
/** The chat the next message goes to, `null` for a new one. */
|
|
67
|
-
chatId: string | null;
|
|
68
|
-
send: (text: string) => void;
|
|
69
|
-
/** Stops the reply. What arrived so far stays. */
|
|
70
|
-
stop: () => void;
|
|
71
|
-
newChat: () => void;
|
|
72
|
-
/** Opens a past chat from `listChats`. */
|
|
73
|
-
openChat: (chatId: string) => void;
|
|
74
|
-
/** The visitor's past chats with this agent. */
|
|
75
|
-
listChats: () => Promise<AgentChatSummary[]>;
|
|
76
|
-
/** Lets a tool waiting for approval run, once, for this chat, or always for this visitor. */
|
|
77
|
-
approve: (toolCallId: string, scope?: "ONCE" | "SESSION" | "USER") => void;
|
|
78
|
-
reject: (toolCallId: string) => void;
|
|
79
|
-
};
|
|
80
|
-
type AgentChatOptions = {
|
|
81
|
-
/**
|
|
82
|
-
* The record the visitor is looking at, so they can say "this one". Sent
|
|
83
|
-
* with each message. Keys are what the agent reads, so use field names.
|
|
84
|
-
*/
|
|
85
|
-
record?: {
|
|
86
|
-
id: string;
|
|
87
|
-
fields: Record<string, unknown>;
|
|
88
|
-
} | null;
|
|
89
|
-
};
|
|
90
|
-
/**
|
|
91
|
-
* A chat with one of the app's Softr agents, as the signed-in visitor. No UI:
|
|
92
|
-
* render `messages` with the app's own components.
|
|
93
|
-
*
|
|
94
|
-
* @example
|
|
95
|
-
* const chat = useAgentChat(AGENT_ID, { record: ticket && { id: ticket.id, fields: ticket.fields } })
|
|
96
|
-
* <form onSubmit={(e) => { e.preventDefault(); chat.send(draft) }}>
|
|
97
|
-
*/
|
|
98
|
-
declare function useAgentChat(agentId: string, options?: AgentChatOptions): AgentChat;
|
|
99
|
-
//#endregion
|
|
100
|
-
export { AgentBlock, AgentChat, AgentChatOptions, AgentMessage, AgentQuestion, AgentTodo, AgentToolCall, useAgentChat };
|
|
@@ -1,419 +0,0 @@
|
|
|
1
|
-
import { assert } from "../assertions.js";
|
|
2
|
-
import { useCurrentUser } from "../auth/isomorphic.js";
|
|
3
|
-
import { agentChatFn, decideAgentToolFn, listAgentChatsFn, loadAgentChatFn } from "./agent-fns.js";
|
|
4
|
-
import { useCallback, useEffect, useRef, useState } from "react";
|
|
5
|
-
|
|
6
|
-
//#region src/agent/use-agent-chat.ts
|
|
7
|
-
/**
|
|
8
|
-
* A chat with one of the app's Softr agents, as the signed-in visitor. No UI:
|
|
9
|
-
* render `messages` with the app's own components.
|
|
10
|
-
*
|
|
11
|
-
* @example
|
|
12
|
-
* const chat = useAgentChat(AGENT_ID, { record: ticket && { id: ticket.id, fields: ticket.fields } })
|
|
13
|
-
* <form onSubmit={(e) => { e.preventDefault(); chat.send(draft) }}>
|
|
14
|
-
*/
|
|
15
|
-
function useAgentChat(agentId, options = {}) {
|
|
16
|
-
const [messages, setMessages] = useState([]);
|
|
17
|
-
const [live, setLive] = useState(null);
|
|
18
|
-
const [status, setStatus] = useState("idle");
|
|
19
|
-
const [loading, setLoading] = useState(false);
|
|
20
|
-
const [error, setError] = useState(null);
|
|
21
|
-
const [chatId, setChatId] = useState(null);
|
|
22
|
-
const storeKey = chatKey(agentId, useCurrentUser()?.id ?? null);
|
|
23
|
-
const chatIdRef = useRef(chatId);
|
|
24
|
-
chatIdRef.current = chatId;
|
|
25
|
-
const recordRef = useRef(options.record ?? null);
|
|
26
|
-
recordRef.current = options.record ?? null;
|
|
27
|
-
const liveRef = useRef(live);
|
|
28
|
-
liveRef.current = live;
|
|
29
|
-
const abortRef = useRef(null);
|
|
30
|
-
useEffect(() => () => abortRef.current?.abort(), []);
|
|
31
|
-
const commitLive = useCallback((blocks) => {
|
|
32
|
-
setLive(null);
|
|
33
|
-
if (!blocks?.some((b) => b.type !== "text" || b.text.trim())) return;
|
|
34
|
-
setMessages((prev) => [...prev, {
|
|
35
|
-
id: crypto.randomUUID(),
|
|
36
|
-
role: "assistant",
|
|
37
|
-
blocks: endRunningTools(blocks)
|
|
38
|
-
}]);
|
|
39
|
-
}, []);
|
|
40
|
-
const stream = useCallback(async (message) => {
|
|
41
|
-
abortRef.current?.abort();
|
|
42
|
-
const controller = new AbortController();
|
|
43
|
-
abortRef.current = controller;
|
|
44
|
-
setError(null);
|
|
45
|
-
setStatus("thinking");
|
|
46
|
-
let blocks = [];
|
|
47
|
-
try {
|
|
48
|
-
const request = {
|
|
49
|
-
agentId,
|
|
50
|
-
message,
|
|
51
|
-
sessionId: chatIdRef.current,
|
|
52
|
-
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
53
|
-
pageName: document.title,
|
|
54
|
-
pageUrl: location.href,
|
|
55
|
-
record: recordRef.current
|
|
56
|
-
};
|
|
57
|
-
const form = new FormData();
|
|
58
|
-
form.append("payload", JSON.stringify(request));
|
|
59
|
-
const res = await fetch(agentChatFn.url, {
|
|
60
|
-
method: "POST",
|
|
61
|
-
body: form,
|
|
62
|
-
signal: controller.signal
|
|
63
|
-
});
|
|
64
|
-
if (!res.ok) throw new Error(await failureMessage(res));
|
|
65
|
-
assert(res.body, "agent chat: the reply has no body");
|
|
66
|
-
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
67
|
-
let buffer = "";
|
|
68
|
-
const onLine = (line) => {
|
|
69
|
-
const event = parseEvent(line);
|
|
70
|
-
if (event === null) return;
|
|
71
|
-
if (event.sessionId && event.sessionId !== chatIdRef.current) {
|
|
72
|
-
chatIdRef.current = event.sessionId;
|
|
73
|
-
setChatId(event.sessionId);
|
|
74
|
-
saveChatId(storeKey, event.sessionId);
|
|
75
|
-
}
|
|
76
|
-
blocks = reduceEvent(blocks, event);
|
|
77
|
-
setLive(blocks);
|
|
78
|
-
setStatus("replying");
|
|
79
|
-
};
|
|
80
|
-
for (;;) {
|
|
81
|
-
const { done, value } = await reader.read();
|
|
82
|
-
if (done) break;
|
|
83
|
-
buffer += value;
|
|
84
|
-
const lines = buffer.split("\n");
|
|
85
|
-
buffer = lines.pop() ?? "";
|
|
86
|
-
lines.forEach(onLine);
|
|
87
|
-
}
|
|
88
|
-
onLine(buffer);
|
|
89
|
-
} catch (err) {
|
|
90
|
-
if (controller.signal.aborted) return;
|
|
91
|
-
setError(err instanceof Error ? err : new Error(String(err)));
|
|
92
|
-
}
|
|
93
|
-
if (abortRef.current !== controller) return;
|
|
94
|
-
abortRef.current = null;
|
|
95
|
-
commitLive(blocks);
|
|
96
|
-
setStatus("idle");
|
|
97
|
-
}, [
|
|
98
|
-
agentId,
|
|
99
|
-
storeKey,
|
|
100
|
-
commitLive
|
|
101
|
-
]);
|
|
102
|
-
const send = useCallback((text) => {
|
|
103
|
-
const trimmed = text.trim();
|
|
104
|
-
if (!trimmed) return;
|
|
105
|
-
abortRef.current?.abort();
|
|
106
|
-
commitLive(liveRef.current);
|
|
107
|
-
setMessages((prev) => [...prev, {
|
|
108
|
-
id: crypto.randomUUID(),
|
|
109
|
-
role: "user",
|
|
110
|
-
blocks: [{
|
|
111
|
-
type: "text",
|
|
112
|
-
text: trimmed
|
|
113
|
-
}]
|
|
114
|
-
}]);
|
|
115
|
-
stream(trimmed);
|
|
116
|
-
}, [stream, commitLive]);
|
|
117
|
-
const stop = useCallback(() => {
|
|
118
|
-
if (abortRef.current === null) return;
|
|
119
|
-
abortRef.current.abort();
|
|
120
|
-
abortRef.current = null;
|
|
121
|
-
commitLive(liveRef.current);
|
|
122
|
-
setStatus("idle");
|
|
123
|
-
}, [commitLive]);
|
|
124
|
-
const reset = useCallback((id) => {
|
|
125
|
-
abortRef.current?.abort();
|
|
126
|
-
abortRef.current = null;
|
|
127
|
-
chatIdRef.current = id;
|
|
128
|
-
setChatId(id);
|
|
129
|
-
saveChatId(storeKey, id);
|
|
130
|
-
setMessages([]);
|
|
131
|
-
setLive(null);
|
|
132
|
-
setStatus("idle");
|
|
133
|
-
setLoading(false);
|
|
134
|
-
setError(null);
|
|
135
|
-
}, [storeKey]);
|
|
136
|
-
const newChat = useCallback(() => reset(null), [reset]);
|
|
137
|
-
const load = useCallback((id, restoring) => {
|
|
138
|
-
reset(id);
|
|
139
|
-
setLoading(true);
|
|
140
|
-
loadAgentChatFn({ data: {
|
|
141
|
-
agentId,
|
|
142
|
-
sessionId: id
|
|
143
|
-
} }).then((history) => {
|
|
144
|
-
if (chatIdRef.current !== id) return;
|
|
145
|
-
if (history === null) {
|
|
146
|
-
reset(null);
|
|
147
|
-
if (!restoring) setError(new Error(CHAT_GONE_MESSAGE));
|
|
148
|
-
return;
|
|
149
|
-
}
|
|
150
|
-
setLoading(false);
|
|
151
|
-
setMessages(fromHistory(history));
|
|
152
|
-
}).catch((err) => {
|
|
153
|
-
if (chatIdRef.current !== id) return;
|
|
154
|
-
setLoading(false);
|
|
155
|
-
setError(err instanceof Error ? err : new Error(String(err)));
|
|
156
|
-
});
|
|
157
|
-
}, [agentId, reset]);
|
|
158
|
-
const openChat = useCallback((id) => load(id, false), [load]);
|
|
159
|
-
useEffect(() => {
|
|
160
|
-
const saved = savedChatId(storeKey);
|
|
161
|
-
if (saved) load(saved, true);
|
|
162
|
-
else newChat();
|
|
163
|
-
}, [
|
|
164
|
-
storeKey,
|
|
165
|
-
load,
|
|
166
|
-
newChat
|
|
167
|
-
]);
|
|
168
|
-
const listChats = useCallback(() => listAgentChatsFn({ data: { agentId } }), [agentId]);
|
|
169
|
-
const setToolStatus = useCallback((toolCallId, next) => {
|
|
170
|
-
const update = (blocks) => blocks.map((b) => b.type === "tool" && b.id === toolCallId ? {
|
|
171
|
-
...b,
|
|
172
|
-
status: next
|
|
173
|
-
} : b);
|
|
174
|
-
setLive((prev) => prev && update(prev));
|
|
175
|
-
setMessages((prev) => prev.map((m) => ({
|
|
176
|
-
...m,
|
|
177
|
-
blocks: update(m.blocks)
|
|
178
|
-
})));
|
|
179
|
-
}, []);
|
|
180
|
-
const decide = useCallback((toolCallId, decision, scope) => {
|
|
181
|
-
const sessionId = chatIdRef.current;
|
|
182
|
-
const tool = [...messages.flatMap((m) => m.blocks), ...liveRef.current ?? []].find((b) => b.type === "tool" && b.id === toolCallId);
|
|
183
|
-
if (sessionId === null || tool?.status !== "awaiting-approval") return;
|
|
184
|
-
setToolStatus(toolCallId, decision === "APPROVE" ? "approved" : "rejected");
|
|
185
|
-
decideAgentToolFn({ data: {
|
|
186
|
-
agentId,
|
|
187
|
-
sessionId,
|
|
188
|
-
toolCallId,
|
|
189
|
-
toolName: tool.name,
|
|
190
|
-
decision,
|
|
191
|
-
scope
|
|
192
|
-
} }).then((saved) => {
|
|
193
|
-
if (!saved) {
|
|
194
|
-
reset(null);
|
|
195
|
-
setError(new Error(CHAT_GONE_MESSAGE));
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
if (decision !== "APPROVE") return;
|
|
199
|
-
abortRef.current?.abort();
|
|
200
|
-
commitLive(liveRef.current);
|
|
201
|
-
stream("");
|
|
202
|
-
}).catch((err) => {
|
|
203
|
-
setToolStatus(toolCallId, "awaiting-approval");
|
|
204
|
-
setError(err instanceof Error ? err : new Error(String(err)));
|
|
205
|
-
});
|
|
206
|
-
}, [
|
|
207
|
-
agentId,
|
|
208
|
-
messages,
|
|
209
|
-
setToolStatus,
|
|
210
|
-
commitLive,
|
|
211
|
-
stream,
|
|
212
|
-
reset
|
|
213
|
-
]);
|
|
214
|
-
const approve = useCallback((toolCallId, scope = "ONCE") => decide(toolCallId, "APPROVE", scope), [decide]);
|
|
215
|
-
const reject = useCallback((toolCallId) => decide(toolCallId, "REJECT", "ONCE"), [decide]);
|
|
216
|
-
return {
|
|
217
|
-
messages: live === null ? messages : [...messages, {
|
|
218
|
-
id: "live",
|
|
219
|
-
role: "assistant",
|
|
220
|
-
blocks: live
|
|
221
|
-
}],
|
|
222
|
-
status,
|
|
223
|
-
loading,
|
|
224
|
-
error,
|
|
225
|
-
chatId,
|
|
226
|
-
send,
|
|
227
|
-
stop,
|
|
228
|
-
newChat,
|
|
229
|
-
openChat,
|
|
230
|
-
listChats,
|
|
231
|
-
approve,
|
|
232
|
-
reject
|
|
233
|
-
};
|
|
234
|
-
}
|
|
235
|
-
const TODO_TOOL = "TodoWrite";
|
|
236
|
-
/** Its question shows as a question block, so the call itself is noise. */
|
|
237
|
-
const QUESTION_TOOL = "AskUserQuestion";
|
|
238
|
-
function parseEvent(line) {
|
|
239
|
-
if (!line.trim()) return null;
|
|
240
|
-
try {
|
|
241
|
-
return JSON.parse(line);
|
|
242
|
-
} catch {
|
|
243
|
-
return null;
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
function reduceEvent(blocks, event) {
|
|
247
|
-
switch (event.type) {
|
|
248
|
-
case "TEXT": {
|
|
249
|
-
const last = blocks.at(-1);
|
|
250
|
-
return last?.type === "text" ? [...blocks.slice(0, -1), {
|
|
251
|
-
type: "text",
|
|
252
|
-
text: last.text + event.response
|
|
253
|
-
}] : [...blocks, {
|
|
254
|
-
type: "text",
|
|
255
|
-
text: event.response
|
|
256
|
-
}];
|
|
257
|
-
}
|
|
258
|
-
case "TOOL_CALL_START":
|
|
259
|
-
if (event.toolName === TODO_TOOL) {
|
|
260
|
-
const todos = parseTodos(event.input);
|
|
261
|
-
if (todos) return upsertTodos(blocks, todos);
|
|
262
|
-
}
|
|
263
|
-
if (event.toolName === QUESTION_TOOL) return blocks;
|
|
264
|
-
if (blocks.some((b) => b.type === "tool" && b.id === event.toolCallId)) return updateTool(blocks, event.toolCallId, (b) => b.status === "running" ? {
|
|
265
|
-
...b,
|
|
266
|
-
input: event.input ?? b.input,
|
|
267
|
-
thought: event.innerThought ?? b.thought
|
|
268
|
-
} : b);
|
|
269
|
-
return [...blocks, {
|
|
270
|
-
type: "tool",
|
|
271
|
-
id: event.toolCallId,
|
|
272
|
-
name: event.toolName,
|
|
273
|
-
input: event.input,
|
|
274
|
-
thought: event.innerThought,
|
|
275
|
-
integration: event.integrationType,
|
|
276
|
-
status: "running"
|
|
277
|
-
}];
|
|
278
|
-
case "TOOL_CALL_END": return updateTool(blocks, event.toolCallId, (b) => b.status === "running" || b.status === "approved" ? {
|
|
279
|
-
...b,
|
|
280
|
-
status: event.failed ? "failed" : "done",
|
|
281
|
-
error: event.errorMessage,
|
|
282
|
-
durationMs: event.durationMs
|
|
283
|
-
} : b);
|
|
284
|
-
case "TOOL_PERMISSION_REQUEST":
|
|
285
|
-
case "INTEGRATION_AUTH_REQUEST": {
|
|
286
|
-
const status = event.type === "TOOL_PERMISSION_REQUEST" ? "awaiting-approval" : "awaiting-connection";
|
|
287
|
-
const integration = event.type === "INTEGRATION_AUTH_REQUEST" ? event.integrationType : void 0;
|
|
288
|
-
if (blocks.some((b) => b.type === "tool" && b.id === event.toolCallId)) return updateTool(blocks, event.toolCallId, (b) => ({
|
|
289
|
-
...b,
|
|
290
|
-
status,
|
|
291
|
-
integration: integration ?? b.integration,
|
|
292
|
-
input: ("input" in event ? event.input : void 0) ?? b.input
|
|
293
|
-
}));
|
|
294
|
-
return [...blocks, {
|
|
295
|
-
type: "tool",
|
|
296
|
-
id: event.toolCallId,
|
|
297
|
-
name: event.toolName,
|
|
298
|
-
input: "input" in event ? event.input : void 0,
|
|
299
|
-
integration,
|
|
300
|
-
status
|
|
301
|
-
}];
|
|
302
|
-
}
|
|
303
|
-
case "QUESTION": return [...blocks, {
|
|
304
|
-
type: "question",
|
|
305
|
-
questions: event.questions
|
|
306
|
-
}];
|
|
307
|
-
case "ERROR": return [...blocks, {
|
|
308
|
-
type: "error",
|
|
309
|
-
message: event.message
|
|
310
|
-
}];
|
|
311
|
-
default: return blocks;
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
function updateTool(blocks, id, update) {
|
|
315
|
-
return blocks.map((b) => b.type === "tool" && b.id === id ? update(b) : b);
|
|
316
|
-
}
|
|
317
|
-
/** A reply that ended without finishing a tool call, stopped or cut off, never will. */
|
|
318
|
-
function endRunningTools(blocks) {
|
|
319
|
-
return blocks.map((b) => b.type === "tool" && b.status === "running" ? {
|
|
320
|
-
...b,
|
|
321
|
-
status: "failed",
|
|
322
|
-
error: "The agent stopped before this step finished."
|
|
323
|
-
} : b);
|
|
324
|
-
}
|
|
325
|
-
/** Each plan update re-sends the whole list, so only the latest one is kept, where the first one was. */
|
|
326
|
-
function upsertTodos(blocks, todos) {
|
|
327
|
-
const index = blocks.findIndex((b) => b.type === "todo");
|
|
328
|
-
if (index === -1) return [...blocks, {
|
|
329
|
-
type: "todo",
|
|
330
|
-
todos
|
|
331
|
-
}];
|
|
332
|
-
return blocks.map((b, i) => i === index ? {
|
|
333
|
-
type: "todo",
|
|
334
|
-
todos
|
|
335
|
-
} : b);
|
|
336
|
-
}
|
|
337
|
-
function parseTodos(input) {
|
|
338
|
-
if (!input) return null;
|
|
339
|
-
try {
|
|
340
|
-
const parsed = JSON.parse(input);
|
|
341
|
-
if (typeof parsed !== "object" || parsed === null || !("todos" in parsed)) return null;
|
|
342
|
-
const outer = parsed.todos;
|
|
343
|
-
const raw = typeof outer === "object" && outer !== null && "todos" in outer ? outer.todos : outer;
|
|
344
|
-
if (!Array.isArray(raw)) return null;
|
|
345
|
-
const todos = raw.flatMap((item) => {
|
|
346
|
-
if (typeof item !== "object" || item === null) return [];
|
|
347
|
-
const { content, status } = item;
|
|
348
|
-
if (typeof content !== "string" || !content.trim()) return [];
|
|
349
|
-
if (status !== "pending" && status !== "in_progress" && status !== "completed") return [];
|
|
350
|
-
return [{
|
|
351
|
-
content,
|
|
352
|
-
status
|
|
353
|
-
}];
|
|
354
|
-
});
|
|
355
|
-
return todos.length > 0 ? todos : null;
|
|
356
|
-
} catch {
|
|
357
|
-
return null;
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
function fromHistory(history) {
|
|
361
|
-
const toolsByMessage = Map.groupBy(history.toolCalls, (call) => call.messageId);
|
|
362
|
-
return history.messages.filter((m) => m.role !== "USER" || m.content.trim()).map((m) => {
|
|
363
|
-
if (m.role === "USER") return {
|
|
364
|
-
id: m.id,
|
|
365
|
-
role: "user",
|
|
366
|
-
blocks: [{
|
|
367
|
-
type: "text",
|
|
368
|
-
text: m.content
|
|
369
|
-
}]
|
|
370
|
-
};
|
|
371
|
-
let blocks = [];
|
|
372
|
-
const calls = (toolsByMessage.get(m.id) ?? []).toSorted((a, b) => a.createdAt - b.createdAt);
|
|
373
|
-
for (const call of calls) {
|
|
374
|
-
const todos = call.toolName === TODO_TOOL ? parseTodos(call.input) : null;
|
|
375
|
-
if (todos) blocks = upsertTodos(blocks, todos);
|
|
376
|
-
else if (call.toolName !== QUESTION_TOOL) blocks.push({
|
|
377
|
-
type: "tool",
|
|
378
|
-
id: call.id,
|
|
379
|
-
name: call.toolName,
|
|
380
|
-
input: call.input,
|
|
381
|
-
thought: call.metadata.innerThought ?? void 0,
|
|
382
|
-
durationMs: call.metadata.durationMs ?? void 0,
|
|
383
|
-
status: call.metadata.failed ? "failed" : "done"
|
|
384
|
-
});
|
|
385
|
-
}
|
|
386
|
-
if (m.content) blocks.push({
|
|
387
|
-
type: "text",
|
|
388
|
-
text: m.content
|
|
389
|
-
});
|
|
390
|
-
return {
|
|
391
|
-
id: m.id,
|
|
392
|
-
role: "assistant",
|
|
393
|
-
blocks
|
|
394
|
-
};
|
|
395
|
-
});
|
|
396
|
-
}
|
|
397
|
-
const CHAT_GONE_MESSAGE = "This chat is no longer available. Start a new one.";
|
|
398
|
-
const chatKey = (agentId, userId) => `softr-agent-chat:${agentId}:${userId ?? "visitor"}`;
|
|
399
|
-
function savedChatId(key) {
|
|
400
|
-
try {
|
|
401
|
-
return localStorage.getItem(key);
|
|
402
|
-
} catch {
|
|
403
|
-
return null;
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
function saveChatId(key, chatId) {
|
|
407
|
-
try {
|
|
408
|
-
if (chatId) localStorage.setItem(key, chatId);
|
|
409
|
-
else localStorage.removeItem(key);
|
|
410
|
-
} catch {}
|
|
411
|
-
}
|
|
412
|
-
async function failureMessage(res) {
|
|
413
|
-
const body = await res.json().catch(() => null);
|
|
414
|
-
if (typeof body === "object" && body !== null && "message" in body && typeof body.message === "string") return body.message;
|
|
415
|
-
return `The agent could not answer (${res.status}).`;
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
//#endregion
|
|
419
|
-
export { useAgentChat };
|
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: agent-chat
|
|
3
|
-
description: >-
|
|
4
|
-
Let visitors chat with one of the app's Softr agents: listAgents() from
|
|
5
|
-
@softr/sdk gives the agents the visitor may use, and useAgentChat(agentId, {
|
|
6
|
-
record }) returns the messages, the reply as it streams, and
|
|
7
|
-
send, stop, approve and reject, with no UI. Build the chat from the app's own
|
|
8
|
-
components. The agent acts on the app's data through the app's MCP, so
|
|
9
|
-
softrMcpMiddleware must list the actions it may use.
|
|
10
|
-
metadata:
|
|
11
|
-
type: sub-skill
|
|
12
|
-
library: softr-sdk
|
|
13
|
-
library_version: 0.0.87-alpha.5
|
|
14
|
-
---
|
|
15
|
-
|
|
16
|
-
**Boundary.** `listAgents` and `useAgentChat` live on `@softr/sdk`. `listAgents` runs in a route loader, `useAgentChat` in a component. Neither needs a route, server function or registration of its own. It chats as the signed-in visitor, or anonymously when no one is signed in.
|
|
17
|
-
|
|
18
|
-
# Agent chat
|
|
19
|
-
|
|
20
|
-
A Softr agent is set up in Studio's Agents tab and attached to the app there. The app gives it a chat. There is no ready-made chat widget: the hook gives the state, and the app draws it with its own components.
|
|
21
|
-
|
|
22
|
-
## Setup
|
|
23
|
-
|
|
24
|
-
```ts
|
|
25
|
-
import { listAgents, useAgentChat } from '@softr/sdk'
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
`listAgents()` resolves to the agents this visitor may chat with, `{ id, title, avatar, thumbnail }[]`. Call it in the route's `loader`. An agent hidden from this visitor isn't in the list, so show no chat when it's empty. When there are several, let the visitor pick one, or pick the one the builder named by its `title`. Take the id from the list, never write one by hand.
|
|
29
|
-
|
|
30
|
-
## Core pattern
|
|
31
|
-
|
|
32
|
-
```tsx
|
|
33
|
-
// agentId comes from listAgents() in the route's loader.
|
|
34
|
-
function AgentPanel({ agentId, ticket }: { agentId: string; ticket: Ticket | null }) {
|
|
35
|
-
const chat = useAgentChat(agentId, {
|
|
36
|
-
record: ticket && { id: ticket.id, fields: { Title: ticket.title, Status: ticket.status } },
|
|
37
|
-
})
|
|
38
|
-
const [draft, setDraft] = useState('')
|
|
39
|
-
|
|
40
|
-
return (
|
|
41
|
-
<>
|
|
42
|
-
{chat.messages.map((message) => (
|
|
43
|
-
<Message key={message.id} message={message} onApprove={chat.approve} onReject={chat.reject} />
|
|
44
|
-
))}
|
|
45
|
-
{chat.error && <p role="alert">{chat.error.message}</p>}
|
|
46
|
-
<form onSubmit={(e) => { e.preventDefault(); chat.send(draft); setDraft('') }}>
|
|
47
|
-
<Textarea value={draft} onChange={(e) => setDraft(e.target.value)} />
|
|
48
|
-
{chat.status === 'idle'
|
|
49
|
-
? <Button type="submit">Send</Button>
|
|
50
|
-
: <Button type="button" onClick={chat.stop}>Stop</Button>}
|
|
51
|
-
</form>
|
|
52
|
-
</>
|
|
53
|
-
)
|
|
54
|
-
}
|
|
55
|
-
```
|
|
56
|
-
|
|
57
|
-
## What the hook returns
|
|
58
|
-
|
|
59
|
-
- `messages`: the whole chat, oldest first. While the agent answers, its reply is the last message and grows as it streams.
|
|
60
|
-
- `status`: `thinking` until the first part of the reply arrives, `replying` until it ends, then `idle`. Show a typing hint while it's `thinking`.
|
|
61
|
-
- `loading`: `true` while a past chat loads. Show a spinner, not the empty-chat greeting.
|
|
62
|
-
- `error`: why the last request failed, or `null`.
|
|
63
|
-
- `send(text)`, `stop()`, `newChat()`.
|
|
64
|
-
- `listChats()` resolves to the visitor's past chats, `{ id, title }[]`, with `title` `null` until the agent names the chat. `openChat(id)` loads one. `chatId` is the open one, `null` for a new chat. The open chat is kept in the browser for each visitor, so the hook reopens it after a remount or a reload.
|
|
65
|
-
- `approve(toolCallId, scope?)` and `reject(toolCallId)` answer a tool waiting for approval. `scope` is `ONCE` (default), `SESSION` for the rest of this chat, or `USER` for always.
|
|
66
|
-
|
|
67
|
-
## Rendering a message
|
|
68
|
-
|
|
69
|
-
Each message has `role` (`user` or `assistant`) and `blocks`, in the order the agent produced them. Render every block type:
|
|
70
|
-
|
|
71
|
-
| Block | Show it as |
|
|
72
|
-
| --- | --- |
|
|
73
|
-
| `text` | Markdown text |
|
|
74
|
-
| `tool` | One line: the tool `name` and its `status`. Collapse finished ones. Expanded, show `thought`, `input`, `error` and `durationMs`. |
|
|
75
|
-
| `todo` | A checklist of the agent's plan. It updates in place. |
|
|
76
|
-
| `question` | The questions with their options. A click on an option sends its label with `send`. |
|
|
77
|
-
| `error` | An error line inside the reply |
|
|
78
|
-
|
|
79
|
-
A `tool` with status `awaiting-approval` blocks the agent until the visitor answers. Show Approve and Reject buttons on it. The agent continues on its own after an approval.
|
|
80
|
-
|
|
81
|
-
A `tool` with status `awaiting-connection` needs the visitor to connect the `integration` first. Code apps can't do that yet. Say which integration the agent needs, and that the builder has to connect it for this agent in Studio.
|
|
82
|
-
|
|
83
|
-
## The chat panel
|
|
84
|
-
|
|
85
|
-
Classic Softr apps ship a chat panel. Visitors expect the same from yours:
|
|
86
|
-
|
|
87
|
-
- A round button in a corner opens it. A right-side panel on desktop, full screen on mobile.
|
|
88
|
-
- The header shows the agent's avatar and name, a picker when there are several agents, new chat, past chats and close.
|
|
89
|
-
- An empty chat greets the visitor with the agent's avatar.
|
|
90
|
-
- The list scrolls to the newest message as the reply streams, until the visitor scrolls up. Then a button takes them back down.
|
|
91
|
-
- Text renders as Markdown, tables included.
|
|
92
|
-
- The input says "Ask {agent title}…". Enter sends. Shift+Enter adds a line.
|
|
93
|
-
- A line under the input: "AI can make mistakes. Please double-check responses."
|
|
94
|
-
- A question with one choice sends on click. One with `multiSelect` or several questions sends once all are answered. An answered question stays locked.
|
|
95
|
-
- Approve offers the three scopes: once, for this chat, always for this agent.
|
|
96
|
-
|
|
97
|
-
## Context
|
|
98
|
-
|
|
99
|
-
`record` is the one record the visitor is looking at, so they can say "close this one". Pass it where a page shows one record, and `null` elsewhere. Use readable field names as keys. The agent reads them as they are.
|
|
100
|
-
|
|
101
|
-
The page title and URL go along on their own. Nothing else about the page does, so don't try to send whole lists.
|
|
102
|
-
|
|
103
|
-
## Letting the agent act on the app
|
|
104
|
-
|
|
105
|
-
The agent reads and changes data through the app's own MCP, as the visitor who is chatting. Their groups and each action's `permissions` apply. The actions it may use are the ones listed in `softrMcpMiddleware`. With no MCP wired, the agent can only talk. Load [mcp/SKILL.md](../mcp/SKILL.md) to wire it.
|
|
106
|
-
|
|
107
|
-
## Failure modes
|
|
108
|
-
|
|
109
|
-
**Building a chat without the hook.** Calling the agents service from the browser fails: only the app's server can sign the request in as the visitor. Use `useAgentChat`.
|
|
110
|
-
|
|
111
|
-
**Rendering only `text` blocks.** A tool waiting for approval never shows, and the agent waits forever. Render every block type.
|
|
112
|
-
|
|
113
|
-
**The hook inside a panel that unmounts when it closes.** Closing it stops a reply that is still coming. Call `useAgentChat` in the component that owns the open state, such as the layout, and pass `chat` into the panel. Keep the selected agent there too, or closing the panel resets it.
|
|
114
|
-
|
|
115
|
-
**An agent id written by hand.** The chat fails on the first message, and an agent hidden from the visitor still shows. Take the id from `listAgents`.
|
|
116
|
-
|
|
117
|
-
**Expecting the agent to change data with no MCP wired.** It answers but can't act. List the actions it needs in `softrMcpMiddleware`.
|
|
118
|
-
|
|
119
|
-
## References
|
|
120
|
-
|
|
121
|
-
- [mcp/SKILL.md](../mcp/SKILL.md): the actions the agent may call
|
|
122
|
-
- [current-user/SKILL.md](../current-user/SKILL.md): showing the chat to signed-in visitors only
|