logic-sdk 0.2.0 → 0.4.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/dist/index.js CHANGED
@@ -44,9 +44,7 @@ export const inProcess = () => ({
44
44
  * ```
45
45
  */
46
46
  export function init() {
47
- return constructors();
48
- }
49
- function constructors() {
47
+ // One implementation behind the typed overloads of `Constructor`: the checks here are the runtime half of those types.
50
48
  const make = (kind) => (def) => {
51
49
  const where = def?.description ? `"${def.description}"` : `a ${kind}`;
52
50
  if (def.authorize !== undefined && typeof def.authorize !== "function")
@@ -55,9 +53,11 @@ function constructors() {
55
53
  throw new Error(`[logic-sdk] expose on ${where} must be \`true\` or left out.`);
56
54
  if (def.expose && !def.authorize)
57
55
  throw new Error(`[logic-sdk] ${where} has expose: true but no authorize. Say who may call it.`);
58
- if (def.expose && !def.outputSchema)
59
- throw new Error(`[logic-sdk] ${where} has expose: true but no outputSchema. Say what callers may see.`);
60
- return Object.freeze({ [BRAND]: kind, kind, outputSchema: undefined, ...def });
56
+ if (def.expose && !def.output)
57
+ throw new Error(`[logic-sdk] ${where} has expose: true but no output. Say what callers may see.`);
58
+ if (typeof def.handler !== "function")
59
+ throw new Error(`[logic-sdk] ${where} needs a handler(ctx, input).`);
60
+ return Object.freeze({ [BRAND]: kind, kind, ...def });
61
61
  };
62
62
  return {
63
63
  /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
@@ -70,13 +70,13 @@ function constructors() {
70
70
  action: make("action"),
71
71
  /** Something that happened. Emitted by mutations, delivered after commit. */
72
72
  event: (def) => Object.freeze({ [BRAND]: "event", kind: "event", ...def }),
73
- /** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, ...)` */
74
- on: (event, execute, opts = {}) => Object.freeze({
73
+ /** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, async (ctx, payload) => …)` */
74
+ on: (event, handler, opts = {}) => Object.freeze({
75
75
  [BRAND]: "listener",
76
76
  kind: "listener",
77
77
  event,
78
78
  description: opts.description,
79
- execute: execute,
79
+ handler,
80
80
  }),
81
81
  };
82
82
  }
@@ -88,7 +88,33 @@ const INTERNAL = Symbol.for("logic-sdk.internal");
88
88
  export function createRegistry(options) {
89
89
  return build(options, {});
90
90
  }
91
+ const isPlain = (v) => !!v && typeof v === "object" && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
92
+ /** Plain objects merge key by key; anything else (values, arrays, null) replaces. `undefined` keeps the base. */
93
+ function mergeConfig(base, patch) {
94
+ if (patch === undefined)
95
+ return base;
96
+ if (!isPlain(base) || !isPlain(patch))
97
+ return patch;
98
+ const keys = new Set([...Object.keys(base), ...Object.keys(patch)]);
99
+ return Object.fromEntries([...keys].map((k) => [k, mergeConfig(base[k], patch[k])])); // fromEntries: `__proto__` stays a key
100
+ }
101
+ /**
102
+ * A frozen copy of plain data: strings, numbers, booleans, null, plain objects and arrays. Anything else (a Date, a Map,
103
+ * a client, a class) is rejected with its path, so settings can't change under everyone else or hide behavior.
104
+ */
105
+ function freezeConfig(value, path = "config") {
106
+ if (value === null || ["string", "number", "boolean", "undefined"].includes(typeof value))
107
+ return value;
108
+ if (Array.isArray(value))
109
+ return Object.freeze(value.map((v, i) => freezeConfig(v, `${path}[${i}]`)));
110
+ if (isPlain(value))
111
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([k, v]) => [k, freezeConfig(v, `${path}.${k}`)])));
112
+ const what = typeof value === "function" ? "a function" : value.constructor?.name ?? typeof value;
113
+ throw new Error(`[logic-sdk] ${path} is ${what}. config holds plain data (strings, numbers, booleans, null, objects, arrays): ` +
114
+ "pass a Date as an ISO string, and put clients in services.");
115
+ }
91
116
  const describeIssues = (issues) => issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
117
+ const isBranded = (v) => !!v && typeof v === "object" && BRAND in v;
92
118
  /**
93
119
  * What `createRegistry` finds in your modules, without a database or services: every function, event and
94
120
  * listener with its id. For tools (the CLI, docs generators) that inspect an app without running it.
@@ -100,19 +126,16 @@ export function describeModules(modules) {
100
126
  const listeners = [];
101
127
  for (const [module, ns] of Object.entries(modules)) {
102
128
  for (const [name, value] of Object.entries(ns)) {
103
- if (!value || typeof value !== "object" || !(BRAND in value) || ids.has(value))
129
+ if (!isBranded(value) || ids.has(value))
104
130
  continue;
105
131
  const id = `${module}.${name}`;
106
132
  ids.set(value, id);
107
- const kind = value[BRAND];
108
- if (kind === "event")
133
+ if (value.kind === "event")
109
134
  events.push({ id, module, name, event: value });
110
- else if (kind === "listener") {
111
- const listener = value;
112
- listeners.push({ id, module, name, listener, event: listener.event() });
113
- }
135
+ else if (value.kind === "listener")
136
+ listeners.push({ id, module, name, listener: value, event: value.event() });
114
137
  else
115
- functions.push({ id, module, name, kind, fn: value, exposed: value.expose === true });
138
+ functions.push({ id, module, name, kind: value.kind, fn: value, exposed: value.expose === true });
116
139
  }
117
140
  }
118
141
  return { ids, functions, events, listeners };
@@ -121,6 +144,7 @@ function build(options, o) {
121
144
  const { ids, functions, events, listeners } = describeModules(options.modules);
122
145
  const database = o.database ?? options.database;
123
146
  const services = o.services ?? options.services ?? {};
147
+ const config = freezeConfig(mergeConfig(options.config ?? {}, o.config));
124
148
  const dispatcher = o.events ?? options.events ?? inProcess();
125
149
  const now = o.now ?? options.now ?? (() => new Date());
126
150
  const wrap = options.wrap ?? ((_c, next) => next());
@@ -176,11 +200,11 @@ function build(options, o) {
176
200
  const failures = [];
177
201
  const event = eventByName.get(envelope.name);
178
202
  for (const l of byEvent.get(envelope.name) ?? []) {
179
- const frame = { scope: envelope.scope, depth: 0, opts: { eventDepth } };
203
+ const frame = { scope: envelope.scope, depth: 0, eventDepth };
180
204
  try {
181
205
  await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
182
- const payload = event ? await parseOwn(event.schema, envelope.payload, `${envelope.name} payload`) : envelope.payload;
183
- return l.listener.execute(payload, { ...actionCtx(frame, l.id), event: { ...envelope, payload } });
206
+ const payload = event ? await parseOwn(event.payload, envelope.payload, `${envelope.name} payload`) : envelope.payload;
207
+ return l.listener.handler({ ...actionCtx(frame, l.id), event: { ...envelope, payload } }, payload); // SAFETY: as in invoke
184
208
  });
185
209
  }
186
210
  catch (error) {
@@ -201,28 +225,31 @@ function build(options, o) {
201
225
  throw new AggregateError(failures.map((f) => f.error), `[logic-sdk] ${failures.length} listener(s) failed for ${envelope.name}: ${failures.map((f) => f.listener).join(", ")}`);
202
226
  }
203
227
  // ── ctx ──────────────────────────────────────────────────────────────────
204
- const child = (frame) => ({ ...frame, depth: frame.depth + 1 });
205
- const rescope = (frame, patch) => ({ ...frame, scope: { ...frame.scope, ...patch } });
206
- function queryCtx(frame, id) {
207
- return {
208
- errors: errorsFor(id),
209
- scope: frame.scope,
210
- now,
211
- signal: frame.opts.signal,
212
- db: frame.tx ? frame.tx.db : database?.db,
213
- run: (fn, input) => invoke(fn, input, child(frame), ["query"]),
214
- with: (patch) => queryCtx(rescope(frame, patch), id),
215
- };
216
- }
228
+ /** The frame a call runs in: one level deeper, with this call's scope patch and signal. */
229
+ const enter = (frame, options) => ({
230
+ ...frame,
231
+ depth: frame.depth + 1,
232
+ scope: options?.scope ? { ...frame.scope, ...options.scope } : frame.scope,
233
+ signal: options?.signal ?? frame.signal,
234
+ abortOn: options?.signal,
235
+ });
236
+ /** What every ctx has. `allowed`: the kinds its `run` may call. */
237
+ const baseCtx = (frame, id, allowed) => ({
238
+ errors: errorsFor(id),
239
+ scope: frame.scope,
240
+ config: config, // Frozen<Cf> here; each app's ctx types it from its own Config
241
+ now,
242
+ run: (fn, input, options) => invoke(fn, input, enter(frame, options), allowed),
243
+ });
244
+ const queryCtx = (frame, id) => ({
245
+ ...baseCtx(frame, id, ["query"]),
246
+ db: frame.tx ? frame.tx.db : database?.db,
247
+ });
217
248
  function mutationCtx(frame, id) {
218
249
  const tx = frame.tx;
219
250
  return {
220
- errors: errorsFor(id),
221
- scope: frame.scope,
222
- now,
223
- signal: frame.opts.signal,
251
+ ...baseCtx(frame, id, ["query", "mutation"]),
224
252
  db: tx.db,
225
- run: (fn, input) => invoke(fn, input, child(frame), ["query", "mutation"]),
226
253
  emit: (event, payload) => {
227
254
  const name = idOf(event);
228
255
  payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
@@ -235,24 +262,17 @@ function build(options, o) {
235
262
  occurredAt: now().toISOString(),
236
263
  };
237
264
  tx.outbox.push(envelope);
238
- const check = parseOwn(event.schema, payload, `${name} payload`).then(() => { });
265
+ const check = parseOwn(event.payload, payload, `${name} payload`).then(() => { });
239
266
  check.catch(() => { }); // surfaced at commit; never an unhandled rejection
240
267
  tx.pending.push(check);
241
268
  },
242
- with: (patch) => mutationCtx(rescope(frame, patch), id),
243
- };
244
- }
245
- function actionCtx(frame, id) {
246
- return {
247
- errors: errorsFor(id),
248
- scope: frame.scope,
249
- now,
250
- signal: frame.opts.signal,
251
- services,
252
- run: (fn, input) => invoke(fn, input, child({ ...frame, tx: undefined }), ["query", "mutation", "action"]),
253
- with: (patch) => actionCtx(rescope(frame, patch), id),
254
269
  };
255
270
  }
271
+ const actionCtx = (frame, id) => ({
272
+ ...baseCtx(frame, id, ["query", "mutation", "action"]),
273
+ signal: frame.signal,
274
+ services,
275
+ });
256
276
  // ── invoke ───────────────────────────────────────────────────────────────
257
277
  async function invoke(fn, rawInput, frame, allowed) {
258
278
  const id = idOf(fn);
@@ -261,20 +281,24 @@ function build(options, o) {
261
281
  const call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth: frame.depth };
262
282
  /** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
263
283
  const prepare = async () => {
264
- frame.opts.signal?.throwIfAborted();
284
+ frame.abortOn?.throwIfAborted();
265
285
  if (fn.authorize) {
266
- const allowed = fn.authorize(frame.scope);
267
- if (allowed instanceof Promise || typeof allowed?.then === "function")
286
+ // SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
287
+ const verdict = fn.authorize(frame.scope);
288
+ if (verdict instanceof Promise)
268
289
  throw new Error(`[logic-sdk] The policy on ${id} returned a Promise. Policies are sync and read only the scope.`);
269
- if (allowed !== true)
290
+ if (verdict !== true)
270
291
  throw new DomainError("forbidden", `${id}.forbidden`);
271
292
  }
272
- return parseInput(fn.inputSchema, rawInput, id, frame.depth > 0);
293
+ // no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
294
+ return fn.input ? parseInput(fn.input, rawInput, id, frame.depth > 0) : undefined;
273
295
  };
274
296
  const execute = async (input, ctx) => {
275
- const stub = o.stubs?.get(fn);
276
- const out = await (stub ? stub(input, ctx) : fn.execute(input, ctx));
277
- return fn.outputSchema ? parseOwn(fn.outputSchema, out, `${id} output`) : out;
297
+ // SAFETY: the handler's types were erased when it was registered. `ctx` was built for its kind,
298
+ // and `input` just passed its own schema (or it takes none).
299
+ const handler = o.stubs?.get(fn) ?? fn.handler;
300
+ const out = await handler(ctx, input);
301
+ return fn.output ? parseOwn(fn.output, out, `${id} output`) : out;
278
302
  };
279
303
  return wrap(call, async () => {
280
304
  if (fn.kind === "query")
@@ -337,7 +361,7 @@ function build(options, o) {
337
361
  try {
338
362
  for (const e of outbox)
339
363
  o.record?.(e);
340
- const eventDepth = (frame.opts.eventDepth ?? 0) + 1;
364
+ const eventDepth = (frame.eventDepth ?? 0) + 1;
341
365
  if (eventDepth > maxEventDepth) {
342
366
  report(new Error(`[logic-sdk] event chain deeper than ${maxEventDepth}: stopped delivering (listener loop?)`), {
343
367
  listener: "(dispatcher)",
@@ -361,27 +385,22 @@ function build(options, o) {
361
385
  report(e, { listener: "(after commit)", envelope: outbox[0] });
362
386
  }
363
387
  }
364
- function makeCaller(scope, opts) {
365
- return {
366
- scope,
367
- run: (fn, input) => invoke(fn, input, { scope, depth: 0, opts }, ["query", "mutation", "action"]),
368
- with: (patch) => makeCaller({ ...scope, ...patch }, opts),
369
- };
370
- }
371
388
  return {
372
- /** The modules you registered (typed), for adapters that build typed routers. */
373
389
  modules: options.modules,
374
- /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
375
- as: (scope, opts = {}) => makeCaller(scope, opts),
376
- /** Everything the registry can do. Adapters read this. */
377
- functions: functions,
378
- events: events,
379
- listeners: listeners,
390
+ as: (scope) => ({
391
+ scope,
392
+ run: (fn, input, options) => invoke(fn, input, enter({ scope, depth: -1 }, options), ["query", "mutation", "action"]), // depth 0
393
+ }),
394
+ functions,
395
+ events,
396
+ listeners,
380
397
  idOf,
381
- /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
382
398
  dispatch,
383
- /** @internal used by `logic-sdk/testing` */
384
- [INTERNAL]: { options, overrides: o, derive: (more) => build(options, { ...o, ...more }) },
399
+ [INTERNAL]: {
400
+ options,
401
+ config,
402
+ derive: (more) => build(options, { ...o, ...more, config: mergeConfig(o.config, more.config) }),
403
+ },
385
404
  };
386
405
  }
387
406
  /** @internal */
package/dist/orpc.d.ts CHANGED
@@ -1,20 +1,17 @@
1
1
  import { type Procedure } from "@orpc/server";
2
2
  import type { StandardSchemaV1 } from "@standard-schema/spec";
3
- import { type Caller, type ErrorKind, type Fn, type Registry } from "./index.ts";
3
+ import { type Caller, type ErrorKind, type ExposedOf, type Fn, type Kind, type Registry } from "./index.ts";
4
4
  /** oRPC context the router expects: bind who is calling per request, in your handler or middleware. */
5
5
  export type ORPCContext<S extends object> = {
6
6
  caller: Caller<S>;
7
7
  };
8
- type ProcedureOf<S extends object, F> = F extends Fn<any, infer I, infer O, true> ? Procedure<ORPCContext<S>, ORPCContext<S>, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}> : never;
8
+ type ProcedureOf<S extends object, F> = F extends Fn<Kind, infer I, infer O, true> ? Procedure<ORPCContext<S>, ORPCContext<S>, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}> : never;
9
9
  /** `{ bookings: { confirm, cancel, … } }`: only functions with `expose: true`. */
10
10
  export type ORPCRouterOf<S extends object, Mods> = {
11
11
  [M in keyof Mods as {} extends ExposedOf<Mods[M]> ? never : M]: {
12
12
  [N in keyof ExposedOf<Mods[M]>]: ProcedureOf<S, Mods[M][N & keyof Mods[M]]>;
13
13
  };
14
14
  };
15
- type ExposedOf<T> = {
16
- [N in keyof T as T[N] extends Fn<any, any, any, true> ? N : never]: T[N];
17
- };
18
15
  /** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
19
16
  export declare const orpcCodeOf: Record<ErrorKind, string>;
20
17
  /**
package/dist/orpc.js CHANGED
@@ -25,12 +25,12 @@ export function toORPCRouter(registry) {
25
25
  for (const f of registry.functions) {
26
26
  if (!f.exposed)
27
27
  continue;
28
- let b = base.input(f.fn.inputSchema);
29
- if (f.fn.outputSchema)
30
- b = b.output(f.fn.outputSchema);
31
- (router[f.module] ??= {})[f.name] = b.handler(async ({ input, context }) => {
28
+ let b = f.fn.input ? base.input(f.fn.input) : base;
29
+ if (f.fn.output)
30
+ b = b.output(f.fn.output);
31
+ (router[f.module] ??= {})[f.name] = b.handler(async ({ input, context, signal }) => {
32
32
  try {
33
- return await context.caller.run(f.fn, input);
33
+ return await context.caller.run(f.fn, input, { signal });
34
34
  }
35
35
  catch (e) {
36
36
  if (isDomainError(e))
package/dist/testing.d.ts CHANGED
@@ -1,29 +1,31 @@
1
- import { type Caller, type CallerOptions, type Envelope, type Fn, type FnIn, type FnOut, type Registry } from "./index.ts";
2
- export interface TestOptions {
1
+ import { type Caller, type DeepPartial, type Envelope, type Fn, type FnIn, type FnOut, type Registry } from "./index.ts";
2
+ export interface TestOptions<Cf = unknown> {
3
3
  /** Replace services (e.g. `{ mailer: memoryMailer() }`). */
4
4
  services?: object;
5
+ /** Override parts of `config` (e.g. `{ orders: { maxItems: 1 } }`). Merged over the registry's, section by section. */
6
+ config?: DeepPartial<Cf>;
5
7
  /** Freeze time. */
6
8
  now?: Date | string | (() => Date);
7
9
  /** Run listeners inline after each mutation (default), or not at all to test one module in isolation. */
8
10
  listeners?: boolean;
9
11
  }
10
- export interface TestTransaction<S extends object, Mods extends Record<string, object> = Record<string, object>> {
12
+ export interface TestTransaction<S extends object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> {
11
13
  /** Bind who is calling, exactly like `registry.as(...)`. */
12
- as(scope: S, opts?: CallerOptions): Caller<S>;
14
+ as(scope: S): Caller<S>;
13
15
  /** Replace a function's implementation for this test. Matched by identity, so `run(availability.hold, …)` hits the stub. */
14
- stub<F extends Fn>(fn: F, impl: (input: FnIn<F>, ctx: any) => Promise<FnOut<F>>): void;
16
+ stub<F extends Fn>(fn: F, impl: (ctx: unknown, input: FnIn<F>) => Promise<FnOut<F>>): void;
15
17
  /** Every event emitted (and committed) so far, in order. */
16
18
  readonly events: Envelope[];
17
19
  /** The test transaction itself: read rows to assert on them. */
18
20
  readonly db: any;
19
21
  /** The registry bound to this test transaction, for adapters: `toFetchHandler(tx.registry, …)`. */
20
- readonly registry: Registry<S, Mods>;
22
+ readonly registry: Registry<S, Mods, Cf>;
21
23
  }
22
24
  /**
23
25
  * Run each test inside a transaction that is always rolled back.
24
26
  * Every top-level mutation inside becomes a savepoint, so a failing mutation rolls back just its own writes,
25
27
  * like it would in production. Run top-level mutations one at a time inside a test (one connection, nested savepoints).
26
28
  */
27
- export declare function createTestRegistry<S extends object, Mods extends Record<string, object>>(registry: Registry<S, Mods>, options?: TestOptions): {
28
- transaction<T>(fn: (t: TestTransaction<S, Mods>) => Promise<T>): Promise<T>;
29
+ export declare function createTestRegistry<S extends object, Mods extends Record<string, object>, Cf>(registry: Registry<S, Mods, Cf>, options?: TestOptions<Cf>): {
30
+ transaction<T>(fn: (t: TestTransaction<S, Mods, Cf>) => Promise<T>): Promise<T>;
29
31
  };
package/dist/testing.js CHANGED
@@ -26,13 +26,14 @@ export function createTestRegistry(registry, options = {}) {
26
26
  const derived = internal(registry).derive({
27
27
  database: outer !== undefined && database?.nest ? database.nest(outer) : database,
28
28
  services: options.services,
29
+ config: options.config,
29
30
  now,
30
31
  stubs,
31
32
  record: (e) => events.push(e),
32
33
  events: options.listeners === false ? { deliver: async () => { } } : undefined,
33
34
  });
34
35
  result = await fn({
35
- as: (scope, opts) => derived.as(scope, opts),
36
+ as: (scope) => derived.as(scope),
36
37
  stub: (f, impl) => void stubs.set(f, impl),
37
38
  events,
38
39
  db: outer,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "logic-sdk",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Queries, mutations, actions and events for TypeScript apps. Transactions, after-commit events and scopes, on any runtime.",
5
5
  "keywords": [
6
6
  "actions",
@@ -24,12 +24,12 @@
24
24
  "license": "MIT",
25
25
  "repository": {
26
26
  "type": "git",
27
- "url": "git+https://github.com/logic-sdk/logic-sdk.git",
27
+ "url": "git+https://github.com/fprl/logic-sdk.git",
28
28
  "directory": "packages/logic-sdk"
29
29
  },
30
- "homepage": "https://github.com/logic-sdk/logic-sdk#readme",
30
+ "homepage": "https://github.com/fprl/logic-sdk#readme",
31
31
  "bugs": {
32
- "url": "https://github.com/logic-sdk/logic-sdk/issues"
32
+ "url": "https://github.com/fprl/logic-sdk/issues"
33
33
  },
34
34
  "type": "module",
35
35
  "sideEffects": false,
@@ -85,7 +85,7 @@
85
85
  "peerDependencies": {
86
86
  "@orpc/server": ">=2.0.0-beta.51 <3",
87
87
  "ai": ">=7 <8",
88
- "@logic-sdk/cli": ">=0.2.0 <0.3.0"
88
+ "@logic-sdk/cli": ">=0.4.0 <0.5.0"
89
89
  },
90
90
  "peerDependenciesMeta": {
91
91
  "@orpc/server": {
package/src/ai.ts CHANGED
@@ -1,7 +1,5 @@
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] };
1
+ import { jsonSchema, tool, type Tool } from "ai";
2
+ import { isDomainError, type Caller, type ExposedFn, type ExposedOf, type FnIn, type FnOut, type Registry, type RegisteredFn } from "./index.ts";
5
3
  type UnionToIntersection<U> = (U extends unknown ? (u: U) => void : never) extends (i: infer I) => void ? I : never;
6
4
 
7
5
  /** `{ bookings_confirm, pricing_priceStay, … }`: one AI SDK tool per exposed function, typed. */
@@ -28,6 +26,9 @@ export interface AIToolsOptions extends AIToolOptions {
28
26
  filter: (fn: RegisteredFn) => boolean;
29
27
  }
30
28
 
29
+ /** What a function without input looks like to the model: an object with nothing in it. It sends `{}`, which run ignores. */
30
+ const noInput = jsonSchema({ type: "object", properties: {}, additionalProperties: false });
31
+
31
32
  /**
32
33
  * One exposed function as an AI SDK tool, run as `caller`: the agent goes through the same policy,
33
34
  * validation, transaction and events as your HTTP API. You name it, like any AI SDK tool.
@@ -40,8 +41,8 @@ export interface AIToolsOptions extends AIToolOptions {
40
41
  * Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
41
42
  * to `onError` and the model gets "internal_error", so internals never land in its context.
42
43
  */
43
- export function toAITool<F extends Fn<any, any, any, true>>(
44
- caller: Caller<any>,
44
+ export function toAITool<F extends ExposedFn>(
45
+ caller: Caller<object>,
45
46
  fn: F,
46
47
  options: AIToolOptions = {},
47
48
  ): Tool<FnIn<F>, FnOut<F>> {
@@ -49,11 +50,11 @@ export function toAITool<F extends Fn<any, any, any, true>>(
49
50
  if (fn.expose !== true) throw new Error("[logic-sdk] toAITool needs a function with expose: true.");
50
51
  return tool({
51
52
  description: fn.description,
52
- inputSchema: fn.inputSchema as FlexibleSchema,
53
- outputSchema: fn.outputSchema as FlexibleSchema,
54
- async execute(input) {
53
+ inputSchema: fn.input ?? noInput,
54
+ outputSchema: fn.output,
55
+ async execute(input, { abortSignal }) {
55
56
  try {
56
- return await caller.run(fn, input);
57
+ return await caller.run(fn, input, { signal: abortSignal });
57
58
  } catch (e) {
58
59
  if (isDomainError(e)) throw e;
59
60
  onError(e);
@@ -79,6 +80,6 @@ export function toAITools<S extends object, Mods extends Record<string, object>>
79
80
  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
81
  const tools: Record<string, Tool> = {};
81
82
  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
+ if (f.exposed && options.filter(f)) tools[`${f.module}_${f.name}`] = toAITool(caller, f.fn as ExposedFn, options);
83
84
  return tools as Partial<AIToolsOf<Mods>>;
84
85
  }
package/src/drizzle.ts CHANGED
@@ -24,7 +24,7 @@ export function drizzleAdapter<Db extends Transactional>(db: Db): DatabaseAdapte
24
24
  db,
25
25
  transactions: "interactive",
26
26
  transaction: (fn) => db.transaction(fn),
27
- nest: (tx) => drizzleAdapter(tx as Transactional) as any,
27
+ nest: (tx) => drizzleAdapter(tx),
28
28
  retryable: (e) => RETRYABLE.has(sqlState(e) ?? ""),
29
29
  };
30
30
  }
package/src/fetch.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { DomainError, isDomainError, type CallerOptions, type ErrorKind, type Registry } from "./index.ts";
1
+ import { DomainError, isDomainError, type ErrorKind, type Registry } from "./index.ts";
2
2
 
3
3
  /**
4
4
  * Throw from `resolveScope` when this mount is session-only and there's no valid session: the client gets 401.
@@ -20,8 +20,6 @@ export const statusOf: Record<ErrorKind, number> = {
20
20
  export interface FetchOptions<S extends object> {
21
21
  /** Build the scope for this request (session → actor, account, locale...). */
22
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
23
  /** Mount point. Default "/". Functions live at `${basePath}${id}`, e.g. `/api/bookings.confirm`. */
26
24
  basePath?: string;
27
25
  /** Unexpected (non-domain) errors. Default: console.error. */
@@ -36,7 +34,7 @@ const json = (body: unknown, status = 200) =>
36
34
  * Publishes only functions with `expose: true`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
37
35
  * queries also accept GET `?input=<json>`.
38
36
  */
39
- export function toFetchHandler<S extends object>(registry: Registry<S, any>, options: FetchOptions<S>) {
37
+ export function toFetchHandler<S extends object>(registry: Registry<S>, options: FetchOptions<S>) {
40
38
  const base = (options.basePath ?? "/").replace(/\/?$/, "/");
41
39
  const exposed = new Map(registry.functions.filter((f) => f.exposed).map((f) => [f.id, f]));
42
40
  const onError = options.onError ?? ((e) => console.error("[logic-sdk] unexpected error", e));
@@ -71,8 +69,7 @@ export function toFetchHandler<S extends object>(registry: Registry<S, any>, opt
71
69
 
72
70
  try {
73
71
  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) });
72
+ return json({ data: await registry.as(scope).run(entry.fn, input, { signal: request.signal }) });
76
73
  } catch (e) {
77
74
  if (isDomainError(e)) return json({ error: { kind: e.kind, code: e.code, details: e.details } }, statusOf[e.kind]);
78
75
  onError(e);