@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.
@@ -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, }: {
@@ -1,4 +1,4 @@
1
- import {z}from'zod';import {createTRPCProxyClient,httpLink}from'@trpc/client';import {AsyncLocalStorage}from'async_hooks';import x from'superjson';import {handleRpc}from'typed-rpc/server';import {inspect}from'util';import Ce 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 pe=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)."),fe=z.object({handler:$,provider:z.nativeEnum(C).nullish()}),me=z.object({provider:z.nativeEnum(C),event:z.string().min(1),handler:$}),ge=z.object({crons:z.array(pe),events:z.array(me).default([]),webhooks:z.array(fe).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 P=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)}};function ne({environment:e,dbPath:r="errors.db"}){let t=new Ce(r,{fileMustExist:false});t.pragma("journal_mode = WAL"),t.exec(`
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(c){o.run(e,c.source,c.message,c.stack??null,c.metadata?JSON.stringify(c.metadata):null,c.requestId??null);}function i(c=5){return t.prepare(`
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(c*60).count>0}function l(c=50){return t.prepare(`
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(c)}function a({body:c,requestId:d}){let E=c,m,h;try{let w=JSON.parse(c);E=w.message??c,m=w.stack,h=w.metadata;}catch{}let f=E.startsWith("[console.warn]")||E.startsWith("[console.error]");return f&&s({source:"client",message:E,stack:m,metadata:h,requestId:d}),{message:E,persisted:f}}function u({result:c,requestId:d}){let m=c.json?.error;return m?(s({source:"server",message:m.message??"Unknown RPC error",stack:m.stack,requestId:d,metadata:m.data?{errorData:m.data}:void 0}),true):false}function p({logger:c=console}={}){n||(process.on("uncaughtException",d=>{s({source:"server",message:d.message,stack:d.stack,metadata:{type:"uncaughtException"}}),c.error("Uncaught exception:",d);}),process.on("unhandledRejection",d=>{s({source:"server",message:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0,metadata:{type:"unhandledRejection"}}),c.error("Unhandled rejection:",d);}),n=true);}return {captureClientLog:a,captureRpcError:u,getRecentErrors:l,hasErrors:i,logError:s,registerProcessHandlers:p}}var qe={error:console.error.bind(console),warn:console.warn.bind(console),info:()=>{},debug:()=>{}};function F(e){try{return JSON.parse(e.data)}catch{return null}}function oe({dbPath:e,handlers:r,errorTracker:t,queueName:o="default",logger:n=qe}){let s=new Ce(e,{fileMustExist:false});s.pragma("journal_mode = WAL");let i=better(s),l=defineQueue({connection:i}),a=new Proxy({},{get(m,h){return f=>l.add(o,{action:h,payload:f})}});function u(m){return l.getJobById(m)}function p(){return l.countJobs({status:JobStatus.Processing})}function c(){return l.countJobs({status:JobStatus.Pending})}function d(){return {pending:l.countJobs({status:JobStatus.Pending}),processing:l.countJobs({status:JobStatus.Processing}),done:l.countJobs({status:JobStatus.Done}),failed:l.countJobs({status:JobStatus.Failed})}}function E(){let m=defineWorker(o,async h=>{let f=F(h);if(!f)throw new Error(`Failed to parse queue payload for job ${h.id}`);let w=r[f.action];if(!w)throw new Error(`No handler registered for action: ${f.action}`);console.log(`Processing job ${h.id} with action: ${f.action}`),await w(f.payload,h);},{queue:l,logger:n,onCompleted:h=>{let w=F(h)?.action??"unknown";console.log(`Job ${h.id} completed: ${w}`);},onFailed:(h,f)=>{let w=F(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:w?.action}}),console.error(`Job ${h.id} failed: ${w?.action??"unknown"}`,f);}});return m.start(),m}return {getActiveJobCount:p,getJob:u,getJobCounts:d,getPendingJobCount:c,queue:a,startWorker:E}}var ue=createTRPCProxyClient({transformer:x,links:[]}),y;function kr({baseUrl:e,realtimeDomain:r,guestServicesUrl:t,environment:o,queueDbPath:n,errorsDbPath:s}){return globalThis.env||(globalThis.env={},globalThis.env.BASE_URL=e,globalThis.env.REALTIME_DOMAIN=r,globalThis.env.GUEST_SERVICES_URL=t,ue=createTRPCProxyClient({transformer:x,links:[httpLink({url:t,transformer:x,headers:()=>{let i=Q();if(!i)throw new Error("Missing request context");return {"x-request-id":i.requestId}}})]}),console.log("Adaptive SDK server environment initialized")),y?(y.environment=o,y.queueDbPath=n,y.errorsDbPath=s):y={environment:o,queueDbPath:n,errorsDbPath:s},y}function I(){if(!y)throw new Error("Adaptive SDK server environment is not initialized. Please call initializeServerEnvironment first.");return y}function ce(){let e=I();!e.errorTracker&&e.errorsDbPath&&(e.errorTracker=ne({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 Fe({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=oe({dbPath:n.queueDbPath,handlers:e,queueName:r,logger:t,errorTracker:n.errorsDbPath?ce():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 Nr(){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 j(e,r){return r.endsWith("*")?e.startsWith(r.slice(0,-1)):e===r}function Dr({procedures:e,jobs:r,transcoder:t,rpcPath:o="/api/*",loggerPath:n="/_logger",queueStatusPath:s="/_queue/status"}){let i=I(),l=i.errorsDbPath?ce():void 0,a=r&&i.queueDbPath?Fe({handlers:r}):void 0;return async(u,p)=>{let c=new URL(u.req.url).pathname;if(n&&l&&u.req.method==="POST"&&j(c,n)){let d=await u.req.text(),E=u.req.header("x-request-id"),{message:m}=l.captureClientLog({body:d,requestId:E??void 0});return console.log("[browser]",m),u.json({status:"ok"})}if(s&&a&&u.req.method==="GET"&&j(c,s))return u.json({activeJobs:a.getActiveJobCount(),pendingJobs:a.getPendingJobCount()});if(u.req.method==="POST"&&j(c,o)){let d=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 Qe({requestId:E??"unknown-request-id",channelId:m,hasTasks:false},async()=>await handleRpc(d,e,{transcoder:t}));return console.log(`[${E}] Response:`,inspect(f,{depth:3,colors:true})),l?.captureRpcError({result:f,requestId:E??void 0}),u.json(f)}await p();}}var de=new AsyncLocalStorage,je=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=ue[r];if(!n||typeof n.mutate!="function")throw new Error(`Property "${String(r)}" is not a mutation procedure`);return n.mutate(t)}}});function Q(){return de.getStore()}function qr(e){let r=Q();r&&Object.assign(r,e);}async function Qe(e,r){return de.run(e,r)}function Hr(){return globalThis.env.BASE_URL}var J=null;function Lr(){return J}function Mr({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 l=x.parse(i.payload);r?.(l),o=i.id;}}catch{}}return t.addEventListener("message",n),{destroy(){t.close(),t.removeEventListener("message",n);}}}async function se({channelId:e,data:r}){J=Date.now(),await fetch(`https://${globalThis.env.REALTIME_DOMAIN}/${e}`,{method:"POST",body:x.stringify(r)}).catch(console.error);}async function Ur(){let e,r=Q()?.channelId;if(!r)throw new Error("API's using `startRealtimeResponse` must be called via `useRealtimeMutation`.");return {next(t){e=t,se({channelId:r,data:t});},end(){return se({channelId:r,data:e}),e}}}function ie(e){throw new P({provider:"AC1",popup:true})}async function Fr(e){let r=await je.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:ie,providers:r.providers};if(e?.required)throw new P({provider:"AC1"});return {userId:null,status:"unauthenticated",signIn:ie,providers:[]}}
26
- export{ge as appConfigSchema,Fr as getAuth,Hr as getBaseUrl,ce as getErrorTracker,Lr as getLastStreamTime,Nr as getQueue,Mr as getRealtimeStore,Q as getRequestContext,Dr as honoMiddleware,kr as initializeServerEnvironment,je as mcp,Qe as runWithContext,se as setRealtimeStore,qr as setRequestContext,Ur as startRealtimeResponse};
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adaptive-ai/sdk",
3
- "version": "0.1.30",
3
+ "version": "0.1.31",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "exports": {