@softr/sdk 0.0.92 → 0.0.93-alpha.0

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_start9 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_start9.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 };