@softr/sdk 0.0.87-alpha.3 → 0.0.87
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/codegen/datasource-docs.js +9 -3
- package/dist/default-error-overlay.d.ts +2 -2
- package/dist/formatting.d.ts +3 -3
- package/dist/index.d.ts +1 -3
- package/dist/index.js +1 -3
- package/dist/mcp.js +2 -4
- package/dist/package.js +1 -1
- package/dist/pwa.d.ts +2 -2
- package/package.json +1 -1
- package/skills/softr-sdk/SKILL.md +3 -7
- 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
- package/dist/agent/agent-fns.d.ts +0 -30
- package/dist/agent/agent-fns.js +0 -164
- package/dist/agent/use-agent-chat.d.ts +0 -94
- package/dist/agent/use-agent-chat.js +0 -367
- package/skills/softr-sdk/agent-chat/SKILL.md +0 -105
package/dist/agent/agent-fns.js
DELETED
|
@@ -1,164 +0,0 @@
|
|
|
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 agentSchema = z.object({
|
|
86
|
-
id: z.string(),
|
|
87
|
-
title: z.string(),
|
|
88
|
-
avatar: z.string().nullish(),
|
|
89
|
-
thumbnail: z.string().nullish()
|
|
90
|
-
});
|
|
91
|
-
/**
|
|
92
|
-
* The agents the visitor may chat with in this app. The builder attaches them
|
|
93
|
-
* in Studio, and each one's visibility settings decide who sees it.
|
|
94
|
-
*/
|
|
95
|
-
const listAgents = createServerFn({ method: "GET" }).handler(async () => {
|
|
96
|
-
const token = readSessionToken();
|
|
97
|
-
const res = await fetch(`${softrApiUrl("SOFTR_PLATFORM_API_URL")}/v1/vibe/applications/${sessionConfig().applicationId}/agents`, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
|
|
98
|
-
if (!res.ok) throw new Error(`Loading agents failed: ${await describeFailure(res)}`);
|
|
99
|
-
return z.array(agentSchema).parse(await res.json());
|
|
100
|
-
});
|
|
101
|
-
const listAgentChatsFn = createServerFn({ method: "POST" }).validator(z.object({ agentId: z.string().min(1) })).handler(async ({ data }) => {
|
|
102
|
-
const res = await agentsFetch(`${encodeURIComponent(data.agentId)}/sessions`);
|
|
103
|
-
if (!res.ok) throw new Error(`Loading chats failed: ${await describeFailure(res)}`);
|
|
104
|
-
return z.array(z.object({
|
|
105
|
-
id: z.string(),
|
|
106
|
-
title: z.string()
|
|
107
|
-
})).parse(await res.json());
|
|
108
|
-
});
|
|
109
|
-
const historySchema = z.object({
|
|
110
|
-
messages: z.array(z.object({
|
|
111
|
-
id: z.string(),
|
|
112
|
-
role: z.enum(["USER", "ASSISTANT"]),
|
|
113
|
-
content: z.string(),
|
|
114
|
-
createdAt: z.number()
|
|
115
|
-
})),
|
|
116
|
-
toolCalls: z.array(z.object({
|
|
117
|
-
id: z.string(),
|
|
118
|
-
messageId: z.string(),
|
|
119
|
-
toolName: z.string(),
|
|
120
|
-
input: z.string(),
|
|
121
|
-
createdAt: z.number(),
|
|
122
|
-
metadata: z.object({
|
|
123
|
-
innerThought: z.string().nullish(),
|
|
124
|
-
durationMs: z.number().nullish(),
|
|
125
|
-
failed: z.boolean().nullish()
|
|
126
|
-
})
|
|
127
|
-
}))
|
|
128
|
-
});
|
|
129
|
-
/** What a past chat holds, or `null` when it's gone or belongs to someone else. */
|
|
130
|
-
const loadAgentChatFn = createServerFn({ method: "POST" }).validator(z.object({
|
|
131
|
-
agentId: z.string().min(1),
|
|
132
|
-
sessionId: z.string().min(1)
|
|
133
|
-
})).handler(async ({ data }) => {
|
|
134
|
-
const res = await agentsFetch(`${encodeURIComponent(data.agentId)}/sessions/${encodeURIComponent(data.sessionId)}`);
|
|
135
|
-
if ([
|
|
136
|
-
401,
|
|
137
|
-
403,
|
|
138
|
-
404,
|
|
139
|
-
410
|
|
140
|
-
].includes(res.status)) return null;
|
|
141
|
-
if (!res.ok) throw new Error(`Loading the chat failed: ${await describeFailure(res)}`);
|
|
142
|
-
return historySchema.parse(await res.json());
|
|
143
|
-
});
|
|
144
|
-
const decideAgentToolFn = createServerFn({ method: "POST" }).validator(z.object({
|
|
145
|
-
agentId: z.string().min(1),
|
|
146
|
-
sessionId: z.string().min(1),
|
|
147
|
-
toolCallId: z.string().min(1),
|
|
148
|
-
toolName: z.string().min(1),
|
|
149
|
-
decision: z.enum(["APPROVE", "REJECT"]),
|
|
150
|
-
scope: z.enum([
|
|
151
|
-
"ONCE",
|
|
152
|
-
"SESSION",
|
|
153
|
-
"USER"
|
|
154
|
-
])
|
|
155
|
-
})).handler(async ({ data: { agentId,...decision } }) => {
|
|
156
|
-
const res = await agentsFetch(`${encodeURIComponent(agentId)}/tool-permission-decisions`, {
|
|
157
|
-
method: "POST",
|
|
158
|
-
body: decision
|
|
159
|
-
});
|
|
160
|
-
if (!res.ok) throw new Error(`Saving the answer failed: ${await describeFailure(res)}`);
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
//#endregion
|
|
164
|
-
export { agentChatFn, decideAgentToolFn, listAgentChatsFn, listAgents, loadAgentChatFn };
|
|
@@ -1,94 +0,0 @@
|
|
|
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 };
|
|
@@ -1,367 +0,0 @@
|
|
|
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 };
|