@softr/sdk 0.0.85 → 0.0.87-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 +12 -0
- package/dist/agent/agent-fns.js +148 -0
- package/dist/agent/use-agent-chat.d.ts +94 -0
- package/dist/agent/use-agent-chat.js +367 -0
- package/dist/core/options.js +5 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -1
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +4 -2
- package/dist/package.js +1 -1
- package/package.json +1 -1
- package/skills/softr-sdk/SKILL.md +5 -1
- package/skills/softr-sdk/agent-chat/SKILL.md +103 -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 +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 +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
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { assert } from "../assertions.js";
|
|
2
|
+
import { fetch } from "../fetch.js";
|
|
3
|
+
import { sessionConfig } from "../auth/config.js";
|
|
4
|
+
import { readSessionToken } from "../auth/session.js";
|
|
5
|
+
import { softrApiUrl } from "../softr-api.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
|
+
/**
|
|
14
|
+
* Where the agents service is. It sits next to the platform API, so unless
|
|
15
|
+
* `SOFTR_AGENTS_API_URL` says otherwise, it's the platform's host with
|
|
16
|
+
* `agents-api` in place of `platform-api`.
|
|
17
|
+
*/
|
|
18
|
+
function agentsApiUrl() {
|
|
19
|
+
const explicit = process.env.SOFTR_AGENTS_API_URL;
|
|
20
|
+
if (explicit) return explicit.replace(/\/+$/, "");
|
|
21
|
+
if (!process.env.SOFTR_PLATFORM_API_URL) return AGENTS_PRODUCTION;
|
|
22
|
+
const platform = new URL(softrApiUrl("SOFTR_PLATFORM_API_URL"));
|
|
23
|
+
assert(platform.hostname.startsWith("platform-api"), () => `can't tell the agents API from ${platform.origin}, set SOFTR_AGENTS_API_URL`);
|
|
24
|
+
platform.hostname = platform.hostname.replace(/^platform-api/, "agents-api");
|
|
25
|
+
return platform.origin;
|
|
26
|
+
}
|
|
27
|
+
function agentsFetch(path, init = {}) {
|
|
28
|
+
const token = readSessionToken();
|
|
29
|
+
return fetch(`${agentsApiUrl()}/v1/agents/${path}`, {
|
|
30
|
+
method: init.method ?? "GET",
|
|
31
|
+
signal: init.signal,
|
|
32
|
+
headers: {
|
|
33
|
+
"Content-Type": "application/json",
|
|
34
|
+
...token ? { Authorization: `Bearer ${token}` } : {},
|
|
35
|
+
"Softr-Application-ID": sessionConfig().applicationId,
|
|
36
|
+
...refererHeader(),
|
|
37
|
+
...init.headers
|
|
38
|
+
},
|
|
39
|
+
body: init.body === void 0 ? void 0 : JSON.stringify(init.body)
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
const chatSchema = z.object({
|
|
43
|
+
agentId: z.string().min(1),
|
|
44
|
+
message: z.string(),
|
|
45
|
+
sessionId: z.string().nullable(),
|
|
46
|
+
timezone: z.string(),
|
|
47
|
+
pageName: z.string(),
|
|
48
|
+
record: z.object({
|
|
49
|
+
id: z.string(),
|
|
50
|
+
fields: z.record(z.string(), z.unknown())
|
|
51
|
+
}).nullable()
|
|
52
|
+
});
|
|
53
|
+
/**
|
|
54
|
+
* Sends one message and streams the reply back as it comes, one JSON event per line.
|
|
55
|
+
*
|
|
56
|
+
* Takes FormData so the browser can call it with plain `fetch` and read the
|
|
57
|
+
* stream itself. A failed call passes the agents service's status and message on.
|
|
58
|
+
*/
|
|
59
|
+
const agentChatFn = createServerFn({ method: "POST" }).validator((data) => {
|
|
60
|
+
const payload = data.get("payload");
|
|
61
|
+
assert(typeof payload === "string", "agent chat: payload is required");
|
|
62
|
+
return chatSchema.parse(JSON.parse(payload));
|
|
63
|
+
}).handler(async ({ data }) => {
|
|
64
|
+
const upstream = await agentsFetch(`${encodeURIComponent(data.agentId)}/chat`, {
|
|
65
|
+
method: "POST",
|
|
66
|
+
signal: getRequest().signal,
|
|
67
|
+
headers: {
|
|
68
|
+
Accept: "application/x-ndjson",
|
|
69
|
+
"X-User-Timezone": data.timezone
|
|
70
|
+
},
|
|
71
|
+
body: {
|
|
72
|
+
message: data.message,
|
|
73
|
+
...data.sessionId ? { sessionId: data.sessionId } : {},
|
|
74
|
+
context: {
|
|
75
|
+
pageName: data.pageName,
|
|
76
|
+
...data.record ? { currentRecord: { data: data.record } } : {}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
return new Response(upstream.body, {
|
|
81
|
+
status: upstream.status,
|
|
82
|
+
headers: { "Content-Type": upstream.headers.get("Content-Type") ?? "application/x-ndjson" }
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
const listAgentChatsFn = createServerFn({ method: "POST" }).validator(z.object({ agentId: z.string().min(1) })).handler(async ({ data }) => {
|
|
86
|
+
const res = await agentsFetch(`${encodeURIComponent(data.agentId)}/sessions`);
|
|
87
|
+
if (!res.ok) throw new Error(`Loading chats failed: ${await describeFailure(res)}`);
|
|
88
|
+
return z.array(z.object({
|
|
89
|
+
id: z.string(),
|
|
90
|
+
title: z.string()
|
|
91
|
+
})).parse(await res.json());
|
|
92
|
+
});
|
|
93
|
+
const historySchema = z.object({
|
|
94
|
+
messages: z.array(z.object({
|
|
95
|
+
id: z.string(),
|
|
96
|
+
role: z.enum(["USER", "ASSISTANT"]),
|
|
97
|
+
content: z.string(),
|
|
98
|
+
createdAt: z.number()
|
|
99
|
+
})),
|
|
100
|
+
toolCalls: z.array(z.object({
|
|
101
|
+
id: z.string(),
|
|
102
|
+
messageId: z.string(),
|
|
103
|
+
toolName: z.string(),
|
|
104
|
+
input: z.string(),
|
|
105
|
+
createdAt: z.number(),
|
|
106
|
+
metadata: z.object({
|
|
107
|
+
innerThought: z.string().nullish(),
|
|
108
|
+
durationMs: z.number().nullish(),
|
|
109
|
+
failed: z.boolean().nullish()
|
|
110
|
+
})
|
|
111
|
+
}))
|
|
112
|
+
});
|
|
113
|
+
/** What a past chat holds, or `null` when it's gone or belongs to someone else. */
|
|
114
|
+
const loadAgentChatFn = createServerFn({ method: "POST" }).validator(z.object({
|
|
115
|
+
agentId: z.string().min(1),
|
|
116
|
+
sessionId: z.string().min(1)
|
|
117
|
+
})).handler(async ({ data }) => {
|
|
118
|
+
const res = await agentsFetch(`${encodeURIComponent(data.agentId)}/sessions/${encodeURIComponent(data.sessionId)}`);
|
|
119
|
+
if ([
|
|
120
|
+
401,
|
|
121
|
+
403,
|
|
122
|
+
404,
|
|
123
|
+
410
|
|
124
|
+
].includes(res.status)) return null;
|
|
125
|
+
if (!res.ok) throw new Error(`Loading the chat failed: ${await describeFailure(res)}`);
|
|
126
|
+
return historySchema.parse(await res.json());
|
|
127
|
+
});
|
|
128
|
+
const decideAgentToolFn = createServerFn({ method: "POST" }).validator(z.object({
|
|
129
|
+
agentId: z.string().min(1),
|
|
130
|
+
sessionId: z.string().min(1),
|
|
131
|
+
toolCallId: z.string().min(1),
|
|
132
|
+
toolName: z.string().min(1),
|
|
133
|
+
decision: z.enum(["APPROVE", "REJECT"]),
|
|
134
|
+
scope: z.enum([
|
|
135
|
+
"ONCE",
|
|
136
|
+
"SESSION",
|
|
137
|
+
"USER"
|
|
138
|
+
])
|
|
139
|
+
})).handler(async ({ data: { agentId,...decision } }) => {
|
|
140
|
+
const res = await agentsFetch(`${encodeURIComponent(agentId)}/tool-permission-decisions`, {
|
|
141
|
+
method: "POST",
|
|
142
|
+
body: decision
|
|
143
|
+
});
|
|
144
|
+
if (!res.ok) throw new Error(`Saving the answer failed: ${await describeFailure(res)}`);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
//#endregion
|
|
148
|
+
export { agentChatFn, decideAgentToolFn, listAgentChatsFn, loadAgentChatFn };
|
|
@@ -0,0 +1,94 @@
|
|
|
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
|
+
* needs the visitor to connect `integration` first, which code apps can't do yet.
|
|
14
|
+
*/
|
|
15
|
+
status: "running" | "done" | "failed" | "awaiting-approval" | "approved" | "rejected" | "awaiting-connection";
|
|
16
|
+
error?: string;
|
|
17
|
+
integration?: string;
|
|
18
|
+
};
|
|
19
|
+
type AgentTodo = {
|
|
20
|
+
content: string;
|
|
21
|
+
status: "pending" | "in_progress" | "completed";
|
|
22
|
+
};
|
|
23
|
+
type AgentQuestion = {
|
|
24
|
+
question: string;
|
|
25
|
+
header: string;
|
|
26
|
+
options: Array<{
|
|
27
|
+
label: string;
|
|
28
|
+
description: string;
|
|
29
|
+
}>;
|
|
30
|
+
multiSelect: boolean;
|
|
31
|
+
};
|
|
32
|
+
/** One piece of a message, in the order the agent produced it. */
|
|
33
|
+
type AgentBlock = {
|
|
34
|
+
type: "text";
|
|
35
|
+
text: string;
|
|
36
|
+
} | AgentToolCall
|
|
37
|
+
/** The agent's plan. It replaces itself as the agent works through it. */ | {
|
|
38
|
+
type: "todo";
|
|
39
|
+
todos: AgentTodo[];
|
|
40
|
+
}
|
|
41
|
+
/** The agent asks the visitor to pick. They answer by sending a message. */ | {
|
|
42
|
+
type: "question";
|
|
43
|
+
questions: AgentQuestion[];
|
|
44
|
+
} | {
|
|
45
|
+
type: "error";
|
|
46
|
+
message: string;
|
|
47
|
+
};
|
|
48
|
+
type AgentMessage = {
|
|
49
|
+
id: string;
|
|
50
|
+
role: "user" | "assistant";
|
|
51
|
+
blocks: AgentBlock[];
|
|
52
|
+
};
|
|
53
|
+
type AgentChat = {
|
|
54
|
+
/** The whole chat, oldest first. While the agent replies, its reply is the last one and grows. */
|
|
55
|
+
messages: AgentMessage[];
|
|
56
|
+
/** `thinking` until the first part of the reply arrives, `replying` until it ends. */
|
|
57
|
+
status: "idle" | "thinking" | "replying";
|
|
58
|
+
/** Why the last request failed. Cleared by the next one. */
|
|
59
|
+
error: Error | null;
|
|
60
|
+
/** The chat the next message goes to, `null` for a new one. */
|
|
61
|
+
chatId: string | null;
|
|
62
|
+
send: (text: string) => void;
|
|
63
|
+
/** Stops the reply. What arrived so far stays. */
|
|
64
|
+
stop: () => void;
|
|
65
|
+
newChat: () => void;
|
|
66
|
+
/** Opens a past chat from `listChats`. */
|
|
67
|
+
openChat: (chatId: string) => void;
|
|
68
|
+
/** The visitor's past chats with this agent. */
|
|
69
|
+
listChats: () => Promise<AgentChatSummary[]>;
|
|
70
|
+
/** Lets a tool waiting for approval run, once, for this chat, or always for this visitor. */
|
|
71
|
+
approve: (toolCallId: string, scope?: "ONCE" | "SESSION" | "USER") => void;
|
|
72
|
+
reject: (toolCallId: string) => void;
|
|
73
|
+
};
|
|
74
|
+
type AgentChatOptions = {
|
|
75
|
+
/**
|
|
76
|
+
* The record the visitor is looking at, so they can say "this one". Sent
|
|
77
|
+
* with each message. Keys are what the agent reads, so use field names.
|
|
78
|
+
*/
|
|
79
|
+
record?: {
|
|
80
|
+
id: string;
|
|
81
|
+
fields: Record<string, unknown>;
|
|
82
|
+
} | null;
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* A chat with one of the app's Softr agents, as the signed-in visitor. No UI:
|
|
86
|
+
* render `messages` with the app's own components.
|
|
87
|
+
*
|
|
88
|
+
* @example
|
|
89
|
+
* const chat = useAgentChat(AGENT_ID, { record: ticket && { id: ticket.id, fields: ticket.fields } })
|
|
90
|
+
* <form onSubmit={(e) => { e.preventDefault(); chat.send(draft) }}>
|
|
91
|
+
*/
|
|
92
|
+
declare function useAgentChat(agentId: string, options?: AgentChatOptions): AgentChat;
|
|
93
|
+
//#endregion
|
|
94
|
+
export { AgentBlock, AgentChat, AgentChatOptions, AgentMessage, AgentQuestion, AgentTodo, AgentToolCall, useAgentChat };
|
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
import { assert } from "../assertions.js";
|
|
2
|
+
import { agentChatFn, decideAgentToolFn, listAgentChatsFn, loadAgentChatFn } from "./agent-fns.js";
|
|
3
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
4
|
+
|
|
5
|
+
//#region src/agent/use-agent-chat.ts
|
|
6
|
+
/**
|
|
7
|
+
* A chat with one of the app's Softr agents, as the signed-in visitor. No UI:
|
|
8
|
+
* render `messages` with the app's own components.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* const chat = useAgentChat(AGENT_ID, { record: ticket && { id: ticket.id, fields: ticket.fields } })
|
|
12
|
+
* <form onSubmit={(e) => { e.preventDefault(); chat.send(draft) }}>
|
|
13
|
+
*/
|
|
14
|
+
function useAgentChat(agentId, options = {}) {
|
|
15
|
+
const [messages, setMessages] = useState([]);
|
|
16
|
+
const [live, setLive] = useState(null);
|
|
17
|
+
const [status, setStatus] = useState("idle");
|
|
18
|
+
const [error, setError] = useState(null);
|
|
19
|
+
const [chatId, setChatId] = useState(null);
|
|
20
|
+
const chatIdRef = useRef(chatId);
|
|
21
|
+
chatIdRef.current = chatId;
|
|
22
|
+
const recordRef = useRef(options.record ?? null);
|
|
23
|
+
recordRef.current = options.record ?? null;
|
|
24
|
+
const liveRef = useRef(live);
|
|
25
|
+
liveRef.current = live;
|
|
26
|
+
const abortRef = useRef(null);
|
|
27
|
+
useEffect(() => () => abortRef.current?.abort(), []);
|
|
28
|
+
const commitLive = useCallback((blocks) => {
|
|
29
|
+
setLive(null);
|
|
30
|
+
if (!blocks?.some((b) => b.type !== "text" || b.text.trim())) return;
|
|
31
|
+
setMessages((prev) => [...prev, {
|
|
32
|
+
id: crypto.randomUUID(),
|
|
33
|
+
role: "assistant",
|
|
34
|
+
blocks: endRunningTools(blocks)
|
|
35
|
+
}]);
|
|
36
|
+
}, []);
|
|
37
|
+
const stream = useCallback(async (message) => {
|
|
38
|
+
abortRef.current?.abort();
|
|
39
|
+
const controller = new AbortController();
|
|
40
|
+
abortRef.current = controller;
|
|
41
|
+
setError(null);
|
|
42
|
+
setStatus("thinking");
|
|
43
|
+
let blocks = [];
|
|
44
|
+
try {
|
|
45
|
+
const request = {
|
|
46
|
+
agentId,
|
|
47
|
+
message,
|
|
48
|
+
sessionId: chatIdRef.current,
|
|
49
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
50
|
+
pageName: document.title,
|
|
51
|
+
record: recordRef.current
|
|
52
|
+
};
|
|
53
|
+
const form = new FormData();
|
|
54
|
+
form.append("payload", JSON.stringify(request));
|
|
55
|
+
const res = await fetch(agentChatFn.url, {
|
|
56
|
+
method: "POST",
|
|
57
|
+
body: form,
|
|
58
|
+
signal: controller.signal
|
|
59
|
+
});
|
|
60
|
+
if (!res.ok) throw new Error(await failureMessage(res));
|
|
61
|
+
assert(res.body, "agent chat: the reply has no body");
|
|
62
|
+
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
63
|
+
let buffer = "";
|
|
64
|
+
const onLine = (line) => {
|
|
65
|
+
const event = parseEvent(line);
|
|
66
|
+
if (event === null) return;
|
|
67
|
+
if (event.sessionId && event.sessionId !== chatIdRef.current) {
|
|
68
|
+
chatIdRef.current = event.sessionId;
|
|
69
|
+
setChatId(event.sessionId);
|
|
70
|
+
}
|
|
71
|
+
blocks = reduceEvent(blocks, event);
|
|
72
|
+
setLive(blocks);
|
|
73
|
+
setStatus("replying");
|
|
74
|
+
};
|
|
75
|
+
for (;;) {
|
|
76
|
+
const { done, value } = await reader.read();
|
|
77
|
+
if (done) break;
|
|
78
|
+
buffer += value;
|
|
79
|
+
const lines = buffer.split("\n");
|
|
80
|
+
buffer = lines.pop() ?? "";
|
|
81
|
+
lines.forEach(onLine);
|
|
82
|
+
}
|
|
83
|
+
onLine(buffer);
|
|
84
|
+
} catch (err) {
|
|
85
|
+
if (controller.signal.aborted) return;
|
|
86
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
87
|
+
}
|
|
88
|
+
if (abortRef.current !== controller) return;
|
|
89
|
+
abortRef.current = null;
|
|
90
|
+
commitLive(blocks);
|
|
91
|
+
setStatus("idle");
|
|
92
|
+
}, [agentId, commitLive]);
|
|
93
|
+
const send = useCallback((text) => {
|
|
94
|
+
const trimmed = text.trim();
|
|
95
|
+
if (!trimmed) return;
|
|
96
|
+
abortRef.current?.abort();
|
|
97
|
+
commitLive(liveRef.current);
|
|
98
|
+
setMessages((prev) => [...prev, {
|
|
99
|
+
id: crypto.randomUUID(),
|
|
100
|
+
role: "user",
|
|
101
|
+
blocks: [{
|
|
102
|
+
type: "text",
|
|
103
|
+
text: trimmed
|
|
104
|
+
}]
|
|
105
|
+
}]);
|
|
106
|
+
stream(trimmed);
|
|
107
|
+
}, [stream, commitLive]);
|
|
108
|
+
const stop = useCallback(() => {
|
|
109
|
+
if (abortRef.current === null) return;
|
|
110
|
+
abortRef.current.abort();
|
|
111
|
+
abortRef.current = null;
|
|
112
|
+
commitLive(liveRef.current);
|
|
113
|
+
setStatus("idle");
|
|
114
|
+
}, [commitLive]);
|
|
115
|
+
const reset = useCallback((id) => {
|
|
116
|
+
abortRef.current?.abort();
|
|
117
|
+
abortRef.current = null;
|
|
118
|
+
chatIdRef.current = id;
|
|
119
|
+
setChatId(id);
|
|
120
|
+
setMessages([]);
|
|
121
|
+
setLive(null);
|
|
122
|
+
setStatus("idle");
|
|
123
|
+
setError(null);
|
|
124
|
+
}, []);
|
|
125
|
+
const newChat = useCallback(() => reset(null), [reset]);
|
|
126
|
+
const openChat = useCallback((id) => {
|
|
127
|
+
reset(id);
|
|
128
|
+
loadAgentChatFn({ data: {
|
|
129
|
+
agentId,
|
|
130
|
+
sessionId: id
|
|
131
|
+
} }).then((history) => {
|
|
132
|
+
if (chatIdRef.current !== id) return;
|
|
133
|
+
if (history === null) {
|
|
134
|
+
reset(null);
|
|
135
|
+
setError(/* @__PURE__ */ new Error("This chat is no longer available. Start a new one."));
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
setMessages(fromHistory(history));
|
|
139
|
+
}).catch((err) => {
|
|
140
|
+
if (chatIdRef.current === id) setError(err instanceof Error ? err : new Error(String(err)));
|
|
141
|
+
});
|
|
142
|
+
}, [agentId, reset]);
|
|
143
|
+
const listChats = useCallback(() => listAgentChatsFn({ data: { agentId } }), [agentId]);
|
|
144
|
+
const setToolStatus = useCallback((toolCallId, next) => {
|
|
145
|
+
const update = (blocks) => blocks.map((b) => b.type === "tool" && b.id === toolCallId ? {
|
|
146
|
+
...b,
|
|
147
|
+
status: next
|
|
148
|
+
} : b);
|
|
149
|
+
setLive((prev) => prev && update(prev));
|
|
150
|
+
setMessages((prev) => prev.map((m) => ({
|
|
151
|
+
...m,
|
|
152
|
+
blocks: update(m.blocks)
|
|
153
|
+
})));
|
|
154
|
+
}, []);
|
|
155
|
+
const decide = useCallback((toolCallId, decision, scope) => {
|
|
156
|
+
const sessionId = chatIdRef.current;
|
|
157
|
+
const tool = [...messages.flatMap((m) => m.blocks), ...liveRef.current ?? []].find((b) => b.type === "tool" && b.id === toolCallId);
|
|
158
|
+
if (sessionId === null || tool?.status !== "awaiting-approval") return;
|
|
159
|
+
setToolStatus(toolCallId, decision === "APPROVE" ? "approved" : "rejected");
|
|
160
|
+
decideAgentToolFn({ data: {
|
|
161
|
+
agentId,
|
|
162
|
+
sessionId,
|
|
163
|
+
toolCallId,
|
|
164
|
+
toolName: tool.name,
|
|
165
|
+
decision,
|
|
166
|
+
scope
|
|
167
|
+
} }).then(() => {
|
|
168
|
+
if (decision !== "APPROVE") return;
|
|
169
|
+
abortRef.current?.abort();
|
|
170
|
+
commitLive(liveRef.current);
|
|
171
|
+
stream("");
|
|
172
|
+
}).catch((err) => {
|
|
173
|
+
setToolStatus(toolCallId, "awaiting-approval");
|
|
174
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
175
|
+
});
|
|
176
|
+
}, [
|
|
177
|
+
agentId,
|
|
178
|
+
messages,
|
|
179
|
+
setToolStatus,
|
|
180
|
+
commitLive,
|
|
181
|
+
stream
|
|
182
|
+
]);
|
|
183
|
+
const approve = useCallback((toolCallId, scope = "ONCE") => decide(toolCallId, "APPROVE", scope), [decide]);
|
|
184
|
+
const reject = useCallback((toolCallId) => decide(toolCallId, "REJECT", "ONCE"), [decide]);
|
|
185
|
+
return {
|
|
186
|
+
messages: live === null ? messages : [...messages, {
|
|
187
|
+
id: "live",
|
|
188
|
+
role: "assistant",
|
|
189
|
+
blocks: live
|
|
190
|
+
}],
|
|
191
|
+
status,
|
|
192
|
+
error,
|
|
193
|
+
chatId,
|
|
194
|
+
send,
|
|
195
|
+
stop,
|
|
196
|
+
newChat,
|
|
197
|
+
openChat,
|
|
198
|
+
listChats,
|
|
199
|
+
approve,
|
|
200
|
+
reject
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
const TODO_TOOL = "TodoWrite";
|
|
204
|
+
/** Its question shows as a question block, so the call itself is noise. */
|
|
205
|
+
const QUESTION_TOOL = "AskUserQuestion";
|
|
206
|
+
function parseEvent(line) {
|
|
207
|
+
if (!line.trim()) return null;
|
|
208
|
+
try {
|
|
209
|
+
return JSON.parse(line);
|
|
210
|
+
} catch {
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
function reduceEvent(blocks, event) {
|
|
215
|
+
switch (event.type) {
|
|
216
|
+
case "TEXT": {
|
|
217
|
+
const last = blocks.at(-1);
|
|
218
|
+
return last?.type === "text" ? [...blocks.slice(0, -1), {
|
|
219
|
+
type: "text",
|
|
220
|
+
text: last.text + event.response
|
|
221
|
+
}] : [...blocks, {
|
|
222
|
+
type: "text",
|
|
223
|
+
text: event.response
|
|
224
|
+
}];
|
|
225
|
+
}
|
|
226
|
+
case "TOOL_CALL_START":
|
|
227
|
+
if (event.toolName === TODO_TOOL) {
|
|
228
|
+
const todos = parseTodos(event.input);
|
|
229
|
+
if (todos) return upsertTodos(blocks, todos);
|
|
230
|
+
}
|
|
231
|
+
if (event.toolName === QUESTION_TOOL) return blocks;
|
|
232
|
+
if (blocks.some((b) => b.type === "tool" && b.id === event.toolCallId)) return updateTool(blocks, event.toolCallId, (b) => b.status === "running" ? {
|
|
233
|
+
...b,
|
|
234
|
+
input: event.input ?? b.input
|
|
235
|
+
} : b);
|
|
236
|
+
return [...blocks, {
|
|
237
|
+
type: "tool",
|
|
238
|
+
id: event.toolCallId,
|
|
239
|
+
name: event.toolName,
|
|
240
|
+
input: event.input,
|
|
241
|
+
integration: event.integrationType,
|
|
242
|
+
status: "running"
|
|
243
|
+
}];
|
|
244
|
+
case "TOOL_CALL_END": return updateTool(blocks, event.toolCallId, (b) => b.status === "running" || b.status === "approved" ? {
|
|
245
|
+
...b,
|
|
246
|
+
status: event.failed ? "failed" : "done",
|
|
247
|
+
error: event.errorMessage
|
|
248
|
+
} : b);
|
|
249
|
+
case "TOOL_PERMISSION_REQUEST":
|
|
250
|
+
case "INTEGRATION_AUTH_REQUEST": {
|
|
251
|
+
const status = event.type === "TOOL_PERMISSION_REQUEST" ? "awaiting-approval" : "awaiting-connection";
|
|
252
|
+
const integration = event.type === "INTEGRATION_AUTH_REQUEST" ? event.integrationType : void 0;
|
|
253
|
+
if (blocks.some((b) => b.type === "tool" && b.id === event.toolCallId)) return updateTool(blocks, event.toolCallId, (b) => ({
|
|
254
|
+
...b,
|
|
255
|
+
status,
|
|
256
|
+
integration: integration ?? b.integration,
|
|
257
|
+
input: ("input" in event ? event.input : void 0) ?? b.input
|
|
258
|
+
}));
|
|
259
|
+
return [...blocks, {
|
|
260
|
+
type: "tool",
|
|
261
|
+
id: event.toolCallId,
|
|
262
|
+
name: event.toolName,
|
|
263
|
+
input: "input" in event ? event.input : void 0,
|
|
264
|
+
integration,
|
|
265
|
+
status
|
|
266
|
+
}];
|
|
267
|
+
}
|
|
268
|
+
case "QUESTION": return [...blocks, {
|
|
269
|
+
type: "question",
|
|
270
|
+
questions: event.questions
|
|
271
|
+
}];
|
|
272
|
+
case "ERROR": return [...blocks, {
|
|
273
|
+
type: "error",
|
|
274
|
+
message: event.message
|
|
275
|
+
}];
|
|
276
|
+
default: return blocks;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
function updateTool(blocks, id, update) {
|
|
280
|
+
return blocks.map((b) => b.type === "tool" && b.id === id ? update(b) : b);
|
|
281
|
+
}
|
|
282
|
+
/** A reply that ended without finishing a tool call, stopped or cut off, never will. */
|
|
283
|
+
function endRunningTools(blocks) {
|
|
284
|
+
return blocks.map((b) => b.type === "tool" && b.status === "running" ? {
|
|
285
|
+
...b,
|
|
286
|
+
status: "failed",
|
|
287
|
+
error: "The agent stopped before this step finished."
|
|
288
|
+
} : b);
|
|
289
|
+
}
|
|
290
|
+
/** Each plan update re-sends the whole list, so only the latest one is kept, where the first one was. */
|
|
291
|
+
function upsertTodos(blocks, todos) {
|
|
292
|
+
const index = blocks.findIndex((b) => b.type === "todo");
|
|
293
|
+
if (index === -1) return [...blocks, {
|
|
294
|
+
type: "todo",
|
|
295
|
+
todos
|
|
296
|
+
}];
|
|
297
|
+
return blocks.map((b, i) => i === index ? {
|
|
298
|
+
type: "todo",
|
|
299
|
+
todos
|
|
300
|
+
} : b);
|
|
301
|
+
}
|
|
302
|
+
function parseTodos(input) {
|
|
303
|
+
if (!input) return null;
|
|
304
|
+
try {
|
|
305
|
+
const parsed = JSON.parse(input);
|
|
306
|
+
if (typeof parsed !== "object" || parsed === null || !("todos" in parsed)) return null;
|
|
307
|
+
const outer = parsed.todos;
|
|
308
|
+
const raw = typeof outer === "object" && outer !== null && "todos" in outer ? outer.todos : outer;
|
|
309
|
+
if (!Array.isArray(raw)) return null;
|
|
310
|
+
const todos = raw.flatMap((item) => {
|
|
311
|
+
if (typeof item !== "object" || item === null) return [];
|
|
312
|
+
const { content, status } = item;
|
|
313
|
+
if (typeof content !== "string" || !content.trim()) return [];
|
|
314
|
+
if (status !== "pending" && status !== "in_progress" && status !== "completed") return [];
|
|
315
|
+
return [{
|
|
316
|
+
content,
|
|
317
|
+
status
|
|
318
|
+
}];
|
|
319
|
+
});
|
|
320
|
+
return todos.length > 0 ? todos : null;
|
|
321
|
+
} catch {
|
|
322
|
+
return null;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
function fromHistory(history) {
|
|
326
|
+
const toolsByMessage = Map.groupBy(history.toolCalls, (call) => call.messageId);
|
|
327
|
+
return history.messages.filter((m) => m.role !== "USER" || m.content.trim()).map((m) => {
|
|
328
|
+
if (m.role === "USER") return {
|
|
329
|
+
id: m.id,
|
|
330
|
+
role: "user",
|
|
331
|
+
blocks: [{
|
|
332
|
+
type: "text",
|
|
333
|
+
text: m.content
|
|
334
|
+
}]
|
|
335
|
+
};
|
|
336
|
+
let blocks = [];
|
|
337
|
+
const calls = (toolsByMessage.get(m.id) ?? []).toSorted((a, b) => a.createdAt - b.createdAt);
|
|
338
|
+
for (const call of calls) {
|
|
339
|
+
const todos = call.toolName === TODO_TOOL ? parseTodos(call.input) : null;
|
|
340
|
+
if (todos) blocks = upsertTodos(blocks, todos);
|
|
341
|
+
else if (call.toolName !== QUESTION_TOOL) blocks.push({
|
|
342
|
+
type: "tool",
|
|
343
|
+
id: call.id,
|
|
344
|
+
name: call.toolName,
|
|
345
|
+
input: call.input,
|
|
346
|
+
status: call.metadata.failed ? "failed" : "done"
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
if (m.content) blocks.push({
|
|
350
|
+
type: "text",
|
|
351
|
+
text: m.content
|
|
352
|
+
});
|
|
353
|
+
return {
|
|
354
|
+
id: m.id,
|
|
355
|
+
role: "assistant",
|
|
356
|
+
blocks
|
|
357
|
+
};
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
async function failureMessage(res) {
|
|
361
|
+
const body = await res.json().catch(() => null);
|
|
362
|
+
if (typeof body === "object" && body !== null && "message" in body && typeof body.message === "string") return body.message;
|
|
363
|
+
return `The agent could not answer (${res.status}).`;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
//#endregion
|
|
367
|
+
export { useAgentChat };
|
package/dist/core/options.js
CHANGED
|
@@ -53,9 +53,13 @@ async function listOptions(query, { label, term = "", offset = null, limit = 20
|
|
|
53
53
|
nextOffset: page.nextOffset
|
|
54
54
|
};
|
|
55
55
|
}
|
|
56
|
-
/**
|
|
56
|
+
/**
|
|
57
|
+
* The text a label field holds: its own text, or the label of the choice or record it names.
|
|
58
|
+
* A multi-value field, such as a lookup, joins the labels of its values.
|
|
59
|
+
*/
|
|
57
60
|
function labelOf(value) {
|
|
58
61
|
if (value === null || value === void 0) return "";
|
|
62
|
+
if (Array.isArray(value)) return value.map(labelOf).filter((text) => text !== "").join(", ");
|
|
59
63
|
if (typeof value === "object") {
|
|
60
64
|
const label = value.label;
|
|
61
65
|
return typeof label === "string" ? label : "";
|
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 { AgentChatSummary } 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 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, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAgentChat, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
|
package/dist/index.js
CHANGED
|
@@ -12,6 +12,7 @@ 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 { useAgentChat } from "./agent/use-agent-chat.js";
|
|
15
16
|
import { Audience } from "./route/audience.js";
|
|
16
17
|
|
|
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 };
|
|
18
|
+
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, 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_start0 from "@tanstack/react-start";
|
|
3
3
|
|
|
4
4
|
//#region src/mcp.d.ts
|
|
5
5
|
|
|
@@ -31,6 +31,6 @@ type SoftrMcpOptions = {
|
|
|
31
31
|
* ],
|
|
32
32
|
* }))
|
|
33
33
|
*/
|
|
34
|
-
declare function softrMcpMiddleware(options?: SoftrMcpOptions):
|
|
34
|
+
declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>;
|
|
35
35
|
//#endregion
|
|
36
36
|
export { softrMcpMiddleware };
|
package/dist/mcp.js
CHANGED
|
@@ -385,8 +385,10 @@ async function rpc(request, origin, actions) {
|
|
|
385
385
|
const token = bearerToken(request);
|
|
386
386
|
if (token === null) return unauthorized(origin);
|
|
387
387
|
const session = await platformSession(token);
|
|
388
|
-
|
|
389
|
-
|
|
388
|
+
let sessionToken;
|
|
389
|
+
if (session.ok) sessionToken = session.sessionToken;
|
|
390
|
+
else if (session.refused && await resolveUser(token) !== null) sessionToken = token;
|
|
391
|
+
else return session.refused ? unauthorized(origin) : unavailable();
|
|
390
392
|
const body = await readJson(request);
|
|
391
393
|
const message = z.object({
|
|
392
394
|
id: z.union([z.string(), z.number()]).optional(),
|
package/dist/package.js
CHANGED
package/package.json
CHANGED
|
@@ -8,7 +8,7 @@ description: >-
|
|
|
8
8
|
metadata:
|
|
9
9
|
type: core
|
|
10
10
|
library: softr-sdk
|
|
11
|
-
library_version: 0.0.
|
|
11
|
+
library_version: 0.0.86
|
|
12
12
|
---
|
|
13
13
|
|
|
14
14
|
# Softr SDK core
|
|
@@ -48,6 +48,7 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
|
|
|
48
48
|
| Sign a visitor in, out, or up | [auth/SKILL.md](./auth/SKILL.md) |
|
|
49
49
|
| Call a connected third-party API (Slack, Stripe, Gmail, …) | [integrations/SKILL.md](./integrations/SKILL.md) |
|
|
50
50
|
| Open the app to AI assistants over MCP | [mcp/SKILL.md](./mcp/SKILL.md) |
|
|
51
|
+
| Let visitors chat with a Softr agent | [agent-chat/SKILL.md](./agent-chat/SKILL.md) |
|
|
51
52
|
| Let visitors install the app on their home screen | [pwa/SKILL.md](./pwa/SKILL.md) |
|
|
52
53
|
| Show a date, a time or a number | [formatting/SKILL.md](./formatting/SKILL.md) |
|
|
53
54
|
|
|
@@ -84,6 +85,9 @@ Calling a connected third-party API (Slack, Stripe, Gmail, Google Calendar, …)
|
|
|
84
85
|
Opening the app to an AI assistant over MCP?
|
|
85
86
|
load softr-sdk/mcp
|
|
86
87
|
|
|
88
|
+
Adding a chat with one of the app's Softr agents?
|
|
89
|
+
load softr-sdk/agent-chat
|
|
90
|
+
|
|
87
91
|
Adding an install button, or making the app installable?
|
|
88
92
|
load softr-sdk/pwa
|
|
89
93
|
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: agent-chat
|
|
3
|
+
description: >-
|
|
4
|
+
Let visitors chat with one of the app's Softr agents: useAgentChat(agentId,
|
|
5
|
+
{ record }) from @softr/sdk returns the messages, the reply as it streams,
|
|
6
|
+
and send, stop, approve and reject, with no UI. Build the chat from the app's
|
|
7
|
+
own components. The agent acts on the app's data through the app's MCP, so
|
|
8
|
+
softrMcpMiddleware must list the actions it may use.
|
|
9
|
+
metadata:
|
|
10
|
+
type: sub-skill
|
|
11
|
+
library: softr-sdk
|
|
12
|
+
library_version: 0.0.86
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
**Boundary.** `useAgentChat` lives on `@softr/sdk` and runs in a component. It needs no 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. The app gives it a chat. There is no ready-made chat widget: the hook gives the state, and the app draws it with its own components.
|
|
20
|
+
|
|
21
|
+
## Setup
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { useAgentChat } from '@softr/sdk'
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The agent id is a string from Studio. Ask the builder for it if you don't have it, and write it as a literal. Never guess or invent one.
|
|
28
|
+
|
|
29
|
+
## Core pattern
|
|
30
|
+
|
|
31
|
+
```tsx
|
|
32
|
+
function AgentPanel({ ticket }: { ticket: Ticket | null }) {
|
|
33
|
+
const chat = useAgentChat('a1b2c3d4-...', {
|
|
34
|
+
record: ticket && { id: ticket.id, fields: { Title: ticket.title, Status: ticket.status } },
|
|
35
|
+
})
|
|
36
|
+
const [draft, setDraft] = useState('')
|
|
37
|
+
|
|
38
|
+
return (
|
|
39
|
+
<>
|
|
40
|
+
{chat.messages.map((message) => (
|
|
41
|
+
<Message key={message.id} message={message} onApprove={chat.approve} onReject={chat.reject} />
|
|
42
|
+
))}
|
|
43
|
+
{chat.error && <p role="alert">{chat.error.message}</p>}
|
|
44
|
+
<form onSubmit={(e) => { e.preventDefault(); chat.send(draft); setDraft('') }}>
|
|
45
|
+
<Textarea value={draft} onChange={(e) => setDraft(e.target.value)} />
|
|
46
|
+
{chat.status === 'idle'
|
|
47
|
+
? <Button type="submit">Send</Button>
|
|
48
|
+
: <Button type="button" onClick={chat.stop}>Stop</Button>}
|
|
49
|
+
</form>
|
|
50
|
+
</>
|
|
51
|
+
)
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## What the hook returns
|
|
56
|
+
|
|
57
|
+
- `messages`: the whole chat, oldest first. While the agent answers, its reply is the last message and grows as it streams.
|
|
58
|
+
- `status`: `thinking` until the first part of the reply arrives, `replying` until it ends, then `idle`. Show a typing hint while it's `thinking`.
|
|
59
|
+
- `error`: why the last request failed, or `null`.
|
|
60
|
+
- `send(text)`, `stop()`, `newChat()`.
|
|
61
|
+
- `listChats()` resolves to the visitor's past chats, `{ id, title }[]`. `openChat(id)` loads one. `chatId` is the open one, `null` for a new chat.
|
|
62
|
+
- `approve(toolCallId, scope?)` and `reject(toolCallId)` answer a tool waiting for approval. `scope` is `ONCE` (default), `SESSION` for the rest of this chat, or `USER` for always.
|
|
63
|
+
|
|
64
|
+
## Rendering a message
|
|
65
|
+
|
|
66
|
+
Each message has `role` (`user` or `assistant`) and `blocks`, in the order the agent produced them. Render every block type:
|
|
67
|
+
|
|
68
|
+
| Block | Show it as |
|
|
69
|
+
| --- | --- |
|
|
70
|
+
| `text` | Markdown text |
|
|
71
|
+
| `tool` | One line: the tool `name` and its `status`. Collapse finished ones. |
|
|
72
|
+
| `todo` | A checklist of the agent's plan. It updates in place. |
|
|
73
|
+
| `question` | The questions with their options. A click on an option sends its label with `send`. |
|
|
74
|
+
| `error` | An error line inside the reply |
|
|
75
|
+
|
|
76
|
+
A `tool` with status `awaiting-approval` blocks the agent until the visitor answers. Show Approve and Reject buttons on it. The agent continues on its own after an approval.
|
|
77
|
+
|
|
78
|
+
A `tool` with status `awaiting-connection` needs the visitor to connect the `integration` first. Code apps can't do that yet. Say which integration the agent needs, and that the builder has to connect it for this agent in Studio.
|
|
79
|
+
|
|
80
|
+
## Context
|
|
81
|
+
|
|
82
|
+
`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.
|
|
83
|
+
|
|
84
|
+
The page title goes along on its own. Nothing else about the page does, so don't try to send whole lists.
|
|
85
|
+
|
|
86
|
+
## Letting the agent act on the app
|
|
87
|
+
|
|
88
|
+
The agent reads and changes data through the app's own MCP, as the visitor who is chatting. Their groups and each action's `permissions` apply. The actions it may use are the ones listed in `softrMcpMiddleware`. With no MCP wired, the agent can only talk. Load [mcp/SKILL.md](../mcp/SKILL.md) to wire it.
|
|
89
|
+
|
|
90
|
+
## Failure modes
|
|
91
|
+
|
|
92
|
+
**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`.
|
|
93
|
+
|
|
94
|
+
**Rendering only `text` blocks.** A tool waiting for approval never shows, and the agent waits forever. Render every block type.
|
|
95
|
+
|
|
96
|
+
**An invented agent id.** The chat fails on the first message. Use the id from Studio.
|
|
97
|
+
|
|
98
|
+
**Expecting the agent to change data with no MCP wired.** It answers but can't act. List the actions it needs in `softrMcpMiddleware`.
|
|
99
|
+
|
|
100
|
+
## References
|
|
101
|
+
|
|
102
|
+
- [mcp/SKILL.md](../mcp/SKILL.md): the actions the agent may call
|
|
103
|
+
- [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.
|
|
12
|
+
library_version: 0.0.86
|
|
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.
|
|
12
|
+
library_version: 0.0.86
|
|
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.
|
|
@@ -7,7 +7,7 @@ description: >-
|
|
|
7
7
|
metadata:
|
|
8
8
|
type: sub-skill
|
|
9
9
|
library: softr-sdk
|
|
10
|
-
library_version: 0.0.
|
|
10
|
+
library_version: 0.0.86
|
|
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.
|
|
@@ -7,7 +7,7 @@ description: >-
|
|
|
7
7
|
metadata:
|
|
8
8
|
type: sub-skill
|
|
9
9
|
library: softr-sdk
|
|
10
|
-
library_version: 0.0.
|
|
10
|
+
library_version: 0.0.86
|
|
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.
|
|
12
|
+
library_version: 0.0.86
|
|
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.
|
|
@@ -8,7 +8,7 @@ description: >-
|
|
|
8
8
|
metadata:
|
|
9
9
|
type: sub-skill
|
|
10
10
|
library: softr-sdk
|
|
11
|
-
library_version: 0.0.
|
|
11
|
+
library_version: 0.0.86
|
|
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.
|
|
12
|
+
library_version: 0.0.86
|
|
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.
|
|
12
|
+
library_version: 0.0.86
|
|
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.
|