@softr/sdk 0.0.90-alpha.4 → 0.0.90-alpha.6

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,30 @@
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 };
@@ -0,0 +1,215 @@
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 };
@@ -0,0 +1,106 @@
1
+ import { AgentChatSummary } from "./agent-fns.js";
2
+
3
+ //#region src/agent/use-agent-chat.d.ts
4
+ /** A step of the agent's work: a tool it calls, and where that call stands. */
5
+ type AgentToolCall = {
6
+ type: "tool";
7
+ id: string;
8
+ name: string;
9
+ /** The tool's input as the agent sent it, usually JSON. */
10
+ input?: string;
11
+ /**
12
+ * `awaiting-approval` waits for `approve` or `reject`. `awaiting-connection`
13
+ * waits for the visitor to `connect` their own `integration` account, and is
14
+ * `connecting` while they sign in.
15
+ */
16
+ status: "running" | "done" | "failed" | "awaiting-approval" | "approved" | "rejected" | "awaiting-connection" | "connecting";
17
+ error?: string;
18
+ integration?: string;
19
+ /** Why the agent calls it, in its own words. */
20
+ thought?: string;
21
+ /** How long a finished call took. */
22
+ durationMs?: number;
23
+ };
24
+ type AgentTodo = {
25
+ content: string;
26
+ status: "pending" | "in_progress" | "completed";
27
+ };
28
+ type AgentQuestion = {
29
+ question: string;
30
+ header: string;
31
+ options: Array<{
32
+ label: string;
33
+ description: string;
34
+ }>;
35
+ multiSelect: boolean;
36
+ };
37
+ /**
38
+ * One piece of a message, in the order the agent produced it. A tool waiting for
39
+ * the visitor comes last, below the text that asks for it, until they answer.
40
+ */
41
+ type AgentBlock = {
42
+ type: "text";
43
+ text: string;
44
+ } | AgentToolCall
45
+ /** The agent's plan. It replaces itself as the agent works through it. */ | {
46
+ type: "todo";
47
+ todos: AgentTodo[];
48
+ }
49
+ /** The agent asks the visitor to pick. They answer by sending a message. */ | {
50
+ type: "question";
51
+ questions: AgentQuestion[];
52
+ } | {
53
+ type: "error";
54
+ message: string;
55
+ };
56
+ type AgentMessage = {
57
+ id: string;
58
+ role: "user" | "assistant";
59
+ blocks: AgentBlock[];
60
+ };
61
+ type AgentChat = {
62
+ /** The whole chat, oldest first. While the agent replies, its reply is the last one and grows. */
63
+ messages: AgentMessage[];
64
+ /** `thinking` until the first part of the reply arrives, `replying` until it ends. */
65
+ status: "idle" | "thinking" | "replying";
66
+ /** True while a past chat loads, including the one reopened on mount. */
67
+ loading: boolean;
68
+ /** Why the last request failed. Cleared by the next one. */
69
+ error: Error | null;
70
+ /** The chat the next message goes to, `null` for a new one. */
71
+ chatId: string | null;
72
+ send: (text: string) => void;
73
+ /** Stops the reply. What arrived so far stays. */
74
+ stop: () => void;
75
+ newChat: () => void;
76
+ /** Opens a past chat from `listChats`. */
77
+ openChat: (chatId: string) => void;
78
+ /** The visitor's past chats with this agent. */
79
+ listChats: () => Promise<AgentChatSummary[]>;
80
+ /** Lets a tool waiting for approval run: once, for the rest of this chat, or for this agent from now on. */
81
+ approve: (toolCallId: string, scope?: "ONCE" | "SESSION" | "USER") => void;
82
+ reject: (toolCallId: string) => void;
83
+ /** Opens the sign-in for a tool's `integration` in a popup. Call it from a click, or the browser blocks the popup. */
84
+ connect: (toolCallId: string) => void;
85
+ };
86
+ type AgentChatOptions = {
87
+ /**
88
+ * The record the visitor is looking at, so they can say "this one". Sent
89
+ * with each message. Keys are what the agent reads, so use field names.
90
+ */
91
+ record?: {
92
+ id: string;
93
+ fields: Record<string, unknown>;
94
+ } | null;
95
+ };
96
+ /**
97
+ * A chat with one of the app's Softr agents, as the signed-in visitor. No UI:
98
+ * render `messages` with the app's own components.
99
+ *
100
+ * @example
101
+ * const chat = useAgentChat(AGENT_ID, { record: ticket && { id: ticket.id, fields: ticket.fields } })
102
+ * <form onSubmit={(e) => { e.preventDefault(); chat.send(draft) }}>
103
+ */
104
+ declare function useAgentChat(agentId: string, options?: AgentChatOptions): AgentChat;
105
+ //#endregion
106
+ export { AgentBlock, AgentChat, AgentChatOptions, AgentMessage, AgentQuestion, AgentTodo, AgentToolCall, useAgentChat };
@@ -0,0 +1,486 @@
1
+ import { assert } from "../assertions.js";
2
+ import { useCurrentUser } from "../auth/isomorphic.js";
3
+ import { agentChatFn, awaitAgentConnectionFn, decideAgentToolFn, finishAgentConnectionFn, listAgentChatsFn, loadAgentChatFn, startAgentConnectionFn } from "./agent-fns.js";
4
+ import { useCallback, useEffect, useRef, useState } from "react";
5
+
6
+ //#region src/agent/use-agent-chat.ts
7
+ /**
8
+ * A chat with one of the app's Softr agents, as the signed-in visitor. No UI:
9
+ * render `messages` with the app's own components.
10
+ *
11
+ * @example
12
+ * const chat = useAgentChat(AGENT_ID, { record: ticket && { id: ticket.id, fields: ticket.fields } })
13
+ * <form onSubmit={(e) => { e.preventDefault(); chat.send(draft) }}>
14
+ */
15
+ function useAgentChat(agentId, options = {}) {
16
+ const [messages, setMessages] = useState([]);
17
+ const [live, setLive] = useState(null);
18
+ const [status, setStatus] = useState("idle");
19
+ const [loading, setLoading] = useState(false);
20
+ const [error, setError] = useState(null);
21
+ const [chatId, setChatId] = useState(null);
22
+ const storeKey = chatKey(agentId, useCurrentUser()?.id ?? null);
23
+ const chatIdRef = useRef(chatId);
24
+ chatIdRef.current = chatId;
25
+ const recordRef = useRef(options.record ?? null);
26
+ recordRef.current = options.record ?? null;
27
+ const liveRef = useRef(live);
28
+ liveRef.current = live;
29
+ const abortRef = useRef(null);
30
+ useEffect(() => () => abortRef.current?.abort(), []);
31
+ const commitLive = useCallback((blocks) => {
32
+ setLive(null);
33
+ if (!blocks?.some((b) => b.type !== "text" || b.text.trim())) return;
34
+ setMessages((prev) => [...prev, {
35
+ id: crypto.randomUUID(),
36
+ role: "assistant",
37
+ blocks: endRunningTools(blocks)
38
+ }]);
39
+ }, []);
40
+ const stream = useCallback(async (message) => {
41
+ abortRef.current?.abort();
42
+ const controller = new AbortController();
43
+ abortRef.current = controller;
44
+ setError(null);
45
+ setStatus("thinking");
46
+ let blocks = [];
47
+ try {
48
+ const request = {
49
+ agentId,
50
+ message,
51
+ sessionId: chatIdRef.current,
52
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
53
+ pageName: document.title,
54
+ pageUrl: location.href,
55
+ record: recordRef.current
56
+ };
57
+ const form = new FormData();
58
+ form.append("payload", JSON.stringify(request));
59
+ const res = await fetch(agentChatFn.url, {
60
+ method: "POST",
61
+ body: form,
62
+ signal: controller.signal
63
+ });
64
+ if (!res.ok) throw new Error(await failureMessage(res));
65
+ assert(res.body, "agent chat: the reply has no body");
66
+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
67
+ let buffer = "";
68
+ const onLine = (line) => {
69
+ const event = parseEvent(line);
70
+ if (event === null) return;
71
+ if (event.sessionId && event.sessionId !== chatIdRef.current) {
72
+ chatIdRef.current = event.sessionId;
73
+ setChatId(event.sessionId);
74
+ saveChatId(storeKey, event.sessionId);
75
+ }
76
+ blocks = reduceEvent(blocks, event);
77
+ setLive(blocks);
78
+ setStatus("replying");
79
+ };
80
+ for (;;) {
81
+ const { done, value } = await reader.read();
82
+ if (done) break;
83
+ buffer += value;
84
+ const lines = buffer.split("\n");
85
+ buffer = lines.pop() ?? "";
86
+ lines.forEach(onLine);
87
+ }
88
+ onLine(buffer);
89
+ } catch (err) {
90
+ if (controller.signal.aborted) return;
91
+ setError(err instanceof Error ? err : new Error(String(err)));
92
+ }
93
+ if (abortRef.current !== controller) return;
94
+ abortRef.current = null;
95
+ commitLive(blocks);
96
+ setStatus("idle");
97
+ }, [
98
+ agentId,
99
+ storeKey,
100
+ commitLive
101
+ ]);
102
+ const send = useCallback((text) => {
103
+ const trimmed = text.trim();
104
+ if (!trimmed) return;
105
+ abortRef.current?.abort();
106
+ commitLive(liveRef.current);
107
+ setMessages((prev) => [...prev, {
108
+ id: crypto.randomUUID(),
109
+ role: "user",
110
+ blocks: [{
111
+ type: "text",
112
+ text: trimmed
113
+ }]
114
+ }]);
115
+ stream(trimmed);
116
+ }, [stream, commitLive]);
117
+ const stop = useCallback(() => {
118
+ if (abortRef.current === null) return;
119
+ abortRef.current.abort();
120
+ abortRef.current = null;
121
+ commitLive(liveRef.current);
122
+ setStatus("idle");
123
+ }, [commitLive]);
124
+ const reset = useCallback((id) => {
125
+ abortRef.current?.abort();
126
+ abortRef.current = null;
127
+ chatIdRef.current = id;
128
+ setChatId(id);
129
+ saveChatId(storeKey, id);
130
+ setMessages([]);
131
+ setLive(null);
132
+ setStatus("idle");
133
+ setLoading(false);
134
+ setError(null);
135
+ }, [storeKey]);
136
+ const newChat = useCallback(() => reset(null), [reset]);
137
+ const load = useCallback((id, restoring) => {
138
+ reset(id);
139
+ setLoading(true);
140
+ loadAgentChatFn({ data: {
141
+ agentId,
142
+ sessionId: id
143
+ } }).then((history) => {
144
+ if (chatIdRef.current !== id) return;
145
+ if (history === null) {
146
+ reset(null);
147
+ if (!restoring) setError(new Error(CHAT_GONE_MESSAGE));
148
+ return;
149
+ }
150
+ setLoading(false);
151
+ setMessages(fromHistory(history));
152
+ }).catch((err) => {
153
+ if (chatIdRef.current !== id) return;
154
+ setLoading(false);
155
+ setError(err instanceof Error ? err : new Error(String(err)));
156
+ });
157
+ }, [agentId, reset]);
158
+ const openChat = useCallback((id) => load(id, false), [load]);
159
+ useEffect(() => {
160
+ const saved = savedChatId(storeKey);
161
+ if (saved) load(saved, true);
162
+ else newChat();
163
+ }, [
164
+ storeKey,
165
+ load,
166
+ newChat
167
+ ]);
168
+ const listChats = useCallback(() => listAgentChatsFn({ data: { agentId } }), [agentId]);
169
+ const setToolStatus = useCallback((toolCallId, next) => {
170
+ const update = (blocks) => blocks.map((b) => b.type === "tool" && b.id === toolCallId ? {
171
+ ...b,
172
+ status: next
173
+ } : b);
174
+ setLive((prev) => prev && update(prev));
175
+ setMessages((prev) => prev.map((m) => ({
176
+ ...m,
177
+ blocks: update(m.blocks)
178
+ })));
179
+ }, []);
180
+ const decide = useCallback((toolCallId, decision, scope) => {
181
+ const sessionId = chatIdRef.current;
182
+ const tool = [...messages.flatMap((m) => m.blocks), ...liveRef.current ?? []].find((b) => b.type === "tool" && b.id === toolCallId);
183
+ if (sessionId === null || tool?.status !== "awaiting-approval") return;
184
+ setToolStatus(toolCallId, decision === "APPROVE" ? "approved" : "rejected");
185
+ decideAgentToolFn({ data: {
186
+ agentId,
187
+ sessionId,
188
+ toolCallId,
189
+ toolName: tool.name,
190
+ decision,
191
+ scope
192
+ } }).then((saved) => {
193
+ if (!saved) {
194
+ reset(null);
195
+ setError(new Error(CHAT_GONE_MESSAGE));
196
+ return;
197
+ }
198
+ if (decision !== "APPROVE") return;
199
+ abortRef.current?.abort();
200
+ commitLive(liveRef.current);
201
+ stream("");
202
+ }).catch((err) => {
203
+ setToolStatus(toolCallId, "awaiting-approval");
204
+ setError(err instanceof Error ? err : new Error(String(err)));
205
+ });
206
+ }, [
207
+ agentId,
208
+ messages,
209
+ setToolStatus,
210
+ commitLive,
211
+ stream,
212
+ reset
213
+ ]);
214
+ const approve = useCallback((toolCallId, scope = "ONCE") => decide(toolCallId, "APPROVE", scope), [decide]);
215
+ const reject = useCallback((toolCallId) => decide(toolCallId, "REJECT", "ONCE"), [decide]);
216
+ 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
+ ]);
264
+ return {
265
+ messages: (live === null ? messages : [...messages, {
266
+ id: "live",
267
+ role: "assistant",
268
+ blocks: live
269
+ }]).map(waitingLast),
270
+ status,
271
+ loading,
272
+ error,
273
+ chatId,
274
+ send,
275
+ stop,
276
+ newChat,
277
+ openChat,
278
+ listChats,
279
+ approve,
280
+ reject,
281
+ connect
282
+ };
283
+ }
284
+ const waitsForVisitor = (b) => b.type === "tool" && (b.status === "awaiting-approval" || b.status === "awaiting-connection" || b.status === "connecting");
285
+ function waitingLast(message) {
286
+ if (!message.blocks.some(waitsForVisitor)) return message;
287
+ const blocks = [...message.blocks.filter((b) => !waitsForVisitor(b)), ...message.blocks.filter(waitsForVisitor)];
288
+ return {
289
+ ...message,
290
+ blocks
291
+ };
292
+ }
293
+ const CONNECT_TIMEOUT_MS = 5 * 6e4;
294
+ const CONNECT_RETRY_MS = 3e3;
295
+ function popupFeatures(width, height) {
296
+ return `width=${width},height=${height},left=${window.screenX + (window.innerWidth - width) / 2},top=${window.screenY + (window.innerHeight - height) / 2}`;
297
+ }
298
+ const TODO_TOOL = "TodoWrite";
299
+ /** Its question shows as a question block, so the call itself is noise. */
300
+ const QUESTION_TOOL = "AskUserQuestion";
301
+ function parseEvent(line) {
302
+ if (!line.trim()) return null;
303
+ try {
304
+ return JSON.parse(line);
305
+ } catch {
306
+ return null;
307
+ }
308
+ }
309
+ function reduceEvent(blocks, event) {
310
+ switch (event.type) {
311
+ case "TEXT": {
312
+ const last = blocks.at(-1);
313
+ return last?.type === "text" ? [...blocks.slice(0, -1), {
314
+ type: "text",
315
+ text: last.text + event.response
316
+ }] : [...blocks, {
317
+ type: "text",
318
+ text: event.response
319
+ }];
320
+ }
321
+ case "TOOL_CALL_START":
322
+ if (event.toolName === TODO_TOOL) {
323
+ const todos = parseTodos(event.input);
324
+ if (todos) return upsertTodos(blocks, todos);
325
+ }
326
+ if (event.toolName === QUESTION_TOOL) return blocks;
327
+ if (blocks.some((b) => b.type === "tool" && b.id === event.toolCallId)) return updateTool(blocks, event.toolCallId, (b) => b.status === "running" ? {
328
+ ...b,
329
+ input: event.input ?? b.input,
330
+ thought: event.innerThought ?? b.thought
331
+ } : b);
332
+ return [...blocks, {
333
+ type: "tool",
334
+ id: event.toolCallId,
335
+ name: event.toolName,
336
+ input: event.input,
337
+ thought: event.innerThought,
338
+ integration: event.integrationType,
339
+ status: "running"
340
+ }];
341
+ case "TOOL_CALL_END": return updateTool(blocks, event.toolCallId, (b) => b.status === "running" || b.status === "approved" ? {
342
+ ...b,
343
+ status: event.failed ? "failed" : "done",
344
+ error: event.errorMessage,
345
+ durationMs: event.durationMs
346
+ } : b);
347
+ case "TOOL_PERMISSION_REQUEST":
348
+ case "INTEGRATION_AUTH_REQUEST": {
349
+ const status = event.type === "TOOL_PERMISSION_REQUEST" ? "awaiting-approval" : "awaiting-connection";
350
+ const integration = event.type === "INTEGRATION_AUTH_REQUEST" ? event.integrationType : void 0;
351
+ if (blocks.some((b) => b.type === "tool" && b.id === event.toolCallId)) return updateTool(blocks, event.toolCallId, (b) => ({
352
+ ...b,
353
+ status,
354
+ integration: integration ?? b.integration,
355
+ input: ("input" in event ? event.input : void 0) ?? b.input
356
+ }));
357
+ return [...blocks, {
358
+ type: "tool",
359
+ id: event.toolCallId,
360
+ name: event.toolName,
361
+ input: "input" in event ? event.input : void 0,
362
+ integration,
363
+ status
364
+ }];
365
+ }
366
+ case "QUESTION": return [...blocks, {
367
+ type: "question",
368
+ questions: event.questions
369
+ }];
370
+ case "ERROR": return [...blocks, {
371
+ type: "error",
372
+ message: event.message
373
+ }];
374
+ default: return blocks;
375
+ }
376
+ }
377
+ function updateTool(blocks, id, update) {
378
+ return blocks.map((b) => b.type === "tool" && b.id === id ? update(b) : b);
379
+ }
380
+ /** A reply that ended without finishing a tool call, stopped or cut off, never will. */
381
+ function endRunningTools(blocks) {
382
+ return blocks.map((b) => b.type === "tool" && b.status === "running" ? {
383
+ ...b,
384
+ status: "failed",
385
+ error: "The agent stopped before this step finished."
386
+ } : b);
387
+ }
388
+ /** Each plan update re-sends the whole list, so only the latest one is kept, where the first one was. */
389
+ function upsertTodos(blocks, todos) {
390
+ const index = blocks.findIndex((b) => b.type === "todo");
391
+ if (index === -1) return [...blocks, {
392
+ type: "todo",
393
+ todos
394
+ }];
395
+ return blocks.map((b, i) => i === index ? {
396
+ type: "todo",
397
+ todos
398
+ } : b);
399
+ }
400
+ function parseTodos(input) {
401
+ if (!input) return null;
402
+ try {
403
+ const parsed = JSON.parse(input);
404
+ if (typeof parsed !== "object" || parsed === null || !("todos" in parsed)) return null;
405
+ const outer = parsed.todos;
406
+ const raw = typeof outer === "object" && outer !== null && "todos" in outer ? outer.todos : outer;
407
+ if (!Array.isArray(raw)) return null;
408
+ const todos = raw.flatMap((item) => {
409
+ if (typeof item !== "object" || item === null) return [];
410
+ const { content, status } = item;
411
+ if (typeof content !== "string" || !content.trim()) return [];
412
+ if (status !== "pending" && status !== "in_progress" && status !== "completed") return [];
413
+ return [{
414
+ content,
415
+ status
416
+ }];
417
+ });
418
+ return todos.length > 0 ? todos : null;
419
+ } catch {
420
+ return null;
421
+ }
422
+ }
423
+ function fromHistory(history) {
424
+ const toolsByMessage = Map.groupBy(history.toolCalls, (call) => call.messageId);
425
+ return history.messages.filter((m) => m.role !== "USER" || m.content.trim()).map((m) => {
426
+ if (m.role === "USER") return {
427
+ id: m.id,
428
+ role: "user",
429
+ blocks: [{
430
+ type: "text",
431
+ text: m.content
432
+ }]
433
+ };
434
+ let blocks = [];
435
+ const calls = (toolsByMessage.get(m.id) ?? []).toSorted((a, b) => a.createdAt - b.createdAt);
436
+ for (const call of calls) {
437
+ const todos = call.toolName === TODO_TOOL ? parseTodos(call.input) : null;
438
+ if (todos) blocks = upsertTodos(blocks, todos);
439
+ else if (call.toolName !== QUESTION_TOOL) blocks.push({
440
+ type: "tool",
441
+ id: call.id,
442
+ name: call.toolName,
443
+ input: call.input,
444
+ thought: call.metadata.innerThought ?? void 0,
445
+ durationMs: call.metadata.durationMs ?? void 0,
446
+ status: call.metadata.failed ? "failed" : "done"
447
+ });
448
+ }
449
+ if (m.content) blocks.push({
450
+ type: "text",
451
+ text: m.content
452
+ });
453
+ return {
454
+ id: m.id,
455
+ role: "assistant",
456
+ blocks
457
+ };
458
+ });
459
+ }
460
+ const CHAT_GONE_MESSAGE = "This chat is no longer available. Start a new one.";
461
+ const VISITOR = "visitor";
462
+ const chatKey = (agentId, userId) => `softr-code-app:agent-chat:${agentId}:${userId ?? VISITOR}`;
463
+ function chatStore(key) {
464
+ return key.endsWith(`:${VISITOR}`) ? sessionStorage : localStorage;
465
+ }
466
+ function savedChatId(key) {
467
+ try {
468
+ return chatStore(key).getItem(key);
469
+ } catch {
470
+ return null;
471
+ }
472
+ }
473
+ function saveChatId(key, chatId) {
474
+ try {
475
+ if (chatId) chatStore(key).setItem(key, chatId);
476
+ else chatStore(key).removeItem(key);
477
+ } catch {}
478
+ }
479
+ async function failureMessage(res) {
480
+ const body = await res.json().catch(() => null);
481
+ if (typeof body === "object" && body !== null && "message" in body && typeof body.message === "string") return body.message;
482
+ return `The agent could not answer (${res.status}).`;
483
+ }
484
+
485
+ //#endregion
486
+ export { useAgentChat };
@@ -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>, _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>], {
26
26
  user: User | null;
27
27
  permissions: Permissions;
28
28
  formatting: Formatting;
@@ -10,7 +10,6 @@ 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";
14
13
  import { createContext, useContext } from "react";
15
14
  import { createMiddleware, createServerFn, getGlobalStartContext } from "@tanstack/react-start";
16
15
  import { getRequestHeader } from "@tanstack/react-start/server";
@@ -35,7 +34,6 @@ import { jsx } from "react/jsx-runtime";
35
34
  function softrAuthMiddleware() {
36
35
  return createMiddleware({ type: "request" }).middleware([
37
36
  embeddingMiddleware(),
38
- appIdentityMiddleware(),
39
37
  bootErrorMiddleware(),
40
38
  pwaMiddleware(),
41
39
  faviconMiddleware()
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_start0 from "@tanstack/react-start";
2
+ import * as _tanstack_react_start6 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_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>;
34
+ declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start6.RequestMiddlewareAfterServer<{}, undefined, undefined>;
35
35
  //#endregion
36
36
  export { softrMcpMiddleware };
package/dist/mcp.js CHANGED
@@ -244,7 +244,8 @@ const WHOAMI = {
244
244
  type: "object",
245
245
  properties: {},
246
246
  additionalProperties: false
247
- }
247
+ },
248
+ annotations: { readOnlyHint: true }
248
249
  };
249
250
  /** How many records a read returns when the caller does not say. */
250
251
  const DEFAULT_LIMIT = 20;
@@ -265,6 +266,7 @@ function describeTool(action) {
265
266
  case "read": return {
266
267
  name: action.id,
267
268
  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 },
268
270
  inputSchema: {
269
271
  type: "object",
270
272
  properties: {
@@ -385,8 +387,10 @@ async function rpc(request, origin, actions) {
385
387
  const token = bearerToken(request);
386
388
  if (token === null) return unauthorized(origin);
387
389
  const session = await platformSession(token);
388
- if (!session.ok) return session.refused ? unauthorized(origin) : unavailable();
389
- const { sessionToken } = session;
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();
390
394
  const body = await readJson(request);
391
395
  const message = z.object({
392
396
  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.4";
2
+ var version = "0.0.90-alpha.6";
3
3
 
4
4
  //#endregion
5
5
  export { version };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "0.0.90-alpha.4",
3
+ "version": "0.0.90-alpha.6",
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.90-alpha.4
12
+ library_version: 0.0.90-alpha.6
13
13
  ---
14
14
 
15
15
  # Softr SDK core
@@ -49,6 +49,7 @@ 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) |
52
53
  | Let visitors install the app on their home screen | [pwa/SKILL.md](./pwa/SKILL.md) |
53
54
  | Show a date, a time or a number | [formatting/SKILL.md](./formatting/SKILL.md) |
54
55
 
@@ -85,6 +86,9 @@ Calling a connected third-party API (Slack, Stripe, Gmail, Google Calendar, …)
85
86
  Opening the app to an AI assistant over MCP?
86
87
  load softr-sdk/mcp
87
88
 
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
+
88
92
  Adding an install button, or making the app installable?
89
93
  load softr-sdk/pwa
90
94
 
@@ -0,0 +1,109 @@
1
+ ---
2
+ name: agent-chat
3
+ description: >-
4
+ Chat with one of the app's Softr agents: listAgents() and useAgentChat(agentId,
5
+ { record }) from @softr/sdk give the chat state with no UI — messages, the
6
+ streaming reply, past chats, approve, reject, connect. Load it for an agent
7
+ chat, approving its actions, which records the agent may change for each
8
+ visitor, or connecting the visitor's account a tool needs.
9
+ metadata:
10
+ type: sub-skill
11
+ library: softr-sdk
12
+ library_version: 0.0.90-alpha.6
13
+ ---
14
+
15
+ **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.
16
+
17
+ # Agent chat
18
+
19
+ A Softr agent is set up in Studio's Agents tab and attached to the app there. There is no chat widget: the hook gives the state, and the app draws it with its own components.
20
+
21
+ ## Setup
22
+
23
+ ```ts
24
+ import { listAgents, useAgentChat } from '@softr/sdk'
25
+ ```
26
+
27
+ `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. A hand-written id fails on the first message, and shows an agent the visitor may not see.
28
+
29
+ ## Core pattern
30
+
31
+ ```tsx
32
+ // agentId comes from listAgents() in the route's loader.
33
+ function AgentPanel({ agentId, ticket }: { agentId: string; ticket: Ticket | null }) {
34
+ const chat = useAgentChat(agentId, {
35
+ record: ticket && { id: ticket.id, fields: { Title: ticket.title, Status: ticket.status } },
36
+ })
37
+ const [draft, setDraft] = useState('')
38
+
39
+ return (
40
+ <>
41
+ {chat.messages.map((message) => (
42
+ <Message key={message.id} message={message} onApprove={chat.approve} onReject={chat.reject} />
43
+ ))}
44
+ {chat.error && <p role="alert">{chat.error.message}</p>}
45
+ <form onSubmit={(e) => { e.preventDefault(); chat.send(draft); setDraft('') }}>
46
+ <Textarea value={draft} onChange={(e) => setDraft(e.target.value)} />
47
+ {chat.status === 'idle'
48
+ ? <Button type="submit">Send</Button>
49
+ : <Button type="button" onClick={chat.stop}>Stop</Button>}
50
+ </form>
51
+ </>
52
+ )
53
+ }
54
+ ```
55
+
56
+ ## What the hook returns
57
+
58
+ - `messages`: the whole chat, oldest first. While the agent answers, its reply is the last message and grows as it streams.
59
+ - `status`: `thinking` until the first part of the reply arrives, `replying` until it ends, then `idle`. Show a typing hint while it's `thinking`.
60
+ - `loading`: `true` while a past chat loads. Show a spinner, not the empty-chat greeting.
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 }[]`, 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 signed-in user, so the hook reopens it after a remount or a reload. A signed-out visitor keeps it only until the tab closes.
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 this agent from now on.
65
+ - `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
+ ## Rendering a message
68
+
69
+ Each message has `role` (`user` or `assistant`) and `blocks`. Render every block type, in the order given. Show only `text` and a tool waiting for approval never appears, so the agent waits forever. A tool waiting for Approve or Connect comes last in its message, below the text asking for it.
70
+
71
+ | Block | Show it as |
72
+ | --- | --- |
73
+ | `text` | Markdown, tables included |
74
+ | `tool` | One line: the tool `name` and its `status`. Collapse finished ones. Expanded, show `thought`, `input` as `Label: value` lines (never raw JSON), `error` and `durationMs`, leaving out empty ones. |
75
+ | `todo` | A checklist of the agent's plan. It updates in place. |
76
+ | `question` | The questions with their options. One question with a single choice sends its label with `send` on click. Several questions, or `multiSelect`, collect the picks and show a Send button, enabled once each question has one. It sends one line per question, picked labels joined by ", ". An answered question stays locked. |
77
+ | `error` | An error line inside the reply |
78
+
79
+ A `tool` with status `awaiting-approval` blocks the agent until the visitor answers. Give it a split Approve button and a Reject button. The button says "Approve once" (`approve(id)`), and its menu offers "Approve for this session" (`approve(id, 'SESSION')`) and "Approve for this agent" (`approve(id, 'USER')`). With only one Approve, the visitor approves the same action again on every call. The agent continues on its own after an approval.
80
+
81
+ 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. Every integration works the same way, so build one button, not one per integration.
82
+
83
+ ## Context
84
+
85
+ `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.
86
+
87
+ The page title and URL go along on their own. Nothing else about the page does, so don't try to send whole lists.
88
+
89
+ ## Letting the agent act on the app
90
+
91
+ The agent reads and changes data through the app's own MCP, as the visitor who is chatting, using the actions `softrMcpMiddleware` lists. With no MCP wired, the agent can only talk. Load [mcp/SKILL.md](../mcp/SKILL.md) to wire it and choose the actions.
92
+
93
+ **The agent calls a listed action directly, with any input.** It skips pages and server functions. Two things guard it: the action's `permissions` say who may run it, and the app's data restrictions say which rows each user group reaches. A read returns every row the visitor may see, and an update or delete takes any id that passes both.
94
+
95
+ - **By default, each visitor changes only their own records.** On a table whose rows belong to a person, such as requests or bookings, open its create, update and delete to every signed-in visitor, and let the table's data restriction narrow edit and delete to the visitor's own rows. The groups that manage everyone's records get no restriction.
96
+ - Split an action by role only for fields one role sets. A request's status goes on its own update with `customGroups` for the managers, and the visitor's update doesn't list it. One update open to every signed-in visitor that writes the status lets an employee have the agent approve their own vacation request.
97
+ - Don't list an update or delete on a table whose rows belong to people until its restriction is in place. Without it, the agent edits anyone's row.
98
+ - Where the app's pages show people only their own rows, the restriction needs a view rule too. The pages' filter lives in server functions, and without the rule the agent reads everyone's rows.
99
+
100
+ ## Failure modes
101
+
102
+ **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`.
103
+
104
+ **The hook inside a component that unmounts when the panel closes.** Closing it stops a reply that is still coming. Call `useAgentChat` in the component that owns the panel's open state and pass `chat` down. Keep the selected agent there too, or closing the panel resets it.
105
+
106
+ ## References
107
+
108
+ - [mcp/SKILL.md](../mcp/SKILL.md): the actions the agent may call
109
+ - [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.90-alpha.4
12
+ library_version: 0.0.90-alpha.6
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.4
12
+ library_version: 0.0.90-alpha.6
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.4
12
+ library_version: 0.0.90-alpha.6
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.4
10
+ library_version: 0.0.90-alpha.6
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.4
11
+ library_version: 0.0.90-alpha.6
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.4
10
+ library_version: 0.0.90-alpha.6
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.4
12
+ library_version: 0.0.90-alpha.6
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.
@@ -53,6 +53,7 @@ The list is the whole tool surface. Write it out:
53
53
 
54
54
  - An action you leave out is invisible to the assistant, even where the app's pages use it freely.
55
55
  - An action you list still obeys its own `permissions`. Listing it does not widen who may run it — the assistant runs as whoever signed in, with that user's groups.
56
+ - The assistant calls the action directly and skips server functions, so a row filter written in one does not apply. A listed read returns every row the user's data restrictions allow, and a listed update or delete takes any id that passes them. On a table whose rows belong to people, list an action only once a data restriction scopes the table to the user's own rows.
56
57
  - Two actions with the same `id` throw at startup. So does anything that is not a `defineQuery` or `defineMutation` value.
57
58
 
58
59
  Reads first. Add a write only when the user asked for one, and name it back to them.
@@ -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.4
12
+ library_version: 0.0.90-alpha.6
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.4
11
+ library_version: 0.0.90-alpha.6
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.4
12
+ library_version: 0.0.90-alpha.6
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.4
12
+ library_version: 0.0.90-alpha.6
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.4
12
+ library_version: 0.0.90-alpha.6
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.4
12
+ library_version: 0.0.90-alpha.6
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,76 +0,0 @@
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 };