@tenxyte/core 0.1.5 → 0.9.0

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/src/modules/ai.ts CHANGED
@@ -0,0 +1,178 @@
1
+ import { TenxyteHttpClient } from '../http/client';
2
+ import { AgentTokenSummary, AgentPendingAction } from '../types';
3
+
4
+ export class AiModule {
5
+ private agentToken: string | null = null;
6
+ private traceId: string | null = null;
7
+
8
+ constructor(private client: TenxyteHttpClient) {
9
+ // Register an interceptor to auto-inject AgentBearer and Trace ID
10
+ this.client.addRequestInterceptor((config) => {
11
+ const headers: Record<string, string> = { ...config.headers };
12
+
13
+ if (this.agentToken) {
14
+ // Determine if we should replace the standard Authorization
15
+ // By Tenxyte specification, AgentToken uses "AgentBearer"
16
+ headers['Authorization'] = `AgentBearer ${this.agentToken}`;
17
+ }
18
+
19
+ if (this.traceId) {
20
+ headers['X-Prompt-Trace-ID'] = this.traceId;
21
+ }
22
+
23
+ return { ...config, headers };
24
+ });
25
+
26
+ // Intercept 202 Accepted and specific 403 errors (Circuit Breaker)
27
+ // Usually, these should be emitted via the main TenxyteClient EventEmitter.
28
+ // For now, we add a response interceptor to handle the HTTP side.
29
+ this.client.addResponseInterceptor(async (response, request) => {
30
+ // Note: Since response streams can only be read once, full integration
31
+ // with EventEmitter for deep inspection (like 202s body) requires cloning.
32
+ if (response.status === 202) {
33
+ // HTTP 202 Accepted indicates HITL awaiting confirmation
34
+ const cloned = response.clone();
35
+ try {
36
+ const data = await cloned.json();
37
+ // Assuming TenxyteClient will fire 'agent:awaiting_approval' based on this later
38
+ console.debug('[Tenxyte AI] Received 202 Awaiting Approval:', data);
39
+ } catch {
40
+ // Ignore parsing errors
41
+ }
42
+ } else if (response.status === 403) {
43
+ const cloned = response.clone();
44
+ try {
45
+ const data = await cloned.json();
46
+ if (data.code === 'BUDGET_EXCEEDED') {
47
+ console.warn('[Tenxyte AI] Network responded with Budget Exceeded for Agent.');
48
+ } else if (data.status === 'suspended') {
49
+ console.warn('[Tenxyte AI] Circuit breaker open for Agent.');
50
+ }
51
+ } catch {
52
+ // Ignore parsing errors
53
+ }
54
+ }
55
+ return response;
56
+ });
57
+ }
58
+
59
+ // ─── AgentToken Lifecycle ───
60
+
61
+ /**
62
+ * Create an AgentToken granting specific deterministic limits to an AI Agent.
63
+ */
64
+ async createAgentToken(data: {
65
+ agent_id: string;
66
+ permissions?: string[];
67
+ expires_in?: number;
68
+ organization?: string;
69
+ budget_limit_usd?: number;
70
+ circuit_breaker?: {
71
+ max_requests?: number;
72
+ window_seconds?: number;
73
+ };
74
+ dead_mans_switch?: {
75
+ heartbeat_required_every?: number;
76
+ };
77
+ }): Promise<{
78
+ id: number;
79
+ token: string;
80
+ agent_id: string;
81
+ status: string;
82
+ expires_at: string;
83
+ }> {
84
+ return this.client.post('/api/v1/auth/ai/tokens/', data);
85
+ }
86
+
87
+ /**
88
+ * Set the SDK to operate on behalf of an Agent using the generated Agent Token payload.
89
+ * Overrides standard `Authorization` headers with `AgentBearer`.
90
+ */
91
+ setAgentToken(token: string): void {
92
+ this.agentToken = token;
93
+ }
94
+
95
+ /** Disables the active Agent override and reverts to standard User session requests. */
96
+ clearAgentToken(): void {
97
+ this.agentToken = null;
98
+ }
99
+
100
+ /** Check if the SDK is currently mocking requests as an AI Agent. */
101
+ isAgentMode(): boolean {
102
+ return this.agentToken !== null;
103
+ }
104
+
105
+ /** List previously provisioned active Agent tokens. */
106
+ async listAgentTokens(): Promise<AgentTokenSummary[]> {
107
+ return this.client.get('/api/v1/auth/ai/tokens/');
108
+ }
109
+
110
+ /** Fetch the status and configuration of a specific AgentToken. */
111
+ async getAgentToken(tokenId: number): Promise<AgentTokenSummary> {
112
+ return this.client.get(`/api/v1/auth/ai/tokens/${tokenId}/`);
113
+ }
114
+
115
+ /** Irreversibly revoke a targeted AgentToken from acting upon the Tenant. */
116
+ async revokeAgentToken(tokenId: number): Promise<{ status: 'revoked' }> {
117
+ return this.client.post(`/api/v1/auth/ai/tokens/${tokenId}/revoke/`);
118
+ }
119
+
120
+ /** Temporarily freeze an AgentToken by forcibly closing its Circuit Breaker. */
121
+ async suspendAgentToken(tokenId: number): Promise<{ status: 'suspended' }> {
122
+ return this.client.post(`/api/v1/auth/ai/tokens/${tokenId}/suspend/`);
123
+ }
124
+
125
+ /** Emergency kill-switch to wipe all operational Agent Tokens. */
126
+ async revokeAllAgentTokens(): Promise<{ status: 'revoked'; count: number }> {
127
+ return this.client.post('/api/v1/auth/ai/tokens/revoke-all/');
128
+ }
129
+
130
+ // ─── Circuit Breaker ───
131
+
132
+ /** Satisfy an Agent's Dead-Man's switch heartbeat requirement to prevent suspension. */
133
+ async sendHeartbeat(tokenId: number): Promise<{ status: 'ok' }> {
134
+ return this.client.post(`/api/v1/auth/ai/tokens/${tokenId}/heartbeat/`);
135
+ }
136
+
137
+ // ─── Human in the Loop (HITL) ───
138
+
139
+ /** List intercepted HTTP 202 actions waiting for Human interaction / approval. */
140
+ async listPendingActions(): Promise<AgentPendingAction[]> {
141
+ return this.client.get('/api/v1/auth/ai/pending-actions/');
142
+ }
143
+
144
+ /** Complete a pending HITL authorization to finally flush the Agent action to backend systems. */
145
+ async confirmPendingAction(confirmationToken: string): Promise<{ status: 'confirmed' }> {
146
+ return this.client.post('/api/v1/auth/ai/pending-actions/confirm/', { token: confirmationToken });
147
+ }
148
+
149
+ /** Block an Agent action permanently. */
150
+ async denyPendingAction(confirmationToken: string): Promise<{ status: 'denied' }> {
151
+ return this.client.post('/api/v1/auth/ai/pending-actions/deny/', { token: confirmationToken });
152
+ }
153
+
154
+ // ─── Traceability and Budget ───
155
+
156
+ /** Start piping the `X-Prompt-Trace-ID` custom header outwards for tracing logs against LLM inputs. */
157
+ setTraceId(traceId: string): void {
158
+ this.traceId = traceId;
159
+ }
160
+
161
+ /** Disable trace forwarding context. */
162
+ clearTraceId(): void {
163
+ this.traceId = null;
164
+ }
165
+
166
+ /**
167
+ * Report consumption costs associated with a backend invocation back to Tenxyte for strict circuit budgeting.
168
+ * @param tokenId - AgentToken evaluating ID.
169
+ * @param usage - Sunk token costs or explicit USD derivations.
170
+ */
171
+ async reportUsage(tokenId: number, usage: {
172
+ cost_usd: number;
173
+ prompt_tokens: number;
174
+ completion_tokens: number;
175
+ }): Promise<{ status: 'ok' } | { error: 'Budget exceeded'; status: 'suspended' }> {
176
+ return this.client.post(`/api/v1/auth/ai/tokens/${tokenId}/report-usage/`, usage);
177
+ }
178
+ }
@@ -1,95 +1,116 @@
1
- import { TenxyteHttpClient } from '../http/client';
2
- import { TokenPair, GeneratedSchema } from '../types';
3
-
4
- export interface LoginEmailOptions {
5
- totp_code?: string;
6
- }
7
-
8
- export interface LoginPhoneOptions {
9
- totp_code?: string;
10
- }
11
-
12
- export type RegisterRequest = any;
13
-
14
- export interface MagicLinkRequest {
15
- email: string;
16
- }
17
-
18
- export interface SocialLoginRequest {
19
- access_token?: string;
20
- authorization_code?: string;
21
- id_token?: string;
22
- }
23
-
24
- export class AuthModule {
25
- constructor(private client: TenxyteHttpClient) { }
26
-
27
- /**
28
- * Authenticate user with email and password
29
- */
30
- async loginWithEmail(
31
- data: GeneratedSchema['LoginEmail'],
32
- ): Promise<TokenPair> {
33
- return this.client.post<TokenPair>('/api/v1/auth/login/email/', data);
34
- }
35
-
36
- /**
37
- * Authenticate user with international phone number and password
38
- */
39
- async loginWithPhone(
40
- data: GeneratedSchema['LoginPhone'],
41
- ): Promise<TokenPair> {
42
- return this.client.post<TokenPair>('/api/v1/auth/login/phone/', data);
43
- }
44
-
45
- /**
46
- * Register a new user
47
- */
48
- async register(data: RegisterRequest): Promise<any> {
49
- return this.client.post<any>('/api/v1/auth/register/', data);
50
- }
51
-
52
- /**
53
- * Logout from the current session
54
- */
55
- async logout(refreshToken: string): Promise<void> {
56
- return this.client.post<void>('/api/v1/auth/logout/', { refresh_token: refreshToken });
57
- }
58
-
59
- /**
60
- * Logout from all sessions (revokes all refresh tokens)
61
- */
62
- async logoutAll(): Promise<void> {
63
- return this.client.post<void>('/api/v1/auth/logout/all/');
64
- }
65
-
66
- /**
67
- * Request a magic link for sign-in
68
- */
69
- async requestMagicLink(data: MagicLinkRequest): Promise<void> {
70
- return this.client.post<void>('/api/v1/auth/magic-link/request/', data);
71
- }
72
-
73
- /**
74
- * Verify a magic link token
75
- */
76
- async verifyMagicLink(token: string): Promise<TokenPair> {
77
- return this.client.get<TokenPair>(`/api/v1/auth/magic-link/verify/`, { params: { token } });
78
- }
79
-
80
- /**
81
- * Perform OAuth2 Social Authentication (e.g. Google, GitHub)
82
- */
83
- async loginWithSocial(provider: 'google' | 'github' | 'microsoft' | 'facebook', data: SocialLoginRequest): Promise<TokenPair> {
84
- return this.client.post<TokenPair>(`/api/v1/auth/social/${provider}/`, data);
85
- }
86
-
87
- /**
88
- * Handle Social Auth Callback (authorization code flow)
89
- */
90
- async handleSocialCallback(provider: 'google' | 'github' | 'microsoft' | 'facebook', code: string, redirectUri: string): Promise<TokenPair> {
91
- return this.client.get<TokenPair>(`/api/v1/auth/social/${provider}/callback/`, {
92
- params: { code, redirect_uri: redirectUri },
93
- });
94
- }
95
- }
1
+ import { TenxyteHttpClient } from '../http/client';
2
+ import { TokenPair, GeneratedSchema } from '../types';
3
+
4
+ export interface LoginEmailOptions {
5
+ totp_code?: string;
6
+ }
7
+
8
+ export interface LoginPhoneOptions {
9
+ totp_code?: string;
10
+ }
11
+
12
+ export type RegisterRequest = any;
13
+
14
+ export interface MagicLinkRequest {
15
+ email: string;
16
+ }
17
+
18
+ export interface SocialLoginRequest {
19
+ access_token?: string;
20
+ authorization_code?: string;
21
+ id_token?: string;
22
+ }
23
+
24
+ export class AuthModule {
25
+ constructor(private client: TenxyteHttpClient) { }
26
+
27
+ /**
28
+ * Authenticate a user with their email and password.
29
+ * @param data - The login credentials and optional TOTP code if 2FA is required.
30
+ * @returns A pair of Access and Refresh tokens upon successful authentication.
31
+ * @throws {TenxyteError} If credentials are invalid, or if `2FA_REQUIRED` without a valid `totp_code`.
32
+ */
33
+ async loginWithEmail(
34
+ data: GeneratedSchema['LoginEmail'],
35
+ ): Promise<TokenPair> {
36
+ return this.client.post<TokenPair>('/api/v1/auth/login/email/', data);
37
+ }
38
+
39
+ /**
40
+ * Authenticate a user with an international phone number and password.
41
+ * @param data - The login credentials and optional TOTP code if 2FA is required.
42
+ * @returns A pair of Access and Refresh tokens.
43
+ */
44
+ async loginWithPhone(
45
+ data: GeneratedSchema['LoginPhone'],
46
+ ): Promise<TokenPair> {
47
+ return this.client.post<TokenPair>('/api/v1/auth/login/phone/', data);
48
+ }
49
+
50
+ /**
51
+ * Registers a new user account.
52
+ * @param data - The registration details (email, password, etc.).
53
+ * @returns The registered user data or a confirmation message.
54
+ */
55
+ async register(data: RegisterRequest): Promise<any> {
56
+ return this.client.post<any>('/api/v1/auth/register/', data);
57
+ }
58
+
59
+ /**
60
+ * Logout from the current session.
61
+ * Informs the backend to immediately revoke the specified refresh token.
62
+ * @param refreshToken - The refresh token to revoke.
63
+ */
64
+ async logout(refreshToken: string): Promise<void> {
65
+ return this.client.post<void>('/api/v1/auth/logout/', { refresh_token: refreshToken });
66
+ }
67
+
68
+ /**
69
+ * Logout from all sessions across all devices.
70
+ * Revokes all refresh tokens currently assigned to the user.
71
+ */
72
+ async logoutAll(): Promise<void> {
73
+ return this.client.post<void>('/api/v1/auth/logout/all/');
74
+ }
75
+
76
+ /**
77
+ * Request a Magic Link for passwordless sign-in.
78
+ * @param data - The email to send the logic link to.
79
+ */
80
+ async requestMagicLink(data: MagicLinkRequest): Promise<void> {
81
+ return this.client.post<void>('/api/v1/auth/magic-link/request/', data);
82
+ }
83
+
84
+ /**
85
+ * Verifies a magic link token extracted from the URL.
86
+ * @param token - The cryptographic token received via email.
87
+ * @returns A session token pair if the token is valid and unexpired.
88
+ */
89
+ async verifyMagicLink(token: string): Promise<TokenPair> {
90
+ return this.client.get<TokenPair>(`/api/v1/auth/magic-link/verify/`, { params: { token } });
91
+ }
92
+
93
+ /**
94
+ * Submits OAuth2 Social Authentication payloads to the backend.
95
+ * Can be used with native mobile SDK tokens (like Apple Sign-In JWTs).
96
+ * @param provider - The OAuth provider ('google', 'github', etc.)
97
+ * @param data - The OAuth tokens (access_token, id_token, etc.)
98
+ * @returns An active session token pair.
99
+ */
100
+ async loginWithSocial(provider: 'google' | 'github' | 'microsoft' | 'facebook', data: SocialLoginRequest): Promise<TokenPair> {
101
+ return this.client.post<TokenPair>(`/api/v1/auth/social/${provider}/`, data);
102
+ }
103
+
104
+ /**
105
+ * Handle Social Auth Callbacks (Authorization Code flow).
106
+ * @param provider - The OAuth provider ('google', 'github', etc.)
107
+ * @param code - The authorization code retrieved from the query string parameters.
108
+ * @param redirectUri - The original redirect URI that was requested.
109
+ * @returns An active session token pair after successful code exchange.
110
+ */
111
+ async handleSocialCallback(provider: 'google' | 'github' | 'microsoft' | 'facebook', code: string, redirectUri: string): Promise<TokenPair> {
112
+ return this.client.get<TokenPair>(`/api/v1/auth/social/${provider}/callback/`, {
113
+ params: { code, redirect_uri: redirectUri },
114
+ });
115
+ }
116
+ }
@@ -0,0 +1,177 @@
1
+ import { TenxyteHttpClient } from '../http/client';
2
+ import { Organization, PaginatedResponse } from '../types';
3
+
4
+ export interface OrgMembership {
5
+ id: number;
6
+ user_id: number;
7
+ email: string;
8
+ first_name: string;
9
+ last_name: string;
10
+ role: { code: string; name: string };
11
+ joined_at: string;
12
+ }
13
+
14
+ export interface OrgTreeNode {
15
+ id: number;
16
+ name: string;
17
+ slug: string;
18
+ children: OrgTreeNode[];
19
+ }
20
+
21
+ export class B2bModule {
22
+ private currentOrgSlug: string | null = null;
23
+
24
+ constructor(private client: TenxyteHttpClient) {
25
+ // Register an interceptor to auto-inject the X-Org-Slug header
26
+ this.client.addRequestInterceptor((config) => {
27
+ if (this.currentOrgSlug) {
28
+ config.headers = {
29
+ ...config.headers,
30
+ 'X-Org-Slug': this.currentOrgSlug,
31
+ };
32
+ }
33
+ return config;
34
+ });
35
+ }
36
+
37
+ // ─── Context Management ───
38
+
39
+ /**
40
+ * Set the active Organization context.
41
+ * Subsequent API requests will automatically include the `X-Org-Slug` header.
42
+ * @param slug - The unique string identifier of the organization.
43
+ */
44
+ switchOrganization(slug: string): void {
45
+ this.currentOrgSlug = slug;
46
+ }
47
+
48
+ /**
49
+ * Clear the active Organization context, dropping the `X-Org-Slug` header for standard User operations.
50
+ */
51
+ clearOrganization(): void {
52
+ this.currentOrgSlug = null;
53
+ }
54
+
55
+ /** Get the currently active Organization slug context if set. */
56
+ getCurrentOrganizationSlug(): string | null {
57
+ return this.currentOrgSlug;
58
+ }
59
+
60
+ // ─── Organizations CRUD ───
61
+
62
+ /** Create a new top-level or child Organization in the backend. */
63
+ async createOrganization(data: {
64
+ name: string;
65
+ slug?: string;
66
+ description?: string;
67
+ parent_id?: number;
68
+ metadata?: Record<string, unknown>;
69
+ max_members?: number;
70
+ }): Promise<Organization> {
71
+ return this.client.post('/api/v1/auth/organizations/', data);
72
+ }
73
+
74
+ /** List organizations the currently authenticated user belongs to. */
75
+ async listMyOrganizations(params?: {
76
+ search?: string;
77
+ is_active?: boolean;
78
+ parent?: string;
79
+ ordering?: string;
80
+ page?: number;
81
+ page_size?: number;
82
+ }): Promise<PaginatedResponse<Organization>> {
83
+ return this.client.get('/api/v1/auth/organizations/', { params });
84
+ }
85
+
86
+ /** Retrieve details about a specific organization by slug. */
87
+ async getOrganization(slug: string): Promise<Organization> {
88
+ return this.client.get(`/api/v1/auth/organizations/${slug}/`);
89
+ }
90
+
91
+ /** Update configuration and metadata of an Organization. */
92
+ async updateOrganization(slug: string, data: Partial<{
93
+ name: string;
94
+ slug: string;
95
+ description: string;
96
+ parent_id: number | null;
97
+ metadata: Record<string, unknown>;
98
+ max_members: number;
99
+ is_active: boolean;
100
+ }>): Promise<Organization> {
101
+ return this.client.patch(`/api/v1/auth/organizations/${slug}/`, data);
102
+ }
103
+
104
+ /** Permanently delete an Organization. */
105
+ async deleteOrganization(slug: string): Promise<{ message: string }> {
106
+ return this.client.delete(`/api/v1/auth/organizations/${slug}/`);
107
+ }
108
+
109
+ /** Retrieve the topology subtree extending downward from this point. */
110
+ async getOrganizationTree(slug: string): Promise<OrgTreeNode> {
111
+ return this.client.get(`/api/v1/auth/organizations/${slug}/tree/`);
112
+ }
113
+
114
+ // ─── Member Management ───
115
+
116
+ /** List users bound to a specific Organization. */
117
+ async listMembers(slug: string, params?: {
118
+ search?: string;
119
+ role?: 'owner' | 'admin' | 'member';
120
+ status?: 'active' | 'inactive' | 'pending';
121
+ ordering?: string;
122
+ page?: number;
123
+ page_size?: number;
124
+ }): Promise<PaginatedResponse<OrgMembership>> {
125
+ return this.client.get(`/api/v1/auth/organizations/${slug}/members/`, { params });
126
+ }
127
+
128
+ /** Add a user directly into an Organization with a designated role. */
129
+ async addMember(slug: string, data: {
130
+ user_id: number;
131
+ role_code: string;
132
+ }): Promise<OrgMembership> {
133
+ return this.client.post(`/api/v1/auth/organizations/${slug}/members/`, data);
134
+ }
135
+
136
+ /** Evolve or demote an existing member's role within the Organization. */
137
+ async updateMemberRole(slug: string, userId: number, roleCode: string): Promise<OrgMembership> {
138
+ return this.client.patch(`/api/v1/auth/organizations/${slug}/members/${userId}/`, { role_code: roleCode });
139
+ }
140
+
141
+ /** Kick a user out of the Organization. */
142
+ async removeMember(slug: string, userId: number): Promise<{ message: string }> {
143
+ return this.client.delete(`/api/v1/auth/organizations/${slug}/members/${userId}/`);
144
+ }
145
+
146
+ // ─── Invitations ───
147
+
148
+ /** Send an onboarding email invitation to join an Organization. */
149
+ async inviteMember(slug: string, data: {
150
+ email: string;
151
+ role_code: string;
152
+ expires_in_days?: number;
153
+ }): Promise<{
154
+ id: number;
155
+ email: string;
156
+ role: string;
157
+ token: string;
158
+ expires_at: string;
159
+ invited_by: { id: number; email: string };
160
+ organization: { id: number; name: string; slug: string };
161
+ }> {
162
+ return this.client.post(`/api/v1/auth/organizations/${slug}/invitations/`, data);
163
+ }
164
+
165
+ /** Fetch a definition matrix of what Organization-level roles can be assigned. */
166
+ async listOrgRoles(): Promise<Array<{
167
+ code: string;
168
+ name: string;
169
+ description: string;
170
+ weight: number;
171
+ permissions: Array<{ code: string; name: string; description: string }>;
172
+ is_system_role: boolean;
173
+ created_at: string;
174
+ }>> {
175
+ return this.client.get('/api/v1/auth/organizations/roles/');
176
+ }
177
+ }