@base44-preview/platform 0.2.0-pr.336.059c4cd → 0.3.0-pr.338.12ff73f
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/README.md +27 -0
- package/dist/react/chat-items.d.ts +51 -0
- package/dist/react/chat-items.js +234 -0
- package/dist/react/chat.types.d.ts +334 -0
- package/dist/react/chat.types.js +1 -0
- package/dist/react/index.d.ts +4 -0
- package/dist/react/index.js +2 -0
- package/dist/react/useBase44Chat.d.ts +48 -0
- package/dist/react/useBase44Chat.js +352 -0
- package/dist/server/modules/webhooks.events.generated.d.ts +80 -21
- package/dist/server/modules/webhooks.events.generated.js +1 -1
- package/package.json +24 -4
package/README.md
CHANGED
|
@@ -233,3 +233,30 @@ exceptions, payloads and credentials are never attached.
|
|
|
233
233
|
|
|
234
234
|
No SDK dependency, package version or lockfile changes are required. Socket.IO
|
|
235
235
|
remains the existing SDK dependency. Chat commands and HTTP APIs are outside this entry point.
|
|
236
|
+
|
|
237
|
+
## React
|
|
238
|
+
|
|
239
|
+
`@base44/platform/react` adds one hook, `useBase44Chat`, that runs a builder chat for one
|
|
240
|
+
app on top of this client: it opens the live session and renews it, turns messages into items
|
|
241
|
+
made for rendering, binds every question the builder asks to the step it belongs to. It renders nothing. React is an optional peer dependency, loaded only by this
|
|
242
|
+
entry; the root entry stays framework-free.
|
|
243
|
+
|
|
244
|
+
```tsx
|
|
245
|
+
import { useBase44Chat } from "@base44/platform/react";
|
|
246
|
+
|
|
247
|
+
const chat = useBase44Chat({ appId, backend, onAppCreated });
|
|
248
|
+
chat.items.map((item) =>
|
|
249
|
+
item.steps.map((step) => step.question?.kind === "approval" && <button onClick={step.question.approve}>Allow</button>),
|
|
250
|
+
);
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
`backend` is four functions your backend provides, in any language behind them: `createApp`,
|
|
254
|
+
`openLiveSession`, `sendMessage` and `submitToolCallInput`, each wrapping one Base44 REST
|
|
255
|
+
call with your credentials, so the browser never holds a key. The hook returns `items`, a
|
|
256
|
+
`status` (`ready`, `submitted`, `building`, `waiting`, `error`), a `connection` (`connecting`,
|
|
257
|
+
`connected`, `disconnected`), an `error`, and the actions `send`, `create` and `clearError`. `send` needs an app; `create` makes
|
|
258
|
+
the first, and the chat watches it while `appId` is `null`. A sent prompt shows at once as a
|
|
259
|
+
`pending` item until Base44's own message arrives; a prompt sent mid-build waits in Base44's
|
|
260
|
+
queue meanwhile. A question is a union on `kind` (`choice`, `secrets`, `approval`) and carries only the
|
|
261
|
+
actions its kind allows, and declining is always one of them. As in Base44's builder, only the
|
|
262
|
+
last assistant message makes the chat wait; a kind this release doesn't know is declined for you. Every shape has JSDoc in `src/react/chat.types.ts`.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { Message } from "../client/modules/builder.events.generated.js";
|
|
2
|
+
import type { ToolCall } from "../client/modules/builder.events.types.js";
|
|
3
|
+
import type { ChatItem, ChatQuestion, ChatStep } from "./chat.types.js";
|
|
4
|
+
/** @internal Sends the answer to the one tool call a question belongs to. */
|
|
5
|
+
export type AnswerToolCall = (approve: boolean, extraUserInput?: Record<string, unknown>) => Promise<void>;
|
|
6
|
+
/** @internal Sends an answer to a given tool call in a given message. */
|
|
7
|
+
export type SubmitAnswer = (toolCallId: string, messageId: string, approve: boolean, extraUserInput?: Record<string, unknown>) => Promise<void>;
|
|
8
|
+
/** @internal Events can arrive out of order, so messages are ordered by when they were created. */
|
|
9
|
+
export declare function sortMessages(messages: Message[]): Message[];
|
|
10
|
+
/** @internal Replaces the message with the same id in place, or adds it at the end. */
|
|
11
|
+
export declare function mergeMessage(messages: Message[], updatedMessage: Message): Message[];
|
|
12
|
+
/** @internal How many of the newest messages a snapshot holds. */
|
|
13
|
+
export declare const SNAPSHOT_SIZE = 50;
|
|
14
|
+
/** @internal A rejoin's snapshot holds only the newest messages: it is the truth for its window,
|
|
15
|
+
* and the messages before its oldest one stay. A snapshot with room to spare holds them all. */
|
|
16
|
+
export declare function mergeSnapshot(heldMessages: Message[], snapshotMessages: Message[]): Message[];
|
|
17
|
+
/** @internal Turns sorted messages into items. A waiting tool call that is not answered yet and is
|
|
18
|
+
* of a kind this release knows carries its own question, in the last turn reply only: the one that
|
|
19
|
+
* makes the chat wait. Older waiting calls keep their status but no question. */
|
|
20
|
+
export declare function toItems(sortedMessages: Message[], answeredToolCallIds: string[], submitAnswer: SubmitAnswer): ChatItem[];
|
|
21
|
+
/** @internal Base44's tool call status, as a step's. */
|
|
22
|
+
export declare function stepStatus(toolCall: ToolCall): ChatStep["status"];
|
|
23
|
+
/** @internal Whether the chat waits on the user. Like Base44's builder, only the last turn reply
|
|
24
|
+
* counts, and a call answered or declined here stops counting. */
|
|
25
|
+
export declare function isWaitingForUser(sortedMessages: Message[], answeredToolCallIds: string[]): boolean;
|
|
26
|
+
/** @internal Waiting calls on the last turn reply whose kind Base44 names and this release doesn't
|
|
27
|
+
* know, to decline. A call with no kind comes only from old messages and is left alone. */
|
|
28
|
+
export declare function unknownKindToolCalls(sortedMessages: Message[]): {
|
|
29
|
+
toolCallId: string;
|
|
30
|
+
messageId: string;
|
|
31
|
+
}[];
|
|
32
|
+
/** @internal The ids of every tool call Base44 reports waiting. */
|
|
33
|
+
export declare function waitingToolCallIds(sortedMessages: Message[]): Set<string>;
|
|
34
|
+
/** @internal A prompt sent from this chat that Base44 has not confirmed, for the app it went to. */
|
|
35
|
+
export interface PendingPrompt {
|
|
36
|
+
id: string;
|
|
37
|
+
content: string;
|
|
38
|
+
createdAt: string;
|
|
39
|
+
appId: string;
|
|
40
|
+
}
|
|
41
|
+
/** @internal Prompts that arrived from Base44 as messages settle the pending ones with the same
|
|
42
|
+
* text. Base44's public send carries no client id, so text is the only link, and a prompt someone
|
|
43
|
+
* else sent to the same app never settles one of ours. */
|
|
44
|
+
export declare function settlePendingPrompts(pendingPrompts: PendingPrompt[], appId: string, arrivedPrompts: string[]): PendingPrompt[];
|
|
45
|
+
/** @internal Pending prompts as items, drawn after the messages Base44 has. */
|
|
46
|
+
export declare function pendingPromptItems(pendingPrompts: PendingPrompt[]): ChatItem[];
|
|
47
|
+
/** @internal Base44's question formats, as one simple shape per kind, each bound to the call that
|
|
48
|
+
* answers it. Base44 keys choice answers by position, so `picked` and `texts` follow `questions`,
|
|
49
|
+
* and like Base44's builder a single pick goes in `selected_label`, several in `selected_labels`,
|
|
50
|
+
* and free text in `custom_text`. A kind this release doesn't know has no shape. */
|
|
51
|
+
export declare function toQuestion(toolCall: ToolCall, answerToolCall: AnswerToolCall): ChatQuestion | undefined;
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/** @internal Events can arrive out of order, so messages are ordered by when they were created. */
|
|
2
|
+
export function sortMessages(messages) {
|
|
3
|
+
return [...messages].sort((first, second) => { var _a, _b, _c, _d; return ((_b = (_a = first.metadata) === null || _a === void 0 ? void 0 : _a.created_date) !== null && _b !== void 0 ? _b : "").localeCompare((_d = (_c = second.metadata) === null || _c === void 0 ? void 0 : _c.created_date) !== null && _d !== void 0 ? _d : ""); });
|
|
4
|
+
}
|
|
5
|
+
/** @internal Replaces the message with the same id in place, or adds it at the end. */
|
|
6
|
+
export function mergeMessage(messages, updatedMessage) {
|
|
7
|
+
const isKnown = messages.some(message => message.id === updatedMessage.id);
|
|
8
|
+
if (!isKnown)
|
|
9
|
+
return [...messages, updatedMessage];
|
|
10
|
+
return messages.map(message => (message.id === updatedMessage.id ? updatedMessage : message));
|
|
11
|
+
}
|
|
12
|
+
/** @internal How many of the newest messages a snapshot holds. */
|
|
13
|
+
export const SNAPSHOT_SIZE = 50;
|
|
14
|
+
/** @internal A rejoin's snapshot holds only the newest messages: it is the truth for its window,
|
|
15
|
+
* and the messages before its oldest one stay. A snapshot with room to spare holds them all. */
|
|
16
|
+
export function mergeSnapshot(heldMessages, snapshotMessages) {
|
|
17
|
+
var _a, _b, _c;
|
|
18
|
+
if (snapshotMessages.length < SNAPSHOT_SIZE)
|
|
19
|
+
return snapshotMessages;
|
|
20
|
+
const oldestSnapshotDate = (_c = (_b = (_a = sortMessages(snapshotMessages)[0]) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.created_date) !== null && _c !== void 0 ? _c : "";
|
|
21
|
+
const snapshotIds = new Set(snapshotMessages.map(message => message.id));
|
|
22
|
+
const olderMessages = heldMessages.filter(message => { var _a, _b; return !snapshotIds.has(message.id) && ((_b = (_a = message.metadata) === null || _a === void 0 ? void 0 : _a.created_date) !== null && _b !== void 0 ? _b : "") < oldestSnapshotDate; });
|
|
23
|
+
return [...olderMessages, ...snapshotMessages];
|
|
24
|
+
}
|
|
25
|
+
/** @internal An assistant message that answers a turn. Base44 injects notices that expect no reply. */
|
|
26
|
+
function isTurnReply(message) {
|
|
27
|
+
var _a;
|
|
28
|
+
return (message === null || message === void 0 ? void 0 : message.role) === "assistant" && !((_a = message.additional_message_params) === null || _a === void 0 ? void 0 : _a.skip_ai_response);
|
|
29
|
+
}
|
|
30
|
+
/** @internal The last assistant message that answers a turn, as Base44's own builder finds it. */
|
|
31
|
+
function lastTurnReply(sortedMessages) {
|
|
32
|
+
return [...sortedMessages].reverse().find(isTurnReply);
|
|
33
|
+
}
|
|
34
|
+
/** @internal Turns sorted messages into items. A waiting tool call that is not answered yet and is
|
|
35
|
+
* of a kind this release knows carries its own question, in the last turn reply only: the one that
|
|
36
|
+
* makes the chat wait. Older waiting calls keep their status but no question. */
|
|
37
|
+
export function toItems(sortedMessages, answeredToolCallIds, submitAnswer) {
|
|
38
|
+
const lastReply = lastTurnReply(sortedMessages);
|
|
39
|
+
return sortedMessages.map(message => {
|
|
40
|
+
var _a, _b, _c, _d;
|
|
41
|
+
return ({
|
|
42
|
+
id: message.id,
|
|
43
|
+
role: message.role === "user" ? "user" : "assistant",
|
|
44
|
+
text: (_a = message.content) !== null && _a !== void 0 ? _a : "",
|
|
45
|
+
createdAt: (_c = (_b = message.metadata) === null || _b === void 0 ? void 0 : _b.created_date) !== null && _c !== void 0 ? _c : "",
|
|
46
|
+
pending: false,
|
|
47
|
+
steps: ((_d = message.tool_calls) !== null && _d !== void 0 ? _d : []).map(toolCall => {
|
|
48
|
+
const isAnswerable = message === lastReply && !answeredToolCallIds.includes(toolCall.id);
|
|
49
|
+
const answerToolCall = isAnswerable
|
|
50
|
+
? (approve, extraUserInput) => submitAnswer(toolCall.id, message.id, approve, extraUserInput)
|
|
51
|
+
: undefined;
|
|
52
|
+
return toStep(toolCall, answerToolCall);
|
|
53
|
+
}),
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function toStep(toolCall, answerToolCall) {
|
|
58
|
+
var _a, _b, _c, _d;
|
|
59
|
+
const toolName = (_a = toolCall.name) !== null && _a !== void 0 ? _a : "";
|
|
60
|
+
const display = "display" in toolCall ? toolCall.display : undefined;
|
|
61
|
+
const files = (_b = display === null || display === void 0 ? void 0 : display.file_paths) !== null && _b !== void 0 ? _b : [];
|
|
62
|
+
const summary = (_c = display === null || display === void 0 ? void 0 : display.summary) !== null && _c !== void 0 ? _c : (_d = toolArguments(toolCall)) === null || _d === void 0 ? void 0 : _d.summary;
|
|
63
|
+
const status = stepStatus(toolCall);
|
|
64
|
+
const question = status === "waiting" && answerToolCall ? toQuestion(toolCall, answerToolCall) : undefined;
|
|
65
|
+
const answered = answersOf(toolCall);
|
|
66
|
+
return {
|
|
67
|
+
id: toolCall.id,
|
|
68
|
+
tool: toolName,
|
|
69
|
+
files,
|
|
70
|
+
label: stepLabel(toolName, files, summary, display),
|
|
71
|
+
status,
|
|
72
|
+
...(question && { question }),
|
|
73
|
+
...(answered && { answered }),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
// Base44's own description of the step reads best; then the entity it touched; then the files.
|
|
77
|
+
function stepLabel(toolName, files, summary, display) {
|
|
78
|
+
if (summary)
|
|
79
|
+
return summary;
|
|
80
|
+
const entityName = display === null || display === void 0 ? void 0 : display.entity_name;
|
|
81
|
+
if (entityName) {
|
|
82
|
+
const recordCount = display === null || display === void 0 ? void 0 : display.record_count;
|
|
83
|
+
return recordCount === undefined ? `${toolName} ${entityName}` : `${toolName} ${entityName} (${recordCount})`;
|
|
84
|
+
}
|
|
85
|
+
return [toolName, ...files].join(" ");
|
|
86
|
+
}
|
|
87
|
+
// What the user answered on a choice, each answer next to the question it answers.
|
|
88
|
+
function answersOf(toolCall) {
|
|
89
|
+
var _a, _b, _c;
|
|
90
|
+
const userInput = "user_input" in toolCall ? toolCall.user_input : undefined;
|
|
91
|
+
if (!((_a = userInput === null || userInput === void 0 ? void 0 : userInput.answers) === null || _a === void 0 ? void 0 : _a.length))
|
|
92
|
+
return undefined;
|
|
93
|
+
const questions = (_c = (_b = toolArguments(toolCall)) === null || _b === void 0 ? void 0 : _b.questions) !== null && _c !== void 0 ? _c : [];
|
|
94
|
+
return userInput.answers.map(answer => {
|
|
95
|
+
var _a, _b, _c, _d;
|
|
96
|
+
const labels = (_a = answer.selected_labels) !== null && _a !== void 0 ? _a : (answer.selected_label ? [answer.selected_label] : []);
|
|
97
|
+
const question = (_d = (_c = questions[(_b = answer.question_index) !== null && _b !== void 0 ? _b : -1]) === null || _c === void 0 ? void 0 : _c.question) !== null && _d !== void 0 ? _d : "";
|
|
98
|
+
return { question, labels, ...(answer.custom_text && { text: answer.custom_text }) };
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/** @internal Base44's tool call status, as a step's. */
|
|
102
|
+
export function stepStatus(toolCall) {
|
|
103
|
+
if (toolCall.status === "running")
|
|
104
|
+
return "running";
|
|
105
|
+
if (toolCall.status === "waiting_for_user_input")
|
|
106
|
+
return "waiting";
|
|
107
|
+
if (toolCall.status === "stopped")
|
|
108
|
+
return "stopped";
|
|
109
|
+
if (toolCall.status === "error")
|
|
110
|
+
return "error";
|
|
111
|
+
return "done";
|
|
112
|
+
}
|
|
113
|
+
/** @internal Whether the chat waits on the user. Like Base44's builder, only the last turn reply
|
|
114
|
+
* counts, and a call answered or declined here stops counting. */
|
|
115
|
+
export function isWaitingForUser(sortedMessages, answeredToolCallIds) {
|
|
116
|
+
var _a;
|
|
117
|
+
const lastReply = lastTurnReply(sortedMessages);
|
|
118
|
+
return !!((_a = lastReply === null || lastReply === void 0 ? void 0 : lastReply.tool_calls) === null || _a === void 0 ? void 0 : _a.some(toolCall => toolCall.status === "waiting_for_user_input" && !answeredToolCallIds.includes(toolCall.id)));
|
|
119
|
+
}
|
|
120
|
+
const KNOWN_QUESTION_KINDS = ["approval", "choice", "input"];
|
|
121
|
+
/** @internal Waiting calls on the last turn reply whose kind Base44 names and this release doesn't
|
|
122
|
+
* know, to decline. A call with no kind comes only from old messages and is left alone. */
|
|
123
|
+
export function unknownKindToolCalls(sortedMessages) {
|
|
124
|
+
var _a;
|
|
125
|
+
const lastReply = lastTurnReply(sortedMessages);
|
|
126
|
+
if (!lastReply)
|
|
127
|
+
return [];
|
|
128
|
+
return ((_a = lastReply.tool_calls) !== null && _a !== void 0 ? _a : [])
|
|
129
|
+
.filter(toolCall => {
|
|
130
|
+
var _a;
|
|
131
|
+
const kind = (_a = toolCall.waiting_on) === null || _a === void 0 ? void 0 : _a.kind;
|
|
132
|
+
return toolCall.status === "waiting_for_user_input" && !!kind && !KNOWN_QUESTION_KINDS.includes(kind);
|
|
133
|
+
})
|
|
134
|
+
.map(toolCall => ({ toolCallId: toolCall.id, messageId: lastReply.id }));
|
|
135
|
+
}
|
|
136
|
+
/** @internal The ids of every tool call Base44 reports waiting. */
|
|
137
|
+
export function waitingToolCallIds(sortedMessages) {
|
|
138
|
+
return new Set(sortedMessages.flatMap(message => { var _a; return ((_a = message.tool_calls) !== null && _a !== void 0 ? _a : []).filter(toolCall => toolCall.status === "waiting_for_user_input").map(toolCall => toolCall.id); }));
|
|
139
|
+
}
|
|
140
|
+
/** @internal Prompts that arrived from Base44 as messages settle the pending ones with the same
|
|
141
|
+
* text. Base44's public send carries no client id, so text is the only link, and a prompt someone
|
|
142
|
+
* else sent to the same app never settles one of ours. */
|
|
143
|
+
export function settlePendingPrompts(pendingPrompts, appId, arrivedPrompts) {
|
|
144
|
+
let stillPending = pendingPrompts;
|
|
145
|
+
for (const arrivedPrompt of arrivedPrompts) {
|
|
146
|
+
const settled = stillPending.find(prompt => prompt.appId === appId && prompt.content.trim() === arrivedPrompt.trim());
|
|
147
|
+
if (settled)
|
|
148
|
+
stillPending = stillPending.filter(prompt => prompt !== settled);
|
|
149
|
+
}
|
|
150
|
+
return stillPending;
|
|
151
|
+
}
|
|
152
|
+
/** @internal Pending prompts as items, drawn after the messages Base44 has. */
|
|
153
|
+
export function pendingPromptItems(pendingPrompts) {
|
|
154
|
+
return pendingPrompts.map(prompt => ({ id: prompt.id, role: "user", text: prompt.content, createdAt: prompt.createdAt, steps: [], pending: true }));
|
|
155
|
+
}
|
|
156
|
+
/** @internal Base44's question formats, as one simple shape per kind, each bound to the call that
|
|
157
|
+
* answers it. Base44 keys choice answers by position, so `picked` and `texts` follow `questions`,
|
|
158
|
+
* and like Base44's builder a single pick goes in `selected_label`, several in `selected_labels`,
|
|
159
|
+
* and free text in `custom_text`. A kind this release doesn't know has no shape. */
|
|
160
|
+
export function toQuestion(toolCall, answerToolCall) {
|
|
161
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
|
|
162
|
+
const kind = (_a = toolCall.waiting_on) === null || _a === void 0 ? void 0 : _a.kind;
|
|
163
|
+
const decline = () => answerToolCall(false);
|
|
164
|
+
if (kind === "choice") {
|
|
165
|
+
const questions = (_c = (_b = toolArguments(toolCall)) === null || _b === void 0 ? void 0 : _b.questions) !== null && _c !== void 0 ? _c : [];
|
|
166
|
+
return {
|
|
167
|
+
kind,
|
|
168
|
+
questions: questions.map(question => {
|
|
169
|
+
var _a, _b;
|
|
170
|
+
return ({
|
|
171
|
+
text: (_a = question.question) !== null && _a !== void 0 ? _a : "",
|
|
172
|
+
description: question.description,
|
|
173
|
+
type: question.type,
|
|
174
|
+
options: ((_b = question.options) !== null && _b !== void 0 ? _b : []).map(option => { var _a; return (typeof option === "string" ? option : (_a = option.label) !== null && _a !== void 0 ? _a : ""); }),
|
|
175
|
+
multi: !!question.multi_select,
|
|
176
|
+
});
|
|
177
|
+
}),
|
|
178
|
+
answer: (picked, texts = []) => {
|
|
179
|
+
const answers = questions.flatMap((question, questionIndex) => {
|
|
180
|
+
var _a, _b;
|
|
181
|
+
const labels = (_a = picked[questionIndex]) !== null && _a !== void 0 ? _a : [];
|
|
182
|
+
const customText = (_b = texts[questionIndex]) === null || _b === void 0 ? void 0 : _b.trim();
|
|
183
|
+
if (!labels.length && !customText)
|
|
184
|
+
return [];
|
|
185
|
+
const answer = { question_index: questionIndex };
|
|
186
|
+
if (question.multi_select && labels.length)
|
|
187
|
+
answer.selected_labels = labels;
|
|
188
|
+
if (!question.multi_select && labels.length)
|
|
189
|
+
answer.selected_label = labels[0];
|
|
190
|
+
if (customText)
|
|
191
|
+
answer.custom_text = customText;
|
|
192
|
+
return [answer];
|
|
193
|
+
});
|
|
194
|
+
return answerToolCall(true, { answers });
|
|
195
|
+
},
|
|
196
|
+
decline,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
if (kind === "input") {
|
|
200
|
+
const secretFields = (_e = (_d = toolArguments(toolCall)) === null || _d === void 0 ? void 0 : _d.secrets_schema) !== null && _e !== void 0 ? _e : [];
|
|
201
|
+
return {
|
|
202
|
+
kind: "secrets",
|
|
203
|
+
fields: secretFields.map(field => { var _a; return ({ name: (_a = field.secretName) !== null && _a !== void 0 ? _a : "", description: field.description }); }),
|
|
204
|
+
submit: values => answerToolCall(true, { secrets: values }),
|
|
205
|
+
decline,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
if (kind === "approval") {
|
|
209
|
+
// Guards that declare a reason or details carry them; the others name only themselves.
|
|
210
|
+
const approval = toolCall.approval;
|
|
211
|
+
const reason = (_h = (_f = approval === null || approval === void 0 ? void 0 : approval.reason) !== null && _f !== void 0 ? _f : (_g = approval === null || approval === void 0 ? void 0 : approval.details) === null || _g === void 0 ? void 0 : _g.summary) !== null && _h !== void 0 ? _h : "";
|
|
212
|
+
const guard = (_j = approval === null || approval === void 0 ? void 0 : approval.guard) !== null && _j !== void 0 ? _j : "";
|
|
213
|
+
return { kind, action: (_k = toolCall.name) !== null && _k !== void 0 ? _k : "", reason, guard, details: approvalDetails(approval === null || approval === void 0 ? void 0 : approval.details), approve: () => answerToolCall(true), decline };
|
|
214
|
+
}
|
|
215
|
+
return undefined;
|
|
216
|
+
}
|
|
217
|
+
function approvalDetails(details) {
|
|
218
|
+
if (!details)
|
|
219
|
+
return {};
|
|
220
|
+
const mapped = {
|
|
221
|
+
summary: details.summary,
|
|
222
|
+
entityName: details.entity_name,
|
|
223
|
+
changeType: details.change_type,
|
|
224
|
+
changedOps: details.changed_ops,
|
|
225
|
+
functionName: details.function_name,
|
|
226
|
+
method: details.method,
|
|
227
|
+
inspectionFailed: details.inspection_failed,
|
|
228
|
+
};
|
|
229
|
+
return Object.fromEntries(Object.entries(mapped).filter(([, value]) => value !== undefined));
|
|
230
|
+
}
|
|
231
|
+
// The waiting kind says which arguments a call carries; the tool's name only narrows the union.
|
|
232
|
+
function toolArguments(toolCall) {
|
|
233
|
+
return "arguments" in toolCall ? toolCall.arguments : undefined;
|
|
234
|
+
}
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import type { SocketSession } from "../client/modules/builder.types.js";
|
|
2
|
+
/** An app the AI chat works on. */
|
|
3
|
+
export interface Base44App {
|
|
4
|
+
/** ID of the app, 24 lowercase hexadecimal characters. */
|
|
5
|
+
id: string;
|
|
6
|
+
/** Display name of the app. */
|
|
7
|
+
name: string;
|
|
8
|
+
}
|
|
9
|
+
/** An answer to a question the AI waits on. Declining is `approve: false`. */
|
|
10
|
+
export interface ToolCallAnswer {
|
|
11
|
+
/** ID of the tool call being answered. */
|
|
12
|
+
toolCallId: string;
|
|
13
|
+
/** ID of the assistant message that holds the tool call. */
|
|
14
|
+
messageId: string;
|
|
15
|
+
/** Whether to let the tool call run (`true`) or turn it down (`false`). */
|
|
16
|
+
approve: boolean;
|
|
17
|
+
/** What the question asked for. A choice sends `{ answers }`, and a secrets question sends `{ secrets }`. */
|
|
18
|
+
extraUserInput?: Record<string, unknown>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The four calls your backend makes to Base44 for the chat.
|
|
22
|
+
*
|
|
23
|
+
* Each call wraps one Base44 API request with your credentials, so the browser never holds a
|
|
24
|
+
* workspace API key or an access token. Your backend can be written in any language.
|
|
25
|
+
*
|
|
26
|
+
* - `createApp`: [Create app](/api-reference/create-app), with the first prompt as `initial_message`.
|
|
27
|
+
* - `openLiveSession`: [Create socket session](/api-reference/create-socket-session) with `{ app_ids: [appId] }`.
|
|
28
|
+
* Return the response body unchanged. It holds a session token, never the workspace API key.
|
|
29
|
+
* - `sendMessage`: [Send chat message](/api-reference/send-chat-message).
|
|
30
|
+
* - `submitToolCallInput`: [Submit tool-call input](/api-reference/submit-tool-call-input). Send an
|
|
31
|
+
* `X-Request-ID` built from the tool call ID, so a retry resumes the turn only once.
|
|
32
|
+
*
|
|
33
|
+
* Base44 keeps the Send chat message and Submit tool-call input requests open until the AI
|
|
34
|
+
* finishes the turn. Resolve your call once Base44 accepts the request, not when it returns. The
|
|
35
|
+
* chat follows the rest live. A rejected promise from any call sets `error` on the {@link useBase44Chat | chat}.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```typescript
|
|
39
|
+
* // Your four calls, behind your own API routes
|
|
40
|
+
* async function post<T>(path: string, body: unknown): Promise<T> {
|
|
41
|
+
* const response = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
|
42
|
+
* if (!response.ok) throw new Error(`${path} failed: ${response.status}`);
|
|
43
|
+
* return response.json();
|
|
44
|
+
* }
|
|
45
|
+
*
|
|
46
|
+
* const backend: Base44ChatBackend = {
|
|
47
|
+
* createApp: (prompt) => post("/api/chat/apps", { prompt }),
|
|
48
|
+
* openLiveSession: (appId) => post("/api/chat/session", { appId }),
|
|
49
|
+
* sendMessage: (appId, content) => post("/api/chat/message", { appId, content }),
|
|
50
|
+
* submitToolCallInput: (appId, answer) => post("/api/chat/answer", { appId, answer }),
|
|
51
|
+
* };
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
export interface Base44ChatBackend {
|
|
55
|
+
/**
|
|
56
|
+
* Creates an app from its first prompt. The AI starts building inside this call.
|
|
57
|
+
*
|
|
58
|
+
* @param prompt - The first prompt, which describes the app.
|
|
59
|
+
* @returns Promise resolving to the new app.
|
|
60
|
+
*/
|
|
61
|
+
createApp(prompt: string): Promise<Base44App>;
|
|
62
|
+
/**
|
|
63
|
+
* Opens a read-only socket session for one app. The chat calls it on the first connect and again
|
|
64
|
+
* whenever the session expires. Sessions last one hour.
|
|
65
|
+
*
|
|
66
|
+
* @param appId - ID of the app to follow.
|
|
67
|
+
* @returns Promise resolving to the Create socket session response body, unchanged.
|
|
68
|
+
*/
|
|
69
|
+
openLiveSession(appId: string): Promise<SocketSession>;
|
|
70
|
+
/**
|
|
71
|
+
* Sends a prompt to an existing app. Base44 queues a prompt sent while the AI is working. When the
|
|
72
|
+
* app has no queue, Base44 refuses it with a 409, so reject the promise.
|
|
73
|
+
*
|
|
74
|
+
* @param appId - ID of the app.
|
|
75
|
+
* @param content - The prompt.
|
|
76
|
+
* @returns Promise resolving once Base44 accepts the prompt.
|
|
77
|
+
*/
|
|
78
|
+
sendMessage(appId: string, content: string): Promise<void>;
|
|
79
|
+
/**
|
|
80
|
+
* Answers or declines a question the AI waits on.
|
|
81
|
+
*
|
|
82
|
+
* @param appId - ID of the app.
|
|
83
|
+
* @param answer - The tool call and the answer to it.
|
|
84
|
+
* @returns Promise resolving once Base44 accepts the answer.
|
|
85
|
+
*/
|
|
86
|
+
submitToolCallInput(appId: string, answer: ToolCallAnswer): Promise<void>;
|
|
87
|
+
}
|
|
88
|
+
/** One message of the chat, shaped for rendering. */
|
|
89
|
+
export interface ChatItem {
|
|
90
|
+
/** ID of the message. */
|
|
91
|
+
id: string;
|
|
92
|
+
/** Who wrote the message. */
|
|
93
|
+
role: "user" | "assistant";
|
|
94
|
+
/** The message text, as raw markdown. It comes before the steps, and is empty when the message only holds tool calls. */
|
|
95
|
+
text: string;
|
|
96
|
+
/** When the message was created, as an ISO timestamp. Base44's timestamps are UTC with no time zone. A pending prompt carries the browser's time. */
|
|
97
|
+
createdAt: string;
|
|
98
|
+
/** One step per tool call, in order. */
|
|
99
|
+
steps: ChatStep[];
|
|
100
|
+
/**
|
|
101
|
+
* Whether this is a prompt sent from this chat that Base44 hasn't confirmed yet. It shows at once,
|
|
102
|
+
* and Base44's own message replaces it. A failed send removes it. A prompt sent while the AI is
|
|
103
|
+
* working waits in Base44's queue and stays pending until it runs.
|
|
104
|
+
*/
|
|
105
|
+
pending: boolean;
|
|
106
|
+
}
|
|
107
|
+
/** One tool call, as a line of activity. */
|
|
108
|
+
export interface ChatStep {
|
|
109
|
+
/** ID of the tool call. */
|
|
110
|
+
id: string;
|
|
111
|
+
/** Name of the tool, such as `write_file`. */
|
|
112
|
+
tool: string;
|
|
113
|
+
/** The file paths the tool call touched. */
|
|
114
|
+
files: string[];
|
|
115
|
+
/** A line ready to show. It's Base44's description of the step when there is one, then the entity it touched, then the tool name and its files. */
|
|
116
|
+
label: string;
|
|
117
|
+
/**
|
|
118
|
+
* Where the tool call is. A `waiting` step waits on the user. A `stopped` step was declined, or the
|
|
119
|
+
* turn was stopped.
|
|
120
|
+
*/
|
|
121
|
+
status: "running" | "waiting" | "done" | "stopped" | "error";
|
|
122
|
+
/**
|
|
123
|
+
* The question this step waits on, with the actions that answer it. Present only while the step is
|
|
124
|
+
* `waiting` in the last assistant message, which is the one that makes the chat wait. It goes away
|
|
125
|
+
* once answered, and is absent for a question kind this release doesn't know.
|
|
126
|
+
*/
|
|
127
|
+
question?: ChatQuestion;
|
|
128
|
+
/** What the user answered on a choice question, once answered. It stays after the question closes, so the chat's history shows it. */
|
|
129
|
+
answered?: ChatAnswer[];
|
|
130
|
+
}
|
|
131
|
+
/** One answer to a choice question, next to the question it answers. */
|
|
132
|
+
export interface ChatAnswer {
|
|
133
|
+
/** The question text. */
|
|
134
|
+
question: string;
|
|
135
|
+
/** The labels the user picked. */
|
|
136
|
+
labels: string[];
|
|
137
|
+
/** The free text the user wrote, if any. */
|
|
138
|
+
text?: string;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* An open question, with the actions that answer this question and no other.
|
|
142
|
+
*
|
|
143
|
+
* Each kind carries only the actions that make sense for it, and every kind can be declined. The
|
|
144
|
+
* actions never throw. A failure sets `error` on the {@link useBase44Chat | chat}, and the question opens again.
|
|
145
|
+
*
|
|
146
|
+
* The chat declines a question kind this release doesn't know, once per tool call, when Base44
|
|
147
|
+
* names that kind on the last assistant message. If the decline fails, the chat's `error` says
|
|
148
|
+
* so, and the chat tries again after it reconnects.
|
|
149
|
+
*/
|
|
150
|
+
export type ChatQuestion = ChoiceQuestion | SecretsQuestion | ApprovalQuestion;
|
|
151
|
+
/** One of the questions in a {@link ChoiceQuestion}. */
|
|
152
|
+
export interface ChoiceEntry {
|
|
153
|
+
/** The question text. */
|
|
154
|
+
text: string;
|
|
155
|
+
/** Supporting text for the question. */
|
|
156
|
+
description?: string;
|
|
157
|
+
/** Base44's type of question, such as `text_input` for one that takes only a free-text answer. */
|
|
158
|
+
type?: string;
|
|
159
|
+
/** The option labels to pick from. */
|
|
160
|
+
options: string[];
|
|
161
|
+
/** Whether more than one option can be picked. */
|
|
162
|
+
multi: boolean;
|
|
163
|
+
}
|
|
164
|
+
/** The AI offers options and waits for the user to pick. */
|
|
165
|
+
export interface ChoiceQuestion {
|
|
166
|
+
/** Kind of question. */
|
|
167
|
+
kind: "choice";
|
|
168
|
+
/** The questions, in order. */
|
|
169
|
+
questions: ChoiceEntry[];
|
|
170
|
+
/**
|
|
171
|
+
* Answers with the picked labels, and free text where the user wrote some.
|
|
172
|
+
*
|
|
173
|
+
* @param picked - One list of picked labels per question, in the order of `questions`.
|
|
174
|
+
* @param texts - One free-text answer per question, in the same order. Use it for a `text_input` question, or as a note beside a pick. A question with no pick and no text is skipped.
|
|
175
|
+
* @returns Promise resolving once the answer is sent.
|
|
176
|
+
*/
|
|
177
|
+
answer(picked: string[][], texts?: string[]): Promise<void>;
|
|
178
|
+
/**
|
|
179
|
+
* Declines the question. The AI continues without the answer.
|
|
180
|
+
*
|
|
181
|
+
* @returns Promise resolving once the decline is sent.
|
|
182
|
+
*/
|
|
183
|
+
decline(): Promise<void>;
|
|
184
|
+
}
|
|
185
|
+
/** A value the AI needs, such as an API key. */
|
|
186
|
+
export interface SecretField {
|
|
187
|
+
/** Name of the field, used as its key in `submit`. */
|
|
188
|
+
name: string;
|
|
189
|
+
/** Where to get the value. */
|
|
190
|
+
description?: string;
|
|
191
|
+
}
|
|
192
|
+
/** The AI needs secrets, such as API keys. The values go to Base44 and the chat keeps none of them. */
|
|
193
|
+
export interface SecretsQuestion {
|
|
194
|
+
/** Kind of question. */
|
|
195
|
+
kind: "secrets";
|
|
196
|
+
/** The fields to fill. */
|
|
197
|
+
fields: SecretField[];
|
|
198
|
+
/**
|
|
199
|
+
* Submits the values.
|
|
200
|
+
*
|
|
201
|
+
* @param values - The values, keyed by field name.
|
|
202
|
+
* @returns Promise resolving once the values are sent.
|
|
203
|
+
*/
|
|
204
|
+
submit(values: Record<string, string>): Promise<void>;
|
|
205
|
+
/**
|
|
206
|
+
* Declines the question. The AI continues without the values.
|
|
207
|
+
*
|
|
208
|
+
* @returns Promise resolving once the decline is sent.
|
|
209
|
+
*/
|
|
210
|
+
decline(): Promise<void>;
|
|
211
|
+
}
|
|
212
|
+
/** The AI asks for permission to run an action. */
|
|
213
|
+
export interface ApprovalQuestion {
|
|
214
|
+
/** Kind of question. */
|
|
215
|
+
kind: "approval";
|
|
216
|
+
/** Name of the tool that wants to run. */
|
|
217
|
+
action: string;
|
|
218
|
+
/** Why the action needs approval, when Base44 gives a reason. Empty otherwise. */
|
|
219
|
+
reason: string;
|
|
220
|
+
/** The check that paused the action, such as `exec_tool_send_email` or `entity_rls_guard`. */
|
|
221
|
+
guard: string;
|
|
222
|
+
/** What the action would do, as far as the check publishes it. Show it so the user knows what they approve. */
|
|
223
|
+
details: ApprovalDetails;
|
|
224
|
+
/**
|
|
225
|
+
* Lets the action run.
|
|
226
|
+
*
|
|
227
|
+
* @returns Promise resolving once the approval is sent.
|
|
228
|
+
*/
|
|
229
|
+
approve(): Promise<void>;
|
|
230
|
+
/**
|
|
231
|
+
* Declines the action. It never runs, and the AI continues.
|
|
232
|
+
*
|
|
233
|
+
* @returns Promise resolving once the decline is sent.
|
|
234
|
+
*/
|
|
235
|
+
decline(): Promise<void>;
|
|
236
|
+
}
|
|
237
|
+
/** What an action that waits for approval would do. Each check publishes only some of these. */
|
|
238
|
+
export interface ApprovalDetails {
|
|
239
|
+
/** The AI's summary of what the code does. */
|
|
240
|
+
summary?: string;
|
|
241
|
+
/** The entity whose records or access rules change. */
|
|
242
|
+
entityName?: string;
|
|
243
|
+
/** How the access rules change. */
|
|
244
|
+
changeType?: string;
|
|
245
|
+
/** The access operations whose rules change. */
|
|
246
|
+
changedOps?: string[];
|
|
247
|
+
/** The backend function under test. */
|
|
248
|
+
functionName?: string;
|
|
249
|
+
/** The entity method the code calls, such as `delete`. */
|
|
250
|
+
method?: string;
|
|
251
|
+
/** Whether the check couldn't verify the function's source. */
|
|
252
|
+
inspectionFailed?: boolean;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* What the AI is doing. When several hold at once, the first in this list wins.
|
|
256
|
+
*
|
|
257
|
+
* - `error`: Base44 reports that the last build failed.
|
|
258
|
+
* - `waiting`: a question waits on the user.
|
|
259
|
+
* - `building`: the AI is working.
|
|
260
|
+
* - `submitted`: a prompt, a new app or an answer is on its way. It lasts until Base44 reports work, a reply or a queue change, or the call fails.
|
|
261
|
+
* - `ready`: none of the above.
|
|
262
|
+
*/
|
|
263
|
+
export type ChatStatus = "ready" | "submitted" | "building" | "waiting" | "error";
|
|
264
|
+
/**
|
|
265
|
+
* Whether the chat follows the app live.
|
|
266
|
+
*
|
|
267
|
+
* - `connecting`: until the first snapshot arrives.
|
|
268
|
+
* - `connected`: after the first snapshot.
|
|
269
|
+
* - `disconnected`: live updates stopped for good. The session couldn't open, the retries ran out,
|
|
270
|
+
* or Base44 ended the session or the app's subscription. {@link Base44Chat.error} says why.
|
|
271
|
+
*
|
|
272
|
+
* Watching another app, or mounting the chat again, starts over.
|
|
273
|
+
*/
|
|
274
|
+
export type ChatConnection = "connecting" | "connected" | "disconnected";
|
|
275
|
+
/** A failure of a call, of the live connection, or of the build. */
|
|
276
|
+
export interface ChatError {
|
|
277
|
+
/** What went wrong, for people. */
|
|
278
|
+
message: string;
|
|
279
|
+
/**
|
|
280
|
+
* What went wrong, for code. A connection error carries a `PlatformSocketErrorCode`, and a failed
|
|
281
|
+
* build carries `build_failed`. A failed call to your backend carries none.
|
|
282
|
+
*/
|
|
283
|
+
code?: string;
|
|
284
|
+
/** The original error, for logging. */
|
|
285
|
+
cause?: unknown;
|
|
286
|
+
}
|
|
287
|
+
/** Options for {@link useBase44Chat}. */
|
|
288
|
+
export interface Base44ChatOptions {
|
|
289
|
+
/**
|
|
290
|
+
* ID of the app to follow, or `null` until an app exists. While it's `null`, the chat follows the
|
|
291
|
+
* app {@link Base44Chat.create} made. Any change to `appId` forgets that app.
|
|
292
|
+
*/
|
|
293
|
+
appId: string | null;
|
|
294
|
+
/** The four calls your backend makes to Base44. The chat reads the latest on every action, so an inline object works. */
|
|
295
|
+
backend: Base44ChatBackend;
|
|
296
|
+
/**
|
|
297
|
+
* Called with the new app after {@link Base44Chat.create} succeeds. The chat already follows it.
|
|
298
|
+
* Pass its ID back as `appId` to keep it in your own state.
|
|
299
|
+
*/
|
|
300
|
+
onAppCreated?: (app: Base44App) => void;
|
|
301
|
+
}
|
|
302
|
+
/** The chat that {@link useBase44Chat} returns. */
|
|
303
|
+
export interface Base44Chat {
|
|
304
|
+
/** The conversation, oldest first, with open questions bound to their steps. */
|
|
305
|
+
items: ChatItem[];
|
|
306
|
+
/** What the AI is doing. */
|
|
307
|
+
status: ChatStatus;
|
|
308
|
+
/** Whether the chat follows the app live. */
|
|
309
|
+
connection: ChatConnection;
|
|
310
|
+
/**
|
|
311
|
+
* The last failure. It's set whenever `status` is `error`, and on any failed call or connection
|
|
312
|
+
* error. A failed call's error clears on the next action. A connection error stays until
|
|
313
|
+
* {@link Base44Chat.clearError}. A failed build stays while Base44 reports it.
|
|
314
|
+
*/
|
|
315
|
+
error: ChatError | null;
|
|
316
|
+
/**
|
|
317
|
+
* Sends a prompt to the current app. Base44 queues it while the AI is working. The prompt shows
|
|
318
|
+
* at once as a pending item, and the reply arrives through `items`. Without an app, it sets
|
|
319
|
+
* `error`. Use {@link Base44Chat.create} for the first prompt.
|
|
320
|
+
*
|
|
321
|
+
* @param prompt - The prompt to send.
|
|
322
|
+
* @returns Promise resolving once Base44 accepts the prompt. It never rejects.
|
|
323
|
+
*/
|
|
324
|
+
send(prompt: string): Promise<void>;
|
|
325
|
+
/**
|
|
326
|
+
* Creates an app from its first prompt and reports it through `onAppCreated`.
|
|
327
|
+
*
|
|
328
|
+
* @param prompt - The first prompt, which describes the app.
|
|
329
|
+
* @returns Promise resolving once the app exists. It never rejects.
|
|
330
|
+
*/
|
|
331
|
+
create(prompt: string): Promise<void>;
|
|
332
|
+
/** Clears {@link Base44Chat.error}. A failed build's error stays while Base44 reports it. */
|
|
333
|
+
clearError(): void;
|
|
334
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** The `@base44/platform/react` entry: the AI chat for one app, as a React hook. React is an optional peer, loaded only here. */
|
|
2
|
+
export { useBase44Chat } from "./useBase44Chat.js";
|
|
3
|
+
export type { ApprovalDetails, ApprovalQuestion, Base44App, Base44Chat, Base44ChatOptions, Base44ChatBackend, ChatAnswer, ChatConnection, ChatError, ChatItem, ChatQuestion, ChatStatus, ChatStep, ChoiceEntry, ChoiceQuestion, SecretField, SecretsQuestion, ToolCallAnswer, } from "./chat.types.js";
|
|
4
|
+
export type { SocketSession } from "../client/modules/builder.types.js";
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Base44Chat, Base44ChatOptions } from "./chat.types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Runs the AI chat for one app in your own UI.
|
|
4
|
+
*
|
|
5
|
+
* The hook renders nothing. It gives you the conversation and the actions, and you draw them:
|
|
6
|
+
* - Follows the app live, and renews its socket session when it expires.
|
|
7
|
+
* - Turns Base44's messages into {@link ChatItem | items}, with each open question bound to the step it belongs to.
|
|
8
|
+
* - Reports what the AI is doing in {@link Base44Chat.status}, and the live connection in {@link Base44Chat.connection}.
|
|
9
|
+
* - Sends prompts, creates apps and answers questions through the {@link Base44ChatBackend | backend} you pass, so no credential reaches the browser.
|
|
10
|
+
*
|
|
11
|
+
* The actions never throw. A failure sets {@link Base44Chat.error}, and a question whose answer
|
|
12
|
+
* failed opens again. The chat declines a question kind this release doesn't know.
|
|
13
|
+
*
|
|
14
|
+
* Requires a browser environment and can't be used in the backend.
|
|
15
|
+
*
|
|
16
|
+
* The chat follows `appId` when it's set. While `appId` is `null`, it follows the app
|
|
17
|
+
* {@link Base44Chat.create} made, so passing the new ID back is optional. Any change to `appId`
|
|
18
|
+
* forgets that app, so setting it back to `null` starts a new chat. Switching apps closes the old
|
|
19
|
+
* session and starts over.
|
|
20
|
+
*
|
|
21
|
+
* @param options - The app to follow, your backend's calls, and what to do with a created app.
|
|
22
|
+
* @returns The conversation, its status, connection and error, and the actions `send`, `create` and `clearError`.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```typescript
|
|
26
|
+
* // Draw the chat and answer an approval
|
|
27
|
+
* const chat = useBase44Chat({ appId, backend, onAppCreated: selectApp });
|
|
28
|
+
* return (
|
|
29
|
+
* <>
|
|
30
|
+
* {chat.items.map((item) => (
|
|
31
|
+
* <div key={item.id} className={item.role}>
|
|
32
|
+
* {item.text && <p>{item.text}</p>}
|
|
33
|
+
* {item.steps.map((step) =>
|
|
34
|
+
* step.question?.kind === "approval" ? (
|
|
35
|
+
* <button key={step.id} onClick={step.question.approve}>Allow {step.question.action}</button>
|
|
36
|
+
* ) : (
|
|
37
|
+
* <small key={step.id}>{step.label}</small>
|
|
38
|
+
* ),
|
|
39
|
+
* )}
|
|
40
|
+
* </div>
|
|
41
|
+
* ))}
|
|
42
|
+
* {chat.error && <p role="alert">{chat.error.message}</p>}
|
|
43
|
+
* <button onClick={() => (appId ? chat.send(prompt) : chat.create(prompt))}>Send</button>
|
|
44
|
+
* </>
|
|
45
|
+
* );
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export declare function useBase44Chat({ appId, backend, onAppCreated }: Base44ChatOptions): Base44Chat;
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
3
|
+
import { createPlatformClient } from "../client/client.js";
|
|
4
|
+
import { isWaitingForUser, mergeMessage, mergeSnapshot, pendingPromptItems, settlePendingPrompts, sortMessages, toItems, unknownKindToolCalls, waitingToolCallIds } from "./chat-items.js";
|
|
5
|
+
// Base44's public status carries no reason, so a failed build has one error.
|
|
6
|
+
const BUILD_FAILED_ERROR = { message: "The build failed", code: "build_failed" };
|
|
7
|
+
// The target of `submittedTo` while `create` runs, before the new app has an id.
|
|
8
|
+
const NEW_APP = "new-app";
|
|
9
|
+
/**
|
|
10
|
+
* Runs the AI chat for one app in your own UI.
|
|
11
|
+
*
|
|
12
|
+
* The hook renders nothing. It gives you the conversation and the actions, and you draw them:
|
|
13
|
+
* - Follows the app live, and renews its socket session when it expires.
|
|
14
|
+
* - Turns Base44's messages into {@link ChatItem | items}, with each open question bound to the step it belongs to.
|
|
15
|
+
* - Reports what the AI is doing in {@link Base44Chat.status}, and the live connection in {@link Base44Chat.connection}.
|
|
16
|
+
* - Sends prompts, creates apps and answers questions through the {@link Base44ChatBackend | backend} you pass, so no credential reaches the browser.
|
|
17
|
+
*
|
|
18
|
+
* The actions never throw. A failure sets {@link Base44Chat.error}, and a question whose answer
|
|
19
|
+
* failed opens again. The chat declines a question kind this release doesn't know.
|
|
20
|
+
*
|
|
21
|
+
* Requires a browser environment and can't be used in the backend.
|
|
22
|
+
*
|
|
23
|
+
* The chat follows `appId` when it's set. While `appId` is `null`, it follows the app
|
|
24
|
+
* {@link Base44Chat.create} made, so passing the new ID back is optional. Any change to `appId`
|
|
25
|
+
* forgets that app, so setting it back to `null` starts a new chat. Switching apps closes the old
|
|
26
|
+
* session and starts over.
|
|
27
|
+
*
|
|
28
|
+
* @param options - The app to follow, your backend's calls, and what to do with a created app.
|
|
29
|
+
* @returns The conversation, its status, connection and error, and the actions `send`, `create` and `clearError`.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```typescript
|
|
33
|
+
* // Draw the chat and answer an approval
|
|
34
|
+
* const chat = useBase44Chat({ appId, backend, onAppCreated: selectApp });
|
|
35
|
+
* return (
|
|
36
|
+
* <>
|
|
37
|
+
* {chat.items.map((item) => (
|
|
38
|
+
* <div key={item.id} className={item.role}>
|
|
39
|
+
* {item.text && <p>{item.text}</p>}
|
|
40
|
+
* {item.steps.map((step) =>
|
|
41
|
+
* step.question?.kind === "approval" ? (
|
|
42
|
+
* <button key={step.id} onClick={step.question.approve}>Allow {step.question.action}</button>
|
|
43
|
+
* ) : (
|
|
44
|
+
* <small key={step.id}>{step.label}</small>
|
|
45
|
+
* ),
|
|
46
|
+
* )}
|
|
47
|
+
* </div>
|
|
48
|
+
* ))}
|
|
49
|
+
* {chat.error && <p role="alert">{chat.error.message}</p>}
|
|
50
|
+
* <button onClick={() => (appId ? chat.send(prompt) : chat.create(prompt))}>Send</button>
|
|
51
|
+
* </>
|
|
52
|
+
* );
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
export function useBase44Chat({ appId, backend, onAppCreated }) {
|
|
56
|
+
var _a;
|
|
57
|
+
const [messages, setMessages] = useState([]);
|
|
58
|
+
const [buildState, setBuildState] = useState();
|
|
59
|
+
const [connection, setConnection] = useState("connecting");
|
|
60
|
+
// A failed action's error, which the next action clears, and the connection's, which it doesn't.
|
|
61
|
+
const [actionError, setActionError] = useState(null);
|
|
62
|
+
const [connectionError, setConnectionError] = useState(null);
|
|
63
|
+
// Tool calls answered here while Base44 still reports them waiting.
|
|
64
|
+
const [answeredToolCallIds, setAnsweredToolCallIds] = useState([]);
|
|
65
|
+
// The app a prompt, a new app or an answer went to, until Base44 reacts to it.
|
|
66
|
+
const [submittedTo, setSubmittedTo] = useState(null);
|
|
67
|
+
// Prompts sent from here, shown until Base44 has them.
|
|
68
|
+
const [pendingPrompts, setPendingPrompts] = useState([]);
|
|
69
|
+
const pendingPromptCount = useRef(0);
|
|
70
|
+
// Tool calls declined for the user, and those whose decline failed and may try again.
|
|
71
|
+
const declinedToolCalls = useRef(new Set());
|
|
72
|
+
const failedDeclines = useRef(new Set());
|
|
73
|
+
// Tool calls answered from here whose submission ends when Base44 stops reporting them waiting.
|
|
74
|
+
const answersAwaitingBase44 = useRef(new Set());
|
|
75
|
+
// The app `create` made, shown while `appId` is null. Any change to `appId` forgets it.
|
|
76
|
+
const [createdAppId, setCreatedAppId] = useState(null);
|
|
77
|
+
const [previousAppIdProp, setPreviousAppIdProp] = useState(appId);
|
|
78
|
+
const appIdPropChanged = previousAppIdProp !== appId;
|
|
79
|
+
if (appIdPropChanged) {
|
|
80
|
+
setPreviousAppIdProp(appId);
|
|
81
|
+
setCreatedAppId(null);
|
|
82
|
+
}
|
|
83
|
+
// The app this chat shows.
|
|
84
|
+
const currentAppId = appId !== null && appId !== void 0 ? appId : (appIdPropChanged ? null : createdAppId);
|
|
85
|
+
// Switching apps starts over: the state resets in the same render that sees the new app.
|
|
86
|
+
// A submission aimed at the new app, the one `create` just made, stays.
|
|
87
|
+
const [stateAppId, setStateAppId] = useState(currentAppId);
|
|
88
|
+
if (stateAppId !== currentAppId) {
|
|
89
|
+
setStateAppId(currentAppId);
|
|
90
|
+
setMessages([]);
|
|
91
|
+
setBuildState(undefined);
|
|
92
|
+
setConnection("connecting");
|
|
93
|
+
setActionError(null);
|
|
94
|
+
setConnectionError(null);
|
|
95
|
+
setAnsweredToolCallIds([]);
|
|
96
|
+
if (submittedTo !== currentAppId && submittedTo !== NEW_APP)
|
|
97
|
+
setSubmittedTo(null);
|
|
98
|
+
// Only the app `create` just handed over keeps its first prompt; any other is dropped, so it
|
|
99
|
+
// can't reappear when that app is picked later.
|
|
100
|
+
const handedOver = submittedTo !== null && submittedTo === currentAppId;
|
|
101
|
+
setPendingPrompts(pendingPrompts.filter(prompt => prompt.appId === NEW_APP || (handedOver && prompt.appId === currentAppId)));
|
|
102
|
+
}
|
|
103
|
+
// The backend is read through a ref, kept current after every render, so an inline
|
|
104
|
+
// `backend={{…}}` never reopens the socket or changes the actions' identity.
|
|
105
|
+
const backendRef = useRef(backend);
|
|
106
|
+
useEffect(() => {
|
|
107
|
+
backendRef.current = backend;
|
|
108
|
+
});
|
|
109
|
+
// The app the chat follows now, so a call that finishes after a switch doesn't touch the new app.
|
|
110
|
+
const followedAppIdRef = useRef(currentAppId);
|
|
111
|
+
useEffect(() => {
|
|
112
|
+
followedAppIdRef.current = currentAppId;
|
|
113
|
+
}, [currentAppId]);
|
|
114
|
+
const stillFollowing = (targetAppId) => followedAppIdRef.current === targetAppId;
|
|
115
|
+
const reportActionError = useCallback((error) => setActionError({ message: (error === null || error === void 0 ? void 0 : error.message) || "Something went wrong", cause: error }), []);
|
|
116
|
+
// Live updates: a snapshot on every connect, then events.
|
|
117
|
+
useEffect(() => {
|
|
118
|
+
const followedAppId = currentAppId;
|
|
119
|
+
if (!followedAppId)
|
|
120
|
+
return;
|
|
121
|
+
let closed = false;
|
|
122
|
+
const reportConnectionError = (error) => {
|
|
123
|
+
if (closed)
|
|
124
|
+
return;
|
|
125
|
+
setConnectionError({ message: (error === null || error === void 0 ? void 0 : error.message) || "Live updates failed", code: error === null || error === void 0 ? void 0 : error.code, cause: error });
|
|
126
|
+
};
|
|
127
|
+
// A failure of the session or the subscription ends live updates: nothing retries after it.
|
|
128
|
+
const endLiveUpdates = (error) => {
|
|
129
|
+
reportConnectionError(error);
|
|
130
|
+
if (!closed)
|
|
131
|
+
setConnection("disconnected");
|
|
132
|
+
};
|
|
133
|
+
// A new reply ends the submission. A new user message is Base44's copy of a prompt, which
|
|
134
|
+
// settles the pending one.
|
|
135
|
+
const seenMessageIds = new Set();
|
|
136
|
+
const handleIncomingMessages = (incomingMessages) => {
|
|
137
|
+
const newMessages = incomingMessages.filter(message => message.id && !seenMessageIds.has(message.id));
|
|
138
|
+
for (const message of incomingMessages)
|
|
139
|
+
if (message.id)
|
|
140
|
+
seenMessageIds.add(message.id);
|
|
141
|
+
if (newMessages.some(message => message.role !== "user"))
|
|
142
|
+
setSubmittedTo(null);
|
|
143
|
+
const arrivedPrompts = newMessages.filter(message => message.role === "user").map(message => { var _a; return (_a = message.content) !== null && _a !== void 0 ? _a : ""; });
|
|
144
|
+
if (arrivedPrompts.length) {
|
|
145
|
+
setPendingPrompts(prompts => settlePendingPrompts(prompts, followedAppId, arrivedPrompts));
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
// A snapshot replaces the conversation when it is the first, or follows a rewrite of main
|
|
149
|
+
// (undo, restore, sync); after a plain rejoin the messages before its window stay.
|
|
150
|
+
let nextSnapshotReplaces = true;
|
|
151
|
+
// Base44 can resend an earlier turn's status after the next turn has started: one older than
|
|
152
|
+
// the newest seen is stale.
|
|
153
|
+
let latestStatusDate = "";
|
|
154
|
+
// A newer status, whatever its state, means Base44 has reacted, which ends the submission.
|
|
155
|
+
const applyBuildStatus = (buildStatus) => {
|
|
156
|
+
var _a;
|
|
157
|
+
const statusDate = (_a = buildStatus === null || buildStatus === void 0 ? void 0 : buildStatus.last_updated_date) !== null && _a !== void 0 ? _a : "";
|
|
158
|
+
if (statusDate && statusDate < latestStatusDate)
|
|
159
|
+
return;
|
|
160
|
+
const isNewer = !!statusDate && statusDate > latestStatusDate;
|
|
161
|
+
if (statusDate)
|
|
162
|
+
latestStatusDate = statusDate;
|
|
163
|
+
const state = buildStatus === null || buildStatus === void 0 ? void 0 : buildStatus.state;
|
|
164
|
+
setBuildState(state);
|
|
165
|
+
if (isNewer || state === "processing" || state === "error")
|
|
166
|
+
setSubmittedTo(null);
|
|
167
|
+
};
|
|
168
|
+
// The client asks for a session on the first connect and whenever one expires, and forwards
|
|
169
|
+
// no detail of a failed call, so the backend's own error is kept to report.
|
|
170
|
+
let lastSessionError;
|
|
171
|
+
const builderSession = createPlatformClient().builder.init({
|
|
172
|
+
getSession: () => backendRef.current.openLiveSession(followedAppId).then(socketSession => {
|
|
173
|
+
lastSessionError = undefined;
|
|
174
|
+
return socketSession;
|
|
175
|
+
}, (error) => {
|
|
176
|
+
lastSessionError = error;
|
|
177
|
+
throw error;
|
|
178
|
+
}),
|
|
179
|
+
onError: error => {
|
|
180
|
+
if (error.code !== "session_unavailable" || !lastSessionError)
|
|
181
|
+
return endLiveUpdates(error);
|
|
182
|
+
if (closed)
|
|
183
|
+
return;
|
|
184
|
+
setConnectionError({ message: (lastSessionError === null || lastSessionError === void 0 ? void 0 : lastSessionError.message) || error.message, code: error.code, cause: lastSessionError });
|
|
185
|
+
setConnection("disconnected");
|
|
186
|
+
},
|
|
187
|
+
});
|
|
188
|
+
builderSession.subscribe(followedAppId, {
|
|
189
|
+
onSnapshot: snapshot => {
|
|
190
|
+
// A snapshot holds old prompts too, so only an exact match settles one.
|
|
191
|
+
handleIncomingMessages(snapshot.messages);
|
|
192
|
+
const replaceMessages = nextSnapshotReplaces;
|
|
193
|
+
nextSnapshotReplaces = false;
|
|
194
|
+
setMessages(heldMessages => (replaceMessages ? snapshot.messages : mergeSnapshot(heldMessages, snapshot.messages)));
|
|
195
|
+
applyBuildStatus(snapshot.status);
|
|
196
|
+
// A declined call that failed tries again on the next snapshot, after a reconnect.
|
|
197
|
+
for (const declineKey of failedDeclines.current)
|
|
198
|
+
declinedToolCalls.current.delete(declineKey);
|
|
199
|
+
failedDeclines.current.clear();
|
|
200
|
+
setConnection("connected");
|
|
201
|
+
},
|
|
202
|
+
onEvent: event => {
|
|
203
|
+
if (event.type === "message.updated") {
|
|
204
|
+
handleIncomingMessages([event.data.message]);
|
|
205
|
+
setMessages(heldMessages => mergeMessage(heldMessages, event.data.message));
|
|
206
|
+
}
|
|
207
|
+
if (event.type === "message.removed") {
|
|
208
|
+
setMessages(heldMessages => heldMessages.filter(message => message.id !== event.data.message_id));
|
|
209
|
+
}
|
|
210
|
+
if (event.type === "app.status_changed")
|
|
211
|
+
applyBuildStatus(event.data.status);
|
|
212
|
+
if (event.type === "conversation.changed" && event.data.branch_id == null)
|
|
213
|
+
nextSnapshotReplaces = true;
|
|
214
|
+
// A prompt sent while the AI is working waits in Base44's queue: Base44 has it, and it
|
|
215
|
+
// stays pending until it runs.
|
|
216
|
+
if (event.type === "queue.updated" && event.data.branch_id == null)
|
|
217
|
+
setSubmittedTo(null);
|
|
218
|
+
},
|
|
219
|
+
// Only snapshot_unavailable leaves the subscription running.
|
|
220
|
+
onError: error => (error.code === "snapshot_unavailable" ? reportConnectionError(error) : endLiveUpdates(error)),
|
|
221
|
+
});
|
|
222
|
+
// A failed connect also reaches onError, which reports it.
|
|
223
|
+
builderSession.connect().catch(() => { });
|
|
224
|
+
return () => {
|
|
225
|
+
closed = true;
|
|
226
|
+
builderSession.close();
|
|
227
|
+
};
|
|
228
|
+
}, [currentAppId]);
|
|
229
|
+
// Answers one tool call. Its id leaves the answered list again if the submit fails, so the
|
|
230
|
+
// question comes back.
|
|
231
|
+
const submitAnswer = useCallback((toolCallId, messageId, approve, extraUserInput) => {
|
|
232
|
+
if (!currentAppId)
|
|
233
|
+
return Promise.resolve();
|
|
234
|
+
const targetAppId = currentAppId;
|
|
235
|
+
setActionError(null);
|
|
236
|
+
setSubmittedTo(targetAppId);
|
|
237
|
+
setAnsweredToolCallIds(ids => [...ids, toolCallId]);
|
|
238
|
+
answersAwaitingBase44.current.add(toolCallId);
|
|
239
|
+
const answer = { toolCallId, messageId, approve, extraUserInput };
|
|
240
|
+
return backendRef.current.submitToolCallInput(targetAppId, answer).catch((error) => {
|
|
241
|
+
answersAwaitingBase44.current.delete(toolCallId);
|
|
242
|
+
if (!stillFollowing(targetAppId))
|
|
243
|
+
return;
|
|
244
|
+
setAnsweredToolCallIds(ids => ids.filter(answeredId => answeredId !== toolCallId));
|
|
245
|
+
setSubmittedTo(null);
|
|
246
|
+
reportActionError(error);
|
|
247
|
+
});
|
|
248
|
+
}, [currentAppId, reportActionError]);
|
|
249
|
+
const sortedMessages = useMemo(() => sortMessages(messages), [messages]);
|
|
250
|
+
const pendingForCurrentApp = useMemo(() => pendingPrompts.filter(prompt => prompt.appId === currentAppId || (prompt.appId === NEW_APP && !currentAppId)), [pendingPrompts, currentAppId]);
|
|
251
|
+
const items = useMemo(() => [...toItems(sortedMessages, answeredToolCallIds, submitAnswer), ...pendingPromptItems(pendingForCurrentApp)], [sortedMessages, answeredToolCallIds, submitAnswer, pendingForCurrentApp]);
|
|
252
|
+
const waitingForUser = useMemo(() => isWaitingForUser(sortedMessages, answeredToolCallIds), [sortedMessages, answeredToolCallIds]);
|
|
253
|
+
// A kind this release doesn't know is declined once per tool call. If that fails, the step waits
|
|
254
|
+
// again, the error shows, and the next snapshot tries once more.
|
|
255
|
+
useEffect(() => {
|
|
256
|
+
const followedAppId = currentAppId;
|
|
257
|
+
if (!followedAppId)
|
|
258
|
+
return;
|
|
259
|
+
for (const { toolCallId, messageId } of unknownKindToolCalls(sortedMessages)) {
|
|
260
|
+
const declineKey = `${followedAppId}:${toolCallId}`;
|
|
261
|
+
if (declinedToolCalls.current.has(declineKey))
|
|
262
|
+
continue;
|
|
263
|
+
declinedToolCalls.current.add(declineKey);
|
|
264
|
+
setAnsweredToolCallIds(ids => [...ids, toolCallId]);
|
|
265
|
+
backendRef.current.submitToolCallInput(followedAppId, { toolCallId, messageId, approve: false }).catch((error) => {
|
|
266
|
+
failedDeclines.current.add(declineKey);
|
|
267
|
+
setAnsweredToolCallIds(ids => ids.filter(answeredId => answeredId !== toolCallId));
|
|
268
|
+
reportActionError(error);
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
}, [currentAppId, sortedMessages, reportActionError]);
|
|
272
|
+
// An answered call stays hidden while Base44 still reports it waiting, and is forgotten once it
|
|
273
|
+
// doesn't: if Base44 parks it again, its question comes back.
|
|
274
|
+
// An answer's submission ends there too: Base44 has taken it once the call no longer waits.
|
|
275
|
+
useEffect(() => {
|
|
276
|
+
const stillWaiting = waitingToolCallIds(sortedMessages);
|
|
277
|
+
setAnsweredToolCallIds(ids => (ids.every(answeredId => stillWaiting.has(answeredId)) ? ids : ids.filter(answeredId => stillWaiting.has(answeredId))));
|
|
278
|
+
let answerTaken = false;
|
|
279
|
+
for (const toolCallId of answersAwaitingBase44.current) {
|
|
280
|
+
if (stillWaiting.has(toolCallId))
|
|
281
|
+
continue;
|
|
282
|
+
answersAwaitingBase44.current.delete(toolCallId);
|
|
283
|
+
answerTaken = true;
|
|
284
|
+
}
|
|
285
|
+
if (answerTaken)
|
|
286
|
+
setSubmittedTo(target => (target === followedAppIdRef.current ? null : target));
|
|
287
|
+
}, [sortedMessages]);
|
|
288
|
+
const submissionInFlight = (submittedTo === NEW_APP && !currentAppId) || (submittedTo !== null && submittedTo === currentAppId);
|
|
289
|
+
let status = "ready";
|
|
290
|
+
if (buildState === "error")
|
|
291
|
+
status = "error";
|
|
292
|
+
else if (waitingForUser)
|
|
293
|
+
status = "waiting";
|
|
294
|
+
else if (buildState === "processing")
|
|
295
|
+
status = "building";
|
|
296
|
+
else if (submissionInFlight)
|
|
297
|
+
status = "submitted";
|
|
298
|
+
const addPendingPrompt = useCallback((content, targetAppId) => {
|
|
299
|
+
const pendingPrompt = { id: `pending-${++pendingPromptCount.current}`, content, createdAt: new Date().toISOString(), appId: targetAppId };
|
|
300
|
+
setPendingPrompts(prompts => [...prompts, pendingPrompt]);
|
|
301
|
+
return pendingPrompt;
|
|
302
|
+
}, []);
|
|
303
|
+
const send = useCallback((prompt) => {
|
|
304
|
+
if (!currentAppId) {
|
|
305
|
+
setActionError({ message: "There is no app to send to yet: create one first" });
|
|
306
|
+
return Promise.resolve();
|
|
307
|
+
}
|
|
308
|
+
const targetAppId = currentAppId;
|
|
309
|
+
setActionError(null);
|
|
310
|
+
setSubmittedTo(targetAppId);
|
|
311
|
+
const pendingPrompt = addPendingPrompt(prompt, targetAppId);
|
|
312
|
+
return backendRef.current.sendMessage(targetAppId, prompt).catch((error) => {
|
|
313
|
+
setPendingPrompts(prompts => prompts.filter(other => other !== pendingPrompt));
|
|
314
|
+
if (!stillFollowing(targetAppId))
|
|
315
|
+
return;
|
|
316
|
+
setSubmittedTo(null);
|
|
317
|
+
reportActionError(error);
|
|
318
|
+
});
|
|
319
|
+
}, [currentAppId, reportActionError, addPendingPrompt]);
|
|
320
|
+
const create = useCallback(async (prompt) => {
|
|
321
|
+
const startedFrom = followedAppIdRef.current;
|
|
322
|
+
const followsSetApp = appId !== null;
|
|
323
|
+
setActionError(null);
|
|
324
|
+
setSubmittedTo(NEW_APP);
|
|
325
|
+
const pendingPrompt = addPendingPrompt(prompt, NEW_APP);
|
|
326
|
+
try {
|
|
327
|
+
const app = await backendRef.current.createApp(prompt);
|
|
328
|
+
setCreatedAppId(app.id);
|
|
329
|
+
setSubmittedTo(app.id);
|
|
330
|
+
// With appId set, the chat doesn't follow the new app, so its first prompt has nowhere to
|
|
331
|
+
// show; the new app's own snapshot holds it once someone opens it.
|
|
332
|
+
if (followsSetApp)
|
|
333
|
+
setPendingPrompts(prompts => prompts.filter(other => other !== pendingPrompt));
|
|
334
|
+
else
|
|
335
|
+
setPendingPrompts(prompts => prompts.map(other => (other === pendingPrompt ? { ...other, appId: app.id } : other)));
|
|
336
|
+
onAppCreated === null || onAppCreated === void 0 ? void 0 : onAppCreated(app);
|
|
337
|
+
}
|
|
338
|
+
catch (error) {
|
|
339
|
+
setPendingPrompts(prompts => prompts.filter(other => other !== pendingPrompt));
|
|
340
|
+
if (!stillFollowing(startedFrom))
|
|
341
|
+
return;
|
|
342
|
+
setSubmittedTo(null);
|
|
343
|
+
reportActionError(error);
|
|
344
|
+
}
|
|
345
|
+
}, [appId, onAppCreated, reportActionError, addPendingPrompt]);
|
|
346
|
+
const clearError = useCallback(() => {
|
|
347
|
+
setActionError(null);
|
|
348
|
+
setConnectionError(null);
|
|
349
|
+
}, []);
|
|
350
|
+
const error = (_a = actionError !== null && actionError !== void 0 ? actionError : connectionError) !== null && _a !== void 0 ? _a : (buildState === "error" ? BUILD_FAILED_ERROR : null);
|
|
351
|
+
return { items, status, connection, error, send, create, clearError };
|
|
352
|
+
}
|
|
@@ -14,10 +14,6 @@ export interface AppCreatedV1Data {
|
|
|
14
14
|
* Opaque platform id of the app's current owner.
|
|
15
15
|
*/
|
|
16
16
|
owner_id: string;
|
|
17
|
-
/**
|
|
18
|
-
* Your own handle for the owner: the `service_external_id` you gave when you created that service user. Absent when the owner is not a service user.
|
|
19
|
-
*/
|
|
20
|
-
owner_service_external_id?: string;
|
|
21
17
|
/**
|
|
22
18
|
* The kind of app. New values arrive as a new event version.
|
|
23
19
|
*/
|
|
@@ -43,10 +39,6 @@ export interface AppPublishedV1Data {
|
|
|
43
39
|
* Opaque platform id of the app's current owner.
|
|
44
40
|
*/
|
|
45
41
|
owner_id: string;
|
|
46
|
-
/**
|
|
47
|
-
* Your own handle for the owner: the `service_external_id` you gave when you created that service user. Absent when the owner is not a service user.
|
|
48
|
-
*/
|
|
49
|
-
owner_service_external_id?: string;
|
|
50
42
|
/**
|
|
51
43
|
* Id of the version now live.
|
|
52
44
|
*/
|
|
@@ -72,10 +64,6 @@ export interface AppUnpublishedV1Data {
|
|
|
72
64
|
* Opaque platform id of the app's current owner.
|
|
73
65
|
*/
|
|
74
66
|
owner_id: string;
|
|
75
|
-
/**
|
|
76
|
-
* Your own handle for the owner: the `service_external_id` you gave when you created that service user. Absent when the owner is not a service user.
|
|
77
|
-
*/
|
|
78
|
-
owner_service_external_id?: string;
|
|
79
67
|
/**
|
|
80
68
|
* When the app was taken offline (UTC).
|
|
81
69
|
*/
|
|
@@ -102,10 +90,6 @@ export interface AppDeletedV1Data {
|
|
|
102
90
|
* Opaque platform id of the app's current owner.
|
|
103
91
|
*/
|
|
104
92
|
owner_id: string;
|
|
105
|
-
/**
|
|
106
|
-
* Your own handle for the owner: the `service_external_id` you gave when you created that service user. Absent when the owner is not a service user.
|
|
107
|
-
*/
|
|
108
|
-
owner_service_external_id?: string;
|
|
109
93
|
/**
|
|
110
94
|
* When the app was moved to trash (UTC). It can still be restored.
|
|
111
95
|
*/
|
|
@@ -127,10 +111,6 @@ export interface AppRestoredV1Data {
|
|
|
127
111
|
* Opaque platform id of the app's current owner.
|
|
128
112
|
*/
|
|
129
113
|
owner_id: string;
|
|
130
|
-
/**
|
|
131
|
-
* Your own handle for the owner: the `service_external_id` you gave when you created that service user. Absent when the owner is not a service user.
|
|
132
|
-
*/
|
|
133
|
-
owner_service_external_id?: string;
|
|
134
114
|
/**
|
|
135
115
|
* When the app was restored (UTC).
|
|
136
116
|
*/
|
|
@@ -157,6 +137,81 @@ export interface WebhookTestV1Data {
|
|
|
157
137
|
*/
|
|
158
138
|
challenge: string;
|
|
159
139
|
}
|
|
140
|
+
/**
|
|
141
|
+
* Sent when the builder picks the message up, not when it is received: a
|
|
142
|
+
* message sent while another turn runs waits in the queue until then.
|
|
143
|
+
*/
|
|
144
|
+
export interface BuilderTurnStartedV1Data {
|
|
145
|
+
/**
|
|
146
|
+
* The app the event is about.
|
|
147
|
+
*/
|
|
148
|
+
app_id: string;
|
|
149
|
+
/**
|
|
150
|
+
* The workspace the app belongs to.
|
|
151
|
+
*/
|
|
152
|
+
workspace_id: string;
|
|
153
|
+
/**
|
|
154
|
+
* Opaque platform id of the app's current owner.
|
|
155
|
+
*/
|
|
156
|
+
owner_id: string;
|
|
157
|
+
/**
|
|
158
|
+
* The message that started the turn: the id returned when you sent it, and the app's `status.turn_id` while the turn runs.
|
|
159
|
+
*/
|
|
160
|
+
message_id: string;
|
|
161
|
+
/**
|
|
162
|
+
* The conversation the message belongs to.
|
|
163
|
+
*/
|
|
164
|
+
conversation_id?: string;
|
|
165
|
+
/**
|
|
166
|
+
* When the builder started working on the message (UTC).
|
|
167
|
+
*/
|
|
168
|
+
started_at: string;
|
|
169
|
+
/**
|
|
170
|
+
* Set when this turn continues one that was interrupted: the `message_id` of that turn. Follow it back to add up the time the whole response took.
|
|
171
|
+
*/
|
|
172
|
+
continues_message_id?: string;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* The `data` object of `builder.turn_ended.v1`. The builder finished responding to a message.
|
|
176
|
+
*/
|
|
177
|
+
export interface BuilderTurnEndedV1Data {
|
|
178
|
+
/**
|
|
179
|
+
* The app the event is about.
|
|
180
|
+
*/
|
|
181
|
+
app_id: string;
|
|
182
|
+
/**
|
|
183
|
+
* The workspace the app belongs to.
|
|
184
|
+
*/
|
|
185
|
+
workspace_id: string;
|
|
186
|
+
/**
|
|
187
|
+
* Opaque platform id of the app's current owner.
|
|
188
|
+
*/
|
|
189
|
+
owner_id: string;
|
|
190
|
+
/**
|
|
191
|
+
* The message that started the turn: the id returned when you sent it, and the app's `status.turn_id` while the turn runs.
|
|
192
|
+
*/
|
|
193
|
+
message_id: string;
|
|
194
|
+
/**
|
|
195
|
+
* The conversation the message belongs to.
|
|
196
|
+
*/
|
|
197
|
+
conversation_id?: string;
|
|
198
|
+
/**
|
|
199
|
+
* When the builder started working on the message (UTC).
|
|
200
|
+
*/
|
|
201
|
+
started_at: string;
|
|
202
|
+
/**
|
|
203
|
+
* Set when this turn continues one that was interrupted: the `message_id` of that turn. Follow it back to add up the time the whole response took.
|
|
204
|
+
*/
|
|
205
|
+
continues_message_id?: string;
|
|
206
|
+
/**
|
|
207
|
+
* How the turn ended. `finished`: the builder replied and has nothing pending. `waiting_for_user_input`: the builder stopped to ask something, such as a clarifying question or a plan to approve, and continues when the next message answers it. `failed`: the turn hit an error. `cancelled`: the turn was stopped before it ended. `interrupted`: the builder was interrupted, for example by a restart, and continues the work in a new turn whose `continues_message_id` is this message.
|
|
208
|
+
*/
|
|
209
|
+
status: "finished" | "waiting_for_user_input" | "failed" | "cancelled" | "interrupted";
|
|
210
|
+
/**
|
|
211
|
+
* When the turn ended (UTC).
|
|
212
|
+
*/
|
|
213
|
+
ended_at: string;
|
|
214
|
+
}
|
|
160
215
|
/** Every event type Base44 sends, mapped to the shape of its `data` object. */
|
|
161
216
|
export interface WebhookEventMap {
|
|
162
217
|
/** An app was created. */
|
|
@@ -171,6 +226,10 @@ export interface WebhookEventMap {
|
|
|
171
226
|
"app.restored.v1": AppRestoredV1Data;
|
|
172
227
|
/** Carries no domain data — its only job is to be verifiable and echoed. */
|
|
173
228
|
"webhook.test.v1": WebhookTestV1Data;
|
|
229
|
+
/** Sent when the builder picks the message up, not when it is received: a */
|
|
230
|
+
"builder.turn_started.v1": BuilderTurnStartedV1Data;
|
|
231
|
+
/** The builder finished responding to a message. */
|
|
232
|
+
"builder.turn_ended.v1": BuilderTurnEndedV1Data;
|
|
174
233
|
}
|
|
175
234
|
/** Every event type in {@link WebhookEventMap}, so events from a newer Base44 can be told apart at runtime. @internal */
|
|
176
|
-
export declare const WEBHOOK_EVENT_TYPES: readonly ["app.created.v1", "app.published.v1", "app.unpublished.v1", "app.deleted.v1", "app.restored.v1", "webhook.test.v1"];
|
|
235
|
+
export declare const WEBHOOK_EVENT_TYPES: readonly ["app.created.v1", "app.published.v1", "app.unpublished.v1", "app.deleted.v1", "app.restored.v1", "webhook.test.v1", "builder.turn_started.v1", "builder.turn_ended.v1"];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// Generated by scripts/generate-webhook-types.mjs from the schemas published at
|
|
2
2
|
// https://base44.com/webhooks/schemas. Do not edit by hand; run `npm run generate:webhooks`.
|
|
3
3
|
/** Every event type in {@link WebhookEventMap}, so events from a newer Base44 can be told apart at runtime. @internal */
|
|
4
|
-
export const WEBHOOK_EVENT_TYPES = ["app.created.v1", "app.published.v1", "app.unpublished.v1", "app.deleted.v1", "app.restored.v1", "webhook.test.v1"];
|
|
4
|
+
export const WEBHOOK_EVENT_TYPES = ["app.created.v1", "app.published.v1", "app.unpublished.v1", "app.deleted.v1", "app.restored.v1", "webhook.test.v1", "builder.turn_started.v1", "builder.turn_ended.v1"];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@base44-preview/platform",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0-pr.338.12ff73f",
|
|
4
4
|
"description": "Base44 Platform SDK for white-label platforms: a browser client for watching the builder and a server entrypoint for webhooks",
|
|
5
5
|
"main": "dist/client/index.js",
|
|
6
6
|
"types": "dist/client/index.d.ts",
|
|
@@ -14,12 +14,19 @@
|
|
|
14
14
|
"types": "./dist/server/index.d.ts",
|
|
15
15
|
"default": "./dist/server/index.js"
|
|
16
16
|
},
|
|
17
|
+
"./react": {
|
|
18
|
+
"types": "./dist/react/index.d.ts",
|
|
19
|
+
"default": "./dist/react/index.js"
|
|
20
|
+
},
|
|
17
21
|
"./package.json": "./package.json"
|
|
18
22
|
},
|
|
19
23
|
"typesVersions": {
|
|
20
24
|
"*": {
|
|
21
25
|
"server": [
|
|
22
26
|
"dist/server/index.d.ts"
|
|
27
|
+
],
|
|
28
|
+
"react": [
|
|
29
|
+
"dist/react/index.d.ts"
|
|
23
30
|
]
|
|
24
31
|
}
|
|
25
32
|
},
|
|
@@ -51,6 +58,22 @@
|
|
|
51
58
|
"dependencies": {
|
|
52
59
|
"socket.io-client": "^4.8.3"
|
|
53
60
|
},
|
|
61
|
+
"peerDependencies": {
|
|
62
|
+
"react": "^18.0.0 || ^19.0.0"
|
|
63
|
+
},
|
|
64
|
+
"peerDependenciesMeta": {
|
|
65
|
+
"react": {
|
|
66
|
+
"optional": true
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
"devDependencies": {
|
|
70
|
+
"@types/react": "^19.0.0",
|
|
71
|
+
"@types/react-dom": "^19.0.0",
|
|
72
|
+
"jsdom": "^26.0.0",
|
|
73
|
+
"json-schema-to-typescript": "16.0.0",
|
|
74
|
+
"react": "^19.0.0",
|
|
75
|
+
"react-dom": "^19.0.0"
|
|
76
|
+
},
|
|
54
77
|
"keywords": [
|
|
55
78
|
"base44",
|
|
56
79
|
"platform",
|
|
@@ -68,9 +91,6 @@
|
|
|
68
91
|
"url": "https://github.com/base44/javascript-sdk/issues"
|
|
69
92
|
},
|
|
70
93
|
"homepage": "https://github.com/base44/javascript-sdk/tree/main/packages/platform#readme",
|
|
71
|
-
"devDependencies": {
|
|
72
|
-
"json-schema-to-typescript": "16.0.0"
|
|
73
|
-
},
|
|
74
94
|
"engines": {
|
|
75
95
|
"node": ">=20"
|
|
76
96
|
}
|