logic-sdk 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +126 -2
- package/bin/logic-sdk.js +14 -0
- package/dist/ai.d.ts +32 -0
- package/dist/ai.js +39 -0
- package/dist/drizzle.d.ts +18 -0
- package/dist/drizzle.js +23 -0
- package/dist/fetch.d.ts +20 -0
- package/dist/fetch.js +68 -0
- package/dist/index.d.ts +440 -0
- package/dist/index.js +374 -0
- package/dist/orpc.d.ts +31 -0
- package/dist/orpc.js +46 -0
- package/dist/testing.d.ts +29 -0
- package/dist/testing.js +61 -0
- package/package.json +106 -4
- package/src/ai.ts +64 -0
- package/src/drizzle.ts +39 -0
- package/src/fetch.ts +81 -0
- package/src/index.ts +719 -0
- package/src/orpc.ts +65 -0
- package/src/testing.ts +88 -0
package/src/ai.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
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 AIToolsOptions {
|
|
20
|
+
/** Keep only some exposed functions, e.g. `(f) => f.fn.meta?.agent !== false`. */
|
|
21
|
+
filter?: (fn: RegisteredFn) => boolean;
|
|
22
|
+
/** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
|
|
23
|
+
onError?: (error: unknown) => void;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Exposed functions as AI SDK tools, run as `caller`: an agent goes through the same policies,
|
|
28
|
+
* validation, transactions and events as your HTTP API. Tool names are `<module>_<function>`.
|
|
29
|
+
*
|
|
30
|
+
* ```ts
|
|
31
|
+
* const caller = registry.as(await scopeFrom(request));
|
|
32
|
+
* await generateText({ model, tools: toAITools(registry, caller), prompt });
|
|
33
|
+
* ```
|
|
34
|
+
*
|
|
35
|
+
* Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
|
|
36
|
+
* to `onError` and the model gets "internal_error", so internals never land in its context.
|
|
37
|
+
*/
|
|
38
|
+
export function toAITools<S extends object, Mods extends Record<string, object>>(
|
|
39
|
+
registry: Registry<S, Mods>,
|
|
40
|
+
caller: Caller<S>,
|
|
41
|
+
options: AIToolsOptions = {},
|
|
42
|
+
): AIToolsOf<Mods> {
|
|
43
|
+
const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
|
|
44
|
+
const tools: Record<string, Tool> = {};
|
|
45
|
+
|
|
46
|
+
for (const f of registry.functions) {
|
|
47
|
+
if (!f.exposed || (options.filter && !options.filter(f))) continue;
|
|
48
|
+
tools[`${f.module}_${f.name}`] = tool({
|
|
49
|
+
description: f.fn.description,
|
|
50
|
+
inputSchema: f.fn.inputSchema as FlexibleSchema,
|
|
51
|
+
outputSchema: f.fn.outputSchema as FlexibleSchema,
|
|
52
|
+
async execute(input) {
|
|
53
|
+
try {
|
|
54
|
+
return await caller.run(f.fn, input);
|
|
55
|
+
} catch (e) {
|
|
56
|
+
if (isDomainError(e)) throw e;
|
|
57
|
+
onError(e);
|
|
58
|
+
throw new Error("internal_error");
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
return tools as AIToolsOf<Mods>;
|
|
64
|
+
}
|
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,81 @@
|
|
|
1
|
+
import { isDomainError, type CallerOptions, type ErrorKind, type Registry } from "./index.ts";
|
|
2
|
+
|
|
3
|
+
/** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
|
|
4
|
+
export const statusOf: Record<ErrorKind, number> = {
|
|
5
|
+
invalid: 400,
|
|
6
|
+
unauthenticated: 401,
|
|
7
|
+
forbidden: 403,
|
|
8
|
+
not_found: 404,
|
|
9
|
+
conflict: 409,
|
|
10
|
+
rejected: 422,
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export interface FetchOptions<S extends object> {
|
|
14
|
+
/** Build the scope for this request (session → actor, account, locale...). */
|
|
15
|
+
resolveScope: (request: Request, ...rest: any[]) => S | Promise<S>;
|
|
16
|
+
/** Per-request caller options, e.g. `(req) => ({ signal: req.signal })`. */
|
|
17
|
+
callerOptions?: (request: Request, ...rest: any[]) => CallerOptions;
|
|
18
|
+
/** Mount point. Default "/". Functions live at `${basePath}${id}`, e.g. `/api/bookings.confirm`. */
|
|
19
|
+
basePath?: string;
|
|
20
|
+
/** Unexpected (non-domain) errors. Default: console.error. */
|
|
21
|
+
onError?: (error: unknown) => void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const json = (body: unknown, status = 200) =>
|
|
25
|
+
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A web-standard handler (Workers, Bun, Node via Hono or srvx, SvelteKit, Next route handlers...).
|
|
29
|
+
* Publishes only functions with `expose`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
|
|
30
|
+
* queries also accept GET `?input=<json>`.
|
|
31
|
+
* GET `{base}` lists what's exposed.
|
|
32
|
+
*/
|
|
33
|
+
export function toFetchHandler<S extends object>(registry: Registry<S, any>, options: FetchOptions<S>) {
|
|
34
|
+
const base = (options.basePath ?? "/").replace(/\/?$/, "/");
|
|
35
|
+
const exposed = new Map(registry.functions.filter((f) => f.exposed).map((f) => [f.id, f]));
|
|
36
|
+
const onError = options.onError ?? ((e) => console.error("[logic-sdk] unexpected error", e));
|
|
37
|
+
|
|
38
|
+
return async (request: Request, ...rest: any[]): Promise<Response> => {
|
|
39
|
+
const path = new URL(request.url).pathname;
|
|
40
|
+
if (!path.startsWith(base)) return json({ error: { kind: "not_found", code: "route_not_found" } }, 404);
|
|
41
|
+
const id = path.slice(base.length);
|
|
42
|
+
|
|
43
|
+
if (id === "" && request.method === "GET")
|
|
44
|
+
return json({
|
|
45
|
+
functions: [...exposed.values()].map((f) => ({ id: f.id, kind: f.kind, description: f.fn.description })),
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const entry = exposed.get(id);
|
|
49
|
+
if (!entry) return json({ error: { kind: "not_found", code: "function_not_found" } }, 404);
|
|
50
|
+
|
|
51
|
+
let input: unknown;
|
|
52
|
+
try {
|
|
53
|
+
if (request.method === "POST") {
|
|
54
|
+
// JSON only: blocks cross-site "simple" form posts (CSRF) because they can't send this content type without a preflight
|
|
55
|
+
if (!(request.headers.get("content-type") ?? "").toLowerCase().startsWith("application/json"))
|
|
56
|
+
return json({ error: { kind: "invalid", code: "unsupported_media_type" } }, 415);
|
|
57
|
+
const text = await request.text();
|
|
58
|
+
input = text ? JSON.parse(text) : undefined;
|
|
59
|
+
} else if (request.method === "GET" && entry.kind === "query") {
|
|
60
|
+
const raw = new URL(request.url).searchParams.get("input");
|
|
61
|
+
input = raw ? JSON.parse(raw) : undefined;
|
|
62
|
+
} else {
|
|
63
|
+
const res = json({ error: { kind: "invalid", code: "method_not_allowed" } }, 405);
|
|
64
|
+
res.headers.set("allow", entry.kind === "query" ? "GET, POST" : "POST");
|
|
65
|
+
return res;
|
|
66
|
+
}
|
|
67
|
+
} catch {
|
|
68
|
+
return json({ error: { kind: "invalid", code: "malformed_json" } }, 400);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
const scope = await options.resolveScope(request, ...rest);
|
|
73
|
+
const caller = registry.as(scope, options.callerOptions?.(request, ...rest));
|
|
74
|
+
return json({ data: await caller.run(entry.fn, input) });
|
|
75
|
+
} catch (e) {
|
|
76
|
+
if (isDomainError(e)) return json({ error: { kind: e.kind, code: e.code, details: e.details } }, statusOf[e.kind]);
|
|
77
|
+
onError(e);
|
|
78
|
+
return json({ error: { kind: "internal", code: "internal_error" } }, 500);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|