@adaptive-ai/sdk 0.1.30 → 0.1.32
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/server/index.d.ts +104 -10
- package/dist/server/index.js +5 -5
- package/package.json +1 -1
package/dist/server/index.d.ts
CHANGED
|
@@ -1795,6 +1795,12 @@ declare function createErrorTracker({ environment, dbPath, }: {
|
|
|
1795
1795
|
logger?: Pick<Console, "error">;
|
|
1796
1796
|
}) => void;
|
|
1797
1797
|
};
|
|
1798
|
+
export type RequestContext = {
|
|
1799
|
+
requestId: string;
|
|
1800
|
+
channelId?: string;
|
|
1801
|
+
hasTasks?: boolean;
|
|
1802
|
+
};
|
|
1803
|
+
export declare function runWithContext<T>(context: RequestContext, fn: () => Promise<T>): Promise<T>;
|
|
1798
1804
|
export type QueueLogger = {
|
|
1799
1805
|
error: (...args: unknown[]) => void;
|
|
1800
1806
|
warn: (...args: unknown[]) => void;
|
|
@@ -1849,11 +1855,6 @@ export type SignInInput = {
|
|
|
1849
1855
|
} | {
|
|
1850
1856
|
redirectUri?: string;
|
|
1851
1857
|
};
|
|
1852
|
-
export type RequestContext = {
|
|
1853
|
-
requestId: string;
|
|
1854
|
-
channelId?: string;
|
|
1855
|
-
hasTasks?: boolean;
|
|
1856
|
-
};
|
|
1857
1858
|
export interface EmailHandlerInput {
|
|
1858
1859
|
subject: string;
|
|
1859
1860
|
body: string;
|
|
@@ -3283,6 +3284,96 @@ declare let client: {
|
|
|
3283
3284
|
ticketCount: number;
|
|
3284
3285
|
}>>;
|
|
3285
3286
|
};
|
|
3287
|
+
executeComposioTool: {
|
|
3288
|
+
mutate: _trpc_client.Resolver<_trpc_server.BuildProcedure<"mutation", {
|
|
3289
|
+
_config: _trpc_server.RootConfig<{
|
|
3290
|
+
ctx: {
|
|
3291
|
+
appId: string;
|
|
3292
|
+
versionId: string;
|
|
3293
|
+
appName: string;
|
|
3294
|
+
appSubdomain: string;
|
|
3295
|
+
userId: string;
|
|
3296
|
+
isTesting: boolean;
|
|
3297
|
+
rpcMethod: string;
|
|
3298
|
+
requestId: string;
|
|
3299
|
+
type?: undefined;
|
|
3300
|
+
dbUrl?: string | null | undefined;
|
|
3301
|
+
userIdActual?: string | null | undefined;
|
|
3302
|
+
channelId?: string | null | undefined;
|
|
3303
|
+
} | {
|
|
3304
|
+
type: "BOXMAN_REQUEST";
|
|
3305
|
+
boxId: string;
|
|
3306
|
+
isDevelopment: boolean | null;
|
|
3307
|
+
appId?: string | null | undefined;
|
|
3308
|
+
appFolder?: string | null | undefined;
|
|
3309
|
+
rpcMethod?: string | null | undefined;
|
|
3310
|
+
requestId?: string | null | undefined;
|
|
3311
|
+
channelId?: string | null | undefined;
|
|
3312
|
+
platformUserId?: string | null | undefined;
|
|
3313
|
+
invocationTrigger?: "user" | "scheduled" | null | undefined;
|
|
3314
|
+
agent?: string | null | undefined;
|
|
3315
|
+
sessionId?: string | null | undefined;
|
|
3316
|
+
pushToken?: string | null | undefined;
|
|
3317
|
+
};
|
|
3318
|
+
meta: object;
|
|
3319
|
+
errorShape: {
|
|
3320
|
+
data: {
|
|
3321
|
+
zodError: typeToFlattenedError<any, string> | null;
|
|
3322
|
+
code: _trpc_server_rpc.TRPC_ERROR_CODE_KEY;
|
|
3323
|
+
httpStatus: number;
|
|
3324
|
+
path?: string;
|
|
3325
|
+
stack?: string;
|
|
3326
|
+
};
|
|
3327
|
+
message: string;
|
|
3328
|
+
code: _trpc_server_rpc.TRPC_ERROR_CODE_NUMBER;
|
|
3329
|
+
};
|
|
3330
|
+
transformer: typeof superjson;
|
|
3331
|
+
}>;
|
|
3332
|
+
_meta: object;
|
|
3333
|
+
_ctx_out: {
|
|
3334
|
+
type: undefined;
|
|
3335
|
+
appId: string;
|
|
3336
|
+
versionId: string;
|
|
3337
|
+
dbUrl: string | null | undefined;
|
|
3338
|
+
appName: string;
|
|
3339
|
+
appSubdomain: string;
|
|
3340
|
+
userId: string;
|
|
3341
|
+
userIdActual: string | null | undefined;
|
|
3342
|
+
isTesting: boolean;
|
|
3343
|
+
rpcMethod: string;
|
|
3344
|
+
requestId: string;
|
|
3345
|
+
channelId: string | null | undefined;
|
|
3346
|
+
} | {
|
|
3347
|
+
type: "BOXMAN_REQUEST";
|
|
3348
|
+
appId: string | null | undefined;
|
|
3349
|
+
boxId: string;
|
|
3350
|
+
appFolder: string | null | undefined;
|
|
3351
|
+
rpcMethod: string | null | undefined;
|
|
3352
|
+
requestId: string | null | undefined;
|
|
3353
|
+
channelId: string | null | undefined;
|
|
3354
|
+
platformUserId: string | null | undefined;
|
|
3355
|
+
invocationTrigger: "user" | "scheduled" | null | undefined;
|
|
3356
|
+
isDevelopment: boolean | null;
|
|
3357
|
+
agent: string | null | undefined;
|
|
3358
|
+
sessionId: string | null | undefined;
|
|
3359
|
+
pushToken: string | null | undefined;
|
|
3360
|
+
};
|
|
3361
|
+
_input_in: {
|
|
3362
|
+
toolSlug: string;
|
|
3363
|
+
arguments: Record<string, unknown>;
|
|
3364
|
+
connectedAccountId: string;
|
|
3365
|
+
version: string;
|
|
3366
|
+
};
|
|
3367
|
+
_input_out: {
|
|
3368
|
+
toolSlug: string;
|
|
3369
|
+
arguments: Record<string, unknown>;
|
|
3370
|
+
connectedAccountId: string;
|
|
3371
|
+
version: string;
|
|
3372
|
+
};
|
|
3373
|
+
_output_in: typeof _trpc_server.unsetMarker;
|
|
3374
|
+
_output_out: typeof _trpc_server.unsetMarker;
|
|
3375
|
+
}, Record<string, unknown>>>;
|
|
3376
|
+
};
|
|
3286
3377
|
health: {
|
|
3287
3378
|
query: _trpc_client.Resolver<_trpc_server.BuildProcedure<"query", {
|
|
3288
3379
|
_config: _trpc_server.RootConfig<{
|
|
@@ -3455,6 +3546,7 @@ export type InitializeServerEnvironmentInput = {
|
|
|
3455
3546
|
realtimeDomain: string;
|
|
3456
3547
|
guestServicesUrl: string;
|
|
3457
3548
|
environment: string;
|
|
3549
|
+
apiKey?: string;
|
|
3458
3550
|
queueDbPath?: string;
|
|
3459
3551
|
errorsDbPath?: string;
|
|
3460
3552
|
};
|
|
@@ -3479,7 +3571,7 @@ export type HonoLikeContext<TRequestBody = unknown, TJsonResponse extends Respon
|
|
|
3479
3571
|
export type HonoRpcOptions = NonNullable<Parameters<typeof handleRpc>[2]>;
|
|
3480
3572
|
export type HonoMiddlewareNext = () => Promise<void>;
|
|
3481
3573
|
export type HonoMiddlewareHandler<TContext extends HonoLikeContext = HonoLikeContext> = (context: TContext, next: HonoMiddlewareNext) => Promise<Response | void>;
|
|
3482
|
-
export declare function initializeServerEnvironment<THandlers extends QueueHandlers>({ baseUrl, realtimeDomain, guestServicesUrl, environment, queueDbPath, errorsDbPath, }: InitializeServerEnvironmentInput): InitializedServerEnvironment<THandlers>;
|
|
3574
|
+
export declare function initializeServerEnvironment<THandlers extends QueueHandlers>({ baseUrl, realtimeDomain, guestServicesUrl, environment, queueDbPath, errorsDbPath, apiKey, }: InitializeServerEnvironmentInput): InitializedServerEnvironment<THandlers>;
|
|
3483
3575
|
export declare function getErrorTracker(): {
|
|
3484
3576
|
captureClientLog: ({ body, requestId, }: {
|
|
3485
3577
|
body: string;
|
|
@@ -3519,13 +3611,15 @@ export type MCPBase = MutationProxy<typeof client>;
|
|
|
3519
3611
|
export type PromptAgentStrictInput = Omit<Parameters<MCPBase["promptAgent"]>[0], "outputJsonSchema"> & {
|
|
3520
3612
|
outputJsonSchema: object;
|
|
3521
3613
|
};
|
|
3522
|
-
export type
|
|
3614
|
+
export type AllMCP = Omit<MCPBase, "promptAgent"> & {
|
|
3523
3615
|
promptAgent: (args: PromptAgentStrictInput) => ReturnType<MCPBase["promptAgent"]>;
|
|
3524
3616
|
};
|
|
3617
|
+
export type MCP = Omit<AllMCP, "executeComposioTool">;
|
|
3525
3618
|
export declare const mcp: MCP;
|
|
3526
|
-
export
|
|
3527
|
-
|
|
3528
|
-
|
|
3619
|
+
export type ExecuteComposioToolBaseInput<Args extends {}> = Omit<Parameters<AllMCP["executeComposioTool"]>[0], "arguments"> & {
|
|
3620
|
+
arguments: Args;
|
|
3621
|
+
};
|
|
3622
|
+
export declare function executeComposioTool<Input extends ExecuteComposioToolBaseInput<{}> = never>(input: NoInfer<Input>): Promise<Record<string, unknown>>;
|
|
3529
3623
|
export declare function getBaseUrl(): string;
|
|
3530
3624
|
export declare function getLastStreamTime(): number | null;
|
|
3531
3625
|
export declare function getRealtimeStore<T extends object>({ channelId, onUpdate, }: {
|
package/dist/server/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {z}from'zod';import {createTRPCProxyClient,httpLink}from'@trpc/client';import
|
|
1
|
+
import {z}from'zod';import {createTRPCProxyClient,httpLink}from'@trpc/client';import P from'superjson';import {handleRpc}from'typed-rpc/server';import {inspect}from'util';import {AsyncLocalStorage}from'async_hooks';import ke from'better-sqlite3';import {better,defineQueue,defineWorker,JobStatus}from'plainjob';var le={GITHUB_USER:"GITHUB_USER",GITHUB_BOT:"GITHUB_BOT",GOOGLE:"GOOGLE",SLACK:"SLACK",SLACK_BOT:"SLACK_BOT",DISCORD:"DISCORD",NOTION:"NOTION",TWITTER:"TWITTER",LINKEDIN:"LINKEDIN",YAHOO:"YAHOO",FIGMA:"FIGMA",PLAID:"PLAID",SQUARE:"SQUARE",SHOPIFY:"SHOPIFY",WHOOP:"WHOOP"},C={...le,AC1:"AC1"};var fe=z.object({slug:z.string(),name:z.string().optional(),schedule:z.string(),description:z.string().optional(),rpcEndpoint:z.string(),isEnabled:z.boolean().default(true),stopAt:z.string().datetime().optional(),maxExecutions:z.number().optional(),timezone:z.string().optional()}),$=z.string().refine(e=>/^[a-zA-Z0-9_]+$/.test(e),"Must be a valid identifier (letters, numbers, and underscores only)."),me=z.object({handler:$,provider:z.nativeEnum(C).nullish()}),ge=z.object({provider:z.nativeEnum(C),event:z.string().min(1),handler:$}),Ee=z.object({crons:z.array(fe),events:z.array(ge).default([]),webhooks:z.array(me).default([])});function N(e){let r=Object.create(null);for(let t in e){let o=e[t];r[o]=t;}return r}var _={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};N(_);N(_);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 S=class e extends Error{static prefix="__MISSING AUTH FOR SCOPE";static jsonRpcCode=-32001;constructor({provider:r,scope:t,accountId:o,popup:n=false}){let s=btoa(JSON.stringify({provider:r,scope:t,accountId:o}));super(`${e.prefix}: ${s}${n?" --popup":" end"}`);}jsonRpcError(){return {code:e.jsonRpcCode,message:this.message}}static check(r){return r?.message?.startsWith(e.prefix)}};var oe=new AsyncLocalStorage;function F(){return oe.getStore()}async function se(e,r){return oe.run(e,r)}function ie({environment:e,dbPath:r="errors.db"}){let t=new ke(r,{fileMustExist:false});t.pragma("journal_mode = WAL"),t.exec(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS error_logs (
|
|
3
3
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
4
4
|
environment TEXT NOT NULL,
|
|
@@ -15,12 +15,12 @@ import {z}from'zod';import {createTRPCProxyClient,httpLink}from'@trpc/client';im
|
|
|
15
15
|
`);let o=t.prepare(`
|
|
16
16
|
INSERT INTO error_logs (environment, source, message, stack, metadata, request_id)
|
|
17
17
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
18
|
-
`),n=false;function s(
|
|
18
|
+
`),n=false;function s(d){o.run(e,d.source,d.message,d.stack??null,d.metadata?JSON.stringify(d.metadata):null,d.requestId??null);}function i(d=5){return t.prepare(`
|
|
19
19
|
SELECT COUNT(*) as count FROM error_logs
|
|
20
20
|
WHERE created_at > unixepoch() - ?
|
|
21
|
-
`).get(
|
|
21
|
+
`).get(d*60).count>0}function c(d=50){return t.prepare(`
|
|
22
22
|
SELECT * FROM error_logs
|
|
23
23
|
ORDER BY created_at DESC
|
|
24
24
|
LIMIT ?
|
|
25
|
-
`).all(
|
|
26
|
-
export{
|
|
25
|
+
`).all(d)}function a({body:d,requestId:p}){let E=d,m,h;try{let y=JSON.parse(d);E=y.message??d,m=y.stack,h=y.metadata;}catch{}let f=E.startsWith("[console.warn]")||E.startsWith("[console.error]");return f&&s({source:"client",message:E,stack:m,metadata:h,requestId:p}),{message:E,persisted:f}}function u({result:d,requestId:p}){let m=d.json?.error;return m?(s({source:"server",message:m.message??"Unknown RPC error",stack:m.stack,requestId:p,metadata:m.data?{errorData:m.data}:void 0}),true):false}function l({logger:d=console}={}){n||(process.on("uncaughtException",p=>{s({source:"server",message:p.message,stack:p.stack,metadata:{type:"uncaughtException"}}),d.error("Uncaught exception:",p);}),process.on("unhandledRejection",p=>{s({source:"server",message:p instanceof Error?p.message:String(p),stack:p instanceof Error?p.stack:void 0,metadata:{type:"unhandledRejection"}}),d.error("Unhandled rejection:",p);}),n=true);}return {captureClientLog:a,captureRpcError:u,getRecentErrors:c,hasErrors:i,logError:s,registerProcessHandlers:l}}var Le={error:console.error.bind(console),warn:console.warn.bind(console),info:()=>{},debug:()=>{}};function j(e){try{return JSON.parse(e.data)}catch{return null}}function ae({dbPath:e,handlers:r,errorTracker:t,queueName:o="default",logger:n=Le}){let s=new ke(e,{fileMustExist:false});s.pragma("journal_mode = WAL");let i=better(s),c=defineQueue({connection:i}),a=new Proxy({},{get(m,h){return f=>c.add(o,{action:h,payload:f})}});function u(m){return c.getJobById(m)}function l(){return c.countJobs({status:JobStatus.Processing})}function d(){return c.countJobs({status:JobStatus.Pending})}function p(){return {pending:c.countJobs({status:JobStatus.Pending}),processing:c.countJobs({status:JobStatus.Processing}),done:c.countJobs({status:JobStatus.Done}),failed:c.countJobs({status:JobStatus.Failed})}}function E(){let m=defineWorker(o,async h=>{let f=j(h);if(!f)throw new Error(`Failed to parse queue payload for job ${h.id}`);let y=r[f.action];if(!y)throw new Error(`No handler registered for action: ${f.action}`);console.log(`Processing job ${h.id} with action: ${f.action}`),await y(f.payload,h);},{queue:c,logger:n,onCompleted:h=>{let y=j(h)?.action??"unknown";console.log(`Job ${h.id} completed: ${y}`);},onFailed:(h,f)=>{let y=j(h);t?.logError({source:"worker",message:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0,metadata:{jobId:h.id,action:y?.action}}),console.error(`Job ${h.id} failed: ${y?.action??"unknown"}`,f);}});return m.start(),m}return {getActiveJobCount:l,getJob:u,getJobCounts:p,getPendingJobCount:d,queue:a,startWorker:E}}var J=createTRPCProxyClient({transformer:P,links:[]}),w;function Dr({baseUrl:e,realtimeDomain:r,guestServicesUrl:t,environment:o,queueDbPath:n,errorsDbPath:s,apiKey:i}){return globalThis.env||(globalThis.env={},globalThis.env.BASE_URL=e,globalThis.env.REALTIME_DOMAIN=r,globalThis.env.GUEST_SERVICES_URL=t,J=createTRPCProxyClient({transformer:P,links:[httpLink({url:t,transformer:P,headers:()=>{let c=F();return {...c?.requestId?{"x-request-id":c.requestId}:{},...i?{"x-boxman-api-key":i}:{},"x-boxman-app-base-url":e}}})]}),console.log("Adaptive SDK server environment initialized")),w?(w.environment=o,w.queueDbPath=n,w.errorsDbPath=s):w={environment:o,queueDbPath:n,errorsDbPath:s},w}function I(){if(!w)throw new Error("Adaptive SDK server environment is not initialized. Please call initializeServerEnvironment first.");return w}function pe(){let e=I();!e.errorTracker&&e.errorsDbPath&&(e.errorTracker=ie({environment:e.environment,dbPath:e.errorsDbPath}),e.errorTracker.registerProcessHandlers());let{errorTracker:r}=e;if(!r)throw new Error("Adaptive SDK error tracking is not initialized. Pass `errorsDbPath` to initializeServerEnvironment first.");return r}function je({handlers:e,queueName:r,logger:t,autoStartWorker:o=true}){let n=I();if(!n.queue){if(!n.queueDbPath)throw new Error("Adaptive SDK queue is not initialized. Pass `queueDbPath` to initializeServerEnvironment first.");n.queue=ae({dbPath:n.queueDbPath,handlers:e,queueName:r,logger:t,errorTracker:n.errorsDbPath?pe():void 0});}o&&!n.queueWorkerStarted&&(n.queue.startWorker(),n.queueWorkerStarted=true);let{queue:s}=n;if(!s)throw new Error("Adaptive SDK queue is not initialized. Pass `queueDbPath` to initializeServerEnvironment first.");return s}function qr(){return new Proxy({},{get(e,r){let t=I();if(!t.queue)throw new Error("Adaptive SDK queue is not initialized. Pass `queueDbPath` to initializeServerEnvironment first.");return r==="getJob"?t.queue.getJob:t.queue.queue[r]}})}function Q(e,r){return r.endsWith("*")?e.startsWith(r.slice(0,-1)):e===r}function Hr({procedures:e,jobs:r,transcoder:t,rpcPath:o="/api/*",loggerPath:n="/_logger",queueStatusPath:s="/_queue/status"}){let i=I(),c=i.errorsDbPath?pe():void 0,a=r&&i.queueDbPath?je({handlers:r}):void 0;return async(u,l)=>{let d=new URL(u.req.url).pathname;if(n&&c&&u.req.method==="POST"&&Q(d,n)){let p=await u.req.text(),E=u.req.header("x-request-id"),{message:m}=c.captureClientLog({body:p,requestId:E??void 0});return console.log("[browser]",m),u.json({status:"ok"})}if(s&&a&&u.req.method==="GET"&&Q(d,s))return u.json({activeJobs:a.getActiveJobCount(),pendingJobs:a.getPendingJobCount()});if(u.req.method==="POST"&&Q(d,o)){let p=await u.req.json(),E=u.req.header("x-request-id"),m=u.req.header("x-channel-id");E||console.warn("Request is missing x-request-id header. Adaptive AI SDK relies on this for request context."),console.log(`[${E}] Starting request ${u.req.method} ${u.req.url}`),m&&console.log(`[${E}] Channel ID: ${m}`);let f=await se({requestId:E??"unknown-request-id",channelId:m,hasTasks:false},async()=>await handleRpc(p,e,{transcoder:t}));return console.log(`[${E}] Response:`,inspect(f,{depth:3,colors:true})),c?.captureRpcError({result:f,requestId:E??void 0}),u.json(f)}await l();}}var Qe=new Proxy({},{get(e,r){return async t=>{if(globalThis.env===void 0)throw new Error("Adaptive SDK server environment is not initialized. Please call initializeServerEnvironment first.");let n=J[r];if(!n||typeof n.mutate!="function")throw new Error(`Property "${String(r)}" is not a mutation procedure`);return n.mutate(t)}}});async function Lr(e){return await J.executeComposioTool.mutate(e)}function Mr(){return globalThis.env.BASE_URL}var B=null;function Ur(){return B}function Fr({channelId:e,onUpdate:r}){let t=new WebSocket(`wss://${globalThis.env.REALTIME_DOMAIN}/${e}`),o=-1;function n(s){r&&(B=Date.now());try{let i=JSON.parse(s.data.toString());if(i?.id&&i.id>o){let c=P.parse(i.payload);r?.(c),o=i.id;}}catch{}}return t.addEventListener("message",n),{destroy(){t.close(),t.removeEventListener("message",n);}}}async function ue({channelId:e,data:r}){B=Date.now(),await fetch(`https://${globalThis.env.REALTIME_DOMAIN}/${e}`,{method:"POST",body:P.stringify(r)}).catch(console.error);}async function jr(){let e,r=F()?.channelId;if(!r)throw new Error("API's using `startRealtimeResponse` must be called via `useRealtimeMutation`.");return {next(t){e=t,ue({channelId:r,data:t});},end(){return ue({channelId:r,data:e}),e}}}function ce(e){throw new S({provider:"AC1",popup:true})}async function Qr(e){let r=await Qe.getCurrentUser();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:ce,providers:r.providers};if(e?.required)throw new S({provider:"AC1"});return {userId:null,status:"unauthenticated",signIn:ce,providers:[]}}
|
|
26
|
+
export{Ee as appConfigSchema,Lr as executeComposioTool,Qr as getAuth,Mr as getBaseUrl,pe as getErrorTracker,Ur as getLastStreamTime,qr as getQueue,Fr as getRealtimeStore,Hr as honoMiddleware,Dr as initializeServerEnvironment,Qe as mcp,se as runWithContext,ue as setRealtimeStore,jr as startRealtimeResponse};
|