logic-sdk 0.1.0 → 0.3.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/README.md CHANGED
@@ -10,21 +10,20 @@ Write the layer between your routes and your database once, as plain declaration
10
10
  npm i logic-sdk zod
11
11
  ```
12
12
 
13
- Node 26+, Bun or Cloudflare Workers. Postgres through Drizzle for mutations.
13
+ Node 24+, Bun or Cloudflare Workers. Postgres through Drizzle for mutations.
14
14
 
15
15
  ## Quick start
16
16
 
17
- Declare your types and policies once:
17
+ Declare your types once, and who may do what:
18
18
 
19
19
  ```ts
20
20
  // src/logic.ts
21
- export const { query, mutation, action, event, on, createRegistry } =
22
- init<Config>()({
23
- policies: {
24
- public: () => true,
25
- staff: (scope) => is(scope, "agent", "owner", "admin"),
26
- },
27
- });
21
+ export const { query, mutation, action, event, on, createRegistry } = init<Config>();
22
+
23
+ // src/policies.ts: sync type guards over the scope
24
+ export const anyone = () => true;
25
+ export const member = (s: Scope): s is MemberScope => s.actor !== null;
26
+ export const staff = (s: Scope): s is StaffScope => s.actor !== null && s.actor.role !== "guest";
28
27
  ```
29
28
 
30
29
  Write a module:
@@ -35,12 +34,15 @@ export const confirm = mutation({
35
34
  description: "Confirm a pending booking",
36
35
  inputSchema: z.object({ bookingId: z.uuid() }),
37
36
  outputSchema: Booking,
38
- expose: "staff",
37
+ // Who may call it, on every call
38
+ authorize: staff,
39
+ // HTTP, oRPC and AI tools may publish it
40
+ expose: true,
39
41
 
40
42
  async execute({ bookingId }, ctx) {
41
43
  const booking = await findBooking(ctx, bookingId);
42
44
  if (booking.status !== "pending") {
43
- throw ctx.reject("not_pending");
45
+ throw ctx.errors.reject("not_pending");
44
46
  }
45
47
 
46
48
  // Another module, in the same transaction
@@ -75,9 +77,11 @@ await caller.run(bookings.confirm, { bookingId });
75
77
  - **Side effects after commit.** Mutations emit events; listeners send the email once the data is safe.
76
78
  - **Lost races retried.** Deadlocks and serialization failures re-run the mutation in a fresh transaction.
77
79
  - **Who is calling, everywhere.** The scope reaches every nested call and listener, and policies narrow its type.
78
- - **Internal by default.** Only exposed functions reach HTTP, RPC or AI tools, with a required output contract.
79
- - **Agents included.** `toAITools` gives an agent your functions, under the same policies and transactions as your API.
80
- - **Errors without HTTP.** `ctx.reject`, `ctx.conflict`, `ctx.notFound`, `ctx.deny`; adapters map them to statuses.
80
+ - **Authorization on every call.** `authorize` runs whoever calls: HTTP, an agent, a job or another function. Record rules are sync `can*` predicates the CLI checks.
81
+ - **Internal by default.** Only `expose: true` functions reach HTTP, RPC or AI tools, with a required policy and output contract.
82
+ - **Agents included.** `toAITool` gives an agent your functions, under the same policies and transactions as your API. Opt-in, one function at a time or by `filter`.
83
+ - **Settings in one place.** Declare `config` once, fill it from env at the entry, read `ctx.config` anywhere. The CLI fails the build if a module reads env.
84
+ - **Errors without HTTP.** `ctx.errors.reject`, `conflict`, `notFound`, `deny`; adapters map them to statuses.
81
85
  - **Tests without mocks.** Each test is a real transaction on a real database, always rolled back.
82
86
  - **No magic.** No decorators, classes, codegen, build step or `AsyncLocalStorage`.
83
87
 
@@ -95,10 +99,10 @@ await caller.run(bookings.confirm, { bookingId });
95
99
 
96
100
  ```bash
97
101
  npm i -D @logic-sdk/cli
98
- npx logic-sdk list # every function, its kind and policy
102
+ npx logic-sdk list # every function, its kind and policy
99
103
  logic-sdk show bookings.confirm # schemas, what it runs and emits, who calls it
100
104
  logic-sdk graph --format mermaid # who runs whom, who reacts to which event
101
- logic-sdk check # module boundaries, run cycles, no network in transactions
105
+ logic-sdk check # module boundaries, run cycles, no network in transactions, can* checks
102
106
  ```
103
107
 
104
108
  Read-only, `--json` everywhere, exit codes for CI. The `logic-sdk` command ships with the main package and hands off to `@logic-sdk/cli`, so apps that don't use the CLI never download it.
package/dist/ai.d.ts CHANGED
@@ -10,23 +10,36 @@ export type AIToolsOf<Mods> = UnionToIntersection<{
10
10
  [N in keyof ExposedOf<Mods[M]> & string as `${M}_${N}`]: Tool<FnIn<Mods[M][N & keyof Mods[M]]>, FnOut<Mods[M][N & keyof Mods[M]]>>;
11
11
  };
12
12
  }[keyof Mods & string]>;
13
- export interface AIToolsOptions {
14
- /** Keep only some exposed functions, e.g. `(f) => f.fn.meta?.agent !== false`. */
15
- filter?: (fn: RegisteredFn) => boolean;
13
+ export interface AIToolOptions {
16
14
  /** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
17
15
  onError?: (error: unknown) => void;
18
16
  }
17
+ export interface AIToolsOptions extends AIToolOptions {
18
+ /**
19
+ * Which exposed functions an agent may call. Required: the agent door is opt-in, so a function exposed
20
+ * for your UI doesn't become a tool by accident. E.g. `(f) => f.fn.meta?.agent === true`.
21
+ */
22
+ filter: (fn: RegisteredFn) => boolean;
23
+ }
19
24
  /**
20
- * Exposed functions as AI SDK tools, run as `caller`: an agent goes through the same policies,
21
- * validation, transactions and events as your HTTP API. Tool names are `<module>_<function>`.
25
+ * One exposed function as an AI SDK tool, run as `caller`: the agent goes through the same policy,
26
+ * validation, transaction and events as your HTTP API. You name it, like any AI SDK tool.
22
27
  *
23
28
  * ```ts
24
29
  * const caller = registry.as(await scopeFrom(request));
25
- * await generateText({ model, tools: toAITools(registry, caller), prompt });
30
+ * await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
26
31
  * ```
27
32
  *
28
33
  * Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
29
34
  * to `onError` and the model gets "internal_error", so internals never land in its context.
30
35
  */
31
- export declare function toAITools<S extends object, Mods extends Record<string, object>>(registry: Registry<S, Mods>, caller: Caller<S>, options?: AIToolsOptions): AIToolsOf<Mods>;
36
+ export declare function toAITool<F extends Fn<any, any, any, true>>(caller: Caller<any>, fn: F, options?: AIToolOptions): Tool<FnIn<F>, FnOut<F>>;
37
+ /**
38
+ * The exposed functions your `filter` picks, as AI SDK tools named `<module>_<function>`.
39
+ *
40
+ * ```ts
41
+ * tools: toAITools(registry, caller, { filter: (f) => f.fn.meta?.agent === true })
42
+ * ```
43
+ */
44
+ export declare function toAITools<S extends object, Mods extends Record<string, object>>(registry: Registry<S, Mods>, caller: Caller<S>, options: AIToolsOptions): Partial<AIToolsOf<Mods>>;
32
45
  export {};
package/dist/ai.js CHANGED
@@ -1,39 +1,51 @@
1
1
  import { tool } from "ai";
2
2
  import { isDomainError } from "./index.js";
3
3
  /**
4
- * Exposed functions as AI SDK tools, run as `caller`: an agent goes through the same policies,
5
- * validation, transactions and events as your HTTP API. Tool names are `<module>_<function>`.
4
+ * One exposed function as an AI SDK tool, run as `caller`: the agent goes through the same policy,
5
+ * validation, transaction and events as your HTTP API. You name it, like any AI SDK tool.
6
6
  *
7
7
  * ```ts
8
8
  * const caller = registry.as(await scopeFrom(request));
9
- * await generateText({ model, tools: toAITools(registry, caller), prompt });
9
+ * await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
10
10
  * ```
11
11
  *
12
12
  * Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
13
13
  * to `onError` and the model gets "internal_error", so internals never land in its context.
14
14
  */
15
- export function toAITools(registry, caller, options = {}) {
15
+ export function toAITool(caller, fn, options = {}) {
16
16
  const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
17
+ if (fn.expose !== true)
18
+ throw new Error("[logic-sdk] toAITool needs a function with expose: true.");
19
+ return tool({
20
+ description: fn.description,
21
+ inputSchema: fn.inputSchema,
22
+ outputSchema: fn.outputSchema,
23
+ async execute(input, { abortSignal }) {
24
+ try {
25
+ return await caller.run(fn, input, { signal: abortSignal });
26
+ }
27
+ catch (e) {
28
+ if (isDomainError(e))
29
+ throw e;
30
+ onError(e);
31
+ throw new Error("internal_error");
32
+ }
33
+ },
34
+ });
35
+ }
36
+ /**
37
+ * The exposed functions your `filter` picks, as AI SDK tools named `<module>_<function>`.
38
+ *
39
+ * ```ts
40
+ * tools: toAITools(registry, caller, { filter: (f) => f.fn.meta?.agent === true })
41
+ * ```
42
+ */
43
+ export function toAITools(registry, caller, options) {
44
+ if (typeof options?.filter !== "function")
45
+ throw new Error("[logic-sdk] toAITools needs a filter: the agent door is opt-in. E.g. { filter: (f) => f.fn.meta?.agent === true }");
17
46
  const tools = {};
18
- for (const f of registry.functions) {
19
- if (!f.exposed || (options.filter && !options.filter(f)))
20
- continue;
21
- tools[`${f.module}_${f.name}`] = tool({
22
- description: f.fn.description,
23
- inputSchema: f.fn.inputSchema,
24
- outputSchema: f.fn.outputSchema,
25
- async execute(input) {
26
- try {
27
- return await caller.run(f.fn, input);
28
- }
29
- catch (e) {
30
- if (isDomainError(e))
31
- throw e;
32
- onError(e);
33
- throw new Error("internal_error");
34
- }
35
- },
36
- });
37
- }
47
+ for (const f of registry.functions)
48
+ if (f.exposed && options.filter(f))
49
+ tools[`${f.module}_${f.name}`] = toAITool(caller, f.fn, options);
38
50
  return tools;
39
51
  }
package/dist/fetch.d.ts CHANGED
@@ -1,11 +1,14 @@
1
- import { type CallerOptions, type ErrorKind, type Registry } from "./index.ts";
1
+ import { DomainError, type ErrorKind, type Registry } from "./index.ts";
2
+ /**
3
+ * Throw from `resolveScope` when this mount is session-only and there's no valid session: the client gets 401.
4
+ * For mounts that also serve public functions, return a scope with no actor instead, and let policies answer 403.
5
+ */
6
+ export declare const unauthenticated: (code?: string, details?: unknown) => DomainError;
2
7
  /** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
3
8
  export declare const statusOf: Record<ErrorKind, number>;
4
9
  export interface FetchOptions<S extends object> {
5
10
  /** Build the scope for this request (session → actor, account, locale...). */
6
11
  resolveScope: (request: Request, ...rest: any[]) => S | Promise<S>;
7
- /** Per-request caller options, e.g. `(req) => ({ signal: req.signal })`. */
8
- callerOptions?: (request: Request, ...rest: any[]) => CallerOptions;
9
12
  /** Mount point. Default "/". Functions live at `${basePath}${id}`, e.g. `/api/bookings.confirm`. */
10
13
  basePath?: string;
11
14
  /** Unexpected (non-domain) errors. Default: console.error. */
@@ -13,8 +16,7 @@ export interface FetchOptions<S extends object> {
13
16
  }
14
17
  /**
15
18
  * A web-standard handler (Workers, Bun, Node via Hono or srvx, SvelteKit, Next route handlers...).
16
- * Publishes only functions with `expose`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
19
+ * Publishes only functions with `expose: true`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
17
20
  * queries also accept GET `?input=<json>`.
18
- * GET `{base}` lists what's exposed.
19
21
  */
20
22
  export declare function toFetchHandler<S extends object>(registry: Registry<S, any>, options: FetchOptions<S>): (request: Request, ...rest: any[]) => Promise<Response>;
package/dist/fetch.js CHANGED
@@ -1,4 +1,9 @@
1
- import { isDomainError } from "./index.js";
1
+ import { DomainError, isDomainError } from "./index.js";
2
+ /**
3
+ * Throw from `resolveScope` when this mount is session-only and there's no valid session: the client gets 401.
4
+ * For mounts that also serve public functions, return a scope with no actor instead, and let policies answer 403.
5
+ */
6
+ export const unauthenticated = (code = "unauthenticated", details) => new DomainError("unauthenticated", code, details);
2
7
  /** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
3
8
  export const statusOf = {
4
9
  invalid: 400,
@@ -11,9 +16,8 @@ export const statusOf = {
11
16
  const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
12
17
  /**
13
18
  * A web-standard handler (Workers, Bun, Node via Hono or srvx, SvelteKit, Next route handlers...).
14
- * Publishes only functions with `expose`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
19
+ * Publishes only functions with `expose: true`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
15
20
  * queries also accept GET `?input=<json>`.
16
- * GET `{base}` lists what's exposed.
17
21
  */
18
22
  export function toFetchHandler(registry, options) {
19
23
  const base = (options.basePath ?? "/").replace(/\/?$/, "/");
@@ -24,10 +28,6 @@ export function toFetchHandler(registry, options) {
24
28
  if (!path.startsWith(base))
25
29
  return json({ error: { kind: "not_found", code: "route_not_found" } }, 404);
26
30
  const id = path.slice(base.length);
27
- if (id === "" && request.method === "GET")
28
- return json({
29
- functions: [...exposed.values()].map((f) => ({ id: f.id, kind: f.kind, description: f.fn.description })),
30
- });
31
31
  const entry = exposed.get(id);
32
32
  if (!entry)
33
33
  return json({ error: { kind: "not_found", code: "function_not_found" } }, 404);
@@ -55,8 +55,7 @@ export function toFetchHandler(registry, options) {
55
55
  }
56
56
  try {
57
57
  const scope = await options.resolveScope(request, ...rest);
58
- const caller = registry.as(scope, options.callerOptions?.(request, ...rest));
59
- return json({ data: await caller.run(entry.fn, input) });
58
+ return json({ data: await registry.as(scope).run(entry.fn, input, { signal: request.signal }) });
60
59
  }
61
60
  catch (e) {
62
61
  if (isDomainError(e))