@softr/sdk 0.0.90-alpha.2 → 0.0.90-alpha.4
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/app-identity.js +76 -0
- package/dist/auth/isomorphic.d.ts +1 -1
- package/dist/auth/isomorphic.js +2 -0
- package/dist/default-error-overlay.d.ts +2 -2
- package/dist/index.d.ts +1 -3
- package/dist/index.js +1 -3
- package/dist/mcp.js +3 -7
- package/dist/package.js +1 -1
- package/dist/pwa.d.ts +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 -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 -145
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { version } from "./package.js";
|
|
2
|
+
import { assert } from "./assertions.js";
|
|
3
|
+
import { createMiddleware } from "@tanstack/react-start";
|
|
4
|
+
|
|
5
|
+
//#region src/app-identity.ts
|
|
6
|
+
const HTML_TAG = new TextEncoder().encode("<html");
|
|
7
|
+
const HTML_TAG_SEARCH_LIMIT = 1024;
|
|
8
|
+
/**
|
|
9
|
+
* Marks every HTML page with the Softr app it belongs to and the SDK version it
|
|
10
|
+
* runs on, so support can read both from the page source.
|
|
11
|
+
*
|
|
12
|
+
* They go on `<html>` as `data-appid` and `data-sdk-version`, and
|
|
13
|
+
* in a comment just before it. React keeps the attributes when it hydrates, but
|
|
14
|
+
* drops them if it ever renders the document again on the client. The comment
|
|
15
|
+
* sits outside what React owns, so it always stays.
|
|
16
|
+
*/
|
|
17
|
+
function appIdentityMiddleware() {
|
|
18
|
+
return createMiddleware({ type: "request" }).server(async ({ next }) => {
|
|
19
|
+
const result = await next();
|
|
20
|
+
const { response } = result;
|
|
21
|
+
if (!response.body || !response.headers.get("content-type")?.startsWith("text/html")) return result;
|
|
22
|
+
const applicationId = process.env.SOFTR_APPLICATION_ID;
|
|
23
|
+
if (!applicationId) return result;
|
|
24
|
+
assert(/^[\w-]+$/.test(applicationId), `SOFTR_APPLICATION_ID is not an id: "${applicationId}"`);
|
|
25
|
+
const encoder = new TextEncoder();
|
|
26
|
+
const comment = encoder.encode(`<!-- Softr app ${applicationId}, @softr/sdk ${version} -->`);
|
|
27
|
+
const attributes = encoder.encode(` data-appid="${applicationId}" data-sdk-version="${version}"`);
|
|
28
|
+
let held = new Uint8Array(0);
|
|
29
|
+
let done = false;
|
|
30
|
+
const body = response.body.pipeThrough(new TransformStream({
|
|
31
|
+
transform(chunk, controller) {
|
|
32
|
+
if (done) {
|
|
33
|
+
controller.enqueue(chunk);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const bytes = new Uint8Array(held.length + chunk.length);
|
|
37
|
+
bytes.set(held);
|
|
38
|
+
bytes.set(chunk, held.length);
|
|
39
|
+
let at = -1;
|
|
40
|
+
search: for (let i = 0; i + HTML_TAG.length < bytes.length; i++) {
|
|
41
|
+
for (let j = 0; j < HTML_TAG.length; j++) if (bytes[i + j] !== HTML_TAG[j]) continue search;
|
|
42
|
+
const after = bytes[i + HTML_TAG.length];
|
|
43
|
+
if (after === 32 || after === 62) {
|
|
44
|
+
at = i;
|
|
45
|
+
break;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (at === -1) {
|
|
49
|
+
if (bytes.length > HTML_TAG_SEARCH_LIMIT) {
|
|
50
|
+
done = true;
|
|
51
|
+
controller.enqueue(bytes);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
held = bytes;
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
done = true;
|
|
58
|
+
const end = at + HTML_TAG.length;
|
|
59
|
+
controller.enqueue(bytes.subarray(0, at));
|
|
60
|
+
controller.enqueue(comment);
|
|
61
|
+
controller.enqueue(bytes.subarray(at, end));
|
|
62
|
+
controller.enqueue(attributes);
|
|
63
|
+
controller.enqueue(bytes.subarray(end));
|
|
64
|
+
},
|
|
65
|
+
flush(controller) {
|
|
66
|
+
if (!done) controller.enqueue(held);
|
|
67
|
+
}
|
|
68
|
+
}));
|
|
69
|
+
const marked = new Response(body, response);
|
|
70
|
+
marked.headers.delete("content-length");
|
|
71
|
+
return marked;
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
//#endregion
|
|
76
|
+
export { appIdentityMiddleware };
|
|
@@ -22,7 +22,7 @@ import * as _tanstack_react_start0 from "@tanstack/react-start";
|
|
|
22
22
|
* requestMiddleware: [softrAuthMiddleware()],
|
|
23
23
|
* }))
|
|
24
24
|
*/
|
|
25
|
-
declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
|
|
25
|
+
declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
|
|
26
26
|
user: User | null;
|
|
27
27
|
permissions: Permissions;
|
|
28
28
|
formatting: Formatting;
|
package/dist/auth/isomorphic.js
CHANGED
|
@@ -10,6 +10,7 @@ import { bootErrorMiddleware } from "../boot-error.js";
|
|
|
10
10
|
import { pwaMiddleware } from "../pwa.js";
|
|
11
11
|
import { faviconMiddleware } from "../favicon.js";
|
|
12
12
|
import { embeddingMiddleware } from "../embedding.js";
|
|
13
|
+
import { appIdentityMiddleware } from "../app-identity.js";
|
|
13
14
|
import { createContext, useContext } from "react";
|
|
14
15
|
import { createMiddleware, createServerFn, getGlobalStartContext } from "@tanstack/react-start";
|
|
15
16
|
import { getRequestHeader } from "@tanstack/react-start/server";
|
|
@@ -34,6 +35,7 @@ import { jsx } from "react/jsx-runtime";
|
|
|
34
35
|
function softrAuthMiddleware() {
|
|
35
36
|
return createMiddleware({ type: "request" }).middleware([
|
|
36
37
|
embeddingMiddleware(),
|
|
38
|
+
appIdentityMiddleware(),
|
|
37
39
|
bootErrorMiddleware(),
|
|
38
40
|
pwaMiddleware(),
|
|
39
41
|
faviconMiddleware()
|
|
@@ -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/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/mcp.js
CHANGED
|
@@ -244,8 +244,7 @@ const WHOAMI = {
|
|
|
244
244
|
type: "object",
|
|
245
245
|
properties: {},
|
|
246
246
|
additionalProperties: false
|
|
247
|
-
}
|
|
248
|
-
annotations: { readOnlyHint: true }
|
|
247
|
+
}
|
|
249
248
|
};
|
|
250
249
|
/** How many records a read returns when the caller does not say. */
|
|
251
250
|
const DEFAULT_LIMIT = 20;
|
|
@@ -266,7 +265,6 @@ function describeTool(action) {
|
|
|
266
265
|
case "read": return {
|
|
267
266
|
name: action.id,
|
|
268
267
|
description: `Read records from "${action.id}". Returns the fields ${names.join(", ")}. Only records the signed-in user may see come back.`,
|
|
269
|
-
annotations: { readOnlyHint: true },
|
|
270
268
|
inputSchema: {
|
|
271
269
|
type: "object",
|
|
272
270
|
properties: {
|
|
@@ -387,10 +385,8 @@ async function rpc(request, origin, actions) {
|
|
|
387
385
|
const token = bearerToken(request);
|
|
388
386
|
if (token === null) return unauthorized(origin);
|
|
389
387
|
const session = await platformSession(token);
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
else if (session.refused && await resolveUser(token) !== null) sessionToken = token;
|
|
393
|
-
else return session.refused ? unauthorized(origin) : unavailable();
|
|
388
|
+
if (!session.ok) return session.refused ? unauthorized(origin) : unavailable();
|
|
389
|
+
const { sessionToken } = session;
|
|
394
390
|
const body = await readJson(request);
|
|
395
391
|
const message = z.object({
|
|
396
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/package.json
CHANGED
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: core
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.90-alpha.
|
|
12
|
+
library_version: 0.0.90-alpha.4
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
# Softr SDK core
|
|
@@ -49,7 +49,6 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
|
|
|
49
49
|
| Sign a visitor in, out, or up | [auth/SKILL.md](./auth/SKILL.md) |
|
|
50
50
|
| Call a connected third-party API (Slack, Stripe, Gmail, …) | [integrations/SKILL.md](./integrations/SKILL.md) |
|
|
51
51
|
| Open the app to AI assistants over MCP | [mcp/SKILL.md](./mcp/SKILL.md) |
|
|
52
|
-
| Let visitors chat with a Softr agent | [agent-chat/SKILL.md](./agent-chat/SKILL.md) |
|
|
53
52
|
| Let visitors install the app on their home screen | [pwa/SKILL.md](./pwa/SKILL.md) |
|
|
54
53
|
| Show a date, a time or a number | [formatting/SKILL.md](./formatting/SKILL.md) |
|
|
55
54
|
|
|
@@ -86,9 +85,6 @@ Calling a connected third-party API (Slack, Stripe, Gmail, Google Calendar, …)
|
|
|
86
85
|
Opening the app to an AI assistant over MCP?
|
|
87
86
|
load softr-sdk/mcp
|
|
88
87
|
|
|
89
|
-
Adding a chat with one of the app's Softr agents, or a Connect button for the visitor's account it needs?
|
|
90
|
-
load softr-sdk/agent-chat
|
|
91
|
-
|
|
92
88
|
Adding an install button, or making the app installable?
|
|
93
89
|
load softr-sdk/pwa
|
|
94
90
|
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.90-alpha.
|
|
12
|
+
library_version: 0.0.90-alpha.4
|
|
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.90-alpha.
|
|
12
|
+
library_version: 0.0.90-alpha.4
|
|
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.90-alpha.
|
|
10
|
+
library_version: 0.0.90-alpha.4
|
|
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.90-alpha.
|
|
10
|
+
library_version: 0.0.90-alpha.4
|
|
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.90-alpha.
|
|
12
|
+
library_version: 0.0.90-alpha.4
|
|
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.90-alpha.
|
|
11
|
+
library_version: 0.0.90-alpha.4
|
|
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.90-alpha.
|
|
12
|
+
library_version: 0.0.90-alpha.4
|
|
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.90-alpha.
|
|
12
|
+
library_version: 0.0.90-alpha.4
|
|
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.90-alpha.
|
|
12
|
+
library_version: 0.0.90-alpha.4
|
|
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 { softrApiUrl } from "../softr-api.js";
|
|
3
|
-
import { fetch } from "../fetch.js";
|
|
4
|
-
import { sessionConfig } from "../auth/config.js";
|
|
5
|
-
import { readSessionToken } from "../auth/session.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 };
|