@adaptive-ai/sdk 0.0.1 → 0.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.
@@ -1,6 +1,20 @@
1
1
  import { MutationFunction, UseMutationOptions, UseMutationResult } from '@tanstack/react-query';
2
2
 
3
- type AuthProvider = 'GITHUB_USER' | 'GITHUB_BOT' | 'GOOGLE' | 'AC1' | 'SLACK' | 'SLACK_BOT' | 'DISCORD' | 'NOTION' | 'TWITTER' | 'LINKEDIN' | 'FIGMA';
3
+ declare const AuthProvider: {
4
+ readonly GITHUB_USER: "GITHUB_USER";
5
+ readonly GITHUB_BOT: "GITHUB_BOT";
6
+ readonly GOOGLE: "GOOGLE";
7
+ readonly AC1: "AC1";
8
+ readonly SLACK: "SLACK";
9
+ readonly SLACK_BOT: "SLACK_BOT";
10
+ readonly DISCORD: "DISCORD";
11
+ readonly NOTION: "NOTION";
12
+ readonly TWITTER: "TWITTER";
13
+ readonly LINKEDIN: "LINKEDIN";
14
+ readonly YAHOO: "YAHOO";
15
+ readonly FIGMA: "FIGMA";
16
+ };
17
+ type AuthProvider = (typeof AuthProvider)[keyof typeof AuthProvider];
4
18
  type ProviderInput = {
5
19
  provider: AuthProvider;
6
20
  scope?: string[];
@@ -1,2 +1,2 @@
1
- import {useMutation}from'@tanstack/react-query';import {identity}from'lodash';import {nanoid}from'nanoid';import {useState,useEffect,useRef,useCallback}from'react';import p from'superjson';function b(e){return new Promise(r=>{let n=new FileReader;n.onload=()=>{r(n.result);},n.readAsDataURL(e);})}var l=e=>{let{email:r,phoneNumber:n}=e??{},s=r??n,t=new URLSearchParams;e&&"redirectUri"in e&&e.redirectUri?t.set("returnTo",e.redirectUri):t.set("returnTo",window.location.pathname+window.location.search),e?.provider&&e.provider!="AC1"&&(t.set("provider",e.provider),e.scope&&e.scope.length>0&&t.set("scope",e.scope.join(","))),e?.provider=="AC1"&&s&&t.set("identity",s),t.set("stripped","true");let o=window.__APP_ID__;window.__OPEN_AUTH_DRAWER__(`${window.__ROOT_URL__}/setup/${o}?${t.toString()}`);};function M(){return {redirectToLogin:e=>e?.email?l({email:e.email,provider:"AC1"}):l()}}function P(e={}){let[r,n]=useState({userId:void 0,status:"loading",signIn:l,providers:[]});return useEffect(()=>{(async()=>{try{let o=await(await fetch("/api/session",{method:"POST",headers:{"Content-Type":"application/json","x-guest-api-internal":"session","x-version-id":window.__VERSION_ID__,...window.__IS_TESTING__?{"x-is-testing":"true"}:{}}})).json()??{};n({userId:o.userId??null,status:"authenticated",signIn:l,providers:o?.providers??[]});}catch{if(e.required){let o=encodeURIComponent(window.location.pathname+window.location.search),d=window.__APP_ID__;window.top?window.top.location.href=`${window.__ROOT_URL__}/setup/${d}?returnTo=${o}`:window.location.href=`${window.__ROOT_URL__}/setup/${d}?returnTo=${o}`;}else n({userId:null,status:"unauthenticated",signIn:l,providers:[]});}})();},[e.required]),r}function $(){return window.__BASE_URL__}async function I({channelId:e,initialData:r,broadcastOnly:n,onUpdate:s}){let t=r,o=0,d=window.__REALTIME_DOMAIN__;if(n)return {getData(){return t},setData(u){t=u,fetch(`https://${d}/${e}`,{method:"POST",body:p.stringify(t)}).catch(console.error),s?.(u);},destroy(){}};let a=new WebSocket(`wss://${d}/${e}`);return new Promise((u,w)=>{function h(i){try{let c=JSON.parse(i.data.toString());c?.id&&c.id>o?(t=p.parse(c.payload),s?.(t),o=c.id):console.error("Invalid message:",i.data);}catch{console.error("Error parsing message:",i.data);}}function T(i){m(),w(i);}function R(){u({getData(){return t},setData(i){t=i,s?.(i),a.send(p.stringify(i));},destroy:m});}function m(){a.removeEventListener("message",h),a.removeEventListener("error",T),a.removeEventListener("open",R),a.close();}a.addEventListener("message",h),a.addEventListener("error",T),a.addEventListener("open",R);})}function L(e,r){let n=useRef(null),[s,t]=useState(0);return useEffect(()=>((async()=>e&&(n.current=await I({channelId:e,initialData:r,onUpdate:()=>{t(o=>o+1);}})))(),n.current?.destroy),[e,t]),[n.current?.getData(),n.current?.setData??identity]}function C(e,r){let[n,s]=useState(null),[t]=L(n,void 0),o=useCallback(async a=>{let u=nanoid(32);return s(u),await e?.({...a,__channelId:u})},[e]);return {...useMutation(o,r),data:t}}
2
- export{I as connectToRealtimeStore,b as encodeFileAsBase64DataURL,$ as getBaseUrl,P as useAuth,C as useRealtimeMutation,L as useRealtimeStore,M as useRedirectToLogin};
1
+ import {useMutation}from'@tanstack/react-query';import {identity}from'lodash';import {nanoid}from'nanoid';import {useState,useEffect,useRef,useCallback}from'react';import p from'superjson';function b(e){return new Promise(r=>{let n=new FileReader;n.onload=()=>{r(n.result);},n.readAsDataURL(e);})}var l=e=>{let{email:r,phoneNumber:n}=e??{},s=r??n,t=new URLSearchParams;e&&"redirectUri"in e&&e.redirectUri?t.set("returnTo",e.redirectUri):t.set("returnTo",window.location.pathname+window.location.search),e?.provider&&e.provider!="AC1"&&(t.set("provider",e.provider),e.scope&&e.scope.length>0&&t.set("scope",e.scope.join(","))),e?.provider=="AC1"&&s&&t.set("identity",s),t.set("stripped","true");let o=window.__APP_ID__;window.__OPEN_AUTH_DRAWER__(`${window.__ROOT_URL__}/setup/${o}?${t.toString()}`);};function M(){return {redirectToLogin:e=>e?.email?l({email:e.email,provider:"AC1"}):l()}}function $(e={}){let[r,n]=useState({userId:void 0,status:"loading",signIn:l,providers:[]});return useEffect(()=>{(async()=>{try{let o=await(await fetch("/api/session",{method:"POST",headers:{"Content-Type":"application/json","x-guest-api-internal":"session","x-version-id":window.__VERSION_ID__,...window.__IS_TESTING__?{"x-is-testing":"true"}:{}}})).json()??{};n({userId:o.userId??null,status:"authenticated",signIn:l,providers:o?.providers??[]});}catch{if(e.required){let o=encodeURIComponent(window.location.pathname+window.location.search),d=window.__APP_ID__;window.top?window.top.location.href=`${window.__ROOT_URL__}/setup/${d}?returnTo=${o}`:window.location.href=`${window.__ROOT_URL__}/setup/${d}?returnTo=${o}`;}else n({userId:null,status:"unauthenticated",signIn:l,providers:[]});}})();},[e.required]),r}function C(){return window.__BASE_URL__}async function I({channelId:e,initialData:r,broadcastOnly:n,onUpdate:s}){let t=r,o=0,d=window.__REALTIME_DOMAIN__;if(n)return {getData(){return t},setData(u){t=u,fetch(`https://${d}/${e}`,{method:"POST",body:p.stringify(t)}).catch(console.error),s?.(u);},destroy(){}};let a=new WebSocket(`wss://${d}/${e}`);return new Promise((u,w)=>{function T(i){try{let c=JSON.parse(i.data.toString());c?.id&&c.id>o?(t=p.parse(c.payload),s?.(t),o=c.id):console.error("Invalid message:",i.data);}catch{console.error("Error parsing message:",i.data);}}function h(i){m(),w(i);}function R(){u({getData(){return t},setData(i){t=i,s?.(i),a.send(p.stringify(i));},destroy:m});}function m(){a.removeEventListener("message",T),a.removeEventListener("error",h),a.removeEventListener("open",R),a.close();}a.addEventListener("message",T),a.addEventListener("error",h),a.addEventListener("open",R);})}function L(e,r){let n=useRef(null),[s,t]=useState(0);return useEffect(()=>((async()=>e&&(n.current=await I({channelId:e,initialData:r,onUpdate:()=>{t(o=>o+1);}})))(),n.current?.destroy),[e,t]),[n.current?.getData(),n.current?.setData??identity]}function P(e,r){let[n,s]=useState(null),[t]=L(n,void 0),o=useCallback(async a=>{let u=nanoid(32);return s(u),await e?.({...a,__channelId:u})},[e]);return {...useMutation(o,r),data:t}}
2
+ export{I as connectToRealtimeStore,b as encodeFileAsBase64DataURL,C as getBaseUrl,$ as useAuth,P as useRealtimeMutation,L as useRealtimeStore,M as useRedirectToLogin};
@@ -1,16 +1,26 @@
1
- import * as _ac1_db from '@ac1/db';
2
- import { AuthProvider } from '@ac1/iso/auth';
3
1
  import { ZodSchema } from 'zod';
2
+ import { ChatCompletionMessageParam, ChatCompletionContentPart, ChatCompletionMessageFunctionToolCall } from 'openai/resources';
4
3
 
5
- type ProductKind = 'IN_APP_PURCHASE' | 'SUBSCRIPTION';
6
- type TaskStatus = {
7
- id: string;
8
- status: 'RUNNING' | 'COMPLETED' | 'FAILED';
9
- error?: any;
10
- } | {
11
- id: string;
12
- status: 'UNKNOWN';
4
+ declare const ProductKind: {
5
+ readonly SUBSCRIPTION: "SUBSCRIPTION";
6
+ readonly IN_APP_PURCHASE: "IN_APP_PURCHASE";
7
+ };
8
+ type ProductKind = (typeof ProductKind)[keyof typeof ProductKind];
9
+ declare const AuthProvider: {
10
+ readonly GITHUB_USER: "GITHUB_USER";
11
+ readonly GITHUB_BOT: "GITHUB_BOT";
12
+ readonly GOOGLE: "GOOGLE";
13
+ readonly AC1: "AC1";
14
+ readonly SLACK: "SLACK";
15
+ readonly SLACK_BOT: "SLACK_BOT";
16
+ readonly DISCORD: "DISCORD";
17
+ readonly NOTION: "NOTION";
18
+ readonly TWITTER: "TWITTER";
19
+ readonly LINKEDIN: "LINKEDIN";
20
+ readonly YAHOO: "YAHOO";
21
+ readonly FIGMA: "FIGMA";
13
22
  };
23
+ type AuthProvider = (typeof AuthProvider)[keyof typeof AuthProvider];
14
24
  type CatalogVoice = {
15
25
  id: string;
16
26
  name: string;
@@ -24,17 +34,110 @@ type CatalogImageModel = {
24
34
  description?: string;
25
35
  tier: 'FREE' | 'ONE' | 'TWO';
26
36
  };
27
- type AuthStatus = {
28
- status: 'authenticated';
29
- userId: string;
30
- signIn: typeof signIn;
31
- providers: AuthProvider[];
32
- } | {
33
- status: 'unauthenticated';
34
- userId: null;
35
- signIn: typeof signIn;
36
- providers: [];
37
+ declare const AgentDefinitions: {
38
+ readonly ProductManagerAgent: "ProductManagerAgent";
39
+ readonly AppDeveloperAgent: "AppDeveloperAgent";
37
40
  };
41
+ interface ChatCompletionContentPartThinking {
42
+ thought: string;
43
+ signature?: string;
44
+ provider: string;
45
+ }
46
+ interface ChatCompletionContentPartPDF {
47
+ pdf_url: ChatCompletionContentPartPDF.PDFURL;
48
+ /**
49
+ * The type of the content part.
50
+ */
51
+ type: 'pdf_url';
52
+ }
53
+ declare namespace ChatCompletionContentPartPDF {
54
+ interface PDFURL {
55
+ /**
56
+ * The URL of the PDF file.
57
+ */
58
+ url: string;
59
+ }
60
+ }
61
+ interface ChatCompletionContentPartVideo {
62
+ video_url: ChatCompletionContentPartVideo.VideoURL;
63
+ /**
64
+ * The type of the content part.
65
+ */
66
+ type: 'video_url';
67
+ }
68
+ declare namespace ChatCompletionContentPartVideo {
69
+ interface VideoURL {
70
+ /**
71
+ * The URL of the video file.
72
+ */
73
+ url: string;
74
+ }
75
+ }
76
+ interface ChatCompletionContentPartAudio {
77
+ audio_url: ChatCompletionContentPartAudio.AudioURL;
78
+ /**
79
+ * The type of the content part.
80
+ */
81
+ type: 'audio_url';
82
+ }
83
+ declare namespace ChatCompletionContentPartAudio {
84
+ interface AudioURL {
85
+ /**
86
+ * The URL of the audio file.
87
+ */
88
+ url: string;
89
+ }
90
+ }
91
+ type ExternalApiMessage = {
92
+ role: Exclude<ChatCompletionMessageParam['role'], 'function'>;
93
+ content?: string | Array<(ChatCompletionContentPart & {
94
+ cache_control?: {
95
+ type: 'ephemeral';
96
+ };
97
+ }) | (ChatCompletionContentPartPDF & {
98
+ cache_control?: {
99
+ type: 'ephemeral';
100
+ };
101
+ }) | (ChatCompletionContentPartVideo & {
102
+ cache_control?: {
103
+ type: 'ephemeral';
104
+ };
105
+ }) | (ChatCompletionContentPartAudio & {
106
+ cache_control?: {
107
+ type: 'ephemeral';
108
+ };
109
+ })>;
110
+ id?: string;
111
+ tool_call_id?: string | null;
112
+ tool_calls?: Array<ChatCompletionMessageFunctionToolCall> | null;
113
+ thinking?: ChatCompletionContentPartThinking;
114
+ name?: 'client' | 'attachments' | keyof typeof AgentDefinitions | null;
115
+ };
116
+ declare global {
117
+ interface EmailHandlerInput {
118
+ subject: string;
119
+ body: string;
120
+ fromUserId: string;
121
+ }
122
+ interface Window {
123
+ __VERSION_ID__: string;
124
+ __APP_ID__: string;
125
+ __IS_TESTING__: boolean;
126
+ __ROOT_URL__: string;
127
+ __BASE_URL__: string;
128
+ __REALTIME_DOMAIN__: string;
129
+ __OPEN_AUTH_DRAWER__: (url: string) => void;
130
+ }
131
+ }
132
+
133
+ interface RequestContext {
134
+ requestId: string;
135
+ channelId?: string;
136
+ hasTasks?: boolean;
137
+ }
138
+ declare function getRequestContext(): RequestContext | undefined;
139
+ declare function setRequestContext(context: Partial<RequestContext>): void;
140
+ declare function runWithContext<T>(context: RequestContext, fn: () => Promise<T>): Promise<T>;
38
141
  type RedirectInput = {
39
142
  email: string;
40
143
  provider: typeof AuthProvider.AC1;
@@ -44,27 +147,37 @@ type RedirectInput = {
44
147
  provider: typeof AuthProvider.AC1;
45
148
  email: null | undefined;
46
149
  } | {
47
- provider: AuthProvider;
150
+ provider: (typeof AuthProvider)[keyof typeof AuthProvider];
48
151
  };
49
- type ExternalApiMessage = any;
50
- interface RequestContext {
51
- requestId: string;
52
- channelId?: string;
53
- hasTasks?: boolean;
54
- }
55
- declare function getRequestContext(): RequestContext | undefined;
56
- declare function setRequestContext(context: Partial<RequestContext>): void;
57
- declare function runWithContext<T>(context: RequestContext, fn: () => Promise<T>): Promise<T>;
58
152
  declare function signIn(input?: RedirectInput): void;
59
153
  declare function getUserId(input?: {
60
154
  throwIfNotLoggedIn?: boolean;
61
155
  }): Promise<string | null>;
156
+ type AuthStatus = {
157
+ status: 'authenticated';
158
+ userId: string;
159
+ signIn: typeof signIn;
160
+ providers: AuthProvider[];
161
+ } | {
162
+ status: 'unauthenticated';
163
+ userId: null;
164
+ signIn: typeof signIn;
165
+ providers: [];
166
+ };
62
167
  declare function getAuth(input: {
63
168
  required: true;
64
169
  }): Promise<AuthStatus>;
65
170
  declare function getAuth(input?: {
66
171
  required?: boolean;
67
172
  }): Promise<AuthStatus>;
173
+ type TaskStatus = {
174
+ id: string;
175
+ status: 'RUNNING' | 'COMPLETED' | 'FAILED';
176
+ error?: any;
177
+ } | {
178
+ id: string;
179
+ status: 'UNKNOWN';
180
+ };
68
181
  declare function queueTask(runner: () => Promise<void>): Promise<TaskStatus>;
69
182
  declare function getTaskStatus(taskId: string): Promise<TaskStatus>;
70
183
  declare function getStructuredDataFromContent<T>(input: {
@@ -128,33 +241,59 @@ declare function generateDialogue(input: {
128
241
  character: string;
129
242
  text: string;
130
243
  }[];
131
- }): Promise<any>;
244
+ }): Promise<{
245
+ url: string;
246
+ duration: number | undefined;
247
+ }>;
132
248
  declare function generateMusic(input: {
133
249
  text: string;
134
- }): Promise<any>;
250
+ }): Promise<string>;
135
251
  declare function upload(input: {
136
252
  bufferOrBase64: Buffer | string;
137
253
  fileName: string;
138
254
  }): Promise<string>;
139
255
  declare function getOAuthToken(input: {
140
256
  connectionId: string;
141
- }): Promise<any>;
257
+ }): Promise<{
258
+ connectionId: string;
259
+ userId: string | null;
260
+ accessToken: string | null;
261
+ expiresAt: Date | null;
262
+ scope: string[];
263
+ }>;
142
264
  declare function getOAuthConnectionForCurrentUser(input: {
143
265
  provider: Exclude<AuthProvider, 'AC1'>;
144
266
  scope?: string[];
145
267
  required?: boolean;
146
- }): Promise<any>;
268
+ }): Promise<{
269
+ id: string;
270
+ provider: string;
271
+ userId: string | undefined;
272
+ scope: string[];
273
+ } | null>;
147
274
  declare function getOAuthConnection(input: {
148
275
  connectionId: string;
149
- }): Promise<any>;
276
+ }): Promise<{
277
+ id: string;
278
+ provider: string;
279
+ userId: string | undefined;
280
+ scope: string[];
281
+ }>;
150
282
  declare function queryOAuthConnections(input: {
151
283
  userId?: string;
152
284
  provider?: Exclude<AuthProvider, 'AC1'>;
153
285
  scope?: string[];
154
- }): Promise<any>;
286
+ }): Promise<{
287
+ id: string;
288
+ provider: string;
289
+ userId: string | undefined;
290
+ scope: string[];
291
+ }[]>;
155
292
  declare function deleteOAuthConnection(input: {
156
293
  connectionId: string;
157
- }): Promise<any>;
294
+ }): Promise<{
295
+ readonly ok: true;
296
+ }>;
158
297
  declare function sendEmail(input: {
159
298
  markdown: string;
160
299
  subject: string;
@@ -189,9 +328,9 @@ declare function createProduct(input: {
189
328
  }): Promise<{
190
329
  purchaseLink: string;
191
330
  id: string;
192
- kind: _ac1_db.$Enums.ProductKind;
193
331
  description: string;
194
332
  name: string;
333
+ kind: ProductKind;
195
334
  price: number;
196
335
  }>;
197
336
  declare function listProducts(): Promise<{
@@ -206,7 +345,7 @@ declare function listUserPurchases(input?: {
206
345
  userId: string;
207
346
  }): Promise<{
208
347
  id: string;
209
- kind: _ac1_db.$Enums.ProductKind;
348
+ kind: ProductKind;
210
349
  description: string;
211
350
  name: string;
212
351
  price: number;
@@ -240,4 +379,4 @@ declare function getImageModelsCatalog(input: {
240
379
  declare function getBaseUrl(): string;
241
380
  declare function getLastStreamTime(): number | null;
242
381
 
243
- export { type ProductKind, createProduct, deleteOAuthConnection, discontinueProduct, extractTextFromContent, generateCrossAppToken, generateDialogue, generateMusic, generateSoundEffect, getAuth, getBaseUrl, getDialogueVoicesCatalog, getImageModelsCatalog, getLastStreamTime, getOAuthConnection, getOAuthConnectionForCurrentUser, getOAuthToken, getRealtimeStore, getRequestContext, getStructuredDataFromContent, getTTSVoicesCatalog, getTaskStatus, getUserId, inviteUser, isAppOwner, listProducts, listUserPurchases, queryOAuthConnections, queueTask, requestMultimodalModel, runWithContext, searchWithGoogle, sendEmail, setRealtimeStore, setRequestContext, startRealtimeResponse, textToImage, textToSpeech, upload };
382
+ export { createProduct, deleteOAuthConnection, discontinueProduct, extractTextFromContent, generateCrossAppToken, generateDialogue, generateMusic, generateSoundEffect, getAuth, getBaseUrl, getDialogueVoicesCatalog, getImageModelsCatalog, getLastStreamTime, getOAuthConnection, getOAuthConnectionForCurrentUser, getOAuthToken, getRealtimeStore, getRequestContext, getStructuredDataFromContent, getTTSVoicesCatalog, getTaskStatus, getUserId, inviteUser, isAppOwner, listProducts, listUserPurchases, queryOAuthConnections, queueTask, requestMultimodalModel, runWithContext, searchWithGoogle, sendEmail, setRealtimeStore, setRequestContext, startRealtimeResponse, textToImage, textToSpeech, upload };
@@ -1,2 +1,2 @@
1
- import {MissingAuthError}from'@ac1/iso/errors';import {createTRPCProxyClient,httpLink}from'@trpc/client';import {AsyncLocalStorage}from'async_hooks';import {nanoid}from'nanoid';import g from'superjson';import w from'zod-to-json-schema';import {z as z$1}from'zod';var b=z$1.object({GUEST_SERVICES_URL:z$1.string().url().default("http://localhost:3000/trpc"),REALTIME_DOMAIN:z$1.string().default("localhost:3002"),BASE_URL:z$1.string().url().default("http://localhost:3001"),NODE_ENV:z$1.enum(["development","production","test"]).default("development")}),h=b.safeParse({GUEST_SERVICES_URL:process.env.GUEST_SERVICES_URL,REALTIME_DOMAIN:process.env.REALTIME_DOMAIN,BASE_URL:process.env.BASE_URL,NODE_ENV:process.env.NODE_ENV});if(!h.success)throw console.error("Invalid environment variables:",h.error.format()),new Error("Invalid environment variables");var c=h.data;var A=new AsyncLocalStorage,y=null,S=new Set,p=null;function r(){return y||(y=createTRPCProxyClient({transformer:g,links:[httpLink({url:c.GUEST_SERVICES_URL,headers:()=>{let t=T();if(!t)throw new Error("Missing request context");return {"x-request-id":t.requestId}}})]})),y}function T(){return A.getStore()}function k(t){let e=T();e&&Object.assign(e,t);}async function W(t,e){return A.run(t,e)}function E(t){throw new MissingAuthError({provider:t?.provider??"AC1",popup:true})}async function $(t){let n=await r().getCurrentUser.mutate(t);if(n?.error==="SEED")throw new Error('Call to "getUserId" in seed function is not allowed. Seed functions should not depend on user data.');if(!n?.userId){if(t?.throwIfNotLoggedIn??true)throw new MissingAuthError({provider:"AC1"});return null}return n.userId}async function Z(t){let n=await r().getCurrentUser.mutate({throwIfNotLoggedIn:t?.required});if(n?.error==="SEED")throw new Error('Call to "getAuth" in seed function is not allowed. Seed functions should not depend on user data.');if(n.userId)return {userId:n.userId,status:"authenticated",signIn:E,providers:n.providers};if(t?.required)throw new MissingAuthError({provider:"AC1"});return {userId:null,status:"unauthenticated",signIn:E,providers:[]}}async function K(t){let e=r(),n=await e.upsertTaskStatus.mutate({status:"RUNNING"});return S.add(n.id),k({hasTasks:true}),(async()=>{let o=n.id;try{await t(),await e.upsertTaskStatus.mutate({id:o,status:"COMPLETED"});}catch(s){console.error(`Task ${o} failed:`,s.message),await e.upsertTaskStatus.mutate({id:o,status:"FAILED",error:s});}finally{S.delete(n.id);}})(),n}async function z(t){return await r().getTaskStatus.mutate({id:t})}async function J(t){let e=r(),n={...t,schema:w(t.schema)};return await e.extractStructuredDataFromContent.mutate(n)}async function H(t){return await r().extractTextFromContent.mutate(t)}async function Q(t){let e=r(),{stream:n,onProgress:o,...s}=t,d={...s,returnType:w(t.returnType),customTools:t.customTools?.map(i=>({...i,inputSchema:w(i.inputSchema)}))};if(n??o){let i=nanoid(32),f=new WebSocket(`wss://${c.REALTIME_DOMAIN}/${i}`),x=-1,v=C=>{p=Date.now();try{let a=JSON.parse(C.data.toString());if(a?.id&&a.id>x){let R=g.parse(a.payload);a.requestAgentToolCalls instanceof Array?o?.(a.requestAgentToolCalls):n?.(R),x=a.id;}}catch{}};f.addEventListener("message",v);let I=await e.requestMultimodalModel.mutate({...d,realtimeChannelId:i});return n&&n(I),f.close(),f.removeEventListener("message",v),I}return await e.requestMultimodalModel.mutate(d)}async function X(t){return await r().textToImage.mutate(t)}async function Y(t){return await r().textToSpeech.mutate(t)}async function tt(t){return await r().generateSoundEffect.mutate(t)}async function et(t){return await r().generateDialogue.mutate(t)}async function nt(t){return await r().generateMusic.mutate(t)}async function rt(t){let e=r(),n;return typeof t.bufferOrBase64=="string"?n=t.bufferOrBase64:n=t.bufferOrBase64.toString("base64"),await e.uploadToBucket.mutate({base64:n,fileName:t.fileName})}async function ot(t){return await r().getOAuthToken.mutate({connectionId:t.connectionId})}async function st(t){let n=await r().getOAuthConnectionForCurrentUser.mutate({...t,scope:t.scope??[]});if(!n&&t.required)throw new MissingAuthError({provider:t.provider,scope:t.scope,popup:true});return n}async function it(t){return await r().getOAuthConnection.mutate(t)}async function at(t){return await r().queryOAuthConnections.mutate(t)}async function ut(t){return await r().deleteOAuthConnection.mutate(t)}async function ct(t){await r().sendEmail.mutate(t);}async function lt(t){let e=r();if(!t.email)throw new Error("Email is required");if(!t.markdown)throw new Error("`markdown` content is required when inviting by email");return await e.inviteUser.mutate(t)}async function dt(t){return await r().searchWithGoogle.mutate(t)}async function mt(){return await r().isAppOwner.mutate()}async function gt(t){return await r().generateCrossAppToken.mutate(t)}async function pt(t){return await r().createProduct.mutate(t)}async function ft(){return await r().listProducts.mutate()}async function ht(t){return await r().listUserPurchases.mutate(t)}async function yt(t){await r().discontinueProduct.mutate(t);}function wt({channelId:t,onUpdate:e}){let n=new WebSocket(`wss://${c.REALTIME_DOMAIN}/${t}`),o=-1;function s(d){e&&(p=Date.now());try{let u=JSON.parse(d.data.toString());if(u?.id&&u.id>o){let i=g.parse(u.payload);e?.(i),o=u.id;}}catch{}}return n.addEventListener("message",s),{destroy(){n.close(),n.removeEventListener("message",s);}}}async function P({channelId:t,data:e}){p=Date.now(),await fetch(`https://${c.REALTIME_DOMAIN}/${t}`,{method:"POST",body:g.stringify(e)}).catch(console.error);}async function Tt(){let t,e=T()?.channelId;if(!e)throw new Error("API's using `startRealtimeResponse` must be called via `useRealtimeMutation`.");return {next(n){t=n,P({channelId:e,data:n});},end(){return P({channelId:e,data:t}),t}}}async function xt(t){return await r().getTTSVoicesCatalog.mutate(t)}async function vt(t){return await r().getDialogueVoicesCatalog.mutate(t)}async function It(t){return await r().getImageModelsCatalog.mutate(t)}function St(){return c.BASE_URL}function Et(){return p}
2
- export{pt as createProduct,ut as deleteOAuthConnection,yt as discontinueProduct,H as extractTextFromContent,gt as generateCrossAppToken,et as generateDialogue,nt as generateMusic,tt as generateSoundEffect,Z as getAuth,St as getBaseUrl,vt as getDialogueVoicesCatalog,It as getImageModelsCatalog,Et as getLastStreamTime,it as getOAuthConnection,st as getOAuthConnectionForCurrentUser,ot as getOAuthToken,wt as getRealtimeStore,T as getRequestContext,J as getStructuredDataFromContent,xt as getTTSVoicesCatalog,z as getTaskStatus,$ as getUserId,lt as inviteUser,mt as isAppOwner,ft as listProducts,ht as listUserPurchases,at as queryOAuthConnections,K as queueTask,Q as requestMultimodalModel,W as runWithContext,dt as searchWithGoogle,ct as sendEmail,P as setRealtimeStore,k as setRequestContext,Tt as startRealtimeResponse,X as textToImage,Y as textToSpeech,rt as upload};
1
+ import {createTRPCProxyClient,httpLink}from'@trpc/client';import {AsyncLocalStorage}from'async_hooks';import {nanoid}from'nanoid';import S from'superjson';import U from'zod-to-json-schema';import {z}from'zod';function O(e){let t=Object.create(null);for(let r in e){let n=e[r];t[n]=r;}return t}var y={PARSE_ERROR:-32700,BAD_REQUEST:-32600,INTERNAL_SERVER_ERROR:-32603,NOT_IMPLEMENTED:-32603,UNAUTHORIZED:-32001,FORBIDDEN:-32003,NOT_FOUND:-32004,METHOD_NOT_SUPPORTED:-32005,TIMEOUT:-32008,CONFLICT:-32009,PRECONDITION_FAILED:-32012,PAYLOAD_TOO_LARGE:-32013,UNPROCESSABLE_CONTENT:-32022,TOO_MANY_REQUESTS:-32029,CLIENT_CLOSED_REQUEST:-32099};O(y);O(y);typeof window>"u"||"Deno"in window||globalThis.process?.env?.NODE_ENV==="test"||!!globalThis.process?.env?.JEST_WORKER_ID||!!globalThis.process?.env?.VITEST_WORKER_ID;var h=class e extends Error{static prefix="__MISSING AUTH FOR SCOPE";constructor({provider:t,scope:r,accountId:n,popup:o=false}){let s=btoa(JSON.stringify({provider:t,scope:r,accountId:n}));super(`${e.prefix}: ${s}${o?" --popup":" end"}`);}static check(t){return t?.message?.startsWith(e.prefix)}};var we=z.object({GUEST_SERVICES_URL:z.string().url().default("http://localhost:3000/trpc"),REALTIME_DOMAIN:z.string().default("localhost:3002"),BASE_URL:z.string().url().default("http://localhost:3001"),NODE_ENV:z.enum(["development","production","test"]).default("development")}),M=we.safeParse({GUEST_SERVICES_URL:process.env.GUEST_SERVICES_URL,REALTIME_DOMAIN:process.env.REALTIME_DOMAIN,BASE_URL:process.env.BASE_URL,NODE_ENV:process.env.NODE_ENV});if(!M.success)throw console.error("Invalid environment variables:",M.error.format()),new Error("Invalid environment variables");var _=M.data;var ee=new AsyncLocalStorage,F=null,J=new Set,v=null;function u(){return F||(F=createTRPCProxyClient({transformer:S,links:[httpLink({url:_.GUEST_SERVICES_URL,headers:()=>{let e=q();if(!e)throw new Error("Missing request context");return {"x-request-id":e.requestId}}})]})),F}function q(){return ee.getStore()}function _e(e){let t=q();t&&Object.assign(t,e);}async function et(e,t){return ee.run(e,t)}function Z(e){throw new h({provider:e?.provider??"AC1",popup:true})}async function tt(e){let r=await u().getCurrentUser.mutate(e);if(r?.error==="SEED")throw new Error('Call to "getUserId" in seed function is not allowed. Seed functions should not depend on user data.');if(!r?.userId){if(e?.throwIfNotLoggedIn??true)throw new h({provider:"AC1"});return null}return r.userId}async function rt(e){let r=await u().getCurrentUser.mutate({throwIfNotLoggedIn:e?.required});if(r?.error==="SEED")throw new Error('Call to "getAuth" in seed function is not allowed. Seed functions should not depend on user data.');if(r.userId)return {userId:r.userId,status:"authenticated",signIn:Z,providers:r.providers};if(e?.required)throw new h({provider:"AC1"});return {userId:null,status:"unauthenticated",signIn:Z,providers:[]}}async function nt(e){let t=u(),r=await t.upsertTaskStatus.mutate({status:"RUNNING"});return J.add(r.id),_e({hasTasks:true}),(async()=>{let n=r.id;try{await e(),await t.upsertTaskStatus.mutate({id:n,status:"COMPLETED"});}catch(o){console.error(`Task ${n} failed:`,o.message),await t.upsertTaskStatus.mutate({id:n,status:"FAILED",error:o});}finally{J.delete(r.id);}})(),r}async function ot(e){return await u().getTaskStatus.mutate({id:e})}async function st(e){let t=u(),r={...e,schema:U(e.schema)};return await t.extractStructuredDataFromContent.mutate(r)}async function it(e){return await u().extractTextFromContent.mutate(e)}async function at(e){let t=u(),{stream:r,onProgress:n,...o}=e,s={...o,returnType:U(e.returnType),customTools:e.customTools?.map(d=>({...d,inputSchema:U(d.inputSchema)}))};if(r??n){let d=nanoid(32),a=new WebSocket(`wss://${_.REALTIME_DOMAIN}/${d}`),l=-1,c=p=>{v=Date.now();try{let g=JSON.parse(p.data.toString());if(g?.id&&g.id>l){let te=S.parse(g.payload);g.requestAgentToolCalls instanceof Array?n?.(g.requestAgentToolCalls):r?.(te),l=g.id;}}catch{}};a.addEventListener("message",c);let m=await t.requestMultimodalModel.mutate({...s,realtimeChannelId:d});return r&&r(m),a.close(),a.removeEventListener("message",c),m}return await t.requestMultimodalModel.mutate(s)}async function ut(e){return await u().textToImage.mutate(e)}async function ct(e){return await u().textToSpeech.mutate(e)}async function dt(e){return await u().generateSoundEffect.mutate(e)}async function lt(e){return await u().generateDialogue.mutate(e)}async function ft(e){return await u().generateMusic.mutate(e)}async function pt(e){let t=u(),r;return typeof e.bufferOrBase64=="string"?r=e.bufferOrBase64:r=e.bufferOrBase64.toString("base64"),await t.uploadToBucket.mutate({base64:r,fileName:e.fileName})}async function mt(e){return await u().getOAuthToken.mutate({connectionId:e.connectionId})}async function gt(e){let r=await u().getOAuthConnectionForCurrentUser.mutate({...e,scope:e.scope??[]});if(!r&&e.required)throw new h({provider:e.provider,scope:e.scope,popup:true});return r}async function wt(e){return await u().getOAuthConnection.mutate(e)}async function ht(e){return await u().queryOAuthConnections.mutate(e)}async function yt(e){return await u().deleteOAuthConnection.mutate(e)}async function Et(e){await u().sendEmail.mutate(e);}async function Tt(e){let t=u();if(!e.email)throw new Error("Email is required");if(!e.markdown)throw new Error("`markdown` content is required when inviting by email");return await t.inviteUser.mutate(e)}async function _t(e){return await u().searchWithGoogle.mutate(e)}async function Rt(){return await u().isAppOwner.mutate()}async function Pt(e){return await u().generateCrossAppToken.mutate(e)}async function St(e){return await u().createProduct.mutate(e)}async function vt(){return await u().listProducts.mutate()}async function xt(e){return await u().listUserPurchases.mutate(e)}async function It(e){await u().discontinueProduct.mutate(e);}function Ot({channelId:e,onUpdate:t}){let r=new WebSocket(`wss://${_.REALTIME_DOMAIN}/${e}`),n=-1;function o(s){t&&(v=Date.now());try{let i=JSON.parse(s.data.toString());if(i?.id&&i.id>n){let d=S.parse(i.payload);t?.(d),n=i.id;}}catch{}}return r.addEventListener("message",o),{destroy(){r.close(),r.removeEventListener("message",o);}}}async function X({channelId:e,data:t}){v=Date.now(),await fetch(`https://${_.REALTIME_DOMAIN}/${e}`,{method:"POST",body:S.stringify(t)}).catch(console.error);}async function Ct(){let e,t=q()?.channelId;if(!t)throw new Error("API's using `startRealtimeResponse` must be called via `useRealtimeMutation`.");return {next(r){e=r,X({channelId:t,data:r});},end(){return X({channelId:t,data:e}),e}}}async function bt(e){return await u().getTTSVoicesCatalog.mutate(e)}async function At(e){return await u().getDialogueVoicesCatalog.mutate(e)}async function Nt(e){return await u().getImageModelsCatalog.mutate(e)}function Dt(){return _.BASE_URL}function kt(){return v}
2
+ export{St as createProduct,yt as deleteOAuthConnection,It as discontinueProduct,it as extractTextFromContent,Pt as generateCrossAppToken,lt as generateDialogue,ft as generateMusic,dt as generateSoundEffect,rt as getAuth,Dt as getBaseUrl,At as getDialogueVoicesCatalog,Nt as getImageModelsCatalog,kt as getLastStreamTime,wt as getOAuthConnection,gt as getOAuthConnectionForCurrentUser,mt as getOAuthToken,Ot as getRealtimeStore,q as getRequestContext,st as getStructuredDataFromContent,bt as getTTSVoicesCatalog,ot as getTaskStatus,tt as getUserId,Tt as inviteUser,Rt as isAppOwner,vt as listProducts,xt as listUserPurchases,ht as queryOAuthConnections,nt as queueTask,at as requestMultimodalModel,et as runWithContext,_t as searchWithGoogle,Et as sendEmail,X as setRealtimeStore,_e as setRequestContext,Ct as startRealtimeResponse,ut as textToImage,ct as textToSpeech,pt as upload};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adaptive-ai/sdk",
3
- "version": "0.0.1",
3
+ "version": "0.0.4",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "exports": {
@@ -63,8 +63,8 @@
63
63
  "tsup": "^8.2.4",
64
64
  "tsx": "^4.7.1",
65
65
  "typescript": "^5.8.2",
66
- "@ac1/iso": "0.1.1",
67
- "@ac1/core": "0.1.1"
66
+ "@ac1/core": "0.1.1",
67
+ "@ac1/iso": "0.1.1"
68
68
  },
69
69
  "publishConfig": {
70
70
  "access": "public"