@base44-preview/sdk 0.8.37-pr.228.93ccd45 → 0.8.38-pr.212.896c21a

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.
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Type-only base class for Actors.
3
+ *
4
+ * Import and extend this in your actor files:
5
+ * import { Actor } from "@base44/sdk";
6
+ * export class MyActor extends Actor { ... }
7
+ *
8
+ * At deploy time the bundler replaces this import with the compiled
9
+ * Cloudflare Durable Object implementation — this file provides types only.
10
+ */
11
+ import type { Base44Client } from "./client.types.js";
12
+ /**
13
+ * A single client connection. `Send` is the message type this connection accepts
14
+ * via {@link send} — the actor's *outgoing* (server→client) messages.
15
+ */
16
+ export interface Conn<Send = unknown> {
17
+ /** Unique per-connection id (one per socket/tab), the same value the client
18
+ * receives from `subscribe()`. Use this — not userId — to identify a distinct
19
+ * client, so multiple tabs of the same user are separate connections. */
20
+ id: string;
21
+ userId: string;
22
+ appId: string;
23
+ instanceId: string;
24
+ send(data: Send): void;
25
+ reject(code: number, reason: string): void;
26
+ }
27
+ export interface Storage {
28
+ get<T>(key: string): Promise<T | undefined>;
29
+ put(key: string, value: unknown): Promise<void>;
30
+ delete(key: string): Promise<boolean>;
31
+ }
32
+ /**
33
+ * Base class for an Actor.
34
+ *
35
+ * @typeParam Incoming - messages this actor *receives* from clients
36
+ * (`handleMessage`'s `msg`) — the schema's `toServer` section.
37
+ * @typeParam Outgoing - messages this actor *sends* to clients
38
+ * (`conn.send`/`broadcast`) — the schema's `toClient` section.
39
+ *
40
+ * With a generated `schema.jsonc`, wire both from the registry so they can't drift
41
+ * from the client's types:
42
+ * ```ts
43
+ * type Reg = ActorRegistry["MyActor"];
44
+ * class MyActor extends Actor<Reg["toServer"], Reg["toClient"]> { ... }
45
+ * ```
46
+ */
47
+ export declare abstract class Actor<Incoming = unknown, Outgoing = unknown> {
48
+ abstract handleConnect(conn: Conn<Outgoing>): void | Promise<void>;
49
+ abstract handleMessage(conn: Conn<Outgoing>, msg: Incoming): void | Promise<void>;
50
+ abstract handleClose(conn: Conn<Outgoing>): void | Promise<void>;
51
+ abstract handleTick(): void | Promise<void>;
52
+ /**
53
+ * Optional wake hook: runs once when the instance starts, after the
54
+ * platform's credential setup and before any connection is handled — safe
55
+ * to use {@link createServiceClient} and load persisted state here.
56
+ */
57
+ handleStart(): void | Promise<void>;
58
+ /**
59
+ * Managed ticker (opt-in). Override {@link shouldTick} and the platform runs
60
+ * {@link handleTick} on a timer of {@link tickIntervalMs} while it returns true,
61
+ * and stops (letting the Durable Object hibernate — no compute cost) when it
62
+ * returns false. The platform owns scheduling, rescheduling, self-heal, and
63
+ * error-safety — you don't call {@link startLoop}/{@link stopLoop}.
64
+ *
65
+ * Re-evaluated after every connect/message/close and on every tick, so keep it
66
+ * cheap and pure (no async, no side effects). Example: `return this.players >= 2`.
67
+ */
68
+ protected tickIntervalMs: number;
69
+ protected shouldTick?(): boolean;
70
+ protected broadcast(_data: Outgoing): void;
71
+ protected getConnections(): Conn<Outgoing>[];
72
+ protected startLoop(_ms: number): Promise<void>;
73
+ protected stopLoop(): Promise<void>;
74
+ protected get instanceId(): string;
75
+ protected get storage(): Storage;
76
+ /**
77
+ * SDK client acting **as the connected user** — every entity call respects
78
+ * the app's row-level security, evaluated as that user at call time. The
79
+ * default wherever a `conn` is in scope (connect/message/close).
80
+ *
81
+ * Anonymous connections get an unauthenticated client — entity calls run
82
+ * under anonymous RLS, just like any public visitor.
83
+ */
84
+ protected createClientFromConnection(conn: Conn): Base44Client;
85
+ /**
86
+ * Service-role SDK client — bypasses RLS. For work with **no user in scope**
87
+ * (tick, alarm, handleStart). Inside handleMessage/handleConnect prefer
88
+ * `createClientFromConnection(conn)`.
89
+ */
90
+ protected createServiceClient(): Base44Client;
91
+ }
package/dist/actor.js ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Type-only base class for Actors.
3
+ *
4
+ * Import and extend this in your actor files:
5
+ * import { Actor } from "@base44/sdk";
6
+ * export class MyActor extends Actor { ... }
7
+ *
8
+ * At deploy time the bundler replaces this import with the compiled
9
+ * Cloudflare Durable Object implementation — this file provides types only.
10
+ */
11
+ /**
12
+ * Base class for an Actor.
13
+ *
14
+ * @typeParam Incoming - messages this actor *receives* from clients
15
+ * (`handleMessage`'s `msg`) — the schema's `toServer` section.
16
+ * @typeParam Outgoing - messages this actor *sends* to clients
17
+ * (`conn.send`/`broadcast`) — the schema's `toClient` section.
18
+ *
19
+ * With a generated `schema.jsonc`, wire both from the registry so they can't drift
20
+ * from the client's types:
21
+ * ```ts
22
+ * type Reg = ActorRegistry["MyActor"];
23
+ * class MyActor extends Actor<Reg["toServer"], Reg["toClient"]> { ... }
24
+ * ```
25
+ */
26
+ export class Actor {
27
+ constructor() {
28
+ /**
29
+ * Managed ticker (opt-in). Override {@link shouldTick} and the platform runs
30
+ * {@link handleTick} on a timer of {@link tickIntervalMs} while it returns true,
31
+ * and stops (letting the Durable Object hibernate — no compute cost) when it
32
+ * returns false. The platform owns scheduling, rescheduling, self-heal, and
33
+ * error-safety — you don't call {@link startLoop}/{@link stopLoop}.
34
+ *
35
+ * Re-evaluated after every connect/message/close and on every tick, so keep it
36
+ * cheap and pure (no async, no side effects). Example: `return this.players >= 2`.
37
+ */
38
+ this.tickIntervalMs = 100;
39
+ }
40
+ /**
41
+ * Optional wake hook: runs once when the instance starts, after the
42
+ * platform's credential setup and before any connection is handled — safe
43
+ * to use {@link createServiceClient} and load persisted state here.
44
+ */
45
+ handleStart() { }
46
+ broadcast(_data) {
47
+ throw new Error("Actor.broadcast() is only available inside a deployed actor");
48
+ }
49
+ getConnections() {
50
+ throw new Error("Actor.getConnections() is only available inside a deployed actor");
51
+ }
52
+ startLoop(_ms) {
53
+ throw new Error("Actor.startLoop() is only available inside a deployed actor");
54
+ }
55
+ stopLoop() {
56
+ throw new Error("Actor.stopLoop() is only available inside a deployed actor");
57
+ }
58
+ get instanceId() {
59
+ throw new Error("Actor.instanceId is only available inside a deployed actor");
60
+ }
61
+ get storage() {
62
+ throw new Error("Actor.storage is only available inside a deployed actor");
63
+ }
64
+ /**
65
+ * SDK client acting **as the connected user** — every entity call respects
66
+ * the app's row-level security, evaluated as that user at call time. The
67
+ * default wherever a `conn` is in scope (connect/message/close).
68
+ *
69
+ * Anonymous connections get an unauthenticated client — entity calls run
70
+ * under anonymous RLS, just like any public visitor.
71
+ */
72
+ createClientFromConnection(conn) {
73
+ void conn;
74
+ throw new Error("Actor.createClientFromConnection() is only available inside a deployed actor");
75
+ }
76
+ /**
77
+ * Service-role SDK client — bypasses RLS. For work with **no user in scope**
78
+ * (tick, alarm, handleStart). Inside handleMessage/handleConnect prefer
79
+ * `createClientFromConnection(conn)`.
80
+ */
81
+ createServiceClient() {
82
+ throw new Error("Actor.createServiceClient() is only available inside a deployed actor");
83
+ }
84
+ }
package/dist/client.js CHANGED
@@ -12,6 +12,7 @@ import { createAppLogsModule } from "./modules/app-logs.js";
12
12
  import { createUsersModule } from "./modules/users.js";
13
13
  import { RoomsSocket } from "./utils/socket-utils.js";
14
14
  import { createAnalyticsModule } from "./modules/analytics.js";
15
+ import { createActorsModule } from "./modules/actors.js";
15
16
  /**
16
17
  * Creates a Base44 client.
17
18
  *
@@ -51,9 +52,27 @@ import { createAnalyticsModule } from "./modules/analytics.js";
51
52
  */
52
53
  export function createClient(config) {
53
54
  var _a, _b;
54
- const { serverUrl = "https://base44.app", appId, token, serviceToken, requiresAuth = false, appBaseUrl, options, functionsVersion, headers: optionalHeaders, } = config;
55
+ const { serverUrl = "https://base44.app", appId, token, serviceToken, requiresAuth = false, appBaseUrl, options, functionsVersion, headers: optionalHeaders, dispatcherWsUrl, webSocketImpl, } = config;
55
56
  // Normalize appBaseUrl to always be a string (empty if not provided or invalid)
56
57
  const normalizedAppBaseUrl = typeof appBaseUrl === "string" ? appBaseUrl : "";
58
+ // Derive the dispatcher WebSocket URL if not explicitly provided. Default to
59
+ // the app's OWN origin (the app URL proxies /parties to the backend) so the
60
+ // socket is same-origin with the running app, not the API host: prefer an
61
+ // explicit appBaseUrl, then the browser origin, then fall back to serverUrl
62
+ // (Node/SSR, where there's no window). Convert https:// → wss:// (http → ws)
63
+ // and strip the trailing slash.
64
+ const resolvedDispatcherWsUrl = (() => {
65
+ var _a, _b;
66
+ if (dispatcherWsUrl)
67
+ return dispatcherWsUrl.replace(/\/$/, "");
68
+ const appOrigin = normalizedAppBaseUrl ||
69
+ // React Native has a bare `window` with no `location`, so guard both.
70
+ (typeof window !== "undefined" ? (_b = (_a = window.location) === null || _a === void 0 ? void 0 : _a.origin) !== null && _b !== void 0 ? _b : "" : "");
71
+ return (appOrigin || serverUrl)
72
+ .replace(/\/$/, "")
73
+ .replace(/^https:\/\//, "wss://")
74
+ .replace(/^http:\/\//, "ws://");
75
+ })();
57
76
  const socketConfig = {
58
77
  serverUrl,
59
78
  mountPath: "/ws-user-apps/socket.io/",
@@ -151,7 +170,7 @@ export function createClient(config) {
151
170
  serverUrl,
152
171
  token,
153
172
  }),
154
- aiGateway: createAiGatewayModule({ serverUrl, token }),
173
+ aiGateway: createAiGatewayModule({ serverUrl, token, appId }),
155
174
  appLogs: createAppLogsModule(axiosClient, appId),
156
175
  users: createUsersModule(axiosClient, appId),
157
176
  analytics: createAnalyticsModule({
@@ -160,6 +179,22 @@ export function createClient(config) {
160
179
  appId,
161
180
  userAuthModule,
162
181
  }),
182
+ actors: createActorsModule({
183
+ appId,
184
+ dispatcherWsUrl: resolvedDispatcherWsUrl,
185
+ webSocketImpl,
186
+ getToken: async (actorName, instanceId, connId) => {
187
+ // axiosClient interceptors unwrap response.data, so the result is the body directly.
188
+ // conn_id rides inside the signed token (not a WS query param) so it survives
189
+ // proxies that strip params; the dispatcher forwards it as the actor's conn.id.
190
+ // Base44-Functions-Version rides along (like function calls) so live apps get
191
+ // tokens for the *published* actor script and previews get the draft.
192
+ const data = await axiosClient.post(`/apps/${appId}/actor-token`, { handler_name: actorName, instance_id: instanceId, conn_id: connId }, functionsVersion
193
+ ? { headers: { "Base44-Functions-Version": functionsVersion } }
194
+ : undefined);
195
+ return data.token;
196
+ },
197
+ }),
163
198
  cleanup: () => {
164
199
  userModules.analytics.cleanup();
165
200
  if (socket) {
@@ -194,7 +229,7 @@ export function createClient(config) {
194
229
  serverUrl,
195
230
  token,
196
231
  }),
197
- aiGateway: createAiGatewayModule({ serverUrl, token: serviceToken }),
232
+ aiGateway: createAiGatewayModule({ serverUrl, token: serviceToken, appId }),
198
233
  appLogs: createAppLogsModule(serviceRoleAxiosClient, appId),
199
234
  cleanup: () => {
200
235
  if (socket) {
@@ -346,7 +381,6 @@ export function createClientFromRequest(request) {
346
381
  const serverUrlHeader = request.headers.get("Base44-Api-Url");
347
382
  const functionsVersion = request.headers.get("Base44-Functions-Version");
348
383
  const stateHeader = request.headers.get("Base44-State");
349
- const dataEnvHeader = request.headers.get("X-Data-Env");
350
384
  if (!appId) {
351
385
  throw new Error("Base44-App-Id header is required, but is was not found on the request");
352
386
  }
@@ -374,14 +408,6 @@ export function createClientFromRequest(request) {
374
408
  if (stateHeader) {
375
409
  additionalHeaders["Base44-State"] = stateHeader;
376
410
  }
377
- // Propagate the data environment so entity operations from the function stay
378
- // in the same environment (e.g. test data) as the triggering request. This
379
- // matters for the user-scoped client: unlike the service token, the user JWT
380
- // carries no data-env, so without forwarding this header the callbacks fall
381
- // back to production data even when the app runs in test-data mode.
382
- if (dataEnvHeader) {
383
- additionalHeaders["X-Data-Env"] = dataEnvHeader;
384
- }
385
411
  return createClient({
386
412
  serverUrl: serverUrlHeader || "https://base44.app",
387
413
  appId,
@@ -8,6 +8,7 @@ import type { AgentsModule } from "./modules/agents.types.js";
8
8
  import type { AiGatewayModule } from "./modules/ai-gateway.types.js";
9
9
  import type { AppLogsModule } from "./modules/app-logs.types.js";
10
10
  import type { AnalyticsModule } from "./modules/analytics.types.js";
11
+ import type { ActorsModule } from "./modules/actors.types.js";
11
12
  /**
12
13
  * Options for creating a Base44 client.
13
14
  */
@@ -73,6 +74,28 @@ export interface CreateClientConfig {
73
74
  * Additional client options.
74
75
  */
75
76
  options?: CreateClientOptions;
77
+ /**
78
+ * Base WebSocket URL for the Cloudflare Durable Object dispatcher.
79
+ *
80
+ * Defaults to the app's own origin (`appBaseUrl`, else the browser's
81
+ * `window.location.origin`, else `serverUrl`) with `https://` replaced by
82
+ * `wss://` (or `http://` by `ws://`) — so the realtime socket is same-origin
83
+ * with the running app, which proxies `/parties` to the backend.
84
+ * Override when the dispatcher lives at a different host than the app.
85
+ */
86
+ dispatcherWsUrl?: string;
87
+ /**
88
+ * WebSocket implementation for realtime subscriptions in environments
89
+ * without a global `WebSocket` (Node.js < 22). Browsers and Node ≥ 22
90
+ * don't need this.
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * import WS from "ws";
95
+ * const base44 = createClient({ appId, webSocketImpl: WS });
96
+ * ```
97
+ */
98
+ webSocketImpl?: unknown;
76
99
  }
77
100
  /**
78
101
  * The Base44 client instance.
@@ -88,6 +111,8 @@ export interface Base44Client {
88
111
  analytics: AnalyticsModule;
89
112
  /** {@link AppLogsModule | App logs module} for tracking app usage. */
90
113
  appLogs: AppLogsModule;
114
+ /** {@link ActorsModule | Actors module} for subscribing to and sending messages via Cloudflare Durable Object-backed Actors. */
115
+ actors: ActorsModule;
91
116
  /** {@link AuthModule | Auth module} for user authentication and management. */
92
117
  auth: AuthModule;
93
118
  /** {@link UserConnectorsModule | Connectors module} for app-user OAuth flows. */
package/dist/index.d.ts CHANGED
@@ -11,7 +11,9 @@ export type { FunctionsModule, FunctionName, FunctionNameRegistry, } from "./mod
11
11
  export type { AgentsModule, AgentName, AgentNameRegistry, AgentConversation, AgentMessage, AgentMessageReasoning, AgentMessageToolCall, AgentMessageUsage, AgentMessageCustomContext, AgentMessageMetadata, CreateConversationParams, } from "./modules/agents.types.js";
12
12
  export type { AiGatewayModule, AiGatewayConnection, } from "./modules/ai-gateway.types.js";
13
13
  export type { AppLogsModule } from "./modules/app-logs.types.js";
14
+ export type { ActorsModule, ActorClient, ActorNameRegistry, ActorRegistry, } from "./modules/actors.types.js";
14
15
  export type { SsoModule, SsoAccessTokenResponse } from "./modules/sso.types.js";
16
+ export { Actor, type Conn } from "./actor.js";
15
17
  export type { ConnectorsModule, UserConnectorsModule, } from "./modules/connectors.types.js";
16
18
  export type { CustomIntegrationsModule, CustomIntegrationCallParams, CustomIntegrationCallResponse, } from "./modules/custom-integrations.types.js";
17
19
  export type { GetAccessTokenOptions, SaveAccessTokenOptions, RemoveAccessTokenOptions, GetLoginUrlOptions, } from "./utils/auth-utils.types.js";
package/dist/index.js CHANGED
@@ -3,3 +3,4 @@ import { Base44Error } from "./utils/axios-client.js";
3
3
  import { getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, } from "./utils/auth-utils.js";
4
4
  export { createClient, createClientFromRequest, Base44Error, getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, };
5
5
  export * from "./types.js";
6
+ export { Actor } from "./actor.js";
@@ -0,0 +1,21 @@
1
+ export declare function createActorsModule(config: {
2
+ appId: string;
3
+ getToken(actorName: string, instanceId: string, connId: string): Promise<string>;
4
+ dispatcherWsUrl: string;
5
+ /** WebSocket implementation for runtimes without a global one (Node < 22). */
6
+ webSocketImpl?: unknown;
7
+ }): Record<string, ActorClient>;
8
+ /** Handle for an active actor subscription. */
9
+ interface ActorSubscription {
10
+ /** This connection's id — the same value the actor receives as `conn.id`. */
11
+ id: string;
12
+ /** Close the subscription and its underlying socket. */
13
+ unsubscribe(): void;
14
+ }
15
+ interface ActorClient {
16
+ subscribe(instanceId: string, callback: (data: unknown) => void, options?: {
17
+ id?: string;
18
+ }): ActorSubscription;
19
+ send(instanceId: string, data: unknown): void;
20
+ }
21
+ export {};
@@ -0,0 +1,89 @@
1
+ import PartySocket from "partysocket";
2
+ // Module-level map: "ActorName:instanceId" → active socket
3
+ const activeSockets = new Map();
4
+ function socketKey(actorName, instanceId) {
5
+ return `${actorName}:${instanceId}`;
6
+ }
7
+ export function createActorsModule(config) {
8
+ return new Proxy({}, {
9
+ get(_, actorName) {
10
+ return {
11
+ subscribe(instanceId, callback, options) {
12
+ var _a, _b;
13
+ const key = socketKey(actorName, instanceId);
14
+ // close existing if any
15
+ (_a = activeSockets.get(key)) === null || _a === void 0 ? void 0 : _a.close();
16
+ // Connection id: caller-supplied (stable — reuse across reconnects/tabs as
17
+ // you see fit) or auto-generated per subscription. It travels INSIDE the
18
+ // signed actor token (never as a WS query param, which proxies strip);
19
+ // the dispatcher forwards the verified claim as partyserver's _pk, so the
20
+ // actor sees this exact value as conn.id. Reconnects re-mint the token
21
+ // with the same id, so conn.id is stable across reconnects.
22
+ const connId = (_b = options === null || options === void 0 ? void 0 : options.id) !== null && _b !== void 0 ? _b : crypto.randomUUID();
23
+ // query as async fn: called on every (re)connect, fetches a fresh token each time
24
+ const ws = new PartySocket({
25
+ host: config.dispatcherWsUrl,
26
+ party: actorName,
27
+ room: instanceId,
28
+ ...(config.webSocketImpl ? { WebSocket: config.webSocketImpl } : {}),
29
+ query: () => config.getToken(actorName, instanceId, connId).then((token) => ({ token })),
30
+ });
31
+ activeSockets.set(key, ws);
32
+ // Heartbeat / half-open detection. PartySocket only reconnects on a
33
+ // browser close/error event, so a silently-dead connection (TCP alive,
34
+ // no data — common behind proxies/LBs) hangs until the OS idle timeout
35
+ // (~60s). We ping periodically and force a reconnect if nothing comes
36
+ // back within DEAD_MS, cutting detection from ~60s to a few seconds.
37
+ const PING_MS = 1000;
38
+ const DEAD_MS = 3000;
39
+ let lastMsg = Date.now();
40
+ const bumpAlive = () => { lastMsg = Date.now(); };
41
+ ws.addEventListener("open", bumpAlive);
42
+ ws.addEventListener("message", (ev) => {
43
+ bumpAlive();
44
+ let data;
45
+ try {
46
+ data = JSON.parse(ev.data);
47
+ }
48
+ catch (_a) {
49
+ return; // ignore malformed
50
+ }
51
+ // Swallow platform messages — never surface them to the app.
52
+ const msgType = data && typeof data === "object" ? data.type : undefined;
53
+ if (msgType === "__pong")
54
+ return;
55
+ callback(data);
56
+ });
57
+ const heartbeat = setInterval(() => {
58
+ if (Date.now() - lastMsg > DEAD_MS) {
59
+ bumpAlive(); // avoid a reconnect storm while the new socket comes up
60
+ ws.reconnect();
61
+ return;
62
+ }
63
+ try {
64
+ ws.send(JSON.stringify({ type: "__ping" }));
65
+ }
66
+ catch (_a) {
67
+ // socket not open; the watchdog above will force a reconnect
68
+ }
69
+ }, PING_MS);
70
+ return {
71
+ id: connId, // the connection id (same value the actor sees as conn.id)
72
+ unsubscribe() {
73
+ clearInterval(heartbeat);
74
+ activeSockets.delete(key);
75
+ ws.close();
76
+ },
77
+ };
78
+ },
79
+ send(instanceId, data) {
80
+ const key = socketKey(actorName, instanceId);
81
+ const ws = activeSockets.get(key);
82
+ if (!ws)
83
+ throw new Error(`No active subscription for ${actorName}:${instanceId}`);
84
+ ws.send(JSON.stringify(data));
85
+ },
86
+ };
87
+ },
88
+ });
89
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Extend this interface to add typed `subscribe` callbacks and `send` payloads
3
+ * for your deployed Actors.
4
+ *
5
+ * This is separate from {@link ActorNameRegistry} (which is auto-generated
6
+ * by `base44 types generate`), so there are no conflicts.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * declare module "@base44/sdk" {
11
+ * interface ActorRegistry {
12
+ * ChatRoom: {
13
+ * toClient: { type: "joined" | "left" | "message"; userId?: string; from?: string; text?: string };
14
+ * toServer: { type: "message"; text: string };
15
+ * };
16
+ * }
17
+ * }
18
+ * ```
19
+ */
20
+ export interface ActorRegistry {
21
+ }
22
+ /**
23
+ * Auto-populated by `base44 types generate` with the names of your deployed actors.
24
+ * Do not edit this interface manually — use {@link ActorRegistry} for message types.
25
+ */
26
+ export interface ActorNameRegistry {
27
+ }
28
+ type AllActorNames = keyof ActorRegistry | keyof ActorNameRegistry;
29
+ type ToClientFor<N extends string> = N extends keyof ActorRegistry ? ActorRegistry[N] extends {
30
+ toClient: infer I;
31
+ } ? I : unknown : unknown;
32
+ type ToServerFor<N extends string> = N extends keyof ActorRegistry ? ActorRegistry[N] extends {
33
+ toServer: infer O;
34
+ } ? O : unknown : unknown;
35
+ /**
36
+ * Client for a single named Actor.
37
+ * Typed automatically when the actor is registered in {@link ActorRegistry}.
38
+ */
39
+ export interface ActorClient<N extends string = string> {
40
+ /**
41
+ * Open a WebSocket subscription. Returns a {@link ActorSubscription} with the
42
+ * connection `id` (same value the actor sees as `conn.id`) and an `unsubscribe()` method.
43
+ *
44
+ * Pass `options.id` to control the connection id (e.g. a stable per-tab id so a
45
+ * reconnect reuses the same server-side connection); omit it for an auto-generated
46
+ * per-connection id.
47
+ */
48
+ subscribe(instanceId: string, callback: (data: ToClientFor<N>) => void, options?: {
49
+ id?: string;
50
+ }): ActorSubscription;
51
+ /** Send a message over the open socket. Throws if not subscribed. */
52
+ send(instanceId: string, data: ToServerFor<N>): void;
53
+ }
54
+ /** Handle for an active actor subscription. */
55
+ export interface ActorSubscription {
56
+ /** This connection's id — the same value the actor receives as `conn.id`. */
57
+ id: string;
58
+ /** Close the subscription and its underlying socket. */
59
+ unsubscribe(): void;
60
+ }
61
+ /**
62
+ * The actors module provides access to Cloudflare Durable Object-backed
63
+ * Actors deployed by the Base44 platform.
64
+ *
65
+ * Actor names are accessed as dynamic properties on this module:
66
+ * ```typescript
67
+ * const sub = await base44.actors.MyActor.subscribe("room-1", (msg) => {
68
+ * console.log(msg); // typed if MyActor is in ActorRegistry
69
+ * });
70
+ * const { id, unsubscribe } = sub;
71
+ * unsubscribe();
72
+ * ```
73
+ */
74
+ export type ActorsModule = {
75
+ [K in AllActorNames]: K extends keyof ActorRegistry ? ActorClient<string & K> : ActorClient;
76
+ } & Record<string, ActorClient>;
77
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -1,2 +1,2 @@
1
1
  import { AiGatewayModule, AiGatewayModuleConfig } from "./ai-gateway.types.js";
2
- export declare function createAiGatewayModule({ serverUrl, token, }: AiGatewayModuleConfig): AiGatewayModule;
2
+ export declare function createAiGatewayModule({ serverUrl, token, appId, }: AiGatewayModuleConfig): AiGatewayModule;
@@ -1,9 +1,9 @@
1
1
  import { getAccessToken } from "../utils/auth-utils.js";
2
- export function createAiGatewayModule({ serverUrl, token, }) {
2
+ export function createAiGatewayModule({ serverUrl, token, appId, }) {
3
3
  const connection = () => {
4
4
  var _a;
5
5
  return ({
6
- baseURL: `${serverUrl}/api/ai/openai/v1`,
6
+ baseURL: `${serverUrl}/api/apps/${appId}/ai/openai/v1`,
7
7
  token: (_a = token !== null && token !== void 0 ? token : getAccessToken()) !== null && _a !== void 0 ? _a : "",
8
8
  });
9
9
  };
@@ -1,9 +1,8 @@
1
1
  /**
2
2
  * A connection to the Base44 AI Gateway.
3
3
  *
4
- * Contains the base URL and bearer token to use with any OpenAI-compatible client
5
- * (OpenAI SDK, Mastra, Vercel AI SDK, and others) pointed at the Base44 AI
6
- * Gateway.
4
+ * Contains the base URL and bearer token to use with any OpenAI-compatible
5
+ * client pointed at the Base44 AI Gateway.
7
6
  */
8
7
  export interface AiGatewayConnection {
9
8
  /** Base URL of the gateway's OpenAI-compatible endpoint. */
@@ -20,13 +19,15 @@ export interface AiGatewayModuleConfig {
20
19
  serverUrl?: string;
21
20
  /** Authentication token */
22
21
  token?: string;
22
+ /** Application ID */
23
+ appId: string;
23
24
  }
24
25
  /**
25
26
  * AI Gateway module for calling Base44's managed AI models from your own code.
26
27
  *
27
28
  * The gateway exposes an OpenAI-compatible Chat Completions endpoint, so any
28
29
  * OpenAI-compatible SDK works against it:
29
- * - Build custom AI agents with agent SDKs such as Mastra or the Vercel AI SDK
30
+ * - Build custom AI agents or call models directly from your backend code
30
31
  * - Uses your app's models, billing, and credit quota, no API key to manage
31
32
  *
32
33
  * Available in user authentication mode (`base44.aiGateway`) and with the
@@ -46,55 +47,41 @@ export interface AiGatewayModule {
46
47
  *
47
48
  * @example
48
49
  * ```typescript
49
- * // Build an AI agent with Mastra on top of the gateway, inside a backend function
50
- * import { createClientFromRequest } from 'npm:@base44/sdk';
51
- * import { Agent } from 'npm:@mastra/core/agent';
52
- * import { createTool } from 'npm:@mastra/core/tools';
53
- * import { createOpenAICompatible } from 'npm:@ai-sdk/openai-compatible';
54
- * import { z } from 'npm:zod';
50
+ * import { ToolLoopAgent, tool, stepCountIs, hasToolCall } from "ai";
51
+ * import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
52
+ * import { z } from "zod";
55
53
  *
56
- * Deno.serve(async (req) => {
57
- * const base44 = createClientFromRequest(req);
58
- * const { baseURL, token } = base44.aiGateway.connection();
59
- * const models = createOpenAICompatible({ name: 'base44', baseURL, apiKey: token });
54
+ * const request = await base44.entities.ReturnRequest.get(returnId);
55
+ * const { baseURL, token } = base44.aiGateway.connection();
56
+ * // Point any OpenAI-compatible client at `baseURL` with `apiKey: token`.
57
+ * const models = createOpenAICompatible({ name: "base44", baseURL, apiKey: token });
60
58
  *
61
- * const agent = new Agent({
62
- * id: 'order-helper',
63
- * name: 'order-helper',
64
- * instructions: 'Help the user with their orders.',
65
- * model: models('claude_sonnet_4_6'),
66
- * tools: {
67
- * lookupOrder: createTool({
68
- * id: 'lookup-order',
69
- * description: 'Fetch an order by id',
70
- * inputSchema: z.object({ orderId: z.string() }),
71
- * execute: async ({ orderId }) => base44.entities.Order.get(orderId),
72
- * }),
73
- * },
74
- * });
75
- *
76
- * const { text } = await agent.generate('Where is order 123?');
77
- * return Response.json({ text });
59
+ * const agent = new ToolLoopAgent({
60
+ * model: models("automatic"),
61
+ * instructions:
62
+ * "Decide whether this return looks fine or needs the owner's attention. " +
63
+ * "Check the customer's past orders, then submit your verdict.",
64
+ * tools: {
65
+ * searchOrders: tool({
66
+ * description: "This customer's past orders, optionally filtered by status",
67
+ * inputSchema: z.object({ status: z.string().optional() }),
68
+ * execute: ({ status }) => {
69
+ * const query = { customer_email: request.customer_email };
70
+ * if (status) query.status = status;
71
+ * return base44.entities.Order.filter(query, "-created_date", 50);
72
+ * },
73
+ * }),
74
+ * submitVerdict: tool({
75
+ * description: "Record the final verdict",
76
+ * inputSchema: z.object({ decision: z.enum(["approved", "flagged"]), reason: z.string() }),
77
+ * execute: ({ decision, reason }) =>
78
+ * base44.entities.ReturnRequest.update(returnId, { status: decision, review_note: reason }),
79
+ * }),
80
+ * },
81
+ * stopWhen: [stepCountIs(8), hasToolCall("submitVerdict")],
78
82
  * });
79
- * ```
80
83
  *
81
- * @example
82
- * ```typescript
83
- * // Call a model directly with the OpenAI SDK
84
- * import { createClientFromRequest } from 'npm:@base44/sdk';
85
- * import OpenAI from 'npm:openai';
86
- *
87
- * Deno.serve(async (req) => {
88
- * const base44 = createClientFromRequest(req);
89
- * const { baseURL, token } = base44.aiGateway.connection();
90
- *
91
- * const openai = new OpenAI({ baseURL, apiKey: token });
92
- * const res = await openai.chat.completions.create({
93
- * model: 'claude_sonnet_4_6',
94
- * messages: [{ role: 'user', content: 'Hello!' }],
95
- * });
96
- * return Response.json({ text: res.choices[0].message.content });
97
- * });
84
+ * await agent.generate({ prompt: `Review this return request: ${JSON.stringify(request)}` });
98
85
  * ```
99
86
  */
100
87
  connection(): AiGatewayConnection;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/sdk",
3
- "version": "0.8.37-pr.228.93ccd45",
3
+ "version": "0.8.38-pr.212.896c21a",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -27,6 +27,7 @@
27
27
  },
28
28
  "dependencies": {
29
29
  "axios": "^1.17.0",
30
+ "partysocket": "^0.0.23",
30
31
  "socket.io-client": "^4.8.3",
31
32
  "uuid": "^13.0.2"
32
33
  },