@realtimex/sdk 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,144 @@
1
+ # RealtimeX Local App SDK
2
+
3
+ TypeScript/JavaScript SDK for building Local Apps that integrate with RealtimeX.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @realtimex/sdk
9
+ ```
10
+
11
+ ## Prerequisites
12
+
13
+ Before using this SDK, ensure your Supabase database is set up:
14
+
15
+ 1. Open **RealtimeX Main App** → **Local Apps** → Your App → **Configure**
16
+ 2. Enter your Supabase **URL** and **Anon Key**
17
+ 3. Select **Compatible Mode** and click **Login to Supabase**
18
+ 4. Click **Auto-Setup Schema** to create the required tables and functions
19
+
20
+ > **Note:** Schema setup is handled entirely by the Main App. You don't need to run any SQL manually.
21
+
22
+ ## Quick Start
23
+
24
+ ```typescript
25
+ import { RealtimeXSDK } from '@realtimex/sdk';
26
+
27
+ // No config needed - RTX_APP_ID is auto-detected from environment
28
+ const sdk = new RealtimeXSDK();
29
+
30
+ // Insert activity
31
+ const activity = await sdk.activities.insert({
32
+ type: 'new_lead',
33
+ email: 'user@example.com',
34
+ });
35
+
36
+ // Trigger agent (optional - for auto-processing)
37
+ await sdk.webhook.triggerAgent({
38
+ raw_data: activity,
39
+ auto_run: true,
40
+ agent_name: 'processor',
41
+ workspace_slug: 'sales',
42
+ thread_slug: 'general', //create_new for new thread
43
+ prompt: 'Process this lead',//optional
44
+ });
45
+ ```
46
+
47
+ ## How It Works
48
+
49
+ When you start your Local App from the RealtimeX Main App:
50
+
51
+ 1. Environment variables `RTX_APP_ID` and `RTX_APP_NAME` are automatically set
52
+ 2. The SDK auto-detects these - no manual configuration needed
53
+ 3. All operations go through the Main App's proxy endpoints
54
+
55
+ ## Configuration (Optional)
56
+
57
+ ```typescript
58
+ const sdk = new RealtimeXSDK({
59
+ realtimex: {
60
+ url: 'http://custom-host:3001', // Default: localhost:3001
61
+ appId: 'custom-id', // Override auto-detected
62
+ appName: 'My App', // Override auto-detected
63
+ }
64
+ });
65
+ ```
66
+
67
+ ## API Reference
68
+
69
+ ### Activities CRUD
70
+
71
+ ```typescript
72
+ // Insert
73
+ const activity = await sdk.activities.insert({ type: 'order', amount: 100 });
74
+
75
+ // List
76
+ const pending = await sdk.activities.list({ status: 'pending', limit: 50 });
77
+
78
+ // Get
79
+ const item = await sdk.activities.get('activity-uuid');
80
+
81
+ // Update
82
+ await sdk.activities.update('activity-uuid', { status: 'processed' });
83
+
84
+ // Delete
85
+ await sdk.activities.delete('activity-uuid');
86
+ ```
87
+
88
+ ### Webhook - Trigger Agent
89
+
90
+ ```typescript
91
+ // Manual mode (creates calendar event only)
92
+ await sdk.webhook.triggerAgent({
93
+ raw_data: { email: 'customer@example.com' },
94
+ });
95
+
96
+ // Auto-run mode (creates event and triggers agent immediately)
97
+ await sdk.webhook.triggerAgent({
98
+ raw_data: activity,
99
+ auto_run: true,
100
+ agent_name: 'processor',
101
+ workspace_slug: 'sales',
102
+ thread_slug: 'optional-thread', // Optional: specific thread
103
+ });
104
+ ```
105
+
106
+ ### Public APIs
107
+
108
+ ```typescript
109
+ // Get available agents in a workspace
110
+ const agents = await sdk.api.getAgents();
111
+
112
+ // Get all workspaces
113
+ const workspaces = await sdk.api.getWorkspaces();
114
+
115
+ // Get threads in a workspace
116
+ const threads = await sdk.api.getThreads('sales');
117
+
118
+ // Get task status
119
+ const task = await sdk.api.getTask('task-uuid');
120
+ ```
121
+
122
+ ## Environment Variables
123
+
124
+ | Variable | Description |
125
+ |----------|-------------|
126
+ | `RTX_APP_ID` | Auto-set by Main App when starting your app |
127
+ | `RTX_APP_NAME` | Auto-set by Main App when starting your app |
128
+
129
+ ## Architecture
130
+
131
+ ```
132
+ ┌─────────────────┐ ┌──────────────────┐ ┌─────────────┐
133
+ │ Your App │────▶│ RealtimeX Main │────▶│ Supabase │
134
+ │ (SDK) │ │ App (Proxy) │ │ Database │
135
+ └─────────────────┘ └──────────────────┘ └─────────────┘
136
+ ```
137
+
138
+ - Your app uses the SDK to communicate with the Main App
139
+ - Main App proxies all database operations to Supabase
140
+ - Schema is managed by Main App (no direct database access needed)
141
+
142
+ ## License
143
+
144
+ MIT
@@ -0,0 +1,167 @@
1
+ /**
2
+ * RealtimeX Local App SDK - Types
3
+ */
4
+ interface SDKConfig {
5
+ realtimex?: {
6
+ url?: string;
7
+ appId?: string;
8
+ appName?: string;
9
+ };
10
+ }
11
+ interface Activity {
12
+ id: string;
13
+ raw_data: Record<string, unknown>;
14
+ old_data?: Record<string, unknown>;
15
+ status: 'pending' | 'claimed' | 'completed' | 'failed';
16
+ locked_by?: string;
17
+ locked_at?: string;
18
+ completed_at?: string;
19
+ error_message?: string;
20
+ result?: Record<string, unknown>;
21
+ created_at: string;
22
+ }
23
+ interface TriggerAgentPayload {
24
+ raw_data: Record<string, unknown>;
25
+ auto_run?: boolean;
26
+ agent_name?: string;
27
+ workspace_slug?: string;
28
+ thread_slug?: string;
29
+ prompt?: string;
30
+ }
31
+ interface TriggerAgentResponse {
32
+ success: boolean;
33
+ task_uuid?: string;
34
+ calendar_event_uuid?: string;
35
+ auto_run?: boolean;
36
+ message?: string;
37
+ error?: string;
38
+ }
39
+ interface Agent {
40
+ slug: string;
41
+ name: string;
42
+ description?: string;
43
+ hub_id?: string;
44
+ }
45
+ interface Workspace {
46
+ id: number;
47
+ slug: string;
48
+ name: string;
49
+ type: string;
50
+ created_at: string;
51
+ }
52
+ interface Thread {
53
+ id: number;
54
+ slug: string;
55
+ name: string;
56
+ created_at: string;
57
+ }
58
+ interface TaskRun {
59
+ id: number;
60
+ agent_name: string;
61
+ workspace_slug: string;
62
+ thread_slug?: string;
63
+ status: string;
64
+ started_at?: string;
65
+ completed_at?: string;
66
+ error?: string;
67
+ }
68
+ interface Task {
69
+ uuid: string;
70
+ title: string;
71
+ status: string;
72
+ action_type: string;
73
+ source_app: string;
74
+ error?: string;
75
+ created_at: string;
76
+ updated_at: string;
77
+ runs: TaskRun[];
78
+ }
79
+
80
+ /**
81
+ * Activities Module - HTTP Proxy to RealtimeX Main App
82
+ * No direct Supabase access - all operations go through Main App
83
+ */
84
+
85
+ declare class ActivitiesModule {
86
+ private baseUrl;
87
+ private appId;
88
+ constructor(realtimexUrl: string, appId: string);
89
+ private request;
90
+ /**
91
+ * Insert a new activity
92
+ */
93
+ insert(rawData: Record<string, unknown>): Promise<Activity>;
94
+ /**
95
+ * Update an existing activity
96
+ */
97
+ update(id: string, updates: Partial<Activity>): Promise<Activity>;
98
+ /**
99
+ * Delete an activity
100
+ */
101
+ delete(id: string): Promise<void>;
102
+ /**
103
+ * Get a single activity by ID
104
+ */
105
+ get(id: string): Promise<Activity | null>;
106
+ /**
107
+ * List activities with optional filters
108
+ */
109
+ list(options?: {
110
+ status?: string;
111
+ limit?: number;
112
+ offset?: number;
113
+ }): Promise<Activity[]>;
114
+ }
115
+
116
+ /**
117
+ * Webhook Module - Call RealtimeX webhook
118
+ */
119
+
120
+ declare class WebhookModule {
121
+ private realtimexUrl;
122
+ private appName?;
123
+ private appId?;
124
+ constructor(realtimexUrl: string, appName?: string, appId?: string);
125
+ triggerAgent(payload: TriggerAgentPayload): Promise<TriggerAgentResponse>;
126
+ ping(): Promise<{
127
+ success: boolean;
128
+ app_name: string;
129
+ message: string;
130
+ }>;
131
+ }
132
+
133
+ /**
134
+ * API Module - Call RealtimeX public APIs
135
+ */
136
+
137
+ declare class ApiModule {
138
+ private realtimexUrl;
139
+ constructor(realtimexUrl: string);
140
+ getAgents(): Promise<Agent[]>;
141
+ getWorkspaces(): Promise<Workspace[]>;
142
+ getThreads(workspaceSlug: string): Promise<Thread[]>;
143
+ getTask(taskUuid: string): Promise<Task>;
144
+ }
145
+
146
+ /**
147
+ * RealtimeX Local App SDK
148
+ *
149
+ * SDK for building Local Apps that integrate with RealtimeX
150
+ * All operations go through RealtimeX Main App proxy
151
+ */
152
+
153
+ declare class RealtimeXSDK {
154
+ activities: ActivitiesModule;
155
+ webhook: WebhookModule;
156
+ api: ApiModule;
157
+ readonly appId: string;
158
+ readonly appName: string | undefined;
159
+ private static DEFAULT_REALTIMEX_URL;
160
+ constructor(config?: SDKConfig);
161
+ /**
162
+ * Get environment variable (works in Node.js and browser)
163
+ */
164
+ private getEnvVar;
165
+ }
166
+
167
+ export { ActivitiesModule, type Activity, type Agent, ApiModule, RealtimeXSDK, type SDKConfig, type Task, type TaskRun, type Thread, type TriggerAgentPayload, type TriggerAgentResponse, WebhookModule, type Workspace };
@@ -0,0 +1,167 @@
1
+ /**
2
+ * RealtimeX Local App SDK - Types
3
+ */
4
+ interface SDKConfig {
5
+ realtimex?: {
6
+ url?: string;
7
+ appId?: string;
8
+ appName?: string;
9
+ };
10
+ }
11
+ interface Activity {
12
+ id: string;
13
+ raw_data: Record<string, unknown>;
14
+ old_data?: Record<string, unknown>;
15
+ status: 'pending' | 'claimed' | 'completed' | 'failed';
16
+ locked_by?: string;
17
+ locked_at?: string;
18
+ completed_at?: string;
19
+ error_message?: string;
20
+ result?: Record<string, unknown>;
21
+ created_at: string;
22
+ }
23
+ interface TriggerAgentPayload {
24
+ raw_data: Record<string, unknown>;
25
+ auto_run?: boolean;
26
+ agent_name?: string;
27
+ workspace_slug?: string;
28
+ thread_slug?: string;
29
+ prompt?: string;
30
+ }
31
+ interface TriggerAgentResponse {
32
+ success: boolean;
33
+ task_uuid?: string;
34
+ calendar_event_uuid?: string;
35
+ auto_run?: boolean;
36
+ message?: string;
37
+ error?: string;
38
+ }
39
+ interface Agent {
40
+ slug: string;
41
+ name: string;
42
+ description?: string;
43
+ hub_id?: string;
44
+ }
45
+ interface Workspace {
46
+ id: number;
47
+ slug: string;
48
+ name: string;
49
+ type: string;
50
+ created_at: string;
51
+ }
52
+ interface Thread {
53
+ id: number;
54
+ slug: string;
55
+ name: string;
56
+ created_at: string;
57
+ }
58
+ interface TaskRun {
59
+ id: number;
60
+ agent_name: string;
61
+ workspace_slug: string;
62
+ thread_slug?: string;
63
+ status: string;
64
+ started_at?: string;
65
+ completed_at?: string;
66
+ error?: string;
67
+ }
68
+ interface Task {
69
+ uuid: string;
70
+ title: string;
71
+ status: string;
72
+ action_type: string;
73
+ source_app: string;
74
+ error?: string;
75
+ created_at: string;
76
+ updated_at: string;
77
+ runs: TaskRun[];
78
+ }
79
+
80
+ /**
81
+ * Activities Module - HTTP Proxy to RealtimeX Main App
82
+ * No direct Supabase access - all operations go through Main App
83
+ */
84
+
85
+ declare class ActivitiesModule {
86
+ private baseUrl;
87
+ private appId;
88
+ constructor(realtimexUrl: string, appId: string);
89
+ private request;
90
+ /**
91
+ * Insert a new activity
92
+ */
93
+ insert(rawData: Record<string, unknown>): Promise<Activity>;
94
+ /**
95
+ * Update an existing activity
96
+ */
97
+ update(id: string, updates: Partial<Activity>): Promise<Activity>;
98
+ /**
99
+ * Delete an activity
100
+ */
101
+ delete(id: string): Promise<void>;
102
+ /**
103
+ * Get a single activity by ID
104
+ */
105
+ get(id: string): Promise<Activity | null>;
106
+ /**
107
+ * List activities with optional filters
108
+ */
109
+ list(options?: {
110
+ status?: string;
111
+ limit?: number;
112
+ offset?: number;
113
+ }): Promise<Activity[]>;
114
+ }
115
+
116
+ /**
117
+ * Webhook Module - Call RealtimeX webhook
118
+ */
119
+
120
+ declare class WebhookModule {
121
+ private realtimexUrl;
122
+ private appName?;
123
+ private appId?;
124
+ constructor(realtimexUrl: string, appName?: string, appId?: string);
125
+ triggerAgent(payload: TriggerAgentPayload): Promise<TriggerAgentResponse>;
126
+ ping(): Promise<{
127
+ success: boolean;
128
+ app_name: string;
129
+ message: string;
130
+ }>;
131
+ }
132
+
133
+ /**
134
+ * API Module - Call RealtimeX public APIs
135
+ */
136
+
137
+ declare class ApiModule {
138
+ private realtimexUrl;
139
+ constructor(realtimexUrl: string);
140
+ getAgents(): Promise<Agent[]>;
141
+ getWorkspaces(): Promise<Workspace[]>;
142
+ getThreads(workspaceSlug: string): Promise<Thread[]>;
143
+ getTask(taskUuid: string): Promise<Task>;
144
+ }
145
+
146
+ /**
147
+ * RealtimeX Local App SDK
148
+ *
149
+ * SDK for building Local Apps that integrate with RealtimeX
150
+ * All operations go through RealtimeX Main App proxy
151
+ */
152
+
153
+ declare class RealtimeXSDK {
154
+ activities: ActivitiesModule;
155
+ webhook: WebhookModule;
156
+ api: ApiModule;
157
+ readonly appId: string;
158
+ readonly appName: string | undefined;
159
+ private static DEFAULT_REALTIMEX_URL;
160
+ constructor(config?: SDKConfig);
161
+ /**
162
+ * Get environment variable (works in Node.js and browser)
163
+ */
164
+ private getEnvVar;
165
+ }
166
+
167
+ export { ActivitiesModule, type Activity, type Agent, ApiModule, RealtimeXSDK, type SDKConfig, type Task, type TaskRun, type Thread, type TriggerAgentPayload, type TriggerAgentResponse, WebhookModule, type Workspace };
package/dist/index.js ADDED
@@ -0,0 +1,223 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ActivitiesModule: () => ActivitiesModule,
24
+ ApiModule: () => ApiModule,
25
+ RealtimeXSDK: () => RealtimeXSDK,
26
+ WebhookModule: () => WebhookModule
27
+ });
28
+ module.exports = __toCommonJS(index_exports);
29
+
30
+ // src/modules/activities.ts
31
+ var ActivitiesModule = class {
32
+ constructor(realtimexUrl, appId) {
33
+ this.baseUrl = realtimexUrl.replace(/\/$/, "");
34
+ this.appId = appId;
35
+ }
36
+ async request(path, options = {}) {
37
+ const url = `${this.baseUrl}${path}`;
38
+ const headers = {
39
+ "Content-Type": "application/json"
40
+ };
41
+ if (this.appId) {
42
+ headers["X-App-Id"] = this.appId;
43
+ }
44
+ const response = await fetch(url, {
45
+ ...options,
46
+ headers: {
47
+ ...headers,
48
+ ...options.headers
49
+ }
50
+ });
51
+ const data = await response.json();
52
+ if (!response.ok) {
53
+ throw new Error(data.error || `Request failed: ${response.status}`);
54
+ }
55
+ return data;
56
+ }
57
+ /**
58
+ * Insert a new activity
59
+ */
60
+ async insert(rawData) {
61
+ const result = await this.request("/activities", {
62
+ method: "POST",
63
+ body: JSON.stringify({ raw_data: rawData })
64
+ });
65
+ return result.data;
66
+ }
67
+ /**
68
+ * Update an existing activity
69
+ */
70
+ async update(id, updates) {
71
+ const result = await this.request(`/activities/${id}`, {
72
+ method: "PATCH",
73
+ body: JSON.stringify(updates)
74
+ });
75
+ return result.data;
76
+ }
77
+ /**
78
+ * Delete an activity
79
+ */
80
+ async delete(id) {
81
+ await this.request(`/activities/${id}`, {
82
+ method: "DELETE"
83
+ });
84
+ }
85
+ /**
86
+ * Get a single activity by ID
87
+ */
88
+ async get(id) {
89
+ try {
90
+ const result = await this.request(`/activities/${id}`);
91
+ return result.data;
92
+ } catch (error) {
93
+ if (error.message?.includes("not found")) return null;
94
+ throw error;
95
+ }
96
+ }
97
+ /**
98
+ * List activities with optional filters
99
+ */
100
+ async list(options) {
101
+ const params = new URLSearchParams();
102
+ if (options?.status) params.set("status", options.status);
103
+ if (options?.limit) params.set("limit", String(options.limit));
104
+ if (options?.offset) params.set("offset", String(options.offset));
105
+ const query = params.toString() ? `?${params}` : "";
106
+ const result = await this.request(`/activities${query}`);
107
+ return result.data;
108
+ }
109
+ };
110
+
111
+ // src/modules/webhook.ts
112
+ var WebhookModule = class {
113
+ constructor(realtimexUrl, appName, appId) {
114
+ this.realtimexUrl = realtimexUrl.replace(/\/$/, "");
115
+ this.appName = appName;
116
+ this.appId = appId;
117
+ }
118
+ async triggerAgent(payload) {
119
+ if (payload.auto_run && (!payload.agent_name || !payload.workspace_slug)) {
120
+ throw new Error("auto_run requires agent_name and workspace_slug");
121
+ }
122
+ const response = await fetch(`${this.realtimexUrl}/webhooks/realtimex`, {
123
+ method: "POST",
124
+ headers: { "Content-Type": "application/json" },
125
+ body: JSON.stringify({
126
+ app_name: this.appName,
127
+ app_id: this.appId,
128
+ event: "trigger-agent",
129
+ payload: {
130
+ raw_data: payload.raw_data,
131
+ auto_run: payload.auto_run ?? false,
132
+ agent_name: payload.agent_name,
133
+ workspace_slug: payload.workspace_slug,
134
+ thread_slug: payload.thread_slug,
135
+ prompt: payload.prompt ?? ""
136
+ }
137
+ })
138
+ });
139
+ const data = await response.json();
140
+ if (!response.ok) throw new Error(data.error || "Failed to trigger agent");
141
+ return data;
142
+ }
143
+ async ping() {
144
+ const response = await fetch(`${this.realtimexUrl}/webhooks/realtimex`, {
145
+ method: "POST",
146
+ headers: { "Content-Type": "application/json" },
147
+ body: JSON.stringify({
148
+ app_name: this.appName,
149
+ app_id: this.appId,
150
+ event: "ping"
151
+ })
152
+ });
153
+ const data = await response.json();
154
+ if (!response.ok) throw new Error(data.error || "Ping failed");
155
+ return data;
156
+ }
157
+ };
158
+
159
+ // src/modules/api.ts
160
+ var ApiModule = class {
161
+ constructor(realtimexUrl) {
162
+ this.realtimexUrl = realtimexUrl.replace(/\/$/, "");
163
+ }
164
+ async getAgents() {
165
+ const response = await fetch(`${this.realtimexUrl}/agents`);
166
+ const data = await response.json();
167
+ if (!response.ok) throw new Error(data.error || "Failed to get agents");
168
+ return data.agents;
169
+ }
170
+ async getWorkspaces() {
171
+ const response = await fetch(`${this.realtimexUrl}/workspaces`);
172
+ const data = await response.json();
173
+ if (!response.ok) throw new Error(data.error || "Failed to get workspaces");
174
+ return data.workspaces;
175
+ }
176
+ async getThreads(workspaceSlug) {
177
+ const response = await fetch(`${this.realtimexUrl}/workspaces/${encodeURIComponent(workspaceSlug)}/threads`);
178
+ const data = await response.json();
179
+ if (!response.ok) throw new Error(data.error || "Failed to get threads");
180
+ return data.threads;
181
+ }
182
+ async getTask(taskUuid) {
183
+ const response = await fetch(`${this.realtimexUrl}/task/${encodeURIComponent(taskUuid)}`);
184
+ const data = await response.json();
185
+ if (!response.ok) throw new Error(data.error || "Failed to get task");
186
+ return { ...data.task, runs: data.runs };
187
+ }
188
+ };
189
+
190
+ // src/index.ts
191
+ var _RealtimeXSDK = class _RealtimeXSDK {
192
+ constructor(config = {}) {
193
+ const envAppId = this.getEnvVar("RTX_APP_ID");
194
+ const envAppName = this.getEnvVar("RTX_APP_NAME");
195
+ this.appId = config.realtimex?.appId || envAppId || "";
196
+ this.appName = config.realtimex?.appName || envAppName;
197
+ const realtimexUrl = config.realtimex?.url || _RealtimeXSDK.DEFAULT_REALTIMEX_URL;
198
+ this.activities = new ActivitiesModule(realtimexUrl, this.appId);
199
+ this.webhook = new WebhookModule(realtimexUrl, this.appName, this.appId);
200
+ this.api = new ApiModule(realtimexUrl);
201
+ }
202
+ /**
203
+ * Get environment variable (works in Node.js and browser)
204
+ */
205
+ getEnvVar(name) {
206
+ if (typeof process !== "undefined" && process.env) {
207
+ return process.env[name];
208
+ }
209
+ if (typeof window !== "undefined") {
210
+ return window[name];
211
+ }
212
+ return void 0;
213
+ }
214
+ };
215
+ _RealtimeXSDK.DEFAULT_REALTIMEX_URL = "http://localhost:3001";
216
+ var RealtimeXSDK = _RealtimeXSDK;
217
+ // Annotate the CommonJS export names for ESM import in node:
218
+ 0 && (module.exports = {
219
+ ActivitiesModule,
220
+ ApiModule,
221
+ RealtimeXSDK,
222
+ WebhookModule
223
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,193 @@
1
+ // src/modules/activities.ts
2
+ var ActivitiesModule = class {
3
+ constructor(realtimexUrl, appId) {
4
+ this.baseUrl = realtimexUrl.replace(/\/$/, "");
5
+ this.appId = appId;
6
+ }
7
+ async request(path, options = {}) {
8
+ const url = `${this.baseUrl}${path}`;
9
+ const headers = {
10
+ "Content-Type": "application/json"
11
+ };
12
+ if (this.appId) {
13
+ headers["X-App-Id"] = this.appId;
14
+ }
15
+ const response = await fetch(url, {
16
+ ...options,
17
+ headers: {
18
+ ...headers,
19
+ ...options.headers
20
+ }
21
+ });
22
+ const data = await response.json();
23
+ if (!response.ok) {
24
+ throw new Error(data.error || `Request failed: ${response.status}`);
25
+ }
26
+ return data;
27
+ }
28
+ /**
29
+ * Insert a new activity
30
+ */
31
+ async insert(rawData) {
32
+ const result = await this.request("/activities", {
33
+ method: "POST",
34
+ body: JSON.stringify({ raw_data: rawData })
35
+ });
36
+ return result.data;
37
+ }
38
+ /**
39
+ * Update an existing activity
40
+ */
41
+ async update(id, updates) {
42
+ const result = await this.request(`/activities/${id}`, {
43
+ method: "PATCH",
44
+ body: JSON.stringify(updates)
45
+ });
46
+ return result.data;
47
+ }
48
+ /**
49
+ * Delete an activity
50
+ */
51
+ async delete(id) {
52
+ await this.request(`/activities/${id}`, {
53
+ method: "DELETE"
54
+ });
55
+ }
56
+ /**
57
+ * Get a single activity by ID
58
+ */
59
+ async get(id) {
60
+ try {
61
+ const result = await this.request(`/activities/${id}`);
62
+ return result.data;
63
+ } catch (error) {
64
+ if (error.message?.includes("not found")) return null;
65
+ throw error;
66
+ }
67
+ }
68
+ /**
69
+ * List activities with optional filters
70
+ */
71
+ async list(options) {
72
+ const params = new URLSearchParams();
73
+ if (options?.status) params.set("status", options.status);
74
+ if (options?.limit) params.set("limit", String(options.limit));
75
+ if (options?.offset) params.set("offset", String(options.offset));
76
+ const query = params.toString() ? `?${params}` : "";
77
+ const result = await this.request(`/activities${query}`);
78
+ return result.data;
79
+ }
80
+ };
81
+
82
+ // src/modules/webhook.ts
83
+ var WebhookModule = class {
84
+ constructor(realtimexUrl, appName, appId) {
85
+ this.realtimexUrl = realtimexUrl.replace(/\/$/, "");
86
+ this.appName = appName;
87
+ this.appId = appId;
88
+ }
89
+ async triggerAgent(payload) {
90
+ if (payload.auto_run && (!payload.agent_name || !payload.workspace_slug)) {
91
+ throw new Error("auto_run requires agent_name and workspace_slug");
92
+ }
93
+ const response = await fetch(`${this.realtimexUrl}/webhooks/realtimex`, {
94
+ method: "POST",
95
+ headers: { "Content-Type": "application/json" },
96
+ body: JSON.stringify({
97
+ app_name: this.appName,
98
+ app_id: this.appId,
99
+ event: "trigger-agent",
100
+ payload: {
101
+ raw_data: payload.raw_data,
102
+ auto_run: payload.auto_run ?? false,
103
+ agent_name: payload.agent_name,
104
+ workspace_slug: payload.workspace_slug,
105
+ thread_slug: payload.thread_slug,
106
+ prompt: payload.prompt ?? ""
107
+ }
108
+ })
109
+ });
110
+ const data = await response.json();
111
+ if (!response.ok) throw new Error(data.error || "Failed to trigger agent");
112
+ return data;
113
+ }
114
+ async ping() {
115
+ const response = await fetch(`${this.realtimexUrl}/webhooks/realtimex`, {
116
+ method: "POST",
117
+ headers: { "Content-Type": "application/json" },
118
+ body: JSON.stringify({
119
+ app_name: this.appName,
120
+ app_id: this.appId,
121
+ event: "ping"
122
+ })
123
+ });
124
+ const data = await response.json();
125
+ if (!response.ok) throw new Error(data.error || "Ping failed");
126
+ return data;
127
+ }
128
+ };
129
+
130
+ // src/modules/api.ts
131
+ var ApiModule = class {
132
+ constructor(realtimexUrl) {
133
+ this.realtimexUrl = realtimexUrl.replace(/\/$/, "");
134
+ }
135
+ async getAgents() {
136
+ const response = await fetch(`${this.realtimexUrl}/agents`);
137
+ const data = await response.json();
138
+ if (!response.ok) throw new Error(data.error || "Failed to get agents");
139
+ return data.agents;
140
+ }
141
+ async getWorkspaces() {
142
+ const response = await fetch(`${this.realtimexUrl}/workspaces`);
143
+ const data = await response.json();
144
+ if (!response.ok) throw new Error(data.error || "Failed to get workspaces");
145
+ return data.workspaces;
146
+ }
147
+ async getThreads(workspaceSlug) {
148
+ const response = await fetch(`${this.realtimexUrl}/workspaces/${encodeURIComponent(workspaceSlug)}/threads`);
149
+ const data = await response.json();
150
+ if (!response.ok) throw new Error(data.error || "Failed to get threads");
151
+ return data.threads;
152
+ }
153
+ async getTask(taskUuid) {
154
+ const response = await fetch(`${this.realtimexUrl}/task/${encodeURIComponent(taskUuid)}`);
155
+ const data = await response.json();
156
+ if (!response.ok) throw new Error(data.error || "Failed to get task");
157
+ return { ...data.task, runs: data.runs };
158
+ }
159
+ };
160
+
161
+ // src/index.ts
162
+ var _RealtimeXSDK = class _RealtimeXSDK {
163
+ constructor(config = {}) {
164
+ const envAppId = this.getEnvVar("RTX_APP_ID");
165
+ const envAppName = this.getEnvVar("RTX_APP_NAME");
166
+ this.appId = config.realtimex?.appId || envAppId || "";
167
+ this.appName = config.realtimex?.appName || envAppName;
168
+ const realtimexUrl = config.realtimex?.url || _RealtimeXSDK.DEFAULT_REALTIMEX_URL;
169
+ this.activities = new ActivitiesModule(realtimexUrl, this.appId);
170
+ this.webhook = new WebhookModule(realtimexUrl, this.appName, this.appId);
171
+ this.api = new ApiModule(realtimexUrl);
172
+ }
173
+ /**
174
+ * Get environment variable (works in Node.js and browser)
175
+ */
176
+ getEnvVar(name) {
177
+ if (typeof process !== "undefined" && process.env) {
178
+ return process.env[name];
179
+ }
180
+ if (typeof window !== "undefined") {
181
+ return window[name];
182
+ }
183
+ return void 0;
184
+ }
185
+ };
186
+ _RealtimeXSDK.DEFAULT_REALTIMEX_URL = "http://localhost:3001";
187
+ var RealtimeXSDK = _RealtimeXSDK;
188
+ export {
189
+ ActivitiesModule,
190
+ ApiModule,
191
+ RealtimeXSDK,
192
+ WebhookModule
193
+ };
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@realtimex/sdk",
3
+ "version": "1.0.4",
4
+ "description": "SDK for building Local Apps that integrate with RealtimeX",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.mjs",
11
+ "require": "./dist/index.js",
12
+ "types": "./dist/index.d.ts"
13
+ }
14
+ },
15
+ "scripts": {
16
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean",
17
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
18
+ "test": "vitest run",
19
+ "prepublishOnly": "npm run build"
20
+ },
21
+ "keywords": [
22
+ "realtimex",
23
+ "local-apps",
24
+ "sdk",
25
+ "supabase"
26
+ ],
27
+ "author": "RealtimeX Team",
28
+ "license": "MIT",
29
+ "devDependencies": {
30
+ "@types/node": "^20.10.0",
31
+ "rollup": "^4.55.1",
32
+ "tsup": "^8.0.0",
33
+ "typescript": "^5.3.0",
34
+ "vitest": "^1.0.0"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "README.md"
39
+ ],
40
+ "engines": {
41
+ "node": ">=18.0.0"
42
+ }
43
+ }