@softr/sdk 0.0.89-alpha.0 → 0.0.89-alpha.2

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.
@@ -167,6 +167,49 @@ const decideAgentToolFn = createServerFn({ method: "POST" }).validator(z.object(
167
167
  if (!res.ok) throw new Error(`Saving the answer failed: ${await describeFailure(res)}`);
168
168
  return true;
169
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
+ });
170
213
 
171
214
  //#endregion
172
- export { agentChatFn, decideAgentToolFn, listAgentChatsFn, listAgents, loadAgentChatFn };
215
+ export { agentChatFn, awaitAgentConnectionFn, decideAgentToolFn, finishAgentConnectionFn, listAgentChatsFn, listAgents, loadAgentChatFn, startAgentConnectionFn };
@@ -10,9 +10,10 @@ type AgentToolCall = {
10
10
  input?: string;
11
11
  /**
12
12
  * `awaiting-approval` waits for `approve` or `reject`. `awaiting-connection`
13
- * needs the visitor to connect `integration` first, which code apps can't do yet.
13
+ * waits for the visitor to `connect` their own `integration` account, and is
14
+ * `connecting` while they sign in.
14
15
  */
15
- status: "running" | "done" | "failed" | "awaiting-approval" | "approved" | "rejected" | "awaiting-connection";
16
+ status: "running" | "done" | "failed" | "awaiting-approval" | "approved" | "rejected" | "awaiting-connection" | "connecting";
16
17
  error?: string;
17
18
  integration?: string;
18
19
  /** Why the agent calls it, in its own words. */
@@ -76,6 +77,8 @@ type AgentChat = {
76
77
  /** Lets a tool waiting for approval run, once, for this chat, or always for this visitor. */
77
78
  approve: (toolCallId: string, scope?: "ONCE" | "SESSION" | "USER") => void;
78
79
  reject: (toolCallId: string) => void;
80
+ /** Opens the sign-in for a tool's `integration` in a popup. Call it from a click, or the browser blocks the popup. */
81
+ connect: (toolCallId: string) => void;
79
82
  };
80
83
  type AgentChatOptions = {
81
84
  /**
@@ -1,6 +1,6 @@
1
1
  import { assert } from "../assertions.js";
2
2
  import { useCurrentUser } from "../auth/isomorphic.js";
3
- import { agentChatFn, decideAgentToolFn, listAgentChatsFn, loadAgentChatFn } from "./agent-fns.js";
3
+ import { agentChatFn, awaitAgentConnectionFn, decideAgentToolFn, finishAgentConnectionFn, listAgentChatsFn, loadAgentChatFn, startAgentConnectionFn } from "./agent-fns.js";
4
4
  import { useCallback, useEffect, useRef, useState } from "react";
5
5
 
6
6
  //#region src/agent/use-agent-chat.ts
@@ -213,6 +213,54 @@ function useAgentChat(agentId, options = {}) {
213
213
  ]);
214
214
  const approve = useCallback((toolCallId, scope = "ONCE") => decide(toolCallId, "APPROVE", scope), [decide]);
215
215
  const reject = useCallback((toolCallId) => decide(toolCallId, "REJECT", "ONCE"), [decide]);
216
+ const connect = useCallback((toolCallId) => {
217
+ const sessionId = chatIdRef.current;
218
+ const tool = [...messages.flatMap((m) => m.blocks), ...liveRef.current ?? []].find((b) => b.type === "tool" && b.id === toolCallId);
219
+ if (sessionId === null || tool?.status !== "awaiting-connection" || !tool.integration) return;
220
+ const popup = window.open("", "softr-agent-connect", popupFeatures(500, 600));
221
+ if (!popup) {
222
+ setError(/* @__PURE__ */ new Error("Allow pop-ups for this site to connect your account."));
223
+ return;
224
+ }
225
+ setToolStatus(toolCallId, "connecting");
226
+ const connection = {
227
+ integration: tool.integration,
228
+ requestId: crypto.randomUUID()
229
+ };
230
+ const deadline = Date.now() + CONNECT_TIMEOUT_MS;
231
+ (async () => {
232
+ popup.location.href = await startAgentConnectionFn({ data: connection });
233
+ while (!await awaitAgentConnectionFn({ data: connection })) {
234
+ if (Date.now() > deadline) throw new Error("Connecting took too long. Try again.");
235
+ await new Promise((resolve) => setTimeout(resolve, CONNECT_RETRY_MS));
236
+ }
237
+ popup.close();
238
+ if (!await finishAgentConnectionFn({ data: {
239
+ agentId,
240
+ sessionId,
241
+ toolCallId
242
+ } })) {
243
+ reset(null);
244
+ setError(new Error(CHAT_GONE_MESSAGE));
245
+ return;
246
+ }
247
+ setToolStatus(toolCallId, "approved");
248
+ abortRef.current?.abort();
249
+ commitLive(liveRef.current);
250
+ stream("");
251
+ })().catch((err) => {
252
+ popup.close();
253
+ setToolStatus(toolCallId, "awaiting-connection");
254
+ setError(err instanceof Error ? err : new Error(String(err)));
255
+ });
256
+ }, [
257
+ agentId,
258
+ messages,
259
+ setToolStatus,
260
+ commitLive,
261
+ stream,
262
+ reset
263
+ ]);
216
264
  return {
217
265
  messages: live === null ? messages : [...messages, {
218
266
  id: "live",
@@ -229,9 +277,15 @@ function useAgentChat(agentId, options = {}) {
229
277
  openChat,
230
278
  listChats,
231
279
  approve,
232
- reject
280
+ reject,
281
+ connect
233
282
  };
234
283
  }
284
+ const CONNECT_TIMEOUT_MS = 5 * 6e4;
285
+ const CONNECT_RETRY_MS = 3e3;
286
+ function popupFeatures(width, height) {
287
+ return `width=${width},height=${height},left=${window.screenX + (window.innerWidth - width) / 2},top=${window.screenY + (window.innerHeight - height) / 2}`;
288
+ }
235
289
  const TODO_TOOL = "TodoWrite";
236
290
  /** Its question shows as a question block, so the call itself is noise. */
237
291
  const QUESTION_TOOL = "AskUserQuestion";
@@ -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/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_start0 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_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>;
35
35
  //#endregion
36
36
  export { softrMcpMiddleware };
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "0.0.89-alpha.0";
2
+ var version = "0.0.89-alpha.2";
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.89-alpha.0",
3
+ "version": "0.0.89-alpha.2",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: core
11
11
  library: softr-sdk
12
- library_version: 0.0.89-alpha.0
12
+ library_version: 0.0.89-alpha.2
13
13
  ---
14
14
 
15
15
  # Softr SDK core
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 0.0.89-alpha.0
13
+ library_version: 0.0.89-alpha.2
14
14
  ---
15
15
 
16
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.
@@ -63,6 +63,7 @@ function AgentPanel({ agentId, ticket }: { agentId: string; ticket: Ticket | nul
63
63
  - `send(text)`, `stop()`, `newChat()`.
64
64
  - `listChats()` resolves to the visitor's past chats, `{ id, title }[]`, with `title` `null` until the agent names the chat. `openChat(id)` loads one. `chatId` is the open one, `null` for a new chat. The open chat is kept in the browser for each visitor, so the hook reopens it after a remount or a reload.
65
65
  - `approve(toolCallId, scope?)` and `reject(toolCallId)` answer a tool waiting for approval. `scope` is `ONCE` (default), `SESSION` for the rest of this chat, or `USER` for always.
66
+ - `connect(toolCallId)` signs the visitor in to a tool's `integration` in a popup. Call it straight from the click, or the browser blocks the popup.
66
67
 
67
68
  ## Rendering a message
68
69
 
@@ -78,7 +79,7 @@ Each message has `role` (`user` or `assistant`) and `blocks`, in the order the a
78
79
 
79
80
  A `tool` with status `awaiting-approval` blocks the agent until the visitor answers. Show Approve and Reject buttons on it. The agent continues on its own after an approval.
80
81
 
81
- A `tool` with status `awaiting-connection` needs the visitor to connect the `integration` first. Code apps can't do that yet. Say which integration the agent needs, and that the builder has to connect it for this agent in Studio.
82
+ A `tool` with status `awaiting-connection` needs the visitor's own `integration` account, such as their Gmail. Say "You need to connect to {integration} for this request. You'll only need to connect once.", with the name in readable case, and show a Connect button that calls `connect`. While it's `connecting`, show "Connecting…" and disable the button. The agent continues on its own once they're signed in. Any integration works the same way, so don't build one per integration.
82
83
 
83
84
  ## The chat panel
84
85
 
@@ -93,6 +94,8 @@ Classic Softr apps ship a chat panel. Visitors expect the same from yours:
93
94
  - A line under the input: "AI can make mistakes. Please double-check responses."
94
95
  - A question with one choice sends on click. One with `multiSelect` or several questions sends once all are answered. An answered question stays locked.
95
96
  - Approve offers the three scopes: once, for this chat, always for this agent.
97
+ - A tool's `input` is JSON. Show it readable: one `Label: value` line per field, with line breaks kept, never the raw JSON. Leave out `thought`, `input`, `error` or the duration when it's empty.
98
+ - A tool that needs the visitor's account shows a Connect button.
96
99
 
97
100
  ## Context
98
101
 
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.89-alpha.0
12
+ library_version: 0.0.89-alpha.2
13
13
  ---
14
14
 
15
15
  **Boundary.** `auth` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.89-alpha.0
12
+ library_version: 0.0.89-alpha.2
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.89-alpha.0
12
+ library_version: 0.0.89-alpha.2
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.89-alpha.0
10
+ library_version: 0.0.89-alpha.2
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.89-alpha.0
11
+ library_version: 0.0.89-alpha.2
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.89-alpha.0
10
+ library_version: 0.0.89-alpha.2
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.89-alpha.0
12
+ library_version: 0.0.89-alpha.2
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.89-alpha.0
12
+ library_version: 0.0.89-alpha.2
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.89-alpha.0
11
+ library_version: 0.0.89-alpha.2
12
12
  ---
13
13
 
14
14
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineMutation` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.89-alpha.0
12
+ library_version: 0.0.89-alpha.2
13
13
  ---
14
14
 
15
15
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler or a server-side route hook — importing it into a component fails the build. The same holds for any helper that calls `ds`: declare it inside the handler. A function at module level that calls `ds` keeps the server-only import in the browser bundle, and every page stops loading until it moves. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.89-alpha.0
12
+ library_version: 0.0.89-alpha.2
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.89-alpha.0
12
+ library_version: 0.0.89-alpha.2
13
13
  ---
14
14
 
15
15
  **Boundary.** `definePage`, `pageHead`, the access functions and the error predicates come from `@softr/sdk` and work anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.89-alpha.0
12
+ library_version: 0.0.89-alpha.2
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.