@realtimex/sdk 1.3.5-rc.2 → 1.3.7-rc.1

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/dist/index.d.mts CHANGED
@@ -41,6 +41,7 @@ interface TriggerAgentResponse {
41
41
  success: boolean;
42
42
  task_uuid?: string;
43
43
  task_id?: string;
44
+ capability_id?: string;
44
45
  event_id?: string;
45
46
  attempt_id?: string;
46
47
  event_type?: ContractEventType | string;
@@ -59,21 +60,72 @@ interface ContractCallbackMetadata {
59
60
  attempt_id_format?: string;
60
61
  idempotency?: string;
61
62
  }
63
+ interface ContractCapabilityTrigger$1 {
64
+ event: string;
65
+ route?: string;
66
+ payload_template?: Record<string, unknown>;
67
+ }
68
+ interface ContractCapability$1 {
69
+ capability_id: string;
70
+ name: string;
71
+ description?: string;
72
+ input_schema: Record<string, unknown>;
73
+ output_schema?: Record<string, unknown>;
74
+ permission?: string;
75
+ trigger?: ContractCapabilityTrigger$1;
76
+ tags?: string[];
77
+ examples?: string[];
78
+ risk_level?: 'low' | 'medium' | 'high' | null;
79
+ enabled?: boolean;
80
+ }
62
81
  interface LocalAppContractDefinition {
63
82
  id: string;
64
83
  version: string;
84
+ strictness?: 'compatible' | 'strict';
65
85
  events: Record<string, ContractEventType>;
66
86
  supported_events: ContractEventType[];
67
87
  supported_legacy_events: string[];
68
88
  aliases: Record<string, ContractEventType>;
69
89
  status_map: Record<string, string>;
70
90
  legacy_action_map: Record<ContractEventType, string>;
91
+ catalog_hash?: string;
92
+ capability_count?: number;
93
+ capabilities?: ContractCapability$1[];
71
94
  callback?: ContractCallbackMetadata;
72
95
  }
73
96
  interface LocalAppContractResponse {
74
97
  success: boolean;
75
98
  contract: LocalAppContractDefinition;
76
99
  }
100
+ interface LocalAppCapabilitiesResponse {
101
+ success: boolean;
102
+ contract_version: string;
103
+ strictness?: 'compatible' | 'strict';
104
+ catalog_hash?: string;
105
+ count: number;
106
+ capabilities: ContractCapability$1[];
107
+ }
108
+ interface LocalAppCapabilitySearchResponse extends LocalAppCapabilitiesResponse {
109
+ query: string;
110
+ }
111
+ interface LocalAppCapabilityDetailResponse {
112
+ success: boolean;
113
+ contract_version: string;
114
+ strictness?: 'compatible' | 'strict';
115
+ catalog_hash?: string;
116
+ capability: ContractCapability$1;
117
+ }
118
+ interface ContractInvokePayload {
119
+ capability_id: string;
120
+ args?: Record<string, unknown>;
121
+ auto_run?: boolean;
122
+ agent_name?: string;
123
+ workspace_slug?: string;
124
+ thread_slug?: string;
125
+ prompt?: string;
126
+ event_id?: string;
127
+ attempt_id?: string | number;
128
+ }
77
129
  interface Agent {
78
130
  slug: string;
79
131
  name: string;
@@ -1170,10 +1222,19 @@ declare class ContractModule {
1170
1222
  private readonly appId?;
1171
1223
  private readonly apiKey?;
1172
1224
  private cachedContract;
1225
+ private cachedCapabilities;
1226
+ private cachedCapabilityCatalogHash;
1173
1227
  constructor(realtimexUrl: string, appName?: string, appId?: string, apiKey?: string);
1174
1228
  private requestPermission;
1175
1229
  private request;
1176
1230
  getLocalAppV1(forceRefresh?: boolean): Promise<LocalAppContractDefinition>;
1231
+ listCapabilities(forceRefresh?: boolean): Promise<ContractCapability$1[]>;
1232
+ searchCapabilities(query: string): Promise<ContractCapability$1[]>;
1233
+ describeCapability(capabilityId: string): Promise<ContractCapability$1>;
1234
+ search(query: string): Promise<ContractCapability$1[]>;
1235
+ describe(capabilityId: string): Promise<ContractCapability$1>;
1236
+ invoke(payload: ContractInvokePayload): Promise<TriggerAgentResponse>;
1237
+ getCachedCatalogHash(): string | null;
1177
1238
  clearCache(): void;
1178
1239
  }
1179
1240
 
@@ -1383,6 +1444,88 @@ declare class ContractRuntime implements ContractRuntimeInterface {
1383
1444
  private toFailedResult;
1384
1445
  }
1385
1446
 
1447
+ /**
1448
+ * Database Module - Retrieve Supabase config from RealtimeX Main App
1449
+ *
1450
+ * Allows Local Apps to fetch their database configuration (URL, anonKey, mode)
1451
+ * without hardcoding them.
1452
+ */
1453
+ interface DatabaseConfig {
1454
+ url: string;
1455
+ anonKey: string;
1456
+ mode: 'compatible' | 'custom';
1457
+ tables: string[];
1458
+ max_concurrent_tasks: number;
1459
+ }
1460
+ declare class DatabaseModule {
1461
+ private baseUrl;
1462
+ private appId;
1463
+ private apiKey?;
1464
+ constructor(realtimexUrl: string, appId: string, apiKey?: string);
1465
+ private getHeaders;
1466
+ /**
1467
+ * Get the Supabase database configuration for this app.
1468
+ * Returns URL, anonKey, mode, and tables.
1469
+ *
1470
+ * @example
1471
+ * ```ts
1472
+ * const config = await sdk.database.getConfig();
1473
+ * const supabase = createClient(config.url, config.anonKey);
1474
+ * ```
1475
+ */
1476
+ getConfig(): Promise<DatabaseConfig>;
1477
+ }
1478
+
1479
+ /**
1480
+ * Auth Module - Authentication helpers for RealtimeX SDK
1481
+ *
1482
+ * Provides:
1483
+ * - syncSupabaseToken(): Push Supabase JWT to Main App for RLS-aware operations
1484
+ * - getAccessToken(): Retrieve the Keycloak access token from Main App (existing endpoint)
1485
+ */
1486
+ interface AuthTokenResponse {
1487
+ token: string;
1488
+ hasToken: boolean;
1489
+ syncedAt: string | null;
1490
+ source: string | null;
1491
+ }
1492
+ interface SyncTokenResponse {
1493
+ success: boolean;
1494
+ message: string;
1495
+ hasToken: boolean;
1496
+ syncedAt: string | null;
1497
+ source: string | null;
1498
+ }
1499
+ declare class AuthModule {
1500
+ private baseUrl;
1501
+ private appId;
1502
+ private apiKey?;
1503
+ constructor(realtimexUrl: string, appId: string, apiKey?: string);
1504
+ private getHeaders;
1505
+ /**
1506
+ * Push a Supabase access token to the Main App.
1507
+ * This enables Main App to use the token for:
1508
+ * - Realtime subscriptions (bypass RLS)
1509
+ * - CRUD operations on rtx_activities (bypass RLS)
1510
+ *
1511
+ * @param token - Supabase JWT from supabase.auth.signIn()
1512
+ *
1513
+ * @example
1514
+ * ```ts
1515
+ * const { data } = await supabase.auth.signInWithPassword({ email, password });
1516
+ * await sdk.auth.syncSupabaseToken(data.session.access_token);
1517
+ * ```
1518
+ */
1519
+ syncSupabaseToken(token: string): Promise<SyncTokenResponse>;
1520
+ /**
1521
+ * Retrieve the current Keycloak access token from Main App.
1522
+ * This is the existing Token Vending Machine endpoint.
1523
+ *
1524
+ * @returns The access token info, or null if no token is available.
1525
+ */
1526
+ getAccessToken(): Promise<AuthTokenResponse | null>;
1527
+ }
1528
+
1386
1529
  interface ContractHttpClientConfig {
1387
1530
  baseUrl: string;
1388
1531
  appId?: string;
@@ -1707,6 +1850,8 @@ declare class RealtimeXSDK {
1707
1850
  mcp: MCPModule;
1708
1851
  contract: ContractModule;
1709
1852
  contractRuntime: ContractRuntime;
1853
+ database: DatabaseModule;
1854
+ auth: AuthModule;
1710
1855
  readonly appId: string;
1711
1856
  readonly appName: string | undefined;
1712
1857
  readonly apiKey: string | undefined;
@@ -1741,4 +1886,4 @@ declare class RealtimeXSDK {
1741
1886
  getAppDataDir(): Promise<string>;
1742
1887
  }
1743
1888
 
1744
- export { type ACPAdapterContext, type ACPAdapterTelemetryEvent, type ACPAdapterTelemetrySink, ACPContractAdapter, type ACPContractAdapterOptions, type ACPContractRuntime, ACPEventMapper, type ACPExecutionReference, type ACPNotifier, ACPPermissionBridge, type ACPSessionToolUpdate, type ACPSessionUpdateParams, ACPTelemetry, type ACPTextContent, type ACPToolInvocation, type ACPToolKind, type ACPToolStatus, ActivitiesModule, type Activity, type Agent, type AgentChatOptions, type AgentChatResponse, AgentModule, type AgentSession, type AgentSessionInfo, type AgentSessionOptions, ApiModule, type AuthProvider, CONTRACT_ATTEMPT_PREFIX, CONTRACT_EVENT_ID_HEADER, CONTRACT_SIGNATURE_ALGORITHM, CONTRACT_SIGNATURE_HEADER, type CanonicalToolDefinition, type ChatContentBlock, type ChatCustomBlock, type ChatFileBlock, type ChatImageUrlBlock, type ChatMessage, type ChatMessageContent, type ChatOptions, type ChatResponse, type ChatTextBlock, ClaudeToolAdapter, type ClaudeToolCall, type ClaudeToolDefinition, type ClaudeToolResult, CodexToolAdapter, type CodexToolCall, type CodexToolDefinition, type CodexToolResult, ContractCache, type ContractCallbackMetadata, type ContractCallbackRules, type ContractCapability, type ContractCapabilityTrigger, ContractClient, type ContractClientOptions, type ContractDiscoveryResponse, ContractError, type ContractEventType, ContractHttpClient, type ContractHttpClientConfig, ContractModule, ContractRuntime, type ContractRuntimeInterface, type ContractRuntimeOptions, type ContractSignInput, type ContractStrictness, ContractValidationError, type EmbedOptions, type EmbedResponse, type ExecutionContext, type ExecutionResult, type GeminiFunctionDeclaration, GeminiToolAdapter, type GeminiToolCall, type GeminiToolResult, type GetToolsInput, type HostToolAdapter, type IngestExecutionEventInput, LLMModule, LLMPermissionError, LLMProviderError, LOCAL_APP_CONTRACT_VERSION, type LegacyLocalAppContractShape, type LifecycleEventType, type LocalAppContractDefinition, type LocalAppContractResponse, type LocalAppContractV1, MCPModule, type MCPServer, type MCPTool, type MCPToolResult, PermissionDeniedError, type PermissionOption, PermissionRequiredError, PortModule, type ProjectToolsInput, type Provider, type ProviderKind, type ProvidersResponse, RealtimeXSDK, RetryPolicy, type RetryPolicyOptions, type RuntimeExecutionEvent, RuntimeTransportError, type SDKConfig, type STTListenOptions, type STTModel, type STTModelsResponse, STTModule, type STTProvider, type STTProvidersResponse, type STTResponse, ScopeDeniedError, ScopeGuard, StaticAuthProvider, type StaticAuthProviderOptions, type StreamChunk, type StreamChunkEvent, type TTSChunk, type TTSChunkEvent, TTSModule, type TTSOptions, type TTSProvider, type TTSProviderConfig, type TTSProvidersResponse, type Task, TaskModule, type TaskRun, type Thread, type ToolCall, ToolNotFoundError, ToolProjector, ToolValidationError, type TriggerAgentPayload, type TriggerAgentResponse, type VectorDeleteOptions, type VectorDeleteResponse, type VectorQueryOptions, type VectorQueryResponse, type VectorQueryResult, type VectorRecord, VectorStore, type VectorUpsertOptions, type VectorUpsertResponse, WebhookModule, type Workspace, buildContractIdempotencyKey, buildContractSignatureMessage, canonicalEventToLegacyAction, createContractEventId, hashContractPayload, normalizeAttemptId, normalizeContractEvent, normalizeLocalAppContractV1, normalizeSchema, parseAttemptRunId, signContractEvent, toStableToolName };
1889
+ export { type ACPAdapterContext, type ACPAdapterTelemetryEvent, type ACPAdapterTelemetrySink, ACPContractAdapter, type ACPContractAdapterOptions, type ACPContractRuntime, ACPEventMapper, type ACPExecutionReference, type ACPNotifier, ACPPermissionBridge, type ACPSessionToolUpdate, type ACPSessionUpdateParams, ACPTelemetry, type ACPTextContent, type ACPToolInvocation, type ACPToolKind, type ACPToolStatus, ActivitiesModule, type Activity, type Agent, type AgentChatOptions, type AgentChatResponse, AgentModule, type AgentSession, type AgentSessionInfo, type AgentSessionOptions, ApiModule, AuthModule, type AuthProvider, type AuthTokenResponse, CONTRACT_ATTEMPT_PREFIX, CONTRACT_EVENT_ID_HEADER, CONTRACT_SIGNATURE_ALGORITHM, CONTRACT_SIGNATURE_HEADER, type CanonicalToolDefinition, type ChatContentBlock, type ChatCustomBlock, type ChatFileBlock, type ChatImageUrlBlock, type ChatMessage, type ChatMessageContent, type ChatOptions, type ChatResponse, type ChatTextBlock, ClaudeToolAdapter, type ClaudeToolCall, type ClaudeToolDefinition, type ClaudeToolResult, CodexToolAdapter, type CodexToolCall, type CodexToolDefinition, type CodexToolResult, ContractCache, type ContractCallbackMetadata, type ContractCallbackRules, type ContractCapability, type ContractCapabilityTrigger, ContractClient, type ContractClientOptions, type ContractDiscoveryResponse, ContractError, type ContractEventType, ContractHttpClient, type ContractHttpClientConfig, type ContractInvokePayload, ContractModule, ContractRuntime, type ContractRuntimeInterface, type ContractRuntimeOptions, type ContractSignInput, type ContractStrictness, ContractValidationError, type DatabaseConfig, DatabaseModule, type EmbedOptions, type EmbedResponse, type ExecutionContext, type ExecutionResult, type GeminiFunctionDeclaration, GeminiToolAdapter, type GeminiToolCall, type GeminiToolResult, type GetToolsInput, type HostToolAdapter, type IngestExecutionEventInput, LLMModule, LLMPermissionError, LLMProviderError, LOCAL_APP_CONTRACT_VERSION, type LegacyLocalAppContractShape, type LifecycleEventType, type LocalAppCapabilitiesResponse, type LocalAppCapabilityDetailResponse, type LocalAppCapabilitySearchResponse, type LocalAppContractDefinition, type LocalAppContractResponse, type LocalAppContractV1, MCPModule, type MCPServer, type MCPTool, type MCPToolResult, PermissionDeniedError, type PermissionOption, PermissionRequiredError, PortModule, type ProjectToolsInput, type Provider, type ProviderKind, type ProvidersResponse, RealtimeXSDK, RetryPolicy, type RetryPolicyOptions, type RuntimeExecutionEvent, RuntimeTransportError, type SDKConfig, type STTListenOptions, type STTModel, type STTModelsResponse, STTModule, type STTProvider, type STTProvidersResponse, type STTResponse, ScopeDeniedError, ScopeGuard, StaticAuthProvider, type StaticAuthProviderOptions, type StreamChunk, type StreamChunkEvent, type SyncTokenResponse, type TTSChunk, type TTSChunkEvent, TTSModule, type TTSOptions, type TTSProvider, type TTSProviderConfig, type TTSProvidersResponse, type Task, TaskModule, type TaskRun, type Thread, type ToolCall, ToolNotFoundError, ToolProjector, ToolValidationError, type TriggerAgentPayload, type TriggerAgentResponse, type VectorDeleteOptions, type VectorDeleteResponse, type VectorQueryOptions, type VectorQueryResponse, type VectorQueryResult, type VectorRecord, VectorStore, type VectorUpsertOptions, type VectorUpsertResponse, WebhookModule, type Workspace, buildContractIdempotencyKey, buildContractSignatureMessage, canonicalEventToLegacyAction, createContractEventId, hashContractPayload, normalizeAttemptId, normalizeContractEvent, normalizeLocalAppContractV1, normalizeSchema, parseAttemptRunId, signContractEvent, toStableToolName };
package/dist/index.d.ts CHANGED
@@ -41,6 +41,7 @@ interface TriggerAgentResponse {
41
41
  success: boolean;
42
42
  task_uuid?: string;
43
43
  task_id?: string;
44
+ capability_id?: string;
44
45
  event_id?: string;
45
46
  attempt_id?: string;
46
47
  event_type?: ContractEventType | string;
@@ -59,21 +60,72 @@ interface ContractCallbackMetadata {
59
60
  attempt_id_format?: string;
60
61
  idempotency?: string;
61
62
  }
63
+ interface ContractCapabilityTrigger$1 {
64
+ event: string;
65
+ route?: string;
66
+ payload_template?: Record<string, unknown>;
67
+ }
68
+ interface ContractCapability$1 {
69
+ capability_id: string;
70
+ name: string;
71
+ description?: string;
72
+ input_schema: Record<string, unknown>;
73
+ output_schema?: Record<string, unknown>;
74
+ permission?: string;
75
+ trigger?: ContractCapabilityTrigger$1;
76
+ tags?: string[];
77
+ examples?: string[];
78
+ risk_level?: 'low' | 'medium' | 'high' | null;
79
+ enabled?: boolean;
80
+ }
62
81
  interface LocalAppContractDefinition {
63
82
  id: string;
64
83
  version: string;
84
+ strictness?: 'compatible' | 'strict';
65
85
  events: Record<string, ContractEventType>;
66
86
  supported_events: ContractEventType[];
67
87
  supported_legacy_events: string[];
68
88
  aliases: Record<string, ContractEventType>;
69
89
  status_map: Record<string, string>;
70
90
  legacy_action_map: Record<ContractEventType, string>;
91
+ catalog_hash?: string;
92
+ capability_count?: number;
93
+ capabilities?: ContractCapability$1[];
71
94
  callback?: ContractCallbackMetadata;
72
95
  }
73
96
  interface LocalAppContractResponse {
74
97
  success: boolean;
75
98
  contract: LocalAppContractDefinition;
76
99
  }
100
+ interface LocalAppCapabilitiesResponse {
101
+ success: boolean;
102
+ contract_version: string;
103
+ strictness?: 'compatible' | 'strict';
104
+ catalog_hash?: string;
105
+ count: number;
106
+ capabilities: ContractCapability$1[];
107
+ }
108
+ interface LocalAppCapabilitySearchResponse extends LocalAppCapabilitiesResponse {
109
+ query: string;
110
+ }
111
+ interface LocalAppCapabilityDetailResponse {
112
+ success: boolean;
113
+ contract_version: string;
114
+ strictness?: 'compatible' | 'strict';
115
+ catalog_hash?: string;
116
+ capability: ContractCapability$1;
117
+ }
118
+ interface ContractInvokePayload {
119
+ capability_id: string;
120
+ args?: Record<string, unknown>;
121
+ auto_run?: boolean;
122
+ agent_name?: string;
123
+ workspace_slug?: string;
124
+ thread_slug?: string;
125
+ prompt?: string;
126
+ event_id?: string;
127
+ attempt_id?: string | number;
128
+ }
77
129
  interface Agent {
78
130
  slug: string;
79
131
  name: string;
@@ -1170,10 +1222,19 @@ declare class ContractModule {
1170
1222
  private readonly appId?;
1171
1223
  private readonly apiKey?;
1172
1224
  private cachedContract;
1225
+ private cachedCapabilities;
1226
+ private cachedCapabilityCatalogHash;
1173
1227
  constructor(realtimexUrl: string, appName?: string, appId?: string, apiKey?: string);
1174
1228
  private requestPermission;
1175
1229
  private request;
1176
1230
  getLocalAppV1(forceRefresh?: boolean): Promise<LocalAppContractDefinition>;
1231
+ listCapabilities(forceRefresh?: boolean): Promise<ContractCapability$1[]>;
1232
+ searchCapabilities(query: string): Promise<ContractCapability$1[]>;
1233
+ describeCapability(capabilityId: string): Promise<ContractCapability$1>;
1234
+ search(query: string): Promise<ContractCapability$1[]>;
1235
+ describe(capabilityId: string): Promise<ContractCapability$1>;
1236
+ invoke(payload: ContractInvokePayload): Promise<TriggerAgentResponse>;
1237
+ getCachedCatalogHash(): string | null;
1177
1238
  clearCache(): void;
1178
1239
  }
1179
1240
 
@@ -1383,6 +1444,88 @@ declare class ContractRuntime implements ContractRuntimeInterface {
1383
1444
  private toFailedResult;
1384
1445
  }
1385
1446
 
1447
+ /**
1448
+ * Database Module - Retrieve Supabase config from RealtimeX Main App
1449
+ *
1450
+ * Allows Local Apps to fetch their database configuration (URL, anonKey, mode)
1451
+ * without hardcoding them.
1452
+ */
1453
+ interface DatabaseConfig {
1454
+ url: string;
1455
+ anonKey: string;
1456
+ mode: 'compatible' | 'custom';
1457
+ tables: string[];
1458
+ max_concurrent_tasks: number;
1459
+ }
1460
+ declare class DatabaseModule {
1461
+ private baseUrl;
1462
+ private appId;
1463
+ private apiKey?;
1464
+ constructor(realtimexUrl: string, appId: string, apiKey?: string);
1465
+ private getHeaders;
1466
+ /**
1467
+ * Get the Supabase database configuration for this app.
1468
+ * Returns URL, anonKey, mode, and tables.
1469
+ *
1470
+ * @example
1471
+ * ```ts
1472
+ * const config = await sdk.database.getConfig();
1473
+ * const supabase = createClient(config.url, config.anonKey);
1474
+ * ```
1475
+ */
1476
+ getConfig(): Promise<DatabaseConfig>;
1477
+ }
1478
+
1479
+ /**
1480
+ * Auth Module - Authentication helpers for RealtimeX SDK
1481
+ *
1482
+ * Provides:
1483
+ * - syncSupabaseToken(): Push Supabase JWT to Main App for RLS-aware operations
1484
+ * - getAccessToken(): Retrieve the Keycloak access token from Main App (existing endpoint)
1485
+ */
1486
+ interface AuthTokenResponse {
1487
+ token: string;
1488
+ hasToken: boolean;
1489
+ syncedAt: string | null;
1490
+ source: string | null;
1491
+ }
1492
+ interface SyncTokenResponse {
1493
+ success: boolean;
1494
+ message: string;
1495
+ hasToken: boolean;
1496
+ syncedAt: string | null;
1497
+ source: string | null;
1498
+ }
1499
+ declare class AuthModule {
1500
+ private baseUrl;
1501
+ private appId;
1502
+ private apiKey?;
1503
+ constructor(realtimexUrl: string, appId: string, apiKey?: string);
1504
+ private getHeaders;
1505
+ /**
1506
+ * Push a Supabase access token to the Main App.
1507
+ * This enables Main App to use the token for:
1508
+ * - Realtime subscriptions (bypass RLS)
1509
+ * - CRUD operations on rtx_activities (bypass RLS)
1510
+ *
1511
+ * @param token - Supabase JWT from supabase.auth.signIn()
1512
+ *
1513
+ * @example
1514
+ * ```ts
1515
+ * const { data } = await supabase.auth.signInWithPassword({ email, password });
1516
+ * await sdk.auth.syncSupabaseToken(data.session.access_token);
1517
+ * ```
1518
+ */
1519
+ syncSupabaseToken(token: string): Promise<SyncTokenResponse>;
1520
+ /**
1521
+ * Retrieve the current Keycloak access token from Main App.
1522
+ * This is the existing Token Vending Machine endpoint.
1523
+ *
1524
+ * @returns The access token info, or null if no token is available.
1525
+ */
1526
+ getAccessToken(): Promise<AuthTokenResponse | null>;
1527
+ }
1528
+
1386
1529
  interface ContractHttpClientConfig {
1387
1530
  baseUrl: string;
1388
1531
  appId?: string;
@@ -1707,6 +1850,8 @@ declare class RealtimeXSDK {
1707
1850
  mcp: MCPModule;
1708
1851
  contract: ContractModule;
1709
1852
  contractRuntime: ContractRuntime;
1853
+ database: DatabaseModule;
1854
+ auth: AuthModule;
1710
1855
  readonly appId: string;
1711
1856
  readonly appName: string | undefined;
1712
1857
  readonly apiKey: string | undefined;
@@ -1741,4 +1886,4 @@ declare class RealtimeXSDK {
1741
1886
  getAppDataDir(): Promise<string>;
1742
1887
  }
1743
1888
 
1744
- export { type ACPAdapterContext, type ACPAdapterTelemetryEvent, type ACPAdapterTelemetrySink, ACPContractAdapter, type ACPContractAdapterOptions, type ACPContractRuntime, ACPEventMapper, type ACPExecutionReference, type ACPNotifier, ACPPermissionBridge, type ACPSessionToolUpdate, type ACPSessionUpdateParams, ACPTelemetry, type ACPTextContent, type ACPToolInvocation, type ACPToolKind, type ACPToolStatus, ActivitiesModule, type Activity, type Agent, type AgentChatOptions, type AgentChatResponse, AgentModule, type AgentSession, type AgentSessionInfo, type AgentSessionOptions, ApiModule, type AuthProvider, CONTRACT_ATTEMPT_PREFIX, CONTRACT_EVENT_ID_HEADER, CONTRACT_SIGNATURE_ALGORITHM, CONTRACT_SIGNATURE_HEADER, type CanonicalToolDefinition, type ChatContentBlock, type ChatCustomBlock, type ChatFileBlock, type ChatImageUrlBlock, type ChatMessage, type ChatMessageContent, type ChatOptions, type ChatResponse, type ChatTextBlock, ClaudeToolAdapter, type ClaudeToolCall, type ClaudeToolDefinition, type ClaudeToolResult, CodexToolAdapter, type CodexToolCall, type CodexToolDefinition, type CodexToolResult, ContractCache, type ContractCallbackMetadata, type ContractCallbackRules, type ContractCapability, type ContractCapabilityTrigger, ContractClient, type ContractClientOptions, type ContractDiscoveryResponse, ContractError, type ContractEventType, ContractHttpClient, type ContractHttpClientConfig, ContractModule, ContractRuntime, type ContractRuntimeInterface, type ContractRuntimeOptions, type ContractSignInput, type ContractStrictness, ContractValidationError, type EmbedOptions, type EmbedResponse, type ExecutionContext, type ExecutionResult, type GeminiFunctionDeclaration, GeminiToolAdapter, type GeminiToolCall, type GeminiToolResult, type GetToolsInput, type HostToolAdapter, type IngestExecutionEventInput, LLMModule, LLMPermissionError, LLMProviderError, LOCAL_APP_CONTRACT_VERSION, type LegacyLocalAppContractShape, type LifecycleEventType, type LocalAppContractDefinition, type LocalAppContractResponse, type LocalAppContractV1, MCPModule, type MCPServer, type MCPTool, type MCPToolResult, PermissionDeniedError, type PermissionOption, PermissionRequiredError, PortModule, type ProjectToolsInput, type Provider, type ProviderKind, type ProvidersResponse, RealtimeXSDK, RetryPolicy, type RetryPolicyOptions, type RuntimeExecutionEvent, RuntimeTransportError, type SDKConfig, type STTListenOptions, type STTModel, type STTModelsResponse, STTModule, type STTProvider, type STTProvidersResponse, type STTResponse, ScopeDeniedError, ScopeGuard, StaticAuthProvider, type StaticAuthProviderOptions, type StreamChunk, type StreamChunkEvent, type TTSChunk, type TTSChunkEvent, TTSModule, type TTSOptions, type TTSProvider, type TTSProviderConfig, type TTSProvidersResponse, type Task, TaskModule, type TaskRun, type Thread, type ToolCall, ToolNotFoundError, ToolProjector, ToolValidationError, type TriggerAgentPayload, type TriggerAgentResponse, type VectorDeleteOptions, type VectorDeleteResponse, type VectorQueryOptions, type VectorQueryResponse, type VectorQueryResult, type VectorRecord, VectorStore, type VectorUpsertOptions, type VectorUpsertResponse, WebhookModule, type Workspace, buildContractIdempotencyKey, buildContractSignatureMessage, canonicalEventToLegacyAction, createContractEventId, hashContractPayload, normalizeAttemptId, normalizeContractEvent, normalizeLocalAppContractV1, normalizeSchema, parseAttemptRunId, signContractEvent, toStableToolName };
1889
+ export { type ACPAdapterContext, type ACPAdapterTelemetryEvent, type ACPAdapterTelemetrySink, ACPContractAdapter, type ACPContractAdapterOptions, type ACPContractRuntime, ACPEventMapper, type ACPExecutionReference, type ACPNotifier, ACPPermissionBridge, type ACPSessionToolUpdate, type ACPSessionUpdateParams, ACPTelemetry, type ACPTextContent, type ACPToolInvocation, type ACPToolKind, type ACPToolStatus, ActivitiesModule, type Activity, type Agent, type AgentChatOptions, type AgentChatResponse, AgentModule, type AgentSession, type AgentSessionInfo, type AgentSessionOptions, ApiModule, AuthModule, type AuthProvider, type AuthTokenResponse, CONTRACT_ATTEMPT_PREFIX, CONTRACT_EVENT_ID_HEADER, CONTRACT_SIGNATURE_ALGORITHM, CONTRACT_SIGNATURE_HEADER, type CanonicalToolDefinition, type ChatContentBlock, type ChatCustomBlock, type ChatFileBlock, type ChatImageUrlBlock, type ChatMessage, type ChatMessageContent, type ChatOptions, type ChatResponse, type ChatTextBlock, ClaudeToolAdapter, type ClaudeToolCall, type ClaudeToolDefinition, type ClaudeToolResult, CodexToolAdapter, type CodexToolCall, type CodexToolDefinition, type CodexToolResult, ContractCache, type ContractCallbackMetadata, type ContractCallbackRules, type ContractCapability, type ContractCapabilityTrigger, ContractClient, type ContractClientOptions, type ContractDiscoveryResponse, ContractError, type ContractEventType, ContractHttpClient, type ContractHttpClientConfig, type ContractInvokePayload, ContractModule, ContractRuntime, type ContractRuntimeInterface, type ContractRuntimeOptions, type ContractSignInput, type ContractStrictness, ContractValidationError, type DatabaseConfig, DatabaseModule, type EmbedOptions, type EmbedResponse, type ExecutionContext, type ExecutionResult, type GeminiFunctionDeclaration, GeminiToolAdapter, type GeminiToolCall, type GeminiToolResult, type GetToolsInput, type HostToolAdapter, type IngestExecutionEventInput, LLMModule, LLMPermissionError, LLMProviderError, LOCAL_APP_CONTRACT_VERSION, type LegacyLocalAppContractShape, type LifecycleEventType, type LocalAppCapabilitiesResponse, type LocalAppCapabilityDetailResponse, type LocalAppCapabilitySearchResponse, type LocalAppContractDefinition, type LocalAppContractResponse, type LocalAppContractV1, MCPModule, type MCPServer, type MCPTool, type MCPToolResult, PermissionDeniedError, type PermissionOption, PermissionRequiredError, PortModule, type ProjectToolsInput, type Provider, type ProviderKind, type ProvidersResponse, RealtimeXSDK, RetryPolicy, type RetryPolicyOptions, type RuntimeExecutionEvent, RuntimeTransportError, type SDKConfig, type STTListenOptions, type STTModel, type STTModelsResponse, STTModule, type STTProvider, type STTProvidersResponse, type STTResponse, ScopeDeniedError, ScopeGuard, StaticAuthProvider, type StaticAuthProviderOptions, type StreamChunk, type StreamChunkEvent, type SyncTokenResponse, type TTSChunk, type TTSChunkEvent, TTSModule, type TTSOptions, type TTSProvider, type TTSProviderConfig, type TTSProvidersResponse, type Task, TaskModule, type TaskRun, type Thread, type ToolCall, ToolNotFoundError, ToolProjector, ToolValidationError, type TriggerAgentPayload, type TriggerAgentResponse, type VectorDeleteOptions, type VectorDeleteResponse, type VectorQueryOptions, type VectorQueryResponse, type VectorQueryResult, type VectorRecord, VectorStore, type VectorUpsertOptions, type VectorUpsertResponse, WebhookModule, type Workspace, buildContractIdempotencyKey, buildContractSignatureMessage, canonicalEventToLegacyAction, createContractEventId, hashContractPayload, normalizeAttemptId, normalizeContractEvent, normalizeLocalAppContractV1, normalizeSchema, parseAttemptRunId, signContractEvent, toStableToolName };
package/dist/index.js CHANGED
@@ -37,6 +37,7 @@ __export(index_exports, {
37
37
  ActivitiesModule: () => ActivitiesModule,
38
38
  AgentModule: () => AgentModule,
39
39
  ApiModule: () => ApiModule,
40
+ AuthModule: () => AuthModule,
40
41
  CONTRACT_ATTEMPT_PREFIX: () => CONTRACT_ATTEMPT_PREFIX,
41
42
  CONTRACT_EVENT_ID_HEADER: () => CONTRACT_EVENT_ID_HEADER,
42
43
  CONTRACT_SIGNATURE_ALGORITHM: () => CONTRACT_SIGNATURE_ALGORITHM,
@@ -50,6 +51,7 @@ __export(index_exports, {
50
51
  ContractModule: () => ContractModule,
51
52
  ContractRuntime: () => ContractRuntime,
52
53
  ContractValidationError: () => ContractValidationError,
54
+ DatabaseModule: () => DatabaseModule,
53
55
  GeminiToolAdapter: () => GeminiToolAdapter,
54
56
  LLMModule: () => LLMModule,
55
57
  LLMPermissionError: () => LLMPermissionError,
@@ -453,6 +455,8 @@ function buildContractIdempotencyKey({
453
455
  var ContractModule = class {
454
456
  constructor(realtimexUrl, appName, appId, apiKey) {
455
457
  this.cachedContract = null;
458
+ this.cachedCapabilities = null;
459
+ this.cachedCapabilityCatalogHash = null;
456
460
  this.realtimexUrl = realtimexUrl.replace(/\/$/, "");
457
461
  this.appName = appName;
458
462
  this.appId = appId;
@@ -475,16 +479,18 @@ var ContractModule = class {
475
479
  return false;
476
480
  }
477
481
  }
478
- async request(path) {
482
+ async request(path, options = {}) {
479
483
  const url = `${this.realtimexUrl}${path}`;
480
484
  const headers = {
481
- "Content-Type": "application/json"
485
+ "Content-Type": "application/json",
486
+ ...options.headers
482
487
  };
483
488
  if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
484
489
  if (this.appId) headers["x-app-id"] = this.appId;
485
490
  const response = await fetch(url, {
486
- method: "GET",
487
- headers
491
+ method: options.method || "GET",
492
+ headers,
493
+ body: options.body
488
494
  });
489
495
  const data = await response.json();
490
496
  if (response.status === 403) {
@@ -493,7 +499,7 @@ var ContractModule = class {
493
499
  const message = data.message;
494
500
  if (errorCode === "PERMISSION_REQUIRED" && permission) {
495
501
  const granted = await this.requestPermission(permission);
496
- if (granted) return this.request(path);
502
+ if (granted) return this.request(path, options);
497
503
  throw new PermissionDeniedError(permission, message);
498
504
  }
499
505
  if (errorCode === "PERMISSION_DENIED") {
@@ -509,10 +515,89 @@ var ContractModule = class {
509
515
  if (!forceRefresh && this.cachedContract) return this.cachedContract;
510
516
  const data = await this.request("/contracts/local-app/v1");
511
517
  this.cachedContract = data.contract;
518
+ if (Array.isArray(data.contract?.capabilities)) {
519
+ this.cachedCapabilities = data.contract.capabilities;
520
+ this.cachedCapabilityCatalogHash = data.contract.catalog_hash || null;
521
+ }
512
522
  return data.contract;
513
523
  }
524
+ async listCapabilities(forceRefresh = false) {
525
+ if (!forceRefresh && this.cachedCapabilities) return this.cachedCapabilities;
526
+ const data = await this.request(
527
+ "/contracts/local-app/v1/capabilities"
528
+ );
529
+ this.cachedCapabilities = Array.isArray(data.capabilities) ? data.capabilities : [];
530
+ this.cachedCapabilityCatalogHash = data.catalog_hash || null;
531
+ return this.cachedCapabilities;
532
+ }
533
+ async searchCapabilities(query) {
534
+ const normalizedQuery = String(query || "").trim();
535
+ if (!normalizedQuery) {
536
+ throw new Error("searchCapabilities requires a non-empty query");
537
+ }
538
+ const encodedQuery = encodeURIComponent(normalizedQuery);
539
+ const data = await this.request(
540
+ `/contracts/local-app/v1/capabilities/search?q=${encodedQuery}`
541
+ );
542
+ return Array.isArray(data.capabilities) ? data.capabilities : [];
543
+ }
544
+ async describeCapability(capabilityId) {
545
+ const normalizedCapabilityId = String(capabilityId || "").trim();
546
+ if (!normalizedCapabilityId) {
547
+ throw new Error("describeCapability requires a non-empty capability id");
548
+ }
549
+ const encodedCapabilityId = encodeURIComponent(normalizedCapabilityId);
550
+ const data = await this.request(
551
+ `/contracts/local-app/v1/capabilities/${encodedCapabilityId}`
552
+ );
553
+ return data.capability;
554
+ }
555
+ // Alias for agentic contract flow naming.
556
+ async search(query) {
557
+ return this.searchCapabilities(query);
558
+ }
559
+ // Alias for agentic contract flow naming.
560
+ async describe(capabilityId) {
561
+ return this.describeCapability(capabilityId);
562
+ }
563
+ async invoke(payload) {
564
+ const capabilityId = String(payload?.capability_id || "").trim();
565
+ if (!capabilityId) {
566
+ throw new Error("invoke requires payload.capability_id");
567
+ }
568
+ if (payload.auto_run && (!payload.agent_name || !payload.workspace_slug)) {
569
+ throw new Error("auto_run requires agent_name and workspace_slug");
570
+ }
571
+ const args = payload.args && typeof payload.args === "object" && !Array.isArray(payload.args) ? { ...payload.args } : {};
572
+ if (!args.capability) {
573
+ args.capability = capabilityId;
574
+ }
575
+ return this.request("/webhooks/realtimex", {
576
+ method: "POST",
577
+ body: JSON.stringify({
578
+ app_name: this.appName,
579
+ app_id: this.appId,
580
+ event: "task.trigger",
581
+ event_id: payload.event_id || createContractEventId(),
582
+ attempt_id: normalizeAttemptId(payload.attempt_id),
583
+ payload: {
584
+ raw_data: args,
585
+ auto_run: payload.auto_run ?? false,
586
+ agent_name: payload.agent_name,
587
+ workspace_slug: payload.workspace_slug,
588
+ thread_slug: payload.thread_slug,
589
+ prompt: payload.prompt ?? ""
590
+ }
591
+ })
592
+ });
593
+ }
594
+ getCachedCatalogHash() {
595
+ return this.cachedCapabilityCatalogHash;
596
+ }
514
597
  clearCache() {
515
598
  this.cachedContract = null;
599
+ this.cachedCapabilities = null;
600
+ this.cachedCapabilityCatalogHash = null;
516
601
  }
517
602
  };
518
603
 
@@ -2495,6 +2580,7 @@ var ContractRuntime = class {
2495
2580
  tool_call_id: call.tool_call_id,
2496
2581
  args: call.args,
2497
2582
  context: {
2583
+ app_id: context.appId,
2498
2584
  user_id: context.userId,
2499
2585
  workspace_id: context.workspaceId || null,
2500
2586
  request_id: context.requestId || null,
@@ -2507,7 +2593,9 @@ var ContractRuntime = class {
2507
2593
  }
2508
2594
  return {
2509
2595
  app_name: this.appName,
2510
- app_id: this.appId || context.appId,
2596
+ // In API-key dev mode, app_id should be omitted unless explicitly configured
2597
+ // on the runtime. Passing an unknown app_id causes webhook trigger rejection.
2598
+ app_id: this.appId || void 0,
2511
2599
  event: tool.trigger.event,
2512
2600
  event_id: eventId,
2513
2601
  payload
@@ -2621,6 +2709,118 @@ var ContractRuntime = class {
2621
2709
  }
2622
2710
  };
2623
2711
 
2712
+ // src/modules/database.ts
2713
+ var DatabaseModule = class {
2714
+ constructor(realtimexUrl, appId, apiKey) {
2715
+ this.baseUrl = realtimexUrl.replace(/\/$/, "");
2716
+ this.appId = appId;
2717
+ this.apiKey = apiKey;
2718
+ }
2719
+ getHeaders() {
2720
+ const headers = {
2721
+ "Content-Type": "application/json"
2722
+ };
2723
+ if (this.apiKey) {
2724
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
2725
+ }
2726
+ if (this.appId) {
2727
+ headers["x-app-id"] = this.appId;
2728
+ }
2729
+ return headers;
2730
+ }
2731
+ /**
2732
+ * Get the Supabase database configuration for this app.
2733
+ * Returns URL, anonKey, mode, and tables.
2734
+ *
2735
+ * @example
2736
+ * ```ts
2737
+ * const config = await sdk.database.getConfig();
2738
+ * const supabase = createClient(config.url, config.anonKey);
2739
+ * ```
2740
+ */
2741
+ async getConfig() {
2742
+ const response = await fetch(`${this.baseUrl}/sdk/database/config`, {
2743
+ method: "GET",
2744
+ headers: this.getHeaders()
2745
+ });
2746
+ const data = await response.json();
2747
+ if (!response.ok) {
2748
+ throw new Error(data.error || "Failed to get database config");
2749
+ }
2750
+ return data.config;
2751
+ }
2752
+ };
2753
+
2754
+ // src/modules/auth.ts
2755
+ var AuthModule = class {
2756
+ constructor(realtimexUrl, appId, apiKey) {
2757
+ this.baseUrl = realtimexUrl.replace(/\/$/, "");
2758
+ this.appId = appId;
2759
+ this.apiKey = apiKey;
2760
+ }
2761
+ getHeaders() {
2762
+ const headers = {
2763
+ "Content-Type": "application/json"
2764
+ };
2765
+ if (this.apiKey) {
2766
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
2767
+ }
2768
+ if (this.appId) {
2769
+ headers["x-app-id"] = this.appId;
2770
+ }
2771
+ return headers;
2772
+ }
2773
+ /**
2774
+ * Push a Supabase access token to the Main App.
2775
+ * This enables Main App to use the token for:
2776
+ * - Realtime subscriptions (bypass RLS)
2777
+ * - CRUD operations on rtx_activities (bypass RLS)
2778
+ *
2779
+ * @param token - Supabase JWT from supabase.auth.signIn()
2780
+ *
2781
+ * @example
2782
+ * ```ts
2783
+ * const { data } = await supabase.auth.signInWithPassword({ email, password });
2784
+ * await sdk.auth.syncSupabaseToken(data.session.access_token);
2785
+ * ```
2786
+ */
2787
+ async syncSupabaseToken(token) {
2788
+ if (!token || typeof token !== "string") {
2789
+ throw new Error("Token must be a non-empty string");
2790
+ }
2791
+ const response = await fetch(`${this.baseUrl}/sdk/auth/sync-supabase-token`, {
2792
+ method: "POST",
2793
+ headers: this.getHeaders(),
2794
+ body: JSON.stringify({ token })
2795
+ });
2796
+ const data = await response.json();
2797
+ if (!response.ok) {
2798
+ throw new Error(data.error || "Failed to sync Supabase token");
2799
+ }
2800
+ return data;
2801
+ }
2802
+ /**
2803
+ * Retrieve the current Keycloak access token from Main App.
2804
+ * This is the existing Token Vending Machine endpoint.
2805
+ *
2806
+ * @returns The access token info, or null if no token is available.
2807
+ */
2808
+ async getAccessToken() {
2809
+ const response = await fetch(`${this.baseUrl}/sdk/auth/token`, {
2810
+ method: "GET",
2811
+ headers: this.getHeaders()
2812
+ });
2813
+ const data = await response.json();
2814
+ if (response.status === 404) {
2815
+ return null;
2816
+ }
2817
+ if (!response.ok) {
2818
+ throw new Error(data.error || "Failed to get access token");
2819
+ }
2820
+ return data;
2821
+ }
2822
+ };
2823
+
2624
2824
  // src/core/auth/AuthProvider.ts
2625
2825
  var StaticAuthProvider = class {
2626
2826
  constructor(options = {}) {
@@ -3315,6 +3515,8 @@ var _RealtimeXSDK = class _RealtimeXSDK {
3315
3515
  apiKey: this.apiKey,
3316
3516
  permissions: this.permissions
3317
3517
  });
3518
+ this.database = new DatabaseModule(this.realtimexUrl, this.appId, this.apiKey);
3519
+ this.auth = new AuthModule(this.realtimexUrl, this.appId, this.apiKey);
3318
3520
  if (this.permissions.length > 0 && this.appId && !this.apiKey) {
3319
3521
  this.register().catch((err) => {
3320
3522
  console.error("[RealtimeX SDK] Auto-registration failed:", err.message);
@@ -3423,6 +3625,7 @@ var RealtimeXSDK = _RealtimeXSDK;
3423
3625
  ActivitiesModule,
3424
3626
  AgentModule,
3425
3627
  ApiModule,
3628
+ AuthModule,
3426
3629
  CONTRACT_ATTEMPT_PREFIX,
3427
3630
  CONTRACT_EVENT_ID_HEADER,
3428
3631
  CONTRACT_SIGNATURE_ALGORITHM,
@@ -3436,6 +3639,7 @@ var RealtimeXSDK = _RealtimeXSDK;
3436
3639
  ContractModule,
3437
3640
  ContractRuntime,
3438
3641
  ContractValidationError,
3642
+ DatabaseModule,
3439
3643
  GeminiToolAdapter,
3440
3644
  LLMModule,
3441
3645
  LLMPermissionError,
package/dist/index.mjs CHANGED
@@ -363,6 +363,8 @@ function buildContractIdempotencyKey({
363
363
  var ContractModule = class {
364
364
  constructor(realtimexUrl, appName, appId, apiKey) {
365
365
  this.cachedContract = null;
366
+ this.cachedCapabilities = null;
367
+ this.cachedCapabilityCatalogHash = null;
366
368
  this.realtimexUrl = realtimexUrl.replace(/\/$/, "");
367
369
  this.appName = appName;
368
370
  this.appId = appId;
@@ -385,16 +387,18 @@ var ContractModule = class {
385
387
  return false;
386
388
  }
387
389
  }
388
- async request(path) {
390
+ async request(path, options = {}) {
389
391
  const url = `${this.realtimexUrl}${path}`;
390
392
  const headers = {
391
- "Content-Type": "application/json"
393
+ "Content-Type": "application/json",
394
+ ...options.headers
392
395
  };
393
396
  if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
394
397
  if (this.appId) headers["x-app-id"] = this.appId;
395
398
  const response = await fetch(url, {
396
- method: "GET",
397
- headers
399
+ method: options.method || "GET",
400
+ headers,
401
+ body: options.body
398
402
  });
399
403
  const data = await response.json();
400
404
  if (response.status === 403) {
@@ -403,7 +407,7 @@ var ContractModule = class {
403
407
  const message = data.message;
404
408
  if (errorCode === "PERMISSION_REQUIRED" && permission) {
405
409
  const granted = await this.requestPermission(permission);
406
- if (granted) return this.request(path);
410
+ if (granted) return this.request(path, options);
407
411
  throw new PermissionDeniedError(permission, message);
408
412
  }
409
413
  if (errorCode === "PERMISSION_DENIED") {
@@ -419,10 +423,89 @@ var ContractModule = class {
419
423
  if (!forceRefresh && this.cachedContract) return this.cachedContract;
420
424
  const data = await this.request("/contracts/local-app/v1");
421
425
  this.cachedContract = data.contract;
426
+ if (Array.isArray(data.contract?.capabilities)) {
427
+ this.cachedCapabilities = data.contract.capabilities;
428
+ this.cachedCapabilityCatalogHash = data.contract.catalog_hash || null;
429
+ }
422
430
  return data.contract;
423
431
  }
432
+ async listCapabilities(forceRefresh = false) {
433
+ if (!forceRefresh && this.cachedCapabilities) return this.cachedCapabilities;
434
+ const data = await this.request(
435
+ "/contracts/local-app/v1/capabilities"
436
+ );
437
+ this.cachedCapabilities = Array.isArray(data.capabilities) ? data.capabilities : [];
438
+ this.cachedCapabilityCatalogHash = data.catalog_hash || null;
439
+ return this.cachedCapabilities;
440
+ }
441
+ async searchCapabilities(query) {
442
+ const normalizedQuery = String(query || "").trim();
443
+ if (!normalizedQuery) {
444
+ throw new Error("searchCapabilities requires a non-empty query");
445
+ }
446
+ const encodedQuery = encodeURIComponent(normalizedQuery);
447
+ const data = await this.request(
448
+ `/contracts/local-app/v1/capabilities/search?q=${encodedQuery}`
449
+ );
450
+ return Array.isArray(data.capabilities) ? data.capabilities : [];
451
+ }
452
+ async describeCapability(capabilityId) {
453
+ const normalizedCapabilityId = String(capabilityId || "").trim();
454
+ if (!normalizedCapabilityId) {
455
+ throw new Error("describeCapability requires a non-empty capability id");
456
+ }
457
+ const encodedCapabilityId = encodeURIComponent(normalizedCapabilityId);
458
+ const data = await this.request(
459
+ `/contracts/local-app/v1/capabilities/${encodedCapabilityId}`
460
+ );
461
+ return data.capability;
462
+ }
463
+ // Alias for agentic contract flow naming.
464
+ async search(query) {
465
+ return this.searchCapabilities(query);
466
+ }
467
+ // Alias for agentic contract flow naming.
468
+ async describe(capabilityId) {
469
+ return this.describeCapability(capabilityId);
470
+ }
471
+ async invoke(payload) {
472
+ const capabilityId = String(payload?.capability_id || "").trim();
473
+ if (!capabilityId) {
474
+ throw new Error("invoke requires payload.capability_id");
475
+ }
476
+ if (payload.auto_run && (!payload.agent_name || !payload.workspace_slug)) {
477
+ throw new Error("auto_run requires agent_name and workspace_slug");
478
+ }
479
+ const args = payload.args && typeof payload.args === "object" && !Array.isArray(payload.args) ? { ...payload.args } : {};
480
+ if (!args.capability) {
481
+ args.capability = capabilityId;
482
+ }
483
+ return this.request("/webhooks/realtimex", {
484
+ method: "POST",
485
+ body: JSON.stringify({
486
+ app_name: this.appName,
487
+ app_id: this.appId,
488
+ event: "task.trigger",
489
+ event_id: payload.event_id || createContractEventId(),
490
+ attempt_id: normalizeAttemptId(payload.attempt_id),
491
+ payload: {
492
+ raw_data: args,
493
+ auto_run: payload.auto_run ?? false,
494
+ agent_name: payload.agent_name,
495
+ workspace_slug: payload.workspace_slug,
496
+ thread_slug: payload.thread_slug,
497
+ prompt: payload.prompt ?? ""
498
+ }
499
+ })
500
+ });
501
+ }
502
+ getCachedCatalogHash() {
503
+ return this.cachedCapabilityCatalogHash;
504
+ }
424
505
  clearCache() {
425
506
  this.cachedContract = null;
507
+ this.cachedCapabilities = null;
508
+ this.cachedCapabilityCatalogHash = null;
426
509
  }
427
510
  };
428
511
 
@@ -2405,6 +2488,7 @@ var ContractRuntime = class {
2405
2488
  tool_call_id: call.tool_call_id,
2406
2489
  args: call.args,
2407
2490
  context: {
2491
+ app_id: context.appId,
2408
2492
  user_id: context.userId,
2409
2493
  workspace_id: context.workspaceId || null,
2410
2494
  request_id: context.requestId || null,
@@ -2417,7 +2501,9 @@ var ContractRuntime = class {
2417
2501
  }
2418
2502
  return {
2419
2503
  app_name: this.appName,
2420
- app_id: this.appId || context.appId,
2504
+ // In API-key dev mode, app_id should be omitted unless explicitly configured
2505
+ // on the runtime. Passing an unknown app_id causes webhook trigger rejection.
2506
+ app_id: this.appId || void 0,
2421
2507
  event: tool.trigger.event,
2422
2508
  event_id: eventId,
2423
2509
  payload
@@ -2531,6 +2617,118 @@ var ContractRuntime = class {
2531
2617
  }
2532
2618
  };
2533
2619
 
2620
+ // src/modules/database.ts
2621
+ var DatabaseModule = class {
2622
+ constructor(realtimexUrl, appId, apiKey) {
2623
+ this.baseUrl = realtimexUrl.replace(/\/$/, "");
2624
+ this.appId = appId;
2625
+ this.apiKey = apiKey;
2626
+ }
2627
+ getHeaders() {
2628
+ const headers = {
2629
+ "Content-Type": "application/json"
2630
+ };
2631
+ if (this.apiKey) {
2632
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
2633
+ }
2634
+ if (this.appId) {
2635
+ headers["x-app-id"] = this.appId;
2636
+ }
2637
+ return headers;
2638
+ }
2639
+ /**
2640
+ * Get the Supabase database configuration for this app.
2641
+ * Returns URL, anonKey, mode, and tables.
2642
+ *
2643
+ * @example
2644
+ * ```ts
2645
+ * const config = await sdk.database.getConfig();
2646
+ * const supabase = createClient(config.url, config.anonKey);
2647
+ * ```
2648
+ */
2649
+ async getConfig() {
2650
+ const response = await fetch(`${this.baseUrl}/sdk/database/config`, {
2651
+ method: "GET",
2652
+ headers: this.getHeaders()
2653
+ });
2654
+ const data = await response.json();
2655
+ if (!response.ok) {
2656
+ throw new Error(data.error || "Failed to get database config");
2657
+ }
2658
+ return data.config;
2659
+ }
2660
+ };
2661
+
2662
+ // src/modules/auth.ts
2663
+ var AuthModule = class {
2664
+ constructor(realtimexUrl, appId, apiKey) {
2665
+ this.baseUrl = realtimexUrl.replace(/\/$/, "");
2666
+ this.appId = appId;
2667
+ this.apiKey = apiKey;
2668
+ }
2669
+ getHeaders() {
2670
+ const headers = {
2671
+ "Content-Type": "application/json"
2672
+ };
2673
+ if (this.apiKey) {
2674
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
2675
+ }
2676
+ if (this.appId) {
2677
+ headers["x-app-id"] = this.appId;
2678
+ }
2679
+ return headers;
2680
+ }
2681
+ /**
2682
+ * Push a Supabase access token to the Main App.
2683
+ * This enables Main App to use the token for:
2684
+ * - Realtime subscriptions (bypass RLS)
2685
+ * - CRUD operations on rtx_activities (bypass RLS)
2686
+ *
2687
+ * @param token - Supabase JWT from supabase.auth.signIn()
2688
+ *
2689
+ * @example
2690
+ * ```ts
2691
+ * const { data } = await supabase.auth.signInWithPassword({ email, password });
2692
+ * await sdk.auth.syncSupabaseToken(data.session.access_token);
2693
+ * ```
2694
+ */
2695
+ async syncSupabaseToken(token) {
2696
+ if (!token || typeof token !== "string") {
2697
+ throw new Error("Token must be a non-empty string");
2698
+ }
2699
+ const response = await fetch(`${this.baseUrl}/sdk/auth/sync-supabase-token`, {
2700
+ method: "POST",
2701
+ headers: this.getHeaders(),
2702
+ body: JSON.stringify({ token })
2703
+ });
2704
+ const data = await response.json();
2705
+ if (!response.ok) {
2706
+ throw new Error(data.error || "Failed to sync Supabase token");
2707
+ }
2708
+ return data;
2709
+ }
2710
+ /**
2711
+ * Retrieve the current Keycloak access token from Main App.
2712
+ * This is the existing Token Vending Machine endpoint.
2713
+ *
2714
+ * @returns The access token info, or null if no token is available.
2715
+ */
2716
+ async getAccessToken() {
2717
+ const response = await fetch(`${this.baseUrl}/sdk/auth/token`, {
2718
+ method: "GET",
2719
+ headers: this.getHeaders()
2720
+ });
2721
+ const data = await response.json();
2722
+ if (response.status === 404) {
2723
+ return null;
2724
+ }
2725
+ if (!response.ok) {
2726
+ throw new Error(data.error || "Failed to get access token");
2727
+ }
2728
+ return data;
2729
+ }
2730
+ };
2731
+
2534
2732
  // src/core/auth/AuthProvider.ts
2535
2733
  var StaticAuthProvider = class {
2536
2734
  constructor(options = {}) {
@@ -3225,6 +3423,8 @@ var _RealtimeXSDK = class _RealtimeXSDK {
3225
3423
  apiKey: this.apiKey,
3226
3424
  permissions: this.permissions
3227
3425
  });
3426
+ this.database = new DatabaseModule(this.realtimexUrl, this.appId, this.apiKey);
3427
+ this.auth = new AuthModule(this.realtimexUrl, this.appId, this.apiKey);
3228
3428
  if (this.permissions.length > 0 && this.appId && !this.apiKey) {
3229
3429
  this.register().catch((err) => {
3230
3430
  console.error("[RealtimeX SDK] Auto-registration failed:", err.message);
@@ -3332,6 +3532,7 @@ export {
3332
3532
  ActivitiesModule,
3333
3533
  AgentModule,
3334
3534
  ApiModule,
3535
+ AuthModule,
3335
3536
  CONTRACT_ATTEMPT_PREFIX,
3336
3537
  CONTRACT_EVENT_ID_HEADER,
3337
3538
  CONTRACT_SIGNATURE_ALGORITHM,
@@ -3345,6 +3546,7 @@ export {
3345
3546
  ContractModule,
3346
3547
  ContractRuntime,
3347
3548
  ContractValidationError,
3549
+ DatabaseModule,
3348
3550
  GeminiToolAdapter,
3349
3551
  LLMModule,
3350
3552
  LLMPermissionError,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@realtimex/sdk",
3
- "version": "1.3.5-rc.2",
3
+ "version": "1.3.7-rc.1",
4
4
  "description": "SDK for building Local Apps that integrate with RealtimeX",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",