@softr/sdk 0.0.87-alpha.2 → 0.0.87-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.
Files changed (44) hide show
  1. package/dist/agent/agent-fns.d.ts +30 -0
  2. package/dist/agent/agent-fns.js +166 -0
  3. package/dist/agent/use-agent-chat.d.ts +94 -0
  4. package/dist/agent/use-agent-chat.js +367 -0
  5. package/dist/auth/isomorphic.d.ts +2 -3
  6. package/dist/auth/isomorphic.js +1 -4
  7. package/dist/auth/methods/authenticator.js +3 -3
  8. package/dist/auth/methods/code.js +1 -1
  9. package/dist/auth/methods/magicLink.js +1 -1
  10. package/dist/auth/methods/password.js +1 -1
  11. package/dist/auth/methods/passwordLink.js +1 -1
  12. package/dist/auth/methods/signup.js +1 -1
  13. package/dist/auth/methods/social.js +1 -1
  14. package/dist/auth/platform.js +1 -1
  15. package/dist/auth/session.js +7 -8
  16. package/dist/cookies.js +3 -29
  17. package/dist/default-error-overlay.d.ts +2 -2
  18. package/dist/formatting.d.ts +3 -3
  19. package/dist/index.d.ts +3 -1
  20. package/dist/index.js +3 -1
  21. package/dist/mcp.d.ts +2 -2
  22. package/dist/mcp.js +5 -3
  23. package/dist/package.js +1 -1
  24. package/dist/pwa.d.ts +2 -2
  25. package/dist/route/route.js +1 -1
  26. package/dist/softr-config.schema.js +1 -3
  27. package/package.json +1 -1
  28. package/schema/softr.schema.json +0 -5
  29. package/skills/softr-sdk/SKILL.md +7 -8
  30. package/skills/softr-sdk/agent-chat/SKILL.md +105 -0
  31. package/skills/softr-sdk/auth/SKILL.md +1 -1
  32. package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
  33. package/skills/softr-sdk/current-user/SKILL.md +1 -1
  34. package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
  35. package/skills/softr-sdk/formatting/SKILL.md +1 -1
  36. package/skills/softr-sdk/integrations/SKILL.md +1 -1
  37. package/skills/softr-sdk/mcp/SKILL.md +1 -1
  38. package/skills/softr-sdk/pwa/SKILL.md +1 -1
  39. package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
  40. package/skills/softr-sdk/record-queries/SKILL.md +1 -1
  41. package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
  42. package/skills/softr-sdk/routes-and-visibility/SKILL.md +1 -1
  43. package/skills/softr-sdk/workflows/SKILL.md +1 -1
  44. package/dist/embedding.js +0 -33
@@ -9,7 +9,6 @@ import { settings } from "./methods/settings.js";
9
9
  import { bootErrorMiddleware } from "../boot-error.js";
10
10
  import { pwaMiddleware } from "../pwa.js";
11
11
  import { faviconMiddleware } from "../favicon.js";
12
- import { embeddingMiddleware } from "../embedding.js";
13
12
  import { createContext, useContext } from "react";
14
13
  import { createMiddleware, createServerFn, getGlobalStartContext } from "@tanstack/react-start";
15
14
  import { getRequestHeader } from "@tanstack/react-start/server";
@@ -23,8 +22,7 @@ import { jsx } from "react/jsx-runtime";
23
22
  * to read.
24
23
  *
25
24
  * Register it once, as a global request middleware in the app's `src/start.ts`.
26
- * It writes the session cookie, and in production a header that stops other
27
- * sites from embedding the app.
25
+ * It writes nothing but the session cookie.
28
26
  *
29
27
  * @example
30
28
  * export const startInstance = createStart(() => ({
@@ -33,7 +31,6 @@ import { jsx } from "react/jsx-runtime";
33
31
  */
34
32
  function softrAuthMiddleware() {
35
33
  return createMiddleware({ type: "request" }).middleware([
36
- embeddingMiddleware(),
37
34
  bootErrorMiddleware(),
38
35
  pwaMiddleware(),
39
36
  faviconMiddleware()
@@ -46,7 +46,7 @@ async function confirmAuthenticatorSetup(details) {
46
46
  throw new Error(`${result.message}. Check SOFTR_APPLICATION_ID and that the app allows an authenticator app.`);
47
47
  }
48
48
  const { session, backupCodes } = result.data;
49
- writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
49
+ writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
50
50
  user: session.user,
51
51
  permissions: session.permissions
52
52
  }, session.jwt)]);
@@ -75,7 +75,7 @@ async function skipAuthenticatorSetup() {
75
75
  }
76
76
  const { session } = result.data;
77
77
  assert(session, "Expected a session from skipping setup, but got none");
78
- writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
78
+ writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
79
79
  user: session.user,
80
80
  permissions: session.permissions
81
81
  }, session.jwt)]);
@@ -101,7 +101,7 @@ async function verifyAuthenticator(credentials) {
101
101
  }
102
102
  const { session } = result.data;
103
103
  assert(session, "Expected a session from verification, but got none");
104
- writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
104
+ writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
105
105
  user: session.user,
106
106
  permissions: session.permissions
107
107
  }, session.jwt)]);
@@ -56,7 +56,7 @@ async function signInWithCode(credentials) {
56
56
  }
57
57
  const { session } = result.data;
58
58
  assert(session, "Expected a session from sign-in, but got none");
59
- writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
59
+ writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
60
60
  user: session.user,
61
61
  permissions: session.permissions
62
62
  }, session.jwt)]);
@@ -36,7 +36,7 @@ async function signInWithMagicLink(credentials) {
36
36
  }
37
37
  const { session } = result.data;
38
38
  assert(session, "Expected a session from magic-link sign-in, but got none");
39
- writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
39
+ writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
40
40
  user: session.user,
41
41
  permissions: session.permissions
42
42
  }, session.jwt)]);
@@ -35,7 +35,7 @@ async function signIn(credentials) {
35
35
  }
36
36
  const { session } = result.data;
37
37
  assert(session, "Expected a session from sign-in, but got none");
38
- writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
38
+ writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
39
39
  user: session.user,
40
40
  permissions: session.permissions
41
41
  }, session.jwt)]);
@@ -68,7 +68,7 @@ async function setPasswordWithLink(details) {
68
68
  }
69
69
  const { session } = result.data;
70
70
  assert(session, "Expected a session from setting a password, but got none");
71
- writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
71
+ writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
72
72
  user: session.user,
73
73
  permissions: session.permissions
74
74
  }, session.jwt)]);
@@ -66,7 +66,7 @@ async function confirmSignUp(details) {
66
66
  }
67
67
  const { session } = result.data;
68
68
  assert(session, "Expected a session from sign-up, but got none");
69
- writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
69
+ writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
70
70
  user: session.user,
71
71
  permissions: session.permissions
72
72
  }, session.jwt)]);
@@ -41,7 +41,7 @@ async function signInWithGoogle(credentials) {
41
41
  }
42
42
  const { session } = result.data;
43
43
  assert(session, "Expected a session from Google sign-in, but got none");
44
- writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
44
+ writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
45
45
  user: session.user,
46
46
  permissions: session.permissions
47
47
  }, session.jwt)]);
@@ -1,8 +1,8 @@
1
1
  import { assert, panic } from "../assertions.js";
2
2
  import { fetch } from "../fetch.js";
3
- import { softrConfig } from "../softr-config.js";
4
3
  import { permissionsSchema } from "./permissions.js";
5
4
  import { softrApiUrl } from "../softr-api.js";
5
+ import { softrConfig } from "../softr-config.js";
6
6
  import { z } from "zod";
7
7
 
8
8
  //#region src/auth/platform.ts
@@ -1,4 +1,4 @@
1
- import { expireCookie, expireOtherCopy, readRequestCookies, serializeCookie, writeCookies } from "../cookies.js";
1
+ import { readRequestCookies, serializeCookie, writeCookies } from "../cookies.js";
2
2
  import { permissionsSchema } from "./permissions.js";
3
3
  import { sessionConfig } from "./config.js";
4
4
  import { userSchema } from "./user.js";
@@ -65,16 +65,12 @@ function readSessionData(sessionToken) {
65
65
  permissions: payload.permissions
66
66
  };
67
67
  }
68
- /**
69
- * The token cookie, after a deletion of any copy from before `allowEmbedding`
70
- * changed. Both would be sent, and the old one could be read instead.
71
- */
72
68
  function makeSessionTokenCookie(token) {
73
69
  const { name, secure } = sessionCookie(SESSION_TOKEN);
74
- return [...expireOtherCopy(name, secure), serializeCookie(name, sealEnvelope(token, SESSION_TOKEN), {
70
+ return serializeCookie(name, sealEnvelope(token, SESSION_TOKEN), {
75
71
  maxAge: sessionConfig().sessionMaxAge,
76
72
  secure
77
- })];
73
+ });
78
74
  }
79
75
  function makeSessionDataCookie(session, sessionToken) {
80
76
  const { name, secure } = sessionCookie(SESSION_DATA);
@@ -145,7 +141,10 @@ const sessionDataSchema = z.object({
145
141
  */
146
142
  function clearCookies(bases) {
147
143
  const secure = requestIsSecure();
148
- writeCookies(bases.flatMap((base) => secure ? [sessionCookieName(base, secure), base] : [base]).flatMap((name) => expireCookie(name, secure)));
144
+ writeCookies(bases.flatMap((base) => secure ? [sessionCookieName(base, secure), base] : [base]).map((name) => serializeCookie(name, "", {
145
+ maxAge: 0,
146
+ secure
147
+ })));
149
148
  }
150
149
  /**
151
150
  * Over the plaintext token, never the cookie value: that is resealed with a
package/dist/cookies.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import { softAssert } from "./assertions.js";
2
- import { softrConfig } from "./softr-config.js";
3
2
  import { getRequestHeader, getResponseHeaders, setResponseHeader } from "@tanstack/react-start/server";
4
3
 
5
4
  //#region src/cookies.ts
@@ -37,33 +36,8 @@ function serializeCookie(name, value, { maxAge, secure }) {
37
36
  return parts.join("; ");
38
37
  }
39
38
  function sameSiteAttributes(secure) {
40
- return partitions(secure) ? ["SameSite=None", "Partitioned"] : ["SameSite=Lax"];
41
- }
42
- function partitions(secure) {
43
- return secure && (process.env.NODE_ENV !== "production" || (softrConfig().allowEmbedding ?? []).length > 0);
44
- }
45
- function expired(name, partitioned) {
46
- return partitioned ? `${name}=; Path=/; HttpOnly; Secure; SameSite=None; Partitioned; Max-Age=0` : `${name}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`;
47
- }
48
- /**
49
- * The deletions for one cookie. A browser keeps a partitioned and a plain
50
- * cookie of one name apart, and sends both. Which one the app wrote can change
51
- * between sign-in and sign-out, when `allowEmbedding` changes. So over https,
52
- * delete both. The one left behind would keep the visitor signed in.
53
- */
54
- function expireCookie(name, secure) {
55
- if (!secure) return [serializeCookie(name, "", {
56
- maxAge: 0,
57
- secure
58
- })];
59
- return [expired(name, false), expired(name, true)];
60
- }
61
- /**
62
- * The deletion of the copy the other mode would write. Sent with a new cookie,
63
- * so a copy from before `allowEmbedding` changed can't be read in its place.
64
- */
65
- function expireOtherCopy(name, secure) {
66
- return secure ? [expired(name, !partitions(secure))] : [];
39
+ if (secure && process.env.NODE_ENV !== "production") return ["SameSite=None", "Partitioned"];
40
+ return ["SameSite=Lax"];
67
41
  }
68
42
  const USER_TIMEZONE_COOKIE = "user-timezone";
69
43
  function readUserTimezone() {
@@ -82,4 +56,4 @@ function writeCookies(cookies) {
82
56
  }
83
57
 
84
58
  //#endregion
85
- export { expireCookie, expireOtherCopy, readRequestCookies, readUserTimezone, serializeCookie, writeCookies };
59
+ export { readRequestCookies, readUserTimezone, serializeCookie, writeCookies };
@@ -1,4 +1,4 @@
1
- import * as react0 from "react";
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): react0.JSX.Element;
11
+ }: Props): react6.JSX.Element;
12
12
  //#endregion
13
13
  export { DefaultErrorOverlay };
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import * as react3 from "react";
2
+ import * as react0 from "react";
3
3
  import { ReactNode } from "react";
4
4
 
5
5
  //#region src/formatting.d.ts
@@ -94,7 +94,7 @@ declare function FormattingScope({
94
94
  /** A BCP 47 locale, such as `de-DE`. It drops the app's fixed date format inside the scope. */
95
95
  locale?: string;
96
96
  children?: ReactNode;
97
- }): react3.FunctionComponentElement<react3.ProviderProps<Scope>>;
97
+ }): react0.FunctionComponentElement<react0.ProviderProps<Scope>>;
98
98
  /**
99
99
  * A date in the app's format, safe to render on the server. A timestamp whose
100
100
  * zone is not known yet renders `fallback` until the browser supplies it, so
@@ -115,6 +115,6 @@ declare function FormattedDate({
115
115
  time?: boolean;
116
116
  /** What renders while the visitor's zone is unknown. */
117
117
  fallback?: ReactNode;
118
- }): react3.FunctionComponentElement<react3.FragmentProps>;
118
+ }): react0.FunctionComponentElement<react0.FragmentProps>;
119
119
  //#endregion
120
120
  export { DateOptions, DateParts, DateSeparator, DateValue, FixedDateFormat, FormattedDate, Formatting, FormattingScope, WeekDay, formatDate, formatDateTime, formatNumber, useFormatting };
package/dist/index.d.ts CHANGED
@@ -16,5 +16,7 @@ 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";
19
21
  import { Audience } from "./route/audience.js";
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 };
22
+ export { type ActionPermissions, type Agent, type AgentBlock, type AgentChat, type AgentChatOptions, type AgentChatSummary, type AgentMessage, type AgentQuestion, type AgentTodo, type AgentToolCall, 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, listAgents, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAgentChat, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
package/dist/index.js CHANGED
@@ -12,6 +12,8 @@ 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";
15
17
  import { Audience } from "./route/audience.js";
16
18
 
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 };
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, listAgents, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAgentChat, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
package/dist/mcp.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { DatasourceAction } from "./action.js";
2
- import * as _tanstack_react_start6 from "@tanstack/react-start";
2
+ import * as _tanstack_react_start5 from "@tanstack/react-start";
3
3
 
4
4
  //#region src/mcp.d.ts
5
5
 
@@ -31,6 +31,6 @@ type SoftrMcpOptions = {
31
31
  * ],
32
32
  * }))
33
33
  */
34
- declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start6.RequestMiddlewareAfterServer<{}, undefined, undefined>;
34
+ declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start5.RequestMiddlewareAfterServer<{}, undefined, undefined>;
35
35
  //#endregion
36
36
  export { softrMcpMiddleware };
package/dist/mcp.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { assert } from "./assertions.js";
2
2
  import { fetch } from "./fetch.js";
3
- import { softrConfig } from "./softr-config.js";
4
3
  import { sessionConfig } from "./auth/config.js";
5
4
  import { readSessionToken, withSessionToken } from "./auth/session.js";
6
5
  import { softrApiUrl } from "./softr-api.js";
7
6
  import { isDatasourceAction } from "./action.js";
7
+ import { softrConfig } from "./softr-config.js";
8
8
  import { makePlatform } from "./auth/platform.js";
9
9
  import { ds } from "./datasource/datasource.js";
10
10
  import { z } from "zod";
@@ -385,8 +385,10 @@ 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
- if (!session.ok) return session.refused ? unauthorized(origin) : unavailable();
389
- const { sessionToken } = session;
388
+ let sessionToken;
389
+ if (session.ok) sessionToken = session.sessionToken;
390
+ else if (session.refused && await resolveUser(token) !== null) sessionToken = token;
391
+ else return session.refused ? unauthorized(origin) : unavailable();
390
392
  const body = await readJson(request);
391
393
  const message = z.object({
392
394
  id: z.union([z.string(), z.number()]).optional(),
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "0.0.87-alpha.2";
2
+ var version = "0.0.87-alpha.4";
3
3
 
4
4
  //#endregion
5
5
  export { version };
package/dist/pwa.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import * as react1 from "react";
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(): react1.FunctionComponentElement<react1.FragmentProps>;
26
+ declare function SoftrPwaHead(): react4.FunctionComponentElement<react4.FragmentProps>;
27
27
  type PwaPlatform = "ios" | "android" | "desktop";
28
28
  type PwaInstall = {
29
29
  available: false;
@@ -1,6 +1,6 @@
1
1
  import { panic } from "../assertions.js";
2
- import { softrConfig } from "../softr-config.js";
3
2
  import { ACCESS_REASONS, checkRule } from "./visibility.js";
3
+ import { softrConfig } from "../softr-config.js";
4
4
  import { redirect } from "@tanstack/react-router";
5
5
 
6
6
  //#region src/route/route.ts
@@ -21,7 +21,6 @@ const AccessBehaviour = z.union([
21
21
  z.object({ strategy: z.literal("throw") })
22
22
  ], { error: "must be a path like \"/login\", { \"strategy\": \"redirect\", \"to\": \"/login\" } or { \"strategy\": \"throw\" }" });
23
23
  const AppPath = z.string().refine((path$1) => path$1.startsWith("/") && !path$1.includes("?") && !path$1.includes("#") && new URL(path$1, "https://app.invalid").origin === "https://app.invalid", { error: "must be a path on this app like \"/login\", with no \"?\" or \"#\"" });
24
- const Origin = z.string().refine((origin) => origin === "*" || URL.canParse(origin) && new URL(origin).origin === origin && origin.startsWith("https://"), { error: "must be an https origin like \"https://partner.com\", with no path or trailing \"/\", or \"*\" for any site" });
25
24
  const SoftrConfigSchema = z.object({
26
25
  auth: z.strictObject({
27
26
  routes: z.strictObject({
@@ -48,8 +47,7 @@ const SoftrConfigSchema = z.object({
48
47
  alreadyAuthenticated: AccessBehaviour
49
48
  })
50
49
  }),
51
- user: z.strictObject({ properties: z.record(z.string(), z.string()) }).optional(),
52
- allowEmbedding: z.array(Origin).optional()
50
+ user: z.strictObject({ properties: z.record(z.string(), z.string()) }).optional()
53
51
  });
54
52
  function loadSoftrConfig(root) {
55
53
  const file = path.join(root, SOFTR_CONFIG_FILE);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "0.0.87-alpha.2",
3
+ "version": "0.0.87-alpha.4",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
@@ -67,11 +67,6 @@
67
67
  },
68
68
  "required": ["properties"],
69
69
  "additionalProperties": false
70
- },
71
- "allowEmbedding": {
72
- "type": "array",
73
- "description": "Sites that may show the published app in an iframe, signed-in pages included, as https origins like \"https://partner.com\", or \"*\" for any site. Any other site is still blocked. With at least one, session cookies use SameSite=None, which drops the browser's CSRF protection. Empty by default.",
74
- "items": { "type": "string", "pattern": "^(\\*|https://[^/?#]+)$" }
75
70
  }
76
71
  },
77
72
  "required": ["auth"],
@@ -3,13 +3,12 @@ name: softr-sdk
3
3
  description: >-
4
4
  Entry point for @softr/sdk: its four entrypoints (@softr/sdk, /server,
5
5
  /client, /vite) and their client-server boundary, softrAuthMiddleware and the
6
- Softr context, embedding the app in another site's iframe, and which sub-skill
7
- covers each task. Load it when unsure which sub-skill applies, when touching
8
- the wiring, or when the user wants the app embedded elsewhere.
6
+ Softr context, and which sub-skill covers each task. Load it when unsure which
7
+ sub-skill applies, or when touching the wiring.
9
8
  metadata:
10
9
  type: core
11
10
  library: softr-sdk
12
- library_version: 0.0.87-alpha.2
11
+ library_version: 0.0.87-alpha.4
13
12
  ---
14
13
 
15
14
  # Softr SDK core
@@ -49,6 +48,7 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
49
48
  | Sign a visitor in, out, or up | [auth/SKILL.md](./auth/SKILL.md) |
50
49
  | Call a connected third-party API (Slack, Stripe, Gmail, …) | [integrations/SKILL.md](./integrations/SKILL.md) |
51
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
52
  | Let visitors install the app on their home screen | [pwa/SKILL.md](./pwa/SKILL.md) |
53
53
  | Show a date, a time or a number | [formatting/SKILL.md](./formatting/SKILL.md) |
54
54
 
@@ -85,6 +85,9 @@ Calling a connected third-party API (Slack, Stripe, Gmail, Google Calendar, …)
85
85
  Opening the app to an AI assistant over MCP?
86
86
  load softr-sdk/mcp
87
87
 
88
+ Adding a chat with one of the app's Softr agents?
89
+ load softr-sdk/agent-chat
90
+
88
91
  Adding an install button, or making the app installable?
89
92
  load softr-sdk/pwa
90
93
 
@@ -149,7 +152,3 @@ type User = {
149
152
  userGroupIds: Array<SoftrUserGroupId> // the app's own group ids
150
153
  }
151
154
  ```
152
-
153
- ## Embedding the app in another site
154
-
155
- The published app refuses to load inside another site's iframe. The Studio preview is not affected. When the user asks to embed the app on their site, list that site's origin in `softr.json`: `"allowEmbedding": ["https://partner.com"]`. Ask for the exact origin if you don't have it. Only listed sites can embed the app. Use `["*"]` only when the user wants any site to embed it. Remove the list to block embedding again. Sign-in then works inside the embed. Session cookies switch from SameSite=Lax to None, so the app loses the browser's CSRF protection. Only set it when the user asks. There are two more limits to tell the user: Safari may not keep the visitor signed in, and links from emails (magic link, password reset) open the app in a new tab, not in the embed.
@@ -0,0 +1,105 @@
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.4
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
+ - `error`: why the last request failed, or `null`.
62
+ - `send(text)`, `stop()`, `newChat()`.
63
+ - `listChats()` resolves to the visitor's past chats, `{ id, title }[]`. `openChat(id)` loads one. `chatId` is the open one, `null` for a new chat.
64
+ - `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.
65
+
66
+ ## Rendering a message
67
+
68
+ Each message has `role` (`user` or `assistant`) and `blocks`, in the order the agent produced them. Render every block type:
69
+
70
+ | Block | Show it as |
71
+ | --- | --- |
72
+ | `text` | Markdown text |
73
+ | `tool` | One line: the tool `name` and its `status`. Collapse finished ones. |
74
+ | `todo` | A checklist of the agent's plan. It updates in place. |
75
+ | `question` | The questions with their options. A click on an option sends its label with `send`. |
76
+ | `error` | An error line inside the reply |
77
+
78
+ 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.
79
+
80
+ 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.
81
+
82
+ ## Context
83
+
84
+ `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.
85
+
86
+ The page title goes along on its own. Nothing else about the page does, so don't try to send whole lists.
87
+
88
+ ## Letting the agent act on the app
89
+
90
+ 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.
91
+
92
+ ## Failure modes
93
+
94
+ **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`.
95
+
96
+ **Rendering only `text` blocks.** A tool waiting for approval never shows, and the agent waits forever. Render every block type.
97
+
98
+ **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`.
99
+
100
+ **Expecting the agent to change data with no MCP wired.** It answers but can't act. List the actions it needs in `softrMcpMiddleware`.
101
+
102
+ ## References
103
+
104
+ - [mcp/SKILL.md](../mcp/SKILL.md): the actions the agent may call
105
+ - [current-user/SKILL.md](../current-user/SKILL.md): showing the chat to signed-in visitors only
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.87-alpha.2
12
+ library_version: 0.0.87-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.87-alpha.2
12
+ library_version: 0.0.87-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.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.87-alpha.2
12
+ library_version: 0.0.87-alpha.4
13
13
  ---
14
14
 
15
15
  # The current user
@@ -7,7 +7,7 @@ description: >-
7
7
  metadata:
8
8
  type: sub-skill
9
9
  library: softr-sdk
10
- library_version: 0.0.87-alpha.2
10
+ library_version: 0.0.87-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.
@@ -8,7 +8,7 @@ description: >-
8
8
  metadata:
9
9
  type: sub-skill
10
10
  library: softr-sdk
11
- library_version: 0.0.87-alpha.2
11
+ library_version: 0.0.87-alpha.4
12
12
  ---
13
13
 
14
14
  # Dates, times and numbers
@@ -7,7 +7,7 @@ description: >-
7
7
  metadata:
8
8
  type: sub-skill
9
9
  library: softr-sdk
10
- library_version: 0.0.87-alpha.2
10
+ library_version: 0.0.87-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.87-alpha.2
12
+ library_version: 0.0.87-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.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.87-alpha.2
12
+ library_version: 0.0.87-alpha.4
13
13
  ---
14
14
 
15
15
  # Installing the app
@@ -8,7 +8,7 @@ description: >-
8
8
  metadata:
9
9
  type: sub-skill
10
10
  library: softr-sdk
11
- library_version: 0.0.87-alpha.2
11
+ library_version: 0.0.87-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.