@softr/sdk 0.0.90-alpha.5 → 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.
- package/dist/agent/agent-fns.d.ts +30 -0
- package/dist/agent/agent-fns.js +215 -0
- package/dist/agent/use-agent-chat.d.ts +106 -0
- package/dist/agent/use-agent-chat.js +486 -0
- package/dist/auth/isomorphic.d.ts +1 -1
- package/dist/auth/isomorphic.js +0 -2
- package/dist/formatting.d.ts +3 -3
- package/dist/index.d.ts +3 -1
- package/dist/index.js +3 -1
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +7 -3
- package/dist/package.js +1 -1
- package/dist/pwa.d.ts +2 -2
- package/package.json +3 -3
- package/skills/softr-sdk/SKILL.md +5 -1
- package/skills/softr-sdk/agent-chat/SKILL.md +109 -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 +1 -1
- 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 +2 -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 +1 -1
- package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
- package/skills/softr-sdk/routes-and-visibility/SKILL.md +1 -1
- package/skills/softr-sdk/workflows/SKILL.md +1 -1
- package/dist/app-identity.js +0 -77
|
@@ -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
|
|
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;
|
package/dist/auth/isomorphic.js
CHANGED
|
@@ -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/formatting.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import * as
|
|
2
|
+
import * as react0 from "react";
|
|
3
3
|
import { ReactNode } from "react";
|
|
4
4
|
|
|
5
5
|
//#region src/formatting.d.ts
|
|
@@ -94,7 +94,7 @@ declare function FormattingScope({
|
|
|
94
94
|
/** A BCP 47 locale, such as `de-DE`. It drops the app's fixed date format inside the scope. */
|
|
95
95
|
locale?: string;
|
|
96
96
|
children?: ReactNode;
|
|
97
|
-
}):
|
|
97
|
+
}): react0.FunctionComponentElement<react0.ProviderProps<Scope>>;
|
|
98
98
|
/**
|
|
99
99
|
* A date in the app's format, safe to render on the server. A timestamp whose
|
|
100
100
|
* zone is not known yet renders `fallback` until the browser supplies it, so
|
|
@@ -115,6 +115,6 @@ declare function FormattedDate({
|
|
|
115
115
|
time?: boolean;
|
|
116
116
|
/** What renders while the visitor's zone is unknown. */
|
|
117
117
|
fallback?: ReactNode;
|
|
118
|
-
}):
|
|
118
|
+
}): react0.FunctionComponentElement<react0.FragmentProps>;
|
|
119
119
|
//#endregion
|
|
120
120
|
export { DateOptions, DateParts, DateSeparator, DateValue, FixedDateFormat, FormattedDate, Formatting, FormattingScope, WeekDay, formatDate, formatDateTime, formatNumber, useFormatting };
|
package/dist/index.d.ts
CHANGED
|
@@ -16,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
|
|
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):
|
|
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
|
-
|
|
389
|
-
|
|
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
package/dist/pwa.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as react4 from "react";
|
|
2
2
|
import "@tanstack/react-start";
|
|
3
3
|
|
|
4
4
|
//#region src/pwa.d.ts
|
|
@@ -23,7 +23,7 @@ import "@tanstack/react-start";
|
|
|
23
23
|
* )
|
|
24
24
|
* }
|
|
25
25
|
*/
|
|
26
|
-
declare function SoftrPwaHead():
|
|
26
|
+
declare function SoftrPwaHead(): react4.FunctionComponentElement<react4.FragmentProps>;
|
|
27
27
|
type PwaPlatform = "ios" | "android" | "desktop";
|
|
28
28
|
type PwaInstall = {
|
|
29
29
|
available: false;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@softr/sdk",
|
|
3
|
-
"version": "0.0.90-alpha.
|
|
3
|
+
"version": "0.0.90-alpha.6",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
|
|
@@ -21,8 +21,8 @@
|
|
|
21
21
|
},
|
|
22
22
|
"devDependencies": {
|
|
23
23
|
"@tanstack/intent": "^0.3.6",
|
|
24
|
-
"@tanstack/react-router": "^1.
|
|
25
|
-
"@tanstack/react-start": "^1.168.
|
|
24
|
+
"@tanstack/react-router": "^1.168.0",
|
|
25
|
+
"@tanstack/react-start": "^1.168.0",
|
|
26
26
|
"@types/node": "^24.3.0",
|
|
27
27
|
"tsdown": "^0.15.0",
|
|
28
28
|
"typescript": "^5.9.2",
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: core
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.90-alpha.
|
|
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
|
|