@base44-preview/platform 0.2.0-pr.329.cce6621 → 0.2.0-pr.335.2bd5f4f

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.
Files changed (52) hide show
  1. package/README.md +58 -1
  2. package/dist/{modules → client/modules}/builder-socket.js +5 -2
  3. package/dist/react/Base44ChatProvider.d.ts +43 -0
  4. package/dist/react/Base44ChatProvider.js +68 -0
  5. package/dist/react/Message.d.ts +39 -0
  6. package/dist/react/Message.js +55 -0
  7. package/dist/react/chat-items.d.ts +51 -0
  8. package/dist/react/chat-items.js +174 -0
  9. package/dist/react/chat.types.d.ts +299 -0
  10. package/dist/react/chat.types.js +1 -0
  11. package/dist/react/components.types.d.ts +63 -0
  12. package/dist/react/components.types.js +1 -0
  13. package/dist/react/context.d.ts +50 -0
  14. package/dist/react/context.js +57 -0
  15. package/dist/react/fallbacks.d.ts +3 -0
  16. package/dist/react/fallbacks.js +13 -0
  17. package/dist/react/index.d.ts +8 -0
  18. package/dist/react/index.js +5 -0
  19. package/dist/react/useBase44Chat.d.ts +48 -0
  20. package/dist/react/useBase44Chat.js +312 -0
  21. package/dist/server/index.d.ts +3 -0
  22. package/dist/server/index.js +2 -0
  23. package/dist/server/server-url.d.ts +2 -0
  24. package/dist/server/server-url.js +8 -0
  25. package/dist/server/server.d.ts +3 -0
  26. package/dist/server/server.js +8 -0
  27. package/dist/server/server.types.d.ts +10 -0
  28. package/dist/server/server.types.js +1 -0
  29. package/package.json +41 -10
  30. /package/dist/{client.d.ts → client/client.d.ts} +0 -0
  31. /package/dist/{client.js → client/client.js} +0 -0
  32. /package/dist/{client.types.d.ts → client/client.types.d.ts} +0 -0
  33. /package/dist/{client.types.js → client/client.types.js} +0 -0
  34. /package/dist/{errors.d.ts → client/errors.d.ts} +0 -0
  35. /package/dist/{errors.js → client/errors.js} +0 -0
  36. /package/dist/{errors.types.d.ts → client/errors.types.d.ts} +0 -0
  37. /package/dist/{errors.types.js → client/errors.types.js} +0 -0
  38. /package/dist/{index.d.ts → client/index.d.ts} +0 -0
  39. /package/dist/{index.js → client/index.js} +0 -0
  40. /package/dist/{modules → client/modules}/builder-protocol.d.ts +0 -0
  41. /package/dist/{modules → client/modules}/builder-protocol.js +0 -0
  42. /package/dist/{modules → client/modules}/builder-socket.d.ts +0 -0
  43. /package/dist/{modules → client/modules}/builder-subscription.d.ts +0 -0
  44. /package/dist/{modules → client/modules}/builder-subscription.js +0 -0
  45. /package/dist/{modules → client/modules}/builder.d.ts +0 -0
  46. /package/dist/{modules → client/modules}/builder.events.generated.d.ts +0 -0
  47. /package/dist/{modules → client/modules}/builder.events.generated.js +0 -0
  48. /package/dist/{modules → client/modules}/builder.events.types.d.ts +0 -0
  49. /package/dist/{modules → client/modules}/builder.events.types.js +0 -0
  50. /package/dist/{modules → client/modules}/builder.js +0 -0
  51. /package/dist/{modules → client/modules}/builder.types.d.ts +0 -0
  52. /package/dist/{modules → client/modules}/builder.types.js +0 -0
package/README.md CHANGED
@@ -124,7 +124,7 @@ redaction of generated prose or user content.
124
124
  ## Event types
125
125
 
126
126
  The socket protocol is defined by the service's AsyncAPI document, committed as
127
- `asyncapi.json`. `src/modules/builder.events.generated.ts` is generated from it with
127
+ `asyncapi.json`. `src/client/modules/builder.events.generated.ts` is generated from it with
128
128
  `json-schema-to-typescript`: one type per schema, named after the backend model
129
129
  (`Message`, `StatusObject`, `QueueState`, one `*Call` per tool, one `*Approval` per
130
130
  guard), plus `ServerEventMap` and `ClientMessageMap`. Never edit it by hand.
@@ -170,3 +170,60 @@ exceptions, payloads and credentials are never attached.
170
170
 
171
171
  No SDK dependency, package version or lockfile changes are required. Socket.IO
172
172
  remains the existing SDK dependency. Chat commands and HTTP APIs are outside this entry point.
173
+
174
+ ## React
175
+
176
+ `@base44/platform/react` adds one hook, `useBase44Chat`, that runs a builder chat for one
177
+ app on top of this client: it opens the live session and renews it, turns messages into items
178
+ 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
179
+ entry; the root entry stays framework-free.
180
+
181
+ ```tsx
182
+ import { useBase44Chat } from "@base44/platform/react";
183
+
184
+ const chat = useBase44Chat({ appId, backend, onAppCreated });
185
+ chat.items.map((item) =>
186
+ item.steps.map((step) => step.question?.kind === "approval" && <button onClick={step.question.approve}>Allow</button>),
187
+ );
188
+ ```
189
+
190
+ `backend` is four functions your backend provides, in any language behind them: `createApp`,
191
+ `openLiveSession`, `sendMessage` and `submitToolCallInput`, each wrapping one Base44 REST
192
+ call with your credentials, so the browser never holds a key. The hook returns `items`, a
193
+ `status` (`ready`, `submitted`, `building`, `waiting`, `error`), a `connection` (`connecting`,
194
+ `connected`, `disconnected`), an `error`, and the actions `send`, `create` and `clearError`. `send` needs an app; `create` makes
195
+ the first, and the chat watches it while `appId` is `null`. A sent prompt shows at once as a
196
+ `pending` item until Base44's own message arrives; a prompt sent mid-build waits in Base44's
197
+ queue meanwhile. A question is a union on `kind` (`choice`, `secrets`, `approval`) and carries only the
198
+ actions its kind allows, and declining is always one of them. As in Base44's builder, only the
199
+ 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`.
200
+
201
+ ### Provider and parts
202
+
203
+ `<Base44ChatProvider>` calls the hook once and shares the chat through context. Any component
204
+ below it reads the chat with `useChatState()` (`items`, `status`, `connection`, `error`) or
205
+ `useChatActions()` (`send`, `create`, `clearError`), and `<Message>` draws an item with your parts.
206
+
207
+ ```tsx
208
+ import { Base44ChatProvider, Message, useChatState } from "@base44/platform/react";
209
+
210
+ <Base44ChatProvider appId={appId} backend={backend} onAppCreated={selectApp} components={{ question: { Choice, Secrets, Approval } }}>
211
+ <Messages />
212
+ </Base44ChatProvider>
213
+
214
+ function Messages() {
215
+ const { items } = useChatState();
216
+ return items.map((item) => <div key={item.id} className={item.role}><Message item={item} /></div>);
217
+ }
218
+ ```
219
+
220
+ - **A part for every question kind is required.** TypeScript refuses a `components.question`
221
+ without `Choice`, `Secrets` and `Approval`, and a release that adds a kind adds a part, so an
222
+ upgrade tells you what to write. Until then the chat declines the new kind for you.
223
+ - **Message parts are optional.** `Text` and `Step` left out are drawn as plain HTML, with no
224
+ classes and a `data-base44` attribute for CSS.
225
+ - **A fixed order.** `<Message>` draws the text, then each step followed by its open question, if
226
+ it has one. It adds no element of its own. `<Question>` draws a question anywhere else below the provider.
227
+ - **Stable actions.** `useChatActions()` keeps its identity while the app stays the same, also with
228
+ an inline `backend` and `onAppCreated`, so a component that reads only actions doesn't re-render
229
+ when a message arrives.
@@ -123,8 +123,11 @@ export class BuilderSocket {
123
123
  socket.on(name, (raw) => this.roomNotice(code, raw));
124
124
  for (const name of eventNames)
125
125
  socket.on(name, (raw) => this.appEvent(name, raw));
126
- socket.onAny((name, raw) => { if (isUnknownEvent(name))
127
- this.appEvent(name, raw); });
126
+ // An unknown event with no app room (a future session-wide event) has nowhere to go: ignore it.
127
+ socket.onAny((name, raw) => {
128
+ if (isUnknownEvent(name) && appFromRoom(raw === null || raw === void 0 ? void 0 : raw.room))
129
+ this.appEvent(name, raw);
130
+ });
128
131
  socket.connect();
129
132
  }
130
133
  appEvent(name, raw) {
@@ -0,0 +1,43 @@
1
+ import type { Base44ChatProviderProps } from "./components.types.js";
2
+ /**
3
+ * Runs the AI chat for one app for the tree below it. It calls {@link useBase44Chat} once and
4
+ * shares the result through context, so any component below reads it with {@link useChatState}
5
+ * and {@link useChatActions}, and {@link Message} draws an item with your parts.
6
+ *
7
+ * Put it as high as the components that need the chat: a header that shows the status, a preview
8
+ * that waits for the build, and the message list all read the same chat. It renders nothing of its
9
+ * own.
10
+ *
11
+ * You pass a part for every question kind. The message parts, `Text` and `Step`, are optional:
12
+ * one left out is drawn as plain HTML with no classes and a `data-base44` attribute for CSS.
13
+ *
14
+ * @param props - The {@link useBase44Chat} options, the parts, and the children.
15
+ * @returns The children, inside the chat's contexts.
16
+ *
17
+ * @example
18
+ * ```tsx
19
+ * // The provider, a message list, and a composer of your own
20
+ * <Base44ChatProvider appId={appId} backend={backend} onAppCreated={selectApp} components={{ question: { Choice, Secrets, Approval } }}>
21
+ * <Messages />
22
+ * <Composer />
23
+ * </Base44ChatProvider>
24
+ *
25
+ * function Messages() {
26
+ * const { items } = useChatState();
27
+ * return items.map((item) => <div key={item.id} className={item.role}><Message item={item} /></div>);
28
+ * }
29
+ *
30
+ * function Composer() {
31
+ * const { status } = useChatState();
32
+ * const { send } = useChatActions();
33
+ * const [prompt, setPrompt] = useState("");
34
+ * return (
35
+ * <form onSubmit={(e) => { e.preventDefault(); send(prompt); setPrompt(""); }}>
36
+ * <input value={prompt} onChange={(e) => setPrompt(e.target.value)} />
37
+ * <button disabled={status === "submitted" || status === "waiting"}>Send</button>
38
+ * </form>
39
+ * );
40
+ * }
41
+ * ```
42
+ */
43
+ export declare function Base44ChatProvider({ components, children, appId, backend, onAppCreated }: Base44ChatProviderProps): import("react").JSX.Element;
@@ -0,0 +1,68 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { useCallback, useEffect, useMemo, useRef } from "react";
4
+ import { ActionsContext, ComponentsContext, StateContext } from "./context.js";
5
+ import { fallbackMessageComponents } from "./fallbacks.js";
6
+ import { useBase44Chat } from "./useBase44Chat.js";
7
+ /**
8
+ * Runs the AI chat for one app for the tree below it. It calls {@link useBase44Chat} once and
9
+ * shares the result through context, so any component below reads it with {@link useChatState}
10
+ * and {@link useChatActions}, and {@link Message} draws an item with your parts.
11
+ *
12
+ * Put it as high as the components that need the chat: a header that shows the status, a preview
13
+ * that waits for the build, and the message list all read the same chat. It renders nothing of its
14
+ * own.
15
+ *
16
+ * You pass a part for every question kind. The message parts, `Text` and `Step`, are optional:
17
+ * one left out is drawn as plain HTML with no classes and a `data-base44` attribute for CSS.
18
+ *
19
+ * @param props - The {@link useBase44Chat} options, the parts, and the children.
20
+ * @returns The children, inside the chat's contexts.
21
+ *
22
+ * @example
23
+ * ```tsx
24
+ * // The provider, a message list, and a composer of your own
25
+ * <Base44ChatProvider appId={appId} backend={backend} onAppCreated={selectApp} components={{ question: { Choice, Secrets, Approval } }}>
26
+ * <Messages />
27
+ * <Composer />
28
+ * </Base44ChatProvider>
29
+ *
30
+ * function Messages() {
31
+ * const { items } = useChatState();
32
+ * return items.map((item) => <div key={item.id} className={item.role}><Message item={item} /></div>);
33
+ * }
34
+ *
35
+ * function Composer() {
36
+ * const { status } = useChatState();
37
+ * const { send } = useChatActions();
38
+ * const [prompt, setPrompt] = useState("");
39
+ * return (
40
+ * <form onSubmit={(e) => { e.preventDefault(); send(prompt); setPrompt(""); }}>
41
+ * <input value={prompt} onChange={(e) => setPrompt(e.target.value)} />
42
+ * <button disabled={status === "submitted" || status === "waiting"}>Send</button>
43
+ * </form>
44
+ * );
45
+ * }
46
+ * ```
47
+ */
48
+ export function Base44ChatProvider({ components, children, appId, backend, onAppCreated }) {
49
+ var _a;
50
+ // The hook reads the backend through a ref already. The callback goes through one here, so an
51
+ // inline `onAppCreated` keeps `create`, and every reader of the actions, stable.
52
+ const onAppCreatedRef = useRef(onAppCreated);
53
+ useEffect(() => {
54
+ onAppCreatedRef.current = onAppCreated;
55
+ });
56
+ const reportAppCreated = useCallback((app) => { var _a; return (_a = onAppCreatedRef.current) === null || _a === void 0 ? void 0 : _a.call(onAppCreatedRef, app); }, []);
57
+ const { items, status, connection, error, send, create, clearError } = useBase44Chat({ appId, backend, onAppCreated: reportAppCreated });
58
+ const state = useMemo(() => ({ items, status, connection, error }), [items, status, connection, error]);
59
+ const actions = useMemo(() => ({ send, create, clearError }), [send, create, clearError]);
60
+ // Merged part by part, so an inline `components={{…}}` with the same parts keeps the same identity.
61
+ const { Text, Step } = (_a = components.message) !== null && _a !== void 0 ? _a : {};
62
+ const { Choice, Secrets, Approval } = components.question;
63
+ const parts = useMemo(() => ({
64
+ message: { Text: Text !== null && Text !== void 0 ? Text : fallbackMessageComponents.Text, Step: Step !== null && Step !== void 0 ? Step : fallbackMessageComponents.Step },
65
+ question: { Choice, Secrets, Approval },
66
+ }), [Text, Step, Choice, Secrets, Approval]);
67
+ return (_jsx(ComponentsContext.Provider, { value: parts, children: _jsx(ActionsContext.Provider, { value: actions, children: _jsx(StateContext.Provider, { value: state, children: children }) }) }));
68
+ }
@@ -0,0 +1,39 @@
1
+ import type { MessageProps, QuestionProps } from "./components.types.js";
2
+ /**
3
+ * Draws one chat item with the parts from the nearest {@link Base44ChatProvider}, always in the
4
+ * same order: its text, then one `Step` per tool call, each followed by its open question, if it has
5
+ * one. Only the last assistant message carries questions.
6
+ *
7
+ * It adds no element of its own, so wrap it to lay messages out.
8
+ *
9
+ * @param props - The item to draw.
10
+ * @returns The item's parts.
11
+ * @throws {Error} When there is no provider above the component.
12
+ *
13
+ * @example
14
+ * ```tsx
15
+ * // Align by role in your own wrapper
16
+ * <div className={item.role === "user" ? "ml-auto" : ""}>
17
+ * <Message item={item} />
18
+ * </div>
19
+ * ```
20
+ */
21
+ export declare function Message({ item }: MessageProps): import("react").JSX.Element;
22
+ /**
23
+ * Draws an open question with the part for its kind, from the nearest {@link Base44ChatProvider}.
24
+ * The part receives the question with its bound actions. {@link Message} already draws a message's
25
+ * questions; use this to show one somewhere else.
26
+ *
27
+ * @param props - The question to draw.
28
+ * @returns The part for the question's kind.
29
+ * @throws {Error} When there is no provider above the component.
30
+ *
31
+ * @example
32
+ * ```tsx
33
+ * // The open questions, pinned above the composer
34
+ * const { items } = useChatState();
35
+ * const open = items.flatMap((item) => item.steps.flatMap((step) => (step.question ? [step.question] : [])));
36
+ * return open.map((question, i) => <Question key={i} question={question} />);
37
+ * ```
38
+ */
39
+ export declare function Question({ question }: QuestionProps): import("react").JSX.Element;
@@ -0,0 +1,55 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { Fragment } from "react";
4
+ import { useResolvedComponents } from "./context.js";
5
+ /**
6
+ * Draws one chat item with the parts from the nearest {@link Base44ChatProvider}, always in the
7
+ * same order: its text, then one `Step` per tool call, each followed by its open question, if it has
8
+ * one. Only the last assistant message carries questions.
9
+ *
10
+ * It adds no element of its own, so wrap it to lay messages out.
11
+ *
12
+ * @param props - The item to draw.
13
+ * @returns The item's parts.
14
+ * @throws {Error} When there is no provider above the component.
15
+ *
16
+ * @example
17
+ * ```tsx
18
+ * // Align by role in your own wrapper
19
+ * <div className={item.role === "user" ? "ml-auto" : ""}>
20
+ * <Message item={item} />
21
+ * </div>
22
+ * ```
23
+ */
24
+ export function Message({ item }) {
25
+ const { Text, Step } = useResolvedComponents("Message").message;
26
+ return (_jsxs(_Fragment, { children: [item.text && _jsx(Text, { text: item.text, role: item.role, pending: item.pending }), item.steps.map(step => (_jsxs(Fragment, { children: [_jsx(Step, { ...step }), step.question && _jsx(Question, { question: step.question })] }, step.id)))] }));
27
+ }
28
+ /**
29
+ * Draws an open question with the part for its kind, from the nearest {@link Base44ChatProvider}.
30
+ * The part receives the question with its bound actions. {@link Message} already draws a message's
31
+ * questions; use this to show one somewhere else.
32
+ *
33
+ * @param props - The question to draw.
34
+ * @returns The part for the question's kind.
35
+ * @throws {Error} When there is no provider above the component.
36
+ *
37
+ * @example
38
+ * ```tsx
39
+ * // The open questions, pinned above the composer
40
+ * const { items } = useChatState();
41
+ * const open = items.flatMap((item) => item.steps.flatMap((step) => (step.question ? [step.question] : [])));
42
+ * return open.map((question, i) => <Question key={i} question={question} />);
43
+ * ```
44
+ */
45
+ export function Question({ question }) {
46
+ const { Choice, Secrets, Approval } = useResolvedComponents("Question").question;
47
+ switch (question.kind) {
48
+ case "choice":
49
+ return _jsx(Choice, { ...question });
50
+ case "secrets":
51
+ return _jsx(Secrets, { ...question });
52
+ case "approval":
53
+ return _jsx(Approval, { ...question });
54
+ }
55
+ }
@@ -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. With
43
+ * `settleOldestIfUnmatched`, an arrival that matches none settles the oldest, so a prompt Base44
44
+ * changed on the way never stays pending. */
45
+ export declare function settlePendingPrompts(pendingPrompts: PendingPrompt[], appId: string, arrivedPrompts: string[], settleOldestIfUnmatched: boolean): PendingPrompt[];
46
+ /** @internal Pending prompts as items, drawn after the messages Base44 has. */
47
+ export declare function pendingPromptItems(pendingPrompts: PendingPrompt[]): ChatItem[];
48
+ /** @internal Base44's question formats, as one simple shape per kind, each bound to the call that
49
+ * answers it. Base44 keys choice answers by position, so `picked` follows `questions`. A kind this
50
+ * release doesn't know has no shape. */
51
+ export declare function toQuestion(toolCall: ToolCall, answerToolCall: AnswerToolCall): ChatQuestion | undefined;
@@ -0,0 +1,174 @@
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;
59
+ const toolName = (_a = toolCall.name) !== null && _a !== void 0 ? _a : "";
60
+ // Only file tools carry `display.file_paths`.
61
+ const display = "display" in toolCall ? toolCall.display : undefined;
62
+ const files = (_b = display === null || display === void 0 ? void 0 : display.file_paths) !== null && _b !== void 0 ? _b : [];
63
+ const status = stepStatus(toolCall);
64
+ const question = status === "waiting" && answerToolCall ? toQuestion(toolCall, answerToolCall) : undefined;
65
+ return { id: toolCall.id, tool: toolName, files, label: [toolName, ...files].join(" "), status, ...(question && { question }) };
66
+ }
67
+ /** @internal Base44's tool call status, as a step's. */
68
+ export function stepStatus(toolCall) {
69
+ if (toolCall.status === "running")
70
+ return "running";
71
+ if (toolCall.status === "waiting_for_user_input")
72
+ return "waiting";
73
+ if (toolCall.status === "stopped")
74
+ return "stopped";
75
+ if (toolCall.status === "error")
76
+ return "error";
77
+ return "done";
78
+ }
79
+ /** @internal Whether the chat waits on the user. Like Base44's builder, only the last turn reply
80
+ * counts, and a call answered or declined here stops counting. */
81
+ export function isWaitingForUser(sortedMessages, answeredToolCallIds) {
82
+ var _a;
83
+ const lastReply = lastTurnReply(sortedMessages);
84
+ 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)));
85
+ }
86
+ const KNOWN_QUESTION_KINDS = ["approval", "choice", "input"];
87
+ /** @internal Waiting calls on the last turn reply whose kind Base44 names and this release doesn't
88
+ * know, to decline. A call with no kind comes only from old messages and is left alone. */
89
+ export function unknownKindToolCalls(sortedMessages) {
90
+ var _a;
91
+ const lastReply = lastTurnReply(sortedMessages);
92
+ if (!lastReply)
93
+ return [];
94
+ return ((_a = lastReply.tool_calls) !== null && _a !== void 0 ? _a : [])
95
+ .filter(toolCall => {
96
+ var _a;
97
+ const kind = (_a = toolCall.waiting_on) === null || _a === void 0 ? void 0 : _a.kind;
98
+ return toolCall.status === "waiting_for_user_input" && !!kind && !KNOWN_QUESTION_KINDS.includes(kind);
99
+ })
100
+ .map(toolCall => ({ toolCallId: toolCall.id, messageId: lastReply.id }));
101
+ }
102
+ /** @internal The ids of every tool call Base44 reports waiting. */
103
+ export function waitingToolCallIds(sortedMessages) {
104
+ 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); }));
105
+ }
106
+ /** @internal Prompts that arrived from Base44 as messages settle the pending ones with the same
107
+ * text. Base44's public send carries no client id, so text is the only link. With
108
+ * `settleOldestIfUnmatched`, an arrival that matches none settles the oldest, so a prompt Base44
109
+ * changed on the way never stays pending. */
110
+ export function settlePendingPrompts(pendingPrompts, appId, arrivedPrompts, settleOldestIfUnmatched) {
111
+ let stillPending = pendingPrompts;
112
+ for (const arrivedPrompt of arrivedPrompts) {
113
+ const pendingForApp = stillPending.filter(prompt => prompt.appId === appId);
114
+ const exactMatch = pendingForApp.find(prompt => prompt.content.trim() === arrivedPrompt.trim());
115
+ const settled = exactMatch !== null && exactMatch !== void 0 ? exactMatch : (settleOldestIfUnmatched ? pendingForApp[0] : undefined);
116
+ if (settled)
117
+ stillPending = stillPending.filter(prompt => prompt !== settled);
118
+ }
119
+ return stillPending;
120
+ }
121
+ /** @internal Pending prompts as items, drawn after the messages Base44 has. */
122
+ export function pendingPromptItems(pendingPrompts) {
123
+ return pendingPrompts.map(prompt => ({ id: prompt.id, role: "user", text: prompt.content, createdAt: prompt.createdAt, steps: [], pending: true }));
124
+ }
125
+ /** @internal Base44's question formats, as one simple shape per kind, each bound to the call that
126
+ * answers it. Base44 keys choice answers by position, so `picked` follows `questions`. A kind this
127
+ * release doesn't know has no shape. */
128
+ export function toQuestion(toolCall, answerToolCall) {
129
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
130
+ const kind = (_a = toolCall.waiting_on) === null || _a === void 0 ? void 0 : _a.kind;
131
+ const decline = () => answerToolCall(false);
132
+ if (kind === "choice") {
133
+ const questions = (_c = (_b = toolArguments(toolCall)) === null || _b === void 0 ? void 0 : _b.questions) !== null && _c !== void 0 ? _c : [];
134
+ return {
135
+ kind,
136
+ questions: questions.map(question => {
137
+ var _a, _b;
138
+ return ({
139
+ text: (_a = question.question) !== null && _a !== void 0 ? _a : "",
140
+ description: question.description,
141
+ 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 : ""); }),
142
+ multi: !!question.multi_select,
143
+ });
144
+ }),
145
+ answer: picked => {
146
+ const answers = picked
147
+ .map((labels, questionIndex) => ({ question_index: questionIndex, selected_labels: labels }))
148
+ .filter(answer => answer.selected_labels.length);
149
+ return answerToolCall(true, { answers });
150
+ },
151
+ decline,
152
+ };
153
+ }
154
+ if (kind === "input") {
155
+ const secretFields = (_e = (_d = toolArguments(toolCall)) === null || _d === void 0 ? void 0 : _d.secrets_schema) !== null && _e !== void 0 ? _e : [];
156
+ return {
157
+ kind: "secrets",
158
+ fields: secretFields.map(field => { var _a; return ({ name: (_a = field.secretName) !== null && _a !== void 0 ? _a : "", description: field.description }); }),
159
+ submit: values => answerToolCall(true, { secrets: values }),
160
+ decline,
161
+ };
162
+ }
163
+ if (kind === "approval") {
164
+ // Guards that declare a reason or a summary carry them; the others name only themselves.
165
+ const approval = toolCall.approval;
166
+ 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 : "";
167
+ return { kind, action: (_j = toolCall.name) !== null && _j !== void 0 ? _j : "", reason, approve: () => answerToolCall(true), decline };
168
+ }
169
+ return undefined;
170
+ }
171
+ // The waiting kind says which arguments a call carries; the tool's name only narrows the union.
172
+ function toolArguments(toolCall) {
173
+ return "arguments" in toolCall ? toolCall.arguments : undefined;
174
+ }