@softr/sdk 0.0.88-signing.0 → 0.0.89-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.
- package/dist/agent/agent-fns.d.ts +30 -0
- package/dist/agent/agent-fns.js +172 -0
- package/dist/agent/use-agent-chat.d.ts +100 -0
- package/dist/agent/use-agent-chat.js +419 -0
- package/dist/auth/isomorphic.d.ts +3 -2
- package/dist/auth/isomorphic.js +4 -1
- package/dist/auth/methods/authenticator.js +3 -3
- package/dist/auth/methods/code.js +1 -1
- package/dist/auth/methods/magicLink.js +1 -1
- package/dist/auth/methods/password.js +1 -1
- package/dist/auth/methods/passwordLink.js +1 -1
- package/dist/auth/methods/signup.js +1 -1
- package/dist/auth/methods/social.js +1 -1
- package/dist/auth/platform.js +2 -2
- package/dist/auth/session.js +8 -7
- package/dist/codegen/datasource-docs.js +9 -3
- package/dist/cookies.js +29 -3
- package/dist/core/file-upload.js +1 -1
- package/dist/core/workflow.js +1 -1
- package/dist/datasource/record.js +1 -1
- package/dist/embedding.js +33 -0
- package/dist/fetch.js +1 -61
- package/dist/index.d.ts +3 -1
- package/dist/index.js +3 -1
- package/dist/locale-settings.js +1 -1
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +6 -4
- package/dist/package.js +1 -1
- package/dist/pwa.js +2 -2
- package/dist/route/route.js +1 -1
- package/dist/softr-config.schema.js +3 -1
- package/package.json +1 -1
- package/schema/softr.schema.json +5 -0
- package/skills/softr-sdk/SKILL.md +14 -5
- package/skills/softr-sdk/agent-chat/SKILL.md +122 -0
- package/skills/softr-sdk/auth/SKILL.md +1 -1
- package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
- package/skills/softr-sdk/current-user/SKILL.md +9 -5
- package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
- package/skills/softr-sdk/formatting/SKILL.md +1 -1
- package/skills/softr-sdk/integrations/SKILL.md +1 -1
- package/skills/softr-sdk/mcp/SKILL.md +1 -1
- package/skills/softr-sdk/pwa/SKILL.md +1 -1
- package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
- package/skills/softr-sdk/record-queries/SKILL.md +2 -2
- package/skills/softr-sdk/region-visibility/SKILL.md +3 -5
- package/skills/softr-sdk/routes-and-visibility/SKILL.md +85 -44
- package/skills/softr-sdk/workflows/SKILL.md +1 -1
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
import { assert } from "../assertions.js";
|
|
2
|
+
import { useCurrentUser } from "../auth/isomorphic.js";
|
|
3
|
+
import { agentChatFn, decideAgentToolFn, listAgentChatsFn, loadAgentChatFn } 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
|
+
return {
|
|
217
|
+
messages: live === null ? messages : [...messages, {
|
|
218
|
+
id: "live",
|
|
219
|
+
role: "assistant",
|
|
220
|
+
blocks: live
|
|
221
|
+
}],
|
|
222
|
+
status,
|
|
223
|
+
loading,
|
|
224
|
+
error,
|
|
225
|
+
chatId,
|
|
226
|
+
send,
|
|
227
|
+
stop,
|
|
228
|
+
newChat,
|
|
229
|
+
openChat,
|
|
230
|
+
listChats,
|
|
231
|
+
approve,
|
|
232
|
+
reject
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
const TODO_TOOL = "TodoWrite";
|
|
236
|
+
/** Its question shows as a question block, so the call itself is noise. */
|
|
237
|
+
const QUESTION_TOOL = "AskUserQuestion";
|
|
238
|
+
function parseEvent(line) {
|
|
239
|
+
if (!line.trim()) return null;
|
|
240
|
+
try {
|
|
241
|
+
return JSON.parse(line);
|
|
242
|
+
} catch {
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
function reduceEvent(blocks, event) {
|
|
247
|
+
switch (event.type) {
|
|
248
|
+
case "TEXT": {
|
|
249
|
+
const last = blocks.at(-1);
|
|
250
|
+
return last?.type === "text" ? [...blocks.slice(0, -1), {
|
|
251
|
+
type: "text",
|
|
252
|
+
text: last.text + event.response
|
|
253
|
+
}] : [...blocks, {
|
|
254
|
+
type: "text",
|
|
255
|
+
text: event.response
|
|
256
|
+
}];
|
|
257
|
+
}
|
|
258
|
+
case "TOOL_CALL_START":
|
|
259
|
+
if (event.toolName === TODO_TOOL) {
|
|
260
|
+
const todos = parseTodos(event.input);
|
|
261
|
+
if (todos) return upsertTodos(blocks, todos);
|
|
262
|
+
}
|
|
263
|
+
if (event.toolName === QUESTION_TOOL) return blocks;
|
|
264
|
+
if (blocks.some((b) => b.type === "tool" && b.id === event.toolCallId)) return updateTool(blocks, event.toolCallId, (b) => b.status === "running" ? {
|
|
265
|
+
...b,
|
|
266
|
+
input: event.input ?? b.input,
|
|
267
|
+
thought: event.innerThought ?? b.thought
|
|
268
|
+
} : b);
|
|
269
|
+
return [...blocks, {
|
|
270
|
+
type: "tool",
|
|
271
|
+
id: event.toolCallId,
|
|
272
|
+
name: event.toolName,
|
|
273
|
+
input: event.input,
|
|
274
|
+
thought: event.innerThought,
|
|
275
|
+
integration: event.integrationType,
|
|
276
|
+
status: "running"
|
|
277
|
+
}];
|
|
278
|
+
case "TOOL_CALL_END": return updateTool(blocks, event.toolCallId, (b) => b.status === "running" || b.status === "approved" ? {
|
|
279
|
+
...b,
|
|
280
|
+
status: event.failed ? "failed" : "done",
|
|
281
|
+
error: event.errorMessage,
|
|
282
|
+
durationMs: event.durationMs
|
|
283
|
+
} : b);
|
|
284
|
+
case "TOOL_PERMISSION_REQUEST":
|
|
285
|
+
case "INTEGRATION_AUTH_REQUEST": {
|
|
286
|
+
const status = event.type === "TOOL_PERMISSION_REQUEST" ? "awaiting-approval" : "awaiting-connection";
|
|
287
|
+
const integration = event.type === "INTEGRATION_AUTH_REQUEST" ? event.integrationType : void 0;
|
|
288
|
+
if (blocks.some((b) => b.type === "tool" && b.id === event.toolCallId)) return updateTool(blocks, event.toolCallId, (b) => ({
|
|
289
|
+
...b,
|
|
290
|
+
status,
|
|
291
|
+
integration: integration ?? b.integration,
|
|
292
|
+
input: ("input" in event ? event.input : void 0) ?? b.input
|
|
293
|
+
}));
|
|
294
|
+
return [...blocks, {
|
|
295
|
+
type: "tool",
|
|
296
|
+
id: event.toolCallId,
|
|
297
|
+
name: event.toolName,
|
|
298
|
+
input: "input" in event ? event.input : void 0,
|
|
299
|
+
integration,
|
|
300
|
+
status
|
|
301
|
+
}];
|
|
302
|
+
}
|
|
303
|
+
case "QUESTION": return [...blocks, {
|
|
304
|
+
type: "question",
|
|
305
|
+
questions: event.questions
|
|
306
|
+
}];
|
|
307
|
+
case "ERROR": return [...blocks, {
|
|
308
|
+
type: "error",
|
|
309
|
+
message: event.message
|
|
310
|
+
}];
|
|
311
|
+
default: return blocks;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
function updateTool(blocks, id, update) {
|
|
315
|
+
return blocks.map((b) => b.type === "tool" && b.id === id ? update(b) : b);
|
|
316
|
+
}
|
|
317
|
+
/** A reply that ended without finishing a tool call, stopped or cut off, never will. */
|
|
318
|
+
function endRunningTools(blocks) {
|
|
319
|
+
return blocks.map((b) => b.type === "tool" && b.status === "running" ? {
|
|
320
|
+
...b,
|
|
321
|
+
status: "failed",
|
|
322
|
+
error: "The agent stopped before this step finished."
|
|
323
|
+
} : b);
|
|
324
|
+
}
|
|
325
|
+
/** Each plan update re-sends the whole list, so only the latest one is kept, where the first one was. */
|
|
326
|
+
function upsertTodos(blocks, todos) {
|
|
327
|
+
const index = blocks.findIndex((b) => b.type === "todo");
|
|
328
|
+
if (index === -1) return [...blocks, {
|
|
329
|
+
type: "todo",
|
|
330
|
+
todos
|
|
331
|
+
}];
|
|
332
|
+
return blocks.map((b, i) => i === index ? {
|
|
333
|
+
type: "todo",
|
|
334
|
+
todos
|
|
335
|
+
} : b);
|
|
336
|
+
}
|
|
337
|
+
function parseTodos(input) {
|
|
338
|
+
if (!input) return null;
|
|
339
|
+
try {
|
|
340
|
+
const parsed = JSON.parse(input);
|
|
341
|
+
if (typeof parsed !== "object" || parsed === null || !("todos" in parsed)) return null;
|
|
342
|
+
const outer = parsed.todos;
|
|
343
|
+
const raw = typeof outer === "object" && outer !== null && "todos" in outer ? outer.todos : outer;
|
|
344
|
+
if (!Array.isArray(raw)) return null;
|
|
345
|
+
const todos = raw.flatMap((item) => {
|
|
346
|
+
if (typeof item !== "object" || item === null) return [];
|
|
347
|
+
const { content, status } = item;
|
|
348
|
+
if (typeof content !== "string" || !content.trim()) return [];
|
|
349
|
+
if (status !== "pending" && status !== "in_progress" && status !== "completed") return [];
|
|
350
|
+
return [{
|
|
351
|
+
content,
|
|
352
|
+
status
|
|
353
|
+
}];
|
|
354
|
+
});
|
|
355
|
+
return todos.length > 0 ? todos : null;
|
|
356
|
+
} catch {
|
|
357
|
+
return null;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
function fromHistory(history) {
|
|
361
|
+
const toolsByMessage = Map.groupBy(history.toolCalls, (call) => call.messageId);
|
|
362
|
+
return history.messages.filter((m) => m.role !== "USER" || m.content.trim()).map((m) => {
|
|
363
|
+
if (m.role === "USER") return {
|
|
364
|
+
id: m.id,
|
|
365
|
+
role: "user",
|
|
366
|
+
blocks: [{
|
|
367
|
+
type: "text",
|
|
368
|
+
text: m.content
|
|
369
|
+
}]
|
|
370
|
+
};
|
|
371
|
+
let blocks = [];
|
|
372
|
+
const calls = (toolsByMessage.get(m.id) ?? []).toSorted((a, b) => a.createdAt - b.createdAt);
|
|
373
|
+
for (const call of calls) {
|
|
374
|
+
const todos = call.toolName === TODO_TOOL ? parseTodos(call.input) : null;
|
|
375
|
+
if (todos) blocks = upsertTodos(blocks, todos);
|
|
376
|
+
else if (call.toolName !== QUESTION_TOOL) blocks.push({
|
|
377
|
+
type: "tool",
|
|
378
|
+
id: call.id,
|
|
379
|
+
name: call.toolName,
|
|
380
|
+
input: call.input,
|
|
381
|
+
thought: call.metadata.innerThought ?? void 0,
|
|
382
|
+
durationMs: call.metadata.durationMs ?? void 0,
|
|
383
|
+
status: call.metadata.failed ? "failed" : "done"
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
if (m.content) blocks.push({
|
|
387
|
+
type: "text",
|
|
388
|
+
text: m.content
|
|
389
|
+
});
|
|
390
|
+
return {
|
|
391
|
+
id: m.id,
|
|
392
|
+
role: "assistant",
|
|
393
|
+
blocks
|
|
394
|
+
};
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
const CHAT_GONE_MESSAGE = "This chat is no longer available. Start a new one.";
|
|
398
|
+
const chatKey = (agentId, userId) => `softr-agent-chat:${agentId}:${userId ?? "visitor"}`;
|
|
399
|
+
function savedChatId(key) {
|
|
400
|
+
try {
|
|
401
|
+
return localStorage.getItem(key);
|
|
402
|
+
} catch {
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
function saveChatId(key, chatId) {
|
|
407
|
+
try {
|
|
408
|
+
if (chatId) localStorage.setItem(key, chatId);
|
|
409
|
+
else localStorage.removeItem(key);
|
|
410
|
+
} catch {}
|
|
411
|
+
}
|
|
412
|
+
async function failureMessage(res) {
|
|
413
|
+
const body = await res.json().catch(() => null);
|
|
414
|
+
if (typeof body === "object" && body !== null && "message" in body && typeof body.message === "string") return body.message;
|
|
415
|
+
return `The agent could not answer (${res.status}).`;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
//#endregion
|
|
419
|
+
export { useAgentChat };
|
|
@@ -14,14 +14,15 @@ import * as _tanstack_react_start0 from "@tanstack/react-start";
|
|
|
14
14
|
* to read.
|
|
15
15
|
*
|
|
16
16
|
* Register it once, as a global request middleware in the app's `src/start.ts`.
|
|
17
|
-
* It writes
|
|
17
|
+
* It writes the session cookie, and in production a header that stops other
|
|
18
|
+
* sites from embedding the app.
|
|
18
19
|
*
|
|
19
20
|
* @example
|
|
20
21
|
* export const startInstance = createStart(() => ({
|
|
21
22
|
* requestMiddleware: [softrAuthMiddleware()],
|
|
22
23
|
* }))
|
|
23
24
|
*/
|
|
24
|
-
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>], {
|
|
25
|
+
declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
|
|
25
26
|
user: User | null;
|
|
26
27
|
permissions: Permissions;
|
|
27
28
|
formatting: Formatting;
|
package/dist/auth/isomorphic.js
CHANGED
|
@@ -9,6 +9,7 @@ import { settings } from "./methods/settings.js";
|
|
|
9
9
|
import { bootErrorMiddleware } from "../boot-error.js";
|
|
10
10
|
import { pwaMiddleware } from "../pwa.js";
|
|
11
11
|
import { faviconMiddleware } from "../favicon.js";
|
|
12
|
+
import { embeddingMiddleware } from "../embedding.js";
|
|
12
13
|
import { createContext, useContext } from "react";
|
|
13
14
|
import { createMiddleware, createServerFn, getGlobalStartContext } from "@tanstack/react-start";
|
|
14
15
|
import { getRequestHeader } from "@tanstack/react-start/server";
|
|
@@ -22,7 +23,8 @@ import { jsx } from "react/jsx-runtime";
|
|
|
22
23
|
* to read.
|
|
23
24
|
*
|
|
24
25
|
* Register it once, as a global request middleware in the app's `src/start.ts`.
|
|
25
|
-
* It writes
|
|
26
|
+
* It writes the session cookie, and in production a header that stops other
|
|
27
|
+
* sites from embedding the app.
|
|
26
28
|
*
|
|
27
29
|
* @example
|
|
28
30
|
* export const startInstance = createStart(() => ({
|
|
@@ -31,6 +33,7 @@ import { jsx } from "react/jsx-runtime";
|
|
|
31
33
|
*/
|
|
32
34
|
function softrAuthMiddleware() {
|
|
33
35
|
return createMiddleware({ type: "request" }).middleware([
|
|
36
|
+
embeddingMiddleware(),
|
|
34
37
|
bootErrorMiddleware(),
|
|
35
38
|
pwaMiddleware(),
|
|
36
39
|
faviconMiddleware()
|
|
@@ -46,7 +46,7 @@ async function confirmAuthenticatorSetup(details) {
|
|
|
46
46
|
throw new Error(`${result.message}. Check SOFTR_APPLICATION_ID and that the app allows an authenticator app.`);
|
|
47
47
|
}
|
|
48
48
|
const { session, backupCodes } = result.data;
|
|
49
|
-
writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
49
|
+
writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
50
50
|
user: session.user,
|
|
51
51
|
permissions: session.permissions
|
|
52
52
|
}, session.jwt)]);
|
|
@@ -75,7 +75,7 @@ async function skipAuthenticatorSetup() {
|
|
|
75
75
|
}
|
|
76
76
|
const { session } = result.data;
|
|
77
77
|
assert(session, "Expected a session from skipping setup, but got none");
|
|
78
|
-
writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
78
|
+
writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
79
79
|
user: session.user,
|
|
80
80
|
permissions: session.permissions
|
|
81
81
|
}, session.jwt)]);
|
|
@@ -101,7 +101,7 @@ async function verifyAuthenticator(credentials) {
|
|
|
101
101
|
}
|
|
102
102
|
const { session } = result.data;
|
|
103
103
|
assert(session, "Expected a session from verification, but got none");
|
|
104
|
-
writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
104
|
+
writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
105
105
|
user: session.user,
|
|
106
106
|
permissions: session.permissions
|
|
107
107
|
}, session.jwt)]);
|
|
@@ -56,7 +56,7 @@ async function signInWithCode(credentials) {
|
|
|
56
56
|
}
|
|
57
57
|
const { session } = result.data;
|
|
58
58
|
assert(session, "Expected a session from sign-in, but got none");
|
|
59
|
-
writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
59
|
+
writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
60
60
|
user: session.user,
|
|
61
61
|
permissions: session.permissions
|
|
62
62
|
}, session.jwt)]);
|
|
@@ -36,7 +36,7 @@ async function signInWithMagicLink(credentials) {
|
|
|
36
36
|
}
|
|
37
37
|
const { session } = result.data;
|
|
38
38
|
assert(session, "Expected a session from magic-link sign-in, but got none");
|
|
39
|
-
writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
39
|
+
writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
40
40
|
user: session.user,
|
|
41
41
|
permissions: session.permissions
|
|
42
42
|
}, session.jwt)]);
|
|
@@ -35,7 +35,7 @@ async function signIn(credentials) {
|
|
|
35
35
|
}
|
|
36
36
|
const { session } = result.data;
|
|
37
37
|
assert(session, "Expected a session from sign-in, but got none");
|
|
38
|
-
writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
38
|
+
writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
39
39
|
user: session.user,
|
|
40
40
|
permissions: session.permissions
|
|
41
41
|
}, session.jwt)]);
|
|
@@ -68,7 +68,7 @@ async function setPasswordWithLink(details) {
|
|
|
68
68
|
}
|
|
69
69
|
const { session } = result.data;
|
|
70
70
|
assert(session, "Expected a session from setting a password, but got none");
|
|
71
|
-
writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
71
|
+
writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
72
72
|
user: session.user,
|
|
73
73
|
permissions: session.permissions
|
|
74
74
|
}, session.jwt)]);
|
|
@@ -66,7 +66,7 @@ async function confirmSignUp(details) {
|
|
|
66
66
|
}
|
|
67
67
|
const { session } = result.data;
|
|
68
68
|
assert(session, "Expected a session from sign-up, but got none");
|
|
69
|
-
writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
69
|
+
writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
70
70
|
user: session.user,
|
|
71
71
|
permissions: session.permissions
|
|
72
72
|
}, session.jwt)]);
|
|
@@ -41,7 +41,7 @@ async function signInWithGoogle(credentials) {
|
|
|
41
41
|
}
|
|
42
42
|
const { session } = result.data;
|
|
43
43
|
assert(session, "Expected a session from Google sign-in, but got none");
|
|
44
|
-
writeCookies([makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
44
|
+
writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({
|
|
45
45
|
user: session.user,
|
|
46
46
|
permissions: session.permissions
|
|
47
47
|
}, session.jwt)]);
|
package/dist/auth/platform.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { assert, panic } from "../assertions.js";
|
|
2
|
-
import { softrApiUrl } from "../softr-api.js";
|
|
3
2
|
import { fetch } from "../fetch.js";
|
|
4
|
-
import { permissionsSchema } from "./permissions.js";
|
|
5
3
|
import { softrConfig } from "../softr-config.js";
|
|
4
|
+
import { permissionsSchema } from "./permissions.js";
|
|
5
|
+
import { softrApiUrl } from "../softr-api.js";
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/platform.ts
|
package/dist/auth/session.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readRequestCookies, serializeCookie, writeCookies } from "../cookies.js";
|
|
1
|
+
import { expireCookie, expireOtherCopy, readRequestCookies, serializeCookie, writeCookies } from "../cookies.js";
|
|
2
2
|
import { permissionsSchema } from "./permissions.js";
|
|
3
3
|
import { sessionConfig } from "./config.js";
|
|
4
4
|
import { userSchema } from "./user.js";
|
|
@@ -65,12 +65,16 @@ function readSessionData(sessionToken) {
|
|
|
65
65
|
permissions: payload.permissions
|
|
66
66
|
};
|
|
67
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* The token cookie, after a deletion of any copy from before `allowEmbedding`
|
|
70
|
+
* changed. Both would be sent, and the old one could be read instead.
|
|
71
|
+
*/
|
|
68
72
|
function makeSessionTokenCookie(token) {
|
|
69
73
|
const { name, secure } = sessionCookie(SESSION_TOKEN);
|
|
70
|
-
return serializeCookie(name, sealEnvelope(token, SESSION_TOKEN), {
|
|
74
|
+
return [...expireOtherCopy(name, secure), serializeCookie(name, sealEnvelope(token, SESSION_TOKEN), {
|
|
71
75
|
maxAge: sessionConfig().sessionMaxAge,
|
|
72
76
|
secure
|
|
73
|
-
});
|
|
77
|
+
})];
|
|
74
78
|
}
|
|
75
79
|
function makeSessionDataCookie(session, sessionToken) {
|
|
76
80
|
const { name, secure } = sessionCookie(SESSION_DATA);
|
|
@@ -141,10 +145,7 @@ const sessionDataSchema = z.object({
|
|
|
141
145
|
*/
|
|
142
146
|
function clearCookies(bases) {
|
|
143
147
|
const secure = requestIsSecure();
|
|
144
|
-
writeCookies(bases.flatMap((base) => secure ? [sessionCookieName(base, secure), base] : [base]).
|
|
145
|
-
maxAge: 0,
|
|
146
|
-
secure
|
|
147
|
-
})));
|
|
148
|
+
writeCookies(bases.flatMap((base) => secure ? [sessionCookieName(base, secure), base] : [base]).flatMap((name) => expireCookie(name, secure)));
|
|
148
149
|
}
|
|
149
150
|
/**
|
|
150
151
|
* Over the plaintext token, never the cookie value: that is resealed with a
|
|
@@ -73,15 +73,16 @@ function renderUserPropertiesDoc(users, context) {
|
|
|
73
73
|
"",
|
|
74
74
|
"```tsx",
|
|
75
75
|
"import { createFileRoute, redirect } from '@tanstack/react-router'",
|
|
76
|
-
"import { assertRouteAccess,
|
|
76
|
+
"import { assertRouteAccess, definePage, pageHead } from '@softr/sdk'",
|
|
77
77
|
"",
|
|
78
|
-
"const
|
|
78
|
+
"const pageSettings = definePage({ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] }, title: 'Example' })",
|
|
79
79
|
"",
|
|
80
80
|
"export const Route = createFileRoute('/example')({",
|
|
81
81
|
" beforeLoad: (opts) => {",
|
|
82
|
-
" assertRouteAccess(
|
|
82
|
+
" assertRouteAccess(pageSettings, opts)",
|
|
83
83
|
` if (opts.context.user.properties.${first} == null) throw redirect({ to: '/' })`,
|
|
84
84
|
" },",
|
|
85
|
+
" head: pageHead(pageSettings),",
|
|
85
86
|
"})",
|
|
86
87
|
"```",
|
|
87
88
|
"",
|
|
@@ -90,14 +91,19 @@ function renderUserPropertiesDoc(users, context) {
|
|
|
90
91
|
"```tsx",
|
|
91
92
|
"import { createFileRoute } from '@tanstack/react-router'",
|
|
92
93
|
"import { createServerFn } from '@tanstack/react-start'",
|
|
94
|
+
"import { definePage, guardRoute, pageHead } from '@softr/sdk'",
|
|
93
95
|
"",
|
|
94
96
|
`const get${pascalCase(first)} = createServerFn().handler(async ({ context }) => {`,
|
|
95
97
|
" if (!context.user) throw new Error('Not signed in')",
|
|
96
98
|
` return context.user.properties.${first}`,
|
|
97
99
|
"})",
|
|
98
100
|
"",
|
|
101
|
+
"const pageSettings = definePage({ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] }, title: 'Example' })",
|
|
102
|
+
"",
|
|
99
103
|
"export const Route = createFileRoute('/example')({",
|
|
104
|
+
" beforeLoad: guardRoute(pageSettings),",
|
|
100
105
|
` loader: () => get${pascalCase(first)}(),`,
|
|
106
|
+
" head: pageHead(pageSettings),",
|
|
101
107
|
" component: Example,",
|
|
102
108
|
"})",
|
|
103
109
|
"",
|
package/dist/cookies.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { softAssert } from "./assertions.js";
|
|
2
|
+
import { softrConfig } from "./softr-config.js";
|
|
2
3
|
import { getRequestHeader, getResponseHeaders, setResponseHeader } from "@tanstack/react-start/server";
|
|
3
4
|
|
|
4
5
|
//#region src/cookies.ts
|
|
@@ -36,8 +37,33 @@ function serializeCookie(name, value, { maxAge, secure }) {
|
|
|
36
37
|
return parts.join("; ");
|
|
37
38
|
}
|
|
38
39
|
function sameSiteAttributes(secure) {
|
|
39
|
-
|
|
40
|
-
|
|
40
|
+
return partitions(secure) ? ["SameSite=None", "Partitioned"] : ["SameSite=Lax"];
|
|
41
|
+
}
|
|
42
|
+
function partitions(secure) {
|
|
43
|
+
return secure && (process.env.NODE_ENV !== "production" || (softrConfig().allowEmbedding ?? []).length > 0);
|
|
44
|
+
}
|
|
45
|
+
function expired(name, partitioned) {
|
|
46
|
+
return partitioned ? `${name}=; Path=/; HttpOnly; Secure; SameSite=None; Partitioned; Max-Age=0` : `${name}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The deletions for one cookie. A browser keeps a partitioned and a plain
|
|
50
|
+
* cookie of one name apart, and sends both. Which one the app wrote can change
|
|
51
|
+
* between sign-in and sign-out, when `allowEmbedding` changes. So over https,
|
|
52
|
+
* delete both. The one left behind would keep the visitor signed in.
|
|
53
|
+
*/
|
|
54
|
+
function expireCookie(name, secure) {
|
|
55
|
+
if (!secure) return [serializeCookie(name, "", {
|
|
56
|
+
maxAge: 0,
|
|
57
|
+
secure
|
|
58
|
+
})];
|
|
59
|
+
return [expired(name, false), expired(name, true)];
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The deletion of the copy the other mode would write. Sent with a new cookie,
|
|
63
|
+
* so a copy from before `allowEmbedding` changed can't be read in its place.
|
|
64
|
+
*/
|
|
65
|
+
function expireOtherCopy(name, secure) {
|
|
66
|
+
return secure ? [expired(name, !partitions(secure))] : [];
|
|
41
67
|
}
|
|
42
68
|
const USER_TIMEZONE_COOKIE = "user-timezone";
|
|
43
69
|
function readUserTimezone() {
|
|
@@ -56,4 +82,4 @@ function writeCookies(cookies) {
|
|
|
56
82
|
}
|
|
57
83
|
|
|
58
84
|
//#endregion
|
|
59
|
-
export { readRequestCookies, readUserTimezone, serializeCookie, writeCookies };
|
|
85
|
+
export { expireCookie, expireOtherCopy, readRequestCookies, readUserTimezone, serializeCookie, writeCookies };
|