@softr/sdk 0.0.90-alpha.3 → 0.0.90-alpha.5

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.
@@ -0,0 +1,77 @@
1
+ import { version } from "./package.js";
2
+ import { assert } from "./assertions.js";
3
+ import { createMiddleware } from "@tanstack/react-start";
4
+ import * as startServer from "@tanstack/react-start/server";
5
+
6
+ //#region src/app-identity.ts
7
+ const HTML_TAG = new TextEncoder().encode("<html");
8
+ const HTML_TAG_SEARCH_LIMIT = 1024;
9
+ /**
10
+ * Marks every HTML page with the Softr app it belongs to and the SDK version it
11
+ * runs on, so support can read both from the page source.
12
+ *
13
+ * They go on `<html>` as `data-appid` and `data-sdk-version`, and
14
+ * in a comment just before it. React keeps the attributes when it hydrates, but
15
+ * drops them if it ever renders the document again on the client. The comment
16
+ * sits outside what React owns, so it always stays.
17
+ */
18
+ function appIdentityMiddleware() {
19
+ return createMiddleware({ type: "request" }).server(async ({ next }) => {
20
+ const result = await next();
21
+ const { response } = result;
22
+ if (!response.body || !response.headers.get("content-type")?.startsWith("text/html")) return result;
23
+ const applicationId = process.env.SOFTR_APPLICATION_ID;
24
+ if (!applicationId) return result;
25
+ assert(/^[\w-]+$/.test(applicationId), `SOFTR_APPLICATION_ID is not an id: "${applicationId}"`);
26
+ const encoder = new TextEncoder();
27
+ const comment = encoder.encode(`<!-- Softr app ${applicationId}, @softr/sdk ${version} -->`);
28
+ const attributes = encoder.encode(` data-appid="${applicationId}" data-sdk-version="${version}"`);
29
+ let held = new Uint8Array(0);
30
+ let done = false;
31
+ const body = response.body.pipeThrough(new TransformStream({
32
+ transform(chunk, controller) {
33
+ if (done) {
34
+ controller.enqueue(chunk);
35
+ return;
36
+ }
37
+ const bytes = new Uint8Array(held.length + chunk.length);
38
+ bytes.set(held);
39
+ bytes.set(chunk, held.length);
40
+ let at = -1;
41
+ search: for (let i = 0; i + HTML_TAG.length < bytes.length; i++) {
42
+ for (let j = 0; j < HTML_TAG.length; j++) if (bytes[i + j] !== HTML_TAG[j]) continue search;
43
+ const after = bytes[i + HTML_TAG.length];
44
+ if (after === 32 || after === 62) {
45
+ at = i;
46
+ break;
47
+ }
48
+ }
49
+ if (at === -1) {
50
+ if (bytes.length > HTML_TAG_SEARCH_LIMIT) {
51
+ done = true;
52
+ controller.enqueue(bytes);
53
+ return;
54
+ }
55
+ held = bytes;
56
+ return;
57
+ }
58
+ done = true;
59
+ const end = at + HTML_TAG.length;
60
+ controller.enqueue(bytes.subarray(0, at));
61
+ controller.enqueue(comment);
62
+ controller.enqueue(bytes.subarray(at, end));
63
+ controller.enqueue(attributes);
64
+ controller.enqueue(bytes.subarray(end));
65
+ },
66
+ flush(controller) {
67
+ if (!done) controller.enqueue(held);
68
+ }
69
+ }));
70
+ const marked = new Response(body, response);
71
+ marked.headers.delete("content-length");
72
+ return "transferResponseBodyOwnership" in startServer ? startServer.transferResponseBodyOwnership(response, marked) : marked;
73
+ });
74
+ }
75
+
76
+ //#endregion
77
+ 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;
@@ -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,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import * as react0 from "react";
2
+ import * as react2 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
- }): react0.FunctionComponentElement<react0.ProviderProps<Scope>>;
97
+ }): react2.FunctionComponentElement<react2.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
- }): react0.FunctionComponentElement<react0.FragmentProps>;
118
+ }): react2.FunctionComponentElement<react2.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,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, 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 };
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, listAgents, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAgentChat, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
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
- let sessionToken;
391
- if (session.ok) sessionToken = session.sessionToken;
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
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "0.0.90-alpha.3";
2
+ var version = "0.0.90-alpha.5";
3
3
 
4
4
  //#endregion
5
5
  export { version };
package/dist/pwa.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import * as react4 from "react";
1
+ import * as react0 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(): react4.FunctionComponentElement<react4.FragmentProps>;
26
+ declare function SoftrPwaHead(): react0.FunctionComponentElement<react0.FragmentProps>;
27
27
  type PwaPlatform = "ios" | "android" | "desktop";
28
28
  type PwaInstall = {
29
29
  available: false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "0.0.90-alpha.3",
3
+ "version": "0.0.90-alpha.5",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
@@ -21,8 +21,8 @@
21
21
  },
22
22
  "devDependencies": {
23
23
  "@tanstack/intent": "^0.3.6",
24
- "@tanstack/react-router": "^1.168.0",
25
- "@tanstack/react-start": "^1.168.0",
24
+ "@tanstack/react-router": "^1.170.41",
25
+ "@tanstack/react-start": "^1.168.60",
26
26
  "@types/node": "^24.3.0",
27
27
  "tsdown": "^0.15.0",
28
28
  "typescript": "^5.9.2",
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: core
11
11
  library: softr-sdk
12
- library_version: 0.0.90-alpha.3
12
+ library_version: 0.0.90-alpha.5
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.3
12
+ library_version: 0.0.90-alpha.5
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.3
12
+ library_version: 0.0.90-alpha.5
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.90-alpha.3
12
+ library_version: 0.0.90-alpha.5
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.90-alpha.3
10
+ library_version: 0.0.90-alpha.5
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.90-alpha.3
11
+ library_version: 0.0.90-alpha.5
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.90-alpha.3
10
+ library_version: 0.0.90-alpha.5
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.3
12
+ library_version: 0.0.90-alpha.5
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.90-alpha.3
12
+ library_version: 0.0.90-alpha.5
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.90-alpha.3
11
+ library_version: 0.0.90-alpha.5
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.3
12
+ library_version: 0.0.90-alpha.5
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.3
12
+ library_version: 0.0.90-alpha.5
13
13
  ---
14
14
 
15
15
  **Boundary.** `Audience` and `defineVisibility` 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.3
12
+ library_version: 0.0.90-alpha.5
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.3
12
+ library_version: 0.0.90-alpha.5
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 };
@@ -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 };