@base44-preview/platform 0.2.0-pr.335.2bd5f4f → 0.2.0-pr.337.2f0349e

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 (36) hide show
  1. package/README.md +68 -35
  2. package/dist/react/chat-items.d.ts +6 -6
  3. package/dist/react/chat-items.js +79 -19
  4. package/dist/react/chat.types.d.ts +39 -4
  5. package/dist/react/index.d.ts +2 -6
  6. package/dist/react/index.js +1 -4
  7. package/dist/react/useBase44Chat.js +55 -15
  8. package/dist/server/errors.d.ts +53 -0
  9. package/dist/server/errors.js +56 -0
  10. package/dist/server/errors.types.d.ts +60 -0
  11. package/dist/server/index.d.ts +6 -2
  12. package/dist/server/index.js +2 -1
  13. package/dist/server/modules/webhooks-signature.d.ts +11 -0
  14. package/dist/server/modules/webhooks-signature.js +65 -0
  15. package/dist/server/modules/webhooks.d.ts +3 -0
  16. package/dist/server/modules/webhooks.events.generated.d.ts +235 -0
  17. package/dist/server/modules/webhooks.events.generated.js +4 -0
  18. package/dist/server/modules/webhooks.js +91 -0
  19. package/dist/server/modules/webhooks.types.d.ts +218 -0
  20. package/dist/server/modules/webhooks.types.js +1 -0
  21. package/dist/server/server.d.ts +28 -3
  22. package/dist/server/server.js +31 -7
  23. package/dist/server/server.types.d.ts +8 -8
  24. package/package.json +11 -5
  25. package/dist/react/Base44ChatProvider.d.ts +0 -43
  26. package/dist/react/Base44ChatProvider.js +0 -68
  27. package/dist/react/Message.d.ts +0 -39
  28. package/dist/react/Message.js +0 -55
  29. package/dist/react/components.types.d.ts +0 -63
  30. package/dist/react/context.d.ts +0 -50
  31. package/dist/react/context.js +0 -57
  32. package/dist/react/fallbacks.d.ts +0 -3
  33. package/dist/react/fallbacks.js +0 -13
  34. package/dist/server/server-url.d.ts +0 -2
  35. package/dist/server/server-url.js +0 -8
  36. /package/dist/{react/components.types.js → server/errors.types.js} +0 -0
package/README.md CHANGED
@@ -4,10 +4,15 @@
4
4
  npm install @base44/platform
5
5
  ```
6
6
 
7
- This package implements the read-only white-label builder socket contract: a
8
- partner's browser watches the builder chat of up to eight apps over the platform's
9
- shared socket. It is independent of the app SDK (`@base44/sdk`).
10
- The workspace must have white-label sockets enabled; this SDK does not open sessions.
7
+ The Platform SDK for white-label platforms built on Base44. It is independent of the app SDK
8
+ (`@base44/sdk`) and has two entrypoints:
9
+
10
+ - `@base44/platform`, for the browser: implements the read-only white-label builder socket
11
+ contract. A partner's browser watches the builder chat of up to eight apps over the platform's
12
+ shared socket. The workspace must have white-label sockets enabled; this SDK does not open sessions.
13
+ - `@base44/platform/server`, for your backend: verify the webhooks Base44 sends when apps are
14
+ created, published, unpublished, trashed or restored. See
15
+ [Receiving webhooks](#receiving-webhooks-server).
11
16
 
12
17
  ```ts
13
18
  import { createPlatformClient } from "@base44/platform";
@@ -33,6 +38,63 @@ subscription.unsubscribe();
33
38
  builder.close();
34
39
  ```
35
40
 
41
+ ## Receiving webhooks (server)
42
+
43
+ `@base44/platform/server` verifies Base44 outbound webhooks and answers the endpoint
44
+ activation challenge. It uses WebCrypto only (Node 20+, Deno, Bun, Workers, edge runtimes) and
45
+ makes no network calls: pass your workspace's public keys (`whpk_…`) to each call that verifies.
46
+
47
+ The simplest route is `createHandler`. It reads the raw body, verifies it, answers the
48
+ activation challenge and picks the status code: 400 for a delivery that fails verification,
49
+ 500 when your keys are misconfigured, the body can't be read or a callback throws, and 204
50
+ otherwise, including for event types you have no handler for. Base44 retries any answer that
51
+ isn't 2xx; the status only shows in its delivery log which side failed.
52
+
53
+ ```ts
54
+ import { createPlatformServer } from "@base44/platform/server";
55
+
56
+ const platform = createPlatformServer();
57
+ const publicKeys = process.env.BASE44_WEBHOOK_PUBLIC_KEYS!; // two keys during a rotation
58
+
59
+ export const POST = platform.webhooks.createHandler({
60
+ publicKeys,
61
+ on: {
62
+ "app.deleted.v1": async event => forget(event.data.app_id), // event is narrowed per type
63
+ },
64
+ onEvent: event => log(event.type), // every event, before its handler
65
+ onSuccess: event => {}, // return a Response to replace the 204
66
+ onError: (error, event) => report(error), // return a Response to replace the 400/500
67
+ });
68
+ ```
69
+
70
+ For full control, verify and dispatch yourself:
71
+
72
+ ```ts
73
+ export async function POST(request: Request) {
74
+ const rawBody = await request.text(); // exactly as received
75
+ let event;
76
+ try {
77
+ event = await platform.webhooks.verifyEvent(rawBody, request.headers, { publicKeys });
78
+ } catch (error) {
79
+ if (error instanceof WebhookVerificationError) return new Response(null, { status: 400 });
80
+ throw error; // missing/malformed keys: a 500. Base44 retries any non-2xx answer
81
+ }
82
+ switch (event.type) {
83
+ case "webhook.test.v1": return Response.json({ challenge: event.data.challenge }); // activates the endpoint
84
+ case "app.deleted.v1": await forget(event.data.app_id); break;
85
+ }
86
+ return new Response(null, { status: 204 });
87
+ }
88
+ ```
89
+
90
+ An event type added to Base44 after your SDK version arrives as `{ type: "unknown", name, data }`,
91
+ with its real type in `name` and an unchecked `data`, the same shape the client uses. After you
92
+ upgrade, it arrives under its own `type`.
93
+
94
+ Delivery is at least once with no ordering guarantee: deduplicate on `event.id`, and answer
95
+ 2xx to event types you do not handle. Event types are generated from the schemas published at
96
+ `https://base44.com/webhooks/schemas`; run `npm run generate:webhooks` to refresh them.
97
+
36
98
  ## Sessions
37
99
 
38
100
  `/api/builder-socket-session` is your backend's route, not an SDK endpoint. It opens a
@@ -147,7 +209,8 @@ Every exported shape and field has JSDoc. `npm run docs` validates it into `docs
147
209
  `npm run create-docs` runs the app SDK's TypeDoc and Mintlify pipeline for this package,
148
210
  and `npm run copy-docs-local -- --target <mintlify-docs>` copies the result into
149
211
  `developers/references/platform-sdk/docs`. The pipeline's config for this package lives
150
- in `scripts/mintlify-post-processing/`. The Socket messages page is built in mintlify-docs from
212
+ in `scripts/mintlify-post-processing/`, including `reference.ts`, the docs-only entry that combines
213
+ the client and server entrypoints into one reference. The Socket messages page is built in mintlify-docs from
151
214
  the service's AsyncAPI document, not here.
152
215
 
153
216
  `PlatformSocketError` extends `Error` with `code` and optional `appId`. Original
@@ -197,33 +260,3 @@ the first, and the chat watches it while `appId` is `null`. A sent prompt shows
197
260
  queue meanwhile. A question is a union on `kind` (`choice`, `secrets`, `approval`) and carries only the
198
261
  actions its kind allows, and declining is always one of them. As in Base44's builder, only the
199
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`.
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.
@@ -39,13 +39,13 @@ export interface PendingPrompt {
39
39
  appId: string;
40
40
  }
41
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[];
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[];
46
45
  /** @internal Pending prompts as items, drawn after the messages Base44 has. */
47
46
  export declare function pendingPromptItems(pendingPrompts: PendingPrompt[]): ChatItem[];
48
47
  /** @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. */
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
51
  export declare function toQuestion(toolCall: ToolCall, answerToolCall: AnswerToolCall): ChatQuestion | undefined;
@@ -55,14 +55,48 @@ export function toItems(sortedMessages, answeredToolCallIds, submitAnswer) {
55
55
  });
56
56
  }
57
57
  function toStep(toolCall, answerToolCall) {
58
- var _a, _b;
58
+ var _a, _b, _c, _d;
59
59
  const toolName = (_a = toolCall.name) !== null && _a !== void 0 ? _a : "";
60
- // Only file tools carry `display.file_paths`.
61
60
  const display = "display" in toolCall ? toolCall.display : undefined;
62
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
63
  const status = stepStatus(toolCall);
64
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 }) };
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
+ });
66
100
  }
67
101
  /** @internal Base44's tool call status, as a step's. */
68
102
  export function stepStatus(toolCall) {
@@ -104,15 +138,12 @@ export function waitingToolCallIds(sortedMessages) {
104
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); }));
105
139
  }
106
140
  /** @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) {
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) {
111
144
  let stillPending = pendingPrompts;
112
145
  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);
146
+ const settled = stillPending.find(prompt => prompt.appId === appId && prompt.content.trim() === arrivedPrompt.trim());
116
147
  if (settled)
117
148
  stillPending = stillPending.filter(prompt => prompt !== settled);
118
149
  }
@@ -123,10 +154,11 @@ export function pendingPromptItems(pendingPrompts) {
123
154
  return pendingPrompts.map(prompt => ({ id: prompt.id, role: "user", text: prompt.content, createdAt: prompt.createdAt, steps: [], pending: true }));
124
155
  }
125
156
  /** @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. */
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. */
128
160
  export function toQuestion(toolCall, answerToolCall) {
129
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
161
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
130
162
  const kind = (_a = toolCall.waiting_on) === null || _a === void 0 ? void 0 : _a.kind;
131
163
  const decline = () => answerToolCall(false);
132
164
  if (kind === "choice") {
@@ -138,14 +170,27 @@ export function toQuestion(toolCall, answerToolCall) {
138
170
  return ({
139
171
  text: (_a = question.question) !== null && _a !== void 0 ? _a : "",
140
172
  description: question.description,
173
+ type: question.type,
141
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 : ""); }),
142
175
  multi: !!question.multi_select,
143
176
  });
144
177
  }),
145
- answer: picked => {
146
- const answers = picked
147
- .map((labels, questionIndex) => ({ question_index: questionIndex, selected_labels: labels }))
148
- .filter(answer => answer.selected_labels.length);
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
+ });
149
194
  return answerToolCall(true, { answers });
150
195
  },
151
196
  decline,
@@ -161,13 +206,28 @@ export function toQuestion(toolCall, answerToolCall) {
161
206
  };
162
207
  }
163
208
  if (kind === "approval") {
164
- // Guards that declare a reason or a summary carry them; the others name only themselves.
209
+ // Guards that declare a reason or details carry them; the others name only themselves.
165
210
  const approval = toolCall.approval;
166
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 : "";
167
- return { kind, action: (_j = toolCall.name) !== null && _j !== void 0 ? _j : "", reason, approve: () => answerToolCall(true), decline };
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 };
168
214
  }
169
215
  return undefined;
170
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
+ }
171
231
  // The waiting kind says which arguments a call carries; the tool's name only narrows the union.
172
232
  function toolArguments(toolCall) {
173
233
  return "arguments" in toolCall ? toolCall.arguments : undefined;
@@ -112,7 +112,7 @@ export interface ChatStep {
112
112
  tool: string;
113
113
  /** The file paths the tool call touched. */
114
114
  files: string[];
115
- /** The tool name and its files, ready to show. */
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
116
  label: string;
117
117
  /**
118
118
  * Where the tool call is. A `waiting` step waits on the user. A `stopped` step was declined, or the
@@ -125,6 +125,17 @@ export interface ChatStep {
125
125
  * once answered, and is absent for a question kind this release doesn't know.
126
126
  */
127
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;
128
139
  }
129
140
  /**
130
141
  * An open question, with the actions that answer this question and no other.
@@ -143,6 +154,8 @@ export interface ChoiceEntry {
143
154
  text: string;
144
155
  /** Supporting text for the question. */
145
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;
146
159
  /** The option labels to pick from. */
147
160
  options: string[];
148
161
  /** Whether more than one option can be picked. */
@@ -155,12 +168,13 @@ export interface ChoiceQuestion {
155
168
  /** The questions, in order. */
156
169
  questions: ChoiceEntry[];
157
170
  /**
158
- * Answers with the picked labels.
171
+ * Answers with the picked labels, and free text where the user wrote some.
159
172
  *
160
- * @param picked - One list of picked labels per question, in the order of `questions`. An empty list skips that question.
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.
161
175
  * @returns Promise resolving once the answer is sent.
162
176
  */
163
- answer(picked: string[][]): Promise<void>;
177
+ answer(picked: string[][], texts?: string[]): Promise<void>;
164
178
  /**
165
179
  * Declines the question. The AI continues without the answer.
166
180
  *
@@ -203,6 +217,10 @@ export interface ApprovalQuestion {
203
217
  action: string;
204
218
  /** Why the action needs approval, when Base44 gives a reason. Empty otherwise. */
205
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;
206
224
  /**
207
225
  * Lets the action run.
208
226
  *
@@ -216,6 +234,23 @@ export interface ApprovalQuestion {
216
234
  */
217
235
  decline(): Promise<void>;
218
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
+ }
219
254
  /**
220
255
  * What the AI is doing. When several hold at once, the first in this list wins.
221
256
  *
@@ -1,8 +1,4 @@
1
- /** The `@base44/platform/react` entry: the AI chat for one app, as a hook and as a provider that draws it with your parts. React is an optional peer, loaded only here. */
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
2
  export { useBase44Chat } from "./useBase44Chat.js";
3
- export { Base44ChatProvider } from "./Base44ChatProvider.js";
4
- export { useChatActions, useChatState } from "./context.js";
5
- export { Message, Question } from "./Message.js";
6
- export type { ApprovalQuestion, Base44App, Base44Chat, Base44ChatOptions, Base44ChatBackend, ChatConnection, ChatError, ChatItem, ChatQuestion, ChatStatus, ChatStep, ChoiceEntry, ChoiceQuestion, SecretField, SecretsQuestion, ToolCallAnswer, } from "./chat.types.js";
7
- export type { Base44ChatProviderProps, ChatActions, ChatComponents, ChatState, MessageComponents, MessageProps, QuestionComponents, QuestionProps, StepProps, TextProps, } from "./components.types.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";
8
4
  export type { SocketSession } from "../client/modules/builder.types.js";
@@ -1,5 +1,2 @@
1
- /** The `@base44/platform/react` entry: the AI chat for one app, as a hook and as a provider that draws it with your parts. React is an optional peer, loaded only here. */
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
2
  export { useBase44Chat } from "./useBase44Chat.js";
3
- export { Base44ChatProvider } from "./Base44ChatProvider.js";
4
- export { useChatActions, useChatState } from "./context.js";
5
- export { Message, Question } from "./Message.js";
@@ -70,6 +70,8 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
70
70
  // Tool calls declined for the user, and those whose decline failed and may try again.
71
71
  const declinedToolCalls = useRef(new Set());
72
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());
73
75
  // The app `create` made, shown while `appId` is null. Any change to `appId` forgets it.
74
76
  const [createdAppId, setCreatedAppId] = useState(null);
75
77
  const [previousAppIdProp, setPreviousAppIdProp] = useState(appId);
@@ -93,7 +95,10 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
93
95
  setAnsweredToolCallIds([]);
94
96
  if (submittedTo !== currentAppId && submittedTo !== NEW_APP)
95
97
  setSubmittedTo(null);
96
- setPendingPrompts(pendingPrompts.filter(prompt => prompt.appId === currentAppId || prompt.appId === NEW_APP));
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)));
97
102
  }
98
103
  // The backend is read through a ref, kept current after every render, so an inline
99
104
  // `backend={{…}}` never reopens the socket or changes the actions' identity.
@@ -101,6 +106,12 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
101
106
  useEffect(() => {
102
107
  backendRef.current = backend;
103
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;
104
115
  const reportActionError = useCallback((error) => setActionError({ message: (error === null || error === void 0 ? void 0 : error.message) || "Something went wrong", cause: error }), []);
105
116
  // Live updates: a snapshot on every connect, then events.
106
117
  useEffect(() => {
@@ -122,7 +133,7 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
122
133
  // A new reply ends the submission. A new user message is Base44's copy of a prompt, which
123
134
  // settles the pending one.
124
135
  const seenMessageIds = new Set();
125
- const handleIncomingMessages = (incomingMessages, settleOldestIfUnmatched) => {
136
+ const handleIncomingMessages = (incomingMessages) => {
126
137
  const newMessages = incomingMessages.filter(message => message.id && !seenMessageIds.has(message.id));
127
138
  for (const message of incomingMessages)
128
139
  if (message.id)
@@ -131,7 +142,7 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
131
142
  setSubmittedTo(null);
132
143
  const arrivedPrompts = newMessages.filter(message => message.role === "user").map(message => { var _a; return (_a = message.content) !== null && _a !== void 0 ? _a : ""; });
133
144
  if (arrivedPrompts.length) {
134
- setPendingPrompts(prompts => settlePendingPrompts(prompts, followedAppId, arrivedPrompts, settleOldestIfUnmatched));
145
+ setPendingPrompts(prompts => settlePendingPrompts(prompts, followedAppId, arrivedPrompts));
135
146
  }
136
147
  };
137
148
  // A snapshot replaces the conversation when it is the first, or follows a rewrite of main
@@ -140,16 +151,18 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
140
151
  // Base44 can resend an earlier turn's status after the next turn has started: one older than
141
152
  // the newest seen is stale.
142
153
  let latestStatusDate = "";
154
+ // A newer status, whatever its state, means Base44 has reacted, which ends the submission.
143
155
  const applyBuildStatus = (buildStatus) => {
144
156
  var _a;
145
157
  const statusDate = (_a = buildStatus === null || buildStatus === void 0 ? void 0 : buildStatus.last_updated_date) !== null && _a !== void 0 ? _a : "";
146
158
  if (statusDate && statusDate < latestStatusDate)
147
159
  return;
160
+ const isNewer = !!statusDate && statusDate > latestStatusDate;
148
161
  if (statusDate)
149
162
  latestStatusDate = statusDate;
150
163
  const state = buildStatus === null || buildStatus === void 0 ? void 0 : buildStatus.state;
151
164
  setBuildState(state);
152
- if (state === "processing" || state === "error")
165
+ if (isNewer || state === "processing" || state === "error")
153
166
  setSubmittedTo(null);
154
167
  };
155
168
  // The client asks for a session on the first connect and whenever one expires, and forwards
@@ -175,7 +188,7 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
175
188
  builderSession.subscribe(followedAppId, {
176
189
  onSnapshot: snapshot => {
177
190
  // A snapshot holds old prompts too, so only an exact match settles one.
178
- handleIncomingMessages(snapshot.messages, false);
191
+ handleIncomingMessages(snapshot.messages);
179
192
  const replaceMessages = nextSnapshotReplaces;
180
193
  nextSnapshotReplaces = false;
181
194
  setMessages(heldMessages => (replaceMessages ? snapshot.messages : mergeSnapshot(heldMessages, snapshot.messages)));
@@ -188,7 +201,7 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
188
201
  },
189
202
  onEvent: event => {
190
203
  if (event.type === "message.updated") {
191
- handleIncomingMessages([event.data.message], true);
204
+ handleIncomingMessages([event.data.message]);
192
205
  setMessages(heldMessages => mergeMessage(heldMessages, event.data.message));
193
206
  }
194
207
  if (event.type === "message.removed") {
@@ -218,11 +231,16 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
218
231
  const submitAnswer = useCallback((toolCallId, messageId, approve, extraUserInput) => {
219
232
  if (!currentAppId)
220
233
  return Promise.resolve();
234
+ const targetAppId = currentAppId;
221
235
  setActionError(null);
222
- setSubmittedTo(currentAppId);
236
+ setSubmittedTo(targetAppId);
223
237
  setAnsweredToolCallIds(ids => [...ids, toolCallId]);
238
+ answersAwaitingBase44.current.add(toolCallId);
224
239
  const answer = { toolCallId, messageId, approve, extraUserInput };
225
- return backendRef.current.submitToolCallInput(currentAppId, answer).catch((error) => {
240
+ return backendRef.current.submitToolCallInput(targetAppId, answer).catch((error) => {
241
+ answersAwaitingBase44.current.delete(toolCallId);
242
+ if (!stillFollowing(targetAppId))
243
+ return;
226
244
  setAnsweredToolCallIds(ids => ids.filter(answeredId => answeredId !== toolCallId));
227
245
  setSubmittedTo(null);
228
246
  reportActionError(error);
@@ -253,9 +271,19 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
253
271
  }, [currentAppId, sortedMessages, reportActionError]);
254
272
  // An answered call stays hidden while Base44 still reports it waiting, and is forgotten once it
255
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.
256
275
  useEffect(() => {
257
276
  const stillWaiting = waitingToolCallIds(sortedMessages);
258
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));
259
287
  }, [sortedMessages]);
260
288
  const submissionInFlight = (submittedTo === NEW_APP && !currentAppId) || (submittedTo !== null && submittedTo === currentAppId);
261
289
  let status = "ready";
@@ -277,16 +305,21 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
277
305
  setActionError({ message: "There is no app to send to yet: create one first" });
278
306
  return Promise.resolve();
279
307
  }
308
+ const targetAppId = currentAppId;
280
309
  setActionError(null);
281
- setSubmittedTo(currentAppId);
282
- const pendingPrompt = addPendingPrompt(prompt, currentAppId);
283
- return backendRef.current.sendMessage(currentAppId, prompt).catch((error) => {
284
- setSubmittedTo(null);
310
+ setSubmittedTo(targetAppId);
311
+ const pendingPrompt = addPendingPrompt(prompt, targetAppId);
312
+ return backendRef.current.sendMessage(targetAppId, prompt).catch((error) => {
285
313
  setPendingPrompts(prompts => prompts.filter(other => other !== pendingPrompt));
314
+ if (!stillFollowing(targetAppId))
315
+ return;
316
+ setSubmittedTo(null);
286
317
  reportActionError(error);
287
318
  });
288
319
  }, [currentAppId, reportActionError, addPendingPrompt]);
289
320
  const create = useCallback(async (prompt) => {
321
+ const startedFrom = followedAppIdRef.current;
322
+ const followsSetApp = appId !== null;
290
323
  setActionError(null);
291
324
  setSubmittedTo(NEW_APP);
292
325
  const pendingPrompt = addPendingPrompt(prompt, NEW_APP);
@@ -294,15 +327,22 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
294
327
  const app = await backendRef.current.createApp(prompt);
295
328
  setCreatedAppId(app.id);
296
329
  setSubmittedTo(app.id);
297
- setPendingPrompts(prompts => prompts.map(other => (other === pendingPrompt ? { ...other, appId: app.id } : other)));
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)));
298
336
  onAppCreated === null || onAppCreated === void 0 ? void 0 : onAppCreated(app);
299
337
  }
300
338
  catch (error) {
301
- setSubmittedTo(null);
302
339
  setPendingPrompts(prompts => prompts.filter(other => other !== pendingPrompt));
340
+ if (!stillFollowing(startedFrom))
341
+ return;
342
+ setSubmittedTo(null);
303
343
  reportActionError(error);
304
344
  }
305
- }, [onAppCreated, reportActionError, addPendingPrompt]);
345
+ }, [appId, onAppCreated, reportActionError, addPendingPrompt]);
306
346
  const clearError = useCallback(() => {
307
347
  setActionError(null);
308
348
  setConnectionError(null);
@@ -0,0 +1,53 @@
1
+ import type { WebhookConfigurationErrorCode, WebhookVerificationErrorCode } from "./errors.types.js";
2
+ /**
3
+ * The error the SDK reports when a webhook delivery can't be trusted.
4
+ *
5
+ * You don't create it. The [`verifyEvent()`](/developers/references/platform-sdk/docs/interfaces/webhooks#verifyevent) method rejects with
6
+ * it, and [`createHandler()`](/developers/references/platform-sdk/docs/interfaces/webhooks#createhandler) answers it with a 400 and passes it
7
+ * to your `onError`. Check `code` to see what happened, then look the code up below.
8
+ *
9
+ * The error never carries the request body or its signature.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * // Refuse a delivery that doesn't verify
14
+ * try {
15
+ * const event = await platform.webhooks.verifyEvent(rawBody, request.headers, { publicKeys });
16
+ * } catch (error) {
17
+ * if (error instanceof WebhookVerificationError) {
18
+ * return Response.json({ error: error.code }, { status: 400 });
19
+ * }
20
+ * throw error;
21
+ * }
22
+ * ```
23
+ */
24
+ export declare class WebhookVerificationError extends Error {
25
+ /** What happened. One of the [verification error codes](#webhookverificationerrorcode). */
26
+ readonly code: WebhookVerificationErrorCode;
27
+ /** @internal */
28
+ constructor(code: WebhookVerificationErrorCode);
29
+ }
30
+ /**
31
+ * The error the SDK reports when the public keys you passed can't be used, so no delivery can be verified.
32
+ *
33
+ * You don't create it. The [`verifyEvent()`](/developers/references/platform-sdk/docs/interfaces/webhooks#verifyevent) method rejects with
34
+ * it, and [`createHandler()`](/developers/references/platform-sdk/docs/interfaces/webhooks#createhandler) answers it with a 500 and passes it
35
+ * to your `onError`. Base44 retries the delivery, and the retries succeed once you fix the problem.
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * // Log a misconfigured deployment, and let it answer 500
40
+ * export const POST = platform.webhooks.createHandler({
41
+ * publicKeys: process.env.BASE44_WEBHOOK_PUBLIC_KEYS,
42
+ * onError(error) {
43
+ * if (error instanceof WebhookConfigurationError) console.error('Check BASE44_WEBHOOK_PUBLIC_KEYS', error.code);
44
+ * },
45
+ * });
46
+ * ```
47
+ */
48
+ export declare class WebhookConfigurationError extends Error {
49
+ /** What's wrong with the keys. One of the [configuration error codes](#webhookconfigurationerrorcode). */
50
+ readonly code: WebhookConfigurationErrorCode;
51
+ /** @internal */
52
+ constructor(code: WebhookConfigurationErrorCode, detail: string);
53
+ }