logic-sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ai.ts ADDED
@@ -0,0 +1,84 @@
1
+ import { tool, type FlexibleSchema, type Tool } from "ai";
2
+ import { isDomainError, type Caller, type Fn, type FnIn, type FnOut, type Registry, type RegisteredFn } from "./index.ts";
3
+
4
+ type ExposedOf<T> = { [N in keyof T as T[N] extends Fn<any, any, any, true> ? N : never]: T[N] };
5
+ type UnionToIntersection<U> = (U extends unknown ? (u: U) => void : never) extends (i: infer I) => void ? I : never;
6
+
7
+ /** `{ bookings_confirm, pricing_priceStay, … }`: one AI SDK tool per exposed function, typed. */
8
+ export type AIToolsOf<Mods> = UnionToIntersection<
9
+ {
10
+ [M in keyof Mods & string]: {
11
+ [N in keyof ExposedOf<Mods[M]> & string as `${M}_${N}`]: Tool<
12
+ FnIn<Mods[M][N & keyof Mods[M]]>,
13
+ FnOut<Mods[M][N & keyof Mods[M]]>
14
+ >;
15
+ };
16
+ }[keyof Mods & string]
17
+ >;
18
+
19
+ export interface AIToolOptions {
20
+ /** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
21
+ onError?: (error: unknown) => void;
22
+ }
23
+ export interface AIToolsOptions extends AIToolOptions {
24
+ /**
25
+ * Which exposed functions an agent may call. Required: the agent door is opt-in, so a function exposed
26
+ * for your UI doesn't become a tool by accident. E.g. `(f) => f.fn.meta?.agent === true`.
27
+ */
28
+ filter: (fn: RegisteredFn) => boolean;
29
+ }
30
+
31
+ /**
32
+ * One exposed function as an AI SDK tool, run as `caller`: the agent goes through the same policy,
33
+ * validation, transaction and events as your HTTP API. You name it, like any AI SDK tool.
34
+ *
35
+ * ```ts
36
+ * const caller = registry.as(await scopeFrom(request));
37
+ * await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
38
+ * ```
39
+ *
40
+ * Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
41
+ * to `onError` and the model gets "internal_error", so internals never land in its context.
42
+ */
43
+ export function toAITool<F extends Fn<any, any, any, true>>(
44
+ caller: Caller<any>,
45
+ fn: F,
46
+ options: AIToolOptions = {},
47
+ ): Tool<FnIn<F>, FnOut<F>> {
48
+ const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
49
+ if (fn.expose !== true) throw new Error("[logic-sdk] toAITool needs a function with expose: true.");
50
+ return tool({
51
+ description: fn.description,
52
+ inputSchema: fn.inputSchema as FlexibleSchema,
53
+ outputSchema: fn.outputSchema as FlexibleSchema,
54
+ async execute(input) {
55
+ try {
56
+ return await caller.run(fn, input);
57
+ } catch (e) {
58
+ if (isDomainError(e)) throw e;
59
+ onError(e);
60
+ throw new Error("internal_error");
61
+ }
62
+ },
63
+ }) as Tool<FnIn<F>, FnOut<F>>;
64
+ }
65
+
66
+ /**
67
+ * The exposed functions your `filter` picks, as AI SDK tools named `<module>_<function>`.
68
+ *
69
+ * ```ts
70
+ * tools: toAITools(registry, caller, { filter: (f) => f.fn.meta?.agent === true })
71
+ * ```
72
+ */
73
+ export function toAITools<S extends object, Mods extends Record<string, object>>(
74
+ registry: Registry<S, Mods>,
75
+ caller: Caller<S>,
76
+ options: AIToolsOptions,
77
+ ): Partial<AIToolsOf<Mods>> {
78
+ if (typeof options?.filter !== "function")
79
+ throw new Error("[logic-sdk] toAITools needs a filter: the agent door is opt-in. E.g. { filter: (f) => f.fn.meta?.agent === true }");
80
+ const tools: Record<string, Tool> = {};
81
+ for (const f of registry.functions)
82
+ if (f.exposed && options.filter(f)) tools[`${f.module}_${f.name}`] = toAITool(caller, f.fn as Fn<any, any, any, true>, options);
83
+ return tools as Partial<AIToolsOf<Mods>>;
84
+ }
package/src/drizzle.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type { DatabaseAdapter } from "./index.ts";
2
+
3
+ /** Anything with Drizzle's `transaction(fn)`: a database or a transaction (nested = savepoint). */
4
+ interface Transactional {
5
+ transaction<T>(fn: (tx: any) => Promise<T>, config?: any): Promise<T>;
6
+ }
7
+
8
+ /** The transaction type of a Drizzle database: `type Tx = DrizzleTx<typeof db>`. */
9
+ export type DrizzleTx<Db extends Transactional> = Parameters<Parameters<Db["transaction"]>[0]>[0];
10
+
11
+ /** What queries get: the database minus write methods. A type-level guard, not a runtime one. */
12
+ export type DrizzleReader<Db> = Omit<
13
+ Db,
14
+ "insert" | "update" | "delete" | "execute" | "transaction" | "batch" | "run" | "refreshMaterializedView"
15
+ >;
16
+
17
+ /**
18
+ * Use a Drizzle database for mutations. Needs a driver with interactive transactions
19
+ * (node-postgres, postgres.js, PGlite, Neon websocket, Hyperdrive, better-sqlite3, libsql...).
20
+ * Not D1 or HTTP drivers.
21
+ */
22
+ export function drizzleAdapter<Db extends Transactional>(db: Db): DatabaseAdapter<Db, DrizzleTx<Db>> {
23
+ return {
24
+ db,
25
+ transactions: "interactive",
26
+ transaction: (fn) => db.transaction(fn),
27
+ nest: (tx) => drizzleAdapter(tx as Transactional) as any,
28
+ retryable: (e) => RETRYABLE.has(sqlState(e) ?? ""),
29
+ };
30
+ }
31
+
32
+ /** Postgres: serialization_failure, deadlock_detected. The transaction lost a race; running it again is the fix. */
33
+ const RETRYABLE = new Set(["40001", "40P01"]);
34
+
35
+ /** The SQLSTATE of a driver error, also when Drizzle wraps it (`DrizzleQueryError.cause`). Use it to map constraints. */
36
+ export function sqlState(error: unknown): string | undefined {
37
+ for (let e: any = error, i = 0; e && i < 5; e = e.cause, i++) if (typeof e.code === "string") return e.code;
38
+ return undefined;
39
+ }
package/src/fetch.ts ADDED
@@ -0,0 +1,82 @@
1
+ import { DomainError, isDomainError, type CallerOptions, type ErrorKind, type Registry } from "./index.ts";
2
+
3
+ /**
4
+ * Throw from `resolveScope` when this mount is session-only and there's no valid session: the client gets 401.
5
+ * For mounts that also serve public functions, return a scope with no actor instead, and let policies answer 403.
6
+ */
7
+ export const unauthenticated = (code = "unauthenticated", details?: unknown) =>
8
+ new DomainError("unauthenticated", code, details);
9
+
10
+ /** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
11
+ export const statusOf: Record<ErrorKind, number> = {
12
+ invalid: 400,
13
+ unauthenticated: 401,
14
+ forbidden: 403,
15
+ not_found: 404,
16
+ conflict: 409,
17
+ rejected: 422,
18
+ };
19
+
20
+ export interface FetchOptions<S extends object> {
21
+ /** Build the scope for this request (session → actor, account, locale...). */
22
+ resolveScope: (request: Request, ...rest: any[]) => S | Promise<S>;
23
+ /** Per-request caller options, e.g. `(req) => ({ signal: req.signal })`. */
24
+ callerOptions?: (request: Request, ...rest: any[]) => CallerOptions;
25
+ /** Mount point. Default "/". Functions live at `${basePath}${id}`, e.g. `/api/bookings.confirm`. */
26
+ basePath?: string;
27
+ /** Unexpected (non-domain) errors. Default: console.error. */
28
+ onError?: (error: unknown) => void;
29
+ }
30
+
31
+ const json = (body: unknown, status = 200) =>
32
+ new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
33
+
34
+ /**
35
+ * A web-standard handler (Workers, Bun, Node via Hono or srvx, SvelteKit, Next route handlers...).
36
+ * Publishes only functions with `expose: true`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
37
+ * queries also accept GET `?input=<json>`.
38
+ */
39
+ export function toFetchHandler<S extends object>(registry: Registry<S, any>, options: FetchOptions<S>) {
40
+ const base = (options.basePath ?? "/").replace(/\/?$/, "/");
41
+ const exposed = new Map(registry.functions.filter((f) => f.exposed).map((f) => [f.id, f]));
42
+ const onError = options.onError ?? ((e) => console.error("[logic-sdk] unexpected error", e));
43
+
44
+ return async (request: Request, ...rest: any[]): Promise<Response> => {
45
+ const path = new URL(request.url).pathname;
46
+ if (!path.startsWith(base)) return json({ error: { kind: "not_found", code: "route_not_found" } }, 404);
47
+ const id = path.slice(base.length);
48
+
49
+ const entry = exposed.get(id);
50
+ if (!entry) return json({ error: { kind: "not_found", code: "function_not_found" } }, 404);
51
+
52
+ let input: unknown;
53
+ try {
54
+ if (request.method === "POST") {
55
+ // JSON only: blocks cross-site "simple" form posts (CSRF) because they can't send this content type without a preflight
56
+ if (!(request.headers.get("content-type") ?? "").toLowerCase().startsWith("application/json"))
57
+ return json({ error: { kind: "invalid", code: "unsupported_media_type" } }, 415);
58
+ const text = await request.text();
59
+ input = text ? JSON.parse(text) : undefined;
60
+ } else if (request.method === "GET" && entry.kind === "query") {
61
+ const raw = new URL(request.url).searchParams.get("input");
62
+ input = raw ? JSON.parse(raw) : undefined;
63
+ } else {
64
+ const res = json({ error: { kind: "invalid", code: "method_not_allowed" } }, 405);
65
+ res.headers.set("allow", entry.kind === "query" ? "GET, POST" : "POST");
66
+ return res;
67
+ }
68
+ } catch {
69
+ return json({ error: { kind: "invalid", code: "malformed_json" } }, 400);
70
+ }
71
+
72
+ try {
73
+ const scope = await options.resolveScope(request, ...rest);
74
+ const caller = registry.as(scope, options.callerOptions?.(request, ...rest));
75
+ return json({ data: await caller.run(entry.fn, input) });
76
+ } catch (e) {
77
+ if (isDomainError(e)) return json({ error: { kind: e.kind, code: e.code, details: e.details } }, statusOf[e.kind]);
78
+ onError(e);
79
+ return json({ error: { kind: "internal", code: "internal_error" } }, 500);
80
+ }
81
+ };
82
+ }