@adaptive-ai/sdk 0.1.30 → 0.1.31
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 +8 -9
- 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;
|
|
@@ -3455,6 +3456,7 @@ export type InitializeServerEnvironmentInput = {
|
|
|
3455
3456
|
realtimeDomain: string;
|
|
3456
3457
|
guestServicesUrl: string;
|
|
3457
3458
|
environment: string;
|
|
3459
|
+
apiKey?: string;
|
|
3458
3460
|
queueDbPath?: string;
|
|
3459
3461
|
errorsDbPath?: string;
|
|
3460
3462
|
};
|
|
@@ -3479,7 +3481,7 @@ export type HonoLikeContext<TRequestBody = unknown, TJsonResponse extends Respon
|
|
|
3479
3481
|
export type HonoRpcOptions = NonNullable<Parameters<typeof handleRpc>[2]>;
|
|
3480
3482
|
export type HonoMiddlewareNext = () => Promise<void>;
|
|
3481
3483
|
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>;
|
|
3484
|
+
export declare function initializeServerEnvironment<THandlers extends QueueHandlers>({ baseUrl, realtimeDomain, guestServicesUrl, environment, queueDbPath, errorsDbPath, apiKey, }: InitializeServerEnvironmentInput): InitializedServerEnvironment<THandlers>;
|
|
3483
3485
|
export declare function getErrorTracker(): {
|
|
3484
3486
|
captureClientLog: ({ body, requestId, }: {
|
|
3485
3487
|
body: string;
|
|
@@ -3523,9 +3525,6 @@ export type MCP = Omit<MCPBase, "promptAgent"> & {
|
|
|
3523
3525
|
promptAgent: (args: PromptAgentStrictInput) => ReturnType<MCPBase["promptAgent"]>;
|
|
3524
3526
|
};
|
|
3525
3527
|
export declare const mcp: MCP;
|
|
3526
|
-
export declare function getRequestContext(): RequestContext | undefined;
|
|
3527
|
-
export declare function setRequestContext(context: Partial<RequestContext>): void;
|
|
3528
|
-
export declare function runWithContext<T>(context: RequestContext, fn: () => Promise<T>): Promise<T>;
|
|
3529
3528
|
export declare function getBaseUrl(): string;
|
|
3530
3529
|
export declare function getLastStreamTime(): number | null;
|
|
3531
3530
|
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 x=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 ne=new AsyncLocalStorage;function F(){return ne.getStore()}async function oe(e,r){return ne.run(e,r)}function se({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 ie({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 de=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,de=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=se({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=ie({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 oe({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=de[r];if(!n||typeof n.mutate!="function")throw new Error(`Property "${String(r)}" is not a mutation procedure`);return n.mutate(t)}}});function Lr(){return globalThis.env.BASE_URL}var J=null;function Mr(){return J}function Ur({channelId:e,onUpdate:r}){let t=new WebSocket(`wss://${globalThis.env.REALTIME_DOMAIN}/${e}`),o=-1;function n(s){r&&(J=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 ae({channelId:e,data:r}){J=Date.now(),await fetch(`https://${globalThis.env.REALTIME_DOMAIN}/${e}`,{method:"POST",body:P.stringify(r)}).catch(console.error);}async function Fr(){let e,r=F()?.channelId;if(!r)throw new Error("API's using `startRealtimeResponse` must be called via `useRealtimeMutation`.");return {next(t){e=t,ae({channelId:r,data:t});},end(){return ae({channelId:r,data:e}),e}}}function ue(e){throw new x({provider:"AC1",popup:true})}async function jr(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:ue,providers:r.providers};if(e?.required)throw new x({provider:"AC1"});return {userId:null,status:"unauthenticated",signIn:ue,providers:[]}}
|
|
26
|
+
export{Ee as appConfigSchema,jr as getAuth,Lr as getBaseUrl,pe as getErrorTracker,Mr as getLastStreamTime,qr as getQueue,Ur as getRealtimeStore,Hr as honoMiddleware,Dr as initializeServerEnvironment,Qe as mcp,oe as runWithContext,ae as setRealtimeStore,Fr as startRealtimeResponse};
|