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/dist/index.js CHANGED
@@ -17,12 +17,10 @@ export class DomainError extends Error {
17
17
  this.details = details;
18
18
  }
19
19
  }
20
- /** For the edge (`resolveScope`): no valid session. Inside modules, use `ctx.deny()`. */
21
- export const unauthenticated = (code = "unauthenticated", details) => new DomainError("unauthenticated", code, details);
22
20
  /** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
23
21
  export const isDomainError = (e, code) => e instanceof DomainError && (code === undefined || e.code === code);
24
- /** `ctx.reject` and friends for one function or listener (`id` like "bookings.confirm"). */
25
- const failFor = (id) => {
22
+ /** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
23
+ const errorsFor = (id) => {
26
24
  const module = id.slice(0, id.indexOf("."));
27
25
  return {
28
26
  reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
@@ -38,20 +36,28 @@ export const inProcess = () => ({
38
36
  await dispatch(e);
39
37
  },
40
38
  });
39
+ /**
40
+ * Typed constructors for your app:
41
+ *
42
+ * ```ts
43
+ * export const { query, mutation, action, event, on, createRegistry } = init<Config>();
44
+ * ```
45
+ */
41
46
  export function init() {
42
- return ((options) => constructors(options?.policies ?? {}));
47
+ return constructors();
43
48
  }
44
- function constructors(policies) {
45
- const make = (kind) => ({ expose, ...def }) => {
46
- let check;
47
- if (typeof expose === "function")
48
- check = expose;
49
- else if (expose !== undefined) {
50
- check = policies[expose];
51
- if (!check)
52
- throw new Error(`[logic-sdk] Unknown policy "${expose}". Define it in init()({ policies }).`);
53
- }
54
- return Object.freeze({ [BRAND]: kind, kind, outputSchema: undefined, ...def, check });
49
+ function constructors() {
50
+ const make = (kind) => (def) => {
51
+ const where = def?.description ? `"${def.description}"` : `a ${kind}`;
52
+ if (def.authorize !== undefined && typeof def.authorize !== "function")
53
+ throw new Error(`[logic-sdk] authorize on ${where} must be a policy function, like \`authorize: member\`.`);
54
+ if (def.expose !== undefined && def.expose !== true)
55
+ throw new Error(`[logic-sdk] expose on ${where} must be \`true\` or left out.`);
56
+ if (def.expose && !def.authorize)
57
+ 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 });
55
61
  };
56
62
  return {
57
63
  /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
@@ -82,6 +88,31 @@ const INTERNAL = Symbol.for("logic-sdk.internal");
82
88
  export function createRegistry(options) {
83
89
  return build(options, {});
84
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
+ }
85
116
  const describeIssues = (issues) => issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
86
117
  /**
87
118
  * What `createRegistry` finds in your modules, without a database or services: every function, event and
@@ -106,7 +137,7 @@ export function describeModules(modules) {
106
137
  listeners.push({ id, module, name, listener, event: listener.event() });
107
138
  }
108
139
  else
109
- functions.push({ id, module, name, kind, fn: value, exposed: typeof value.check === "function" });
140
+ functions.push({ id, module, name, kind, fn: value, exposed: value.expose === true });
110
141
  }
111
142
  }
112
143
  return { ids, functions, events, listeners };
@@ -115,6 +146,7 @@ function build(options, o) {
115
146
  const { ids, functions, events, listeners } = describeModules(options.modules);
116
147
  const database = o.database ?? options.database;
117
148
  const services = o.services ?? options.services ?? {};
149
+ const config = freezeConfig(mergeConfig(options.config ?? {}, o.config));
118
150
  const dispatcher = o.events ?? options.events ?? inProcess();
119
151
  const now = o.now ?? options.now ?? (() => new Date());
120
152
  const wrap = options.wrap ?? ((_c, next) => next());
@@ -138,14 +170,18 @@ function build(options, o) {
138
170
  const idOf = (x) => {
139
171
  const id = ids.get(x);
140
172
  if (!id)
141
- throw new Error("[logic-sdk] This function or event isn't registered. Add its module to createRegistry({ modules }).");
173
+ throw new Error("[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules }).");
142
174
  return id;
143
175
  };
144
- async function parseInput(schema, value, code) {
176
+ /** Bad input from a caller is their error. Bad input from your own code (a nested call) is a bug. */
177
+ async function parseInput(schema, value, id, nested) {
145
178
  const r = await schema["~standard"].validate(value);
146
- if (r.issues)
147
- throw new DomainError("invalid", code, { issues: describeIssues(r.issues) });
148
- return r.value;
179
+ if (!r.issues)
180
+ return r.value;
181
+ const issues = describeIssues(r.issues);
182
+ if (nested)
183
+ throw new Error(`[logic-sdk] ${id} was run with invalid input: ${JSON.stringify(issues)}`);
184
+ throw new DomainError("invalid", `${id}.invalid_input`, { issues });
149
185
  }
150
186
  /** Output and event payloads are produced by our own code: invalid means a bug, not a bad request. */
151
187
  async function parseOwn(schema, value, what) {
@@ -166,7 +202,7 @@ function build(options, o) {
166
202
  const failures = [];
167
203
  const event = eventByName.get(envelope.name);
168
204
  for (const l of byEvent.get(envelope.name) ?? []) {
169
- const frame = { scope: envelope.scope, depth: 0, opts: { eventDepth } };
205
+ const frame = { scope: envelope.scope, depth: 0, eventDepth };
170
206
  try {
171
207
  await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
172
208
  const payload = event ? await parseOwn(event.schema, envelope.payload, `${envelope.name} payload`) : envelope.payload;
@@ -191,28 +227,33 @@ function build(options, o) {
191
227
  throw new AggregateError(failures.map((f) => f.error), `[logic-sdk] ${failures.length} listener(s) failed for ${envelope.name}: ${failures.map((f) => f.listener).join(", ")}`);
192
228
  }
193
229
  // ── ctx ──────────────────────────────────────────────────────────────────
194
- const child = (frame) => ({ ...frame, depth: frame.depth + 1 });
195
- const rescope = (frame, patch) => ({ ...frame, scope: { ...frame.scope, ...patch } });
230
+ /** The frame a call runs in: one level deeper, with this call's scope patch and signal. */
231
+ const enter = (frame, options) => ({
232
+ ...frame,
233
+ depth: frame.depth + 1,
234
+ scope: options?.scope ? { ...frame.scope, ...options.scope } : frame.scope,
235
+ signal: options?.signal ?? frame.signal,
236
+ abortOn: options?.signal,
237
+ });
196
238
  function queryCtx(frame, id) {
197
239
  return {
198
- ...failFor(id),
240
+ errors: errorsFor(id),
199
241
  scope: frame.scope,
242
+ config: config,
200
243
  now,
201
- signal: frame.opts.signal,
202
244
  db: frame.tx ? frame.tx.db : database?.db,
203
- run: (fn, input) => invoke(fn, input, child(frame), ["query"]),
204
- with: (patch) => queryCtx(rescope(frame, patch), id),
245
+ run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query"]),
205
246
  };
206
247
  }
207
248
  function mutationCtx(frame, id) {
208
249
  const tx = frame.tx;
209
250
  return {
210
- ...failFor(id),
251
+ errors: errorsFor(id),
211
252
  scope: frame.scope,
253
+ config: config,
212
254
  now,
213
- signal: frame.opts.signal,
214
255
  db: tx.db,
215
- run: (fn, input) => invoke(fn, input, child(frame), ["query", "mutation"]),
256
+ run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query", "mutation"]),
216
257
  emit: (event, payload) => {
217
258
  const name = idOf(event);
218
259
  payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
@@ -229,18 +270,17 @@ function build(options, o) {
229
270
  check.catch(() => { }); // surfaced at commit; never an unhandled rejection
230
271
  tx.pending.push(check);
231
272
  },
232
- with: (patch) => mutationCtx(rescope(frame, patch), id),
233
273
  };
234
274
  }
235
275
  function actionCtx(frame, id) {
236
276
  return {
237
- ...failFor(id),
277
+ errors: errorsFor(id),
238
278
  scope: frame.scope,
279
+ config: config,
239
280
  now,
240
- signal: frame.opts.signal,
281
+ signal: frame.signal,
241
282
  services,
242
- run: (fn, input) => invoke(fn, input, child({ ...frame, tx: undefined }), ["query", "mutation", "action"]),
243
- with: (patch) => actionCtx(rescope(frame, patch), id),
283
+ run: (fn, input, options) => invoke(fn, input, enter({ ...frame, tx: undefined }, options), ["query", "mutation", "action"]),
244
284
  };
245
285
  }
246
286
  // ── invoke ───────────────────────────────────────────────────────────────
@@ -249,13 +289,17 @@ function build(options, o) {
249
289
  if (!allowed.includes(fn.kind))
250
290
  throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
251
291
  const call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth: frame.depth };
252
- /** Validate and check before any transaction opens: bad or denied calls never touch the database. */
292
+ /** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
253
293
  const prepare = async () => {
254
- frame.opts.signal?.throwIfAborted();
255
- const input = await parseInput(fn.inputSchema, rawInput, `${id}.invalid_input`);
256
- if (fn.check && !(await fn.check(frame.scope, input)))
257
- throw new DomainError("forbidden", `${id}.forbidden`);
258
- return input;
294
+ frame.abortOn?.throwIfAborted();
295
+ if (fn.authorize) {
296
+ const allowed = fn.authorize(frame.scope);
297
+ if (allowed instanceof Promise || typeof allowed?.then === "function")
298
+ throw new Error(`[logic-sdk] The policy on ${id} returned a Promise. Policies are sync and read only the scope.`);
299
+ if (allowed !== true)
300
+ throw new DomainError("forbidden", `${id}.forbidden`);
301
+ }
302
+ return parseInput(fn.inputSchema, rawInput, id, frame.depth > 0);
259
303
  };
260
304
  const execute = async (input, ctx) => {
261
305
  const stub = o.stubs?.get(fn);
@@ -323,7 +367,7 @@ function build(options, o) {
323
367
  try {
324
368
  for (const e of outbox)
325
369
  o.record?.(e);
326
- const eventDepth = (frame.opts.eventDepth ?? 0) + 1;
370
+ const eventDepth = (frame.eventDepth ?? 0) + 1;
327
371
  if (eventDepth > maxEventDepth) {
328
372
  report(new Error(`[logic-sdk] event chain deeper than ${maxEventDepth}: stopped delivering (listener loop?)`), {
329
373
  listener: "(dispatcher)",
@@ -347,18 +391,17 @@ function build(options, o) {
347
391
  report(e, { listener: "(after commit)", envelope: outbox[0] });
348
392
  }
349
393
  }
350
- function makeCaller(scope, opts) {
394
+ function makeCaller(scope) {
351
395
  return {
352
396
  scope,
353
- run: (fn, input) => invoke(fn, input, { scope, depth: 0, opts }, ["query", "mutation", "action"]),
354
- with: (patch) => makeCaller({ ...scope, ...patch }, opts),
397
+ run: (fn, input, options) => invoke(fn, input, enter({ scope, depth: -1 }, options), ["query", "mutation", "action"]), // depth 0
355
398
  };
356
399
  }
357
400
  return {
358
401
  /** The modules you registered (typed), for adapters that build typed routers. */
359
402
  modules: options.modules,
360
403
  /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
361
- as: (scope, opts = {}) => makeCaller(scope, opts),
404
+ as: (scope) => makeCaller(scope),
362
405
  /** Everything the registry can do. Adapters read this. */
363
406
  functions: functions,
364
407
  events: events,
@@ -367,7 +410,12 @@ function build(options, o) {
367
410
  /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
368
411
  dispatch,
369
412
  /** @internal used by `logic-sdk/testing` */
370
- [INTERNAL]: { options, overrides: o, derive: (more) => build(options, { ...o, ...more }) },
413
+ [INTERNAL]: {
414
+ options,
415
+ overrides: o,
416
+ config,
417
+ derive: (more) => build(options, { ...o, ...more, config: mergeConfig(o.config, more.config) }),
418
+ },
371
419
  };
372
420
  }
373
421
  /** @internal */
package/dist/orpc.d.ts CHANGED
@@ -6,7 +6,7 @@ export type ORPCContext<S extends object> = {
6
6
  caller: Caller<S>;
7
7
  };
8
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;
9
- /** `{ bookings: { confirm, cancel, … } }`: only functions with `expose`. */
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]]>;
package/dist/orpc.js CHANGED
@@ -28,9 +28,9 @@ export function toORPCRouter(registry) {
28
28
  let b = base.input(f.fn.inputSchema);
29
29
  if (f.fn.outputSchema)
30
30
  b = b.output(f.fn.outputSchema);
31
- (router[f.module] ??= {})[f.name] = b.handler(async ({ input, context }) => {
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,15 +1,17 @@
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
16
  stub<F extends Fn>(fn: F, impl: (input: FnIn<F>, ctx: any) => Promise<FnOut<F>>): void;
15
17
  /** Every event emitted (and committed) so far, in order. */
@@ -17,13 +19,13 @@ export interface TestTransaction<S extends object, Mods extends Record<string, o
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.1.0",
3
+ "version": "0.3.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,
@@ -77,15 +77,15 @@
77
77
  "access": "public"
78
78
  },
79
79
  "engines": {
80
- "node": ">=26"
80
+ "node": ">=24"
81
81
  },
82
82
  "dependencies": {
83
83
  "@standard-schema/spec": "^1.1.0"
84
84
  },
85
85
  "peerDependencies": {
86
- "@orpc/server": ">=2.0.0-beta.51",
87
- "ai": ">=7",
88
- "@logic-sdk/cli": ">=0.1.0"
86
+ "@orpc/server": ">=2.0.0-beta.51 <3",
87
+ "ai": ">=7 <8",
88
+ "@logic-sdk/cli": ">=0.3.0 <0.4.0"
89
89
  },
90
90
  "peerDependenciesMeta": {
91
91
  "@orpc/server": {
package/src/ai.ts CHANGED
@@ -16,49 +16,69 @@ export type AIToolsOf<Mods> = UnionToIntersection<
16
16
  }[keyof Mods & string]
17
17
  >;
18
18
 
19
- export interface AIToolsOptions {
20
- /** Keep only some exposed functions, e.g. `(f) => f.fn.meta?.agent !== false`. */
21
- filter?: (fn: RegisteredFn) => boolean;
19
+ export interface AIToolOptions {
22
20
  /** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
23
21
  onError?: (error: unknown) => void;
24
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
+ }
25
30
 
26
31
  /**
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>`.
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.
29
34
  *
30
35
  * ```ts
31
36
  * const caller = registry.as(await scopeFrom(request));
32
- * await generateText({ model, tools: toAITools(registry, caller), prompt });
37
+ * await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
33
38
  * ```
34
39
  *
35
40
  * Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
36
41
  * to `onError` and the model gets "internal_error", so internals never land in its context.
37
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, { abortSignal }) {
55
+ try {
56
+ return await caller.run(fn, input, { signal: abortSignal });
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
+ */
38
73
  export function toAITools<S extends object, Mods extends Record<string, object>>(
39
74
  registry: Registry<S, Mods>,
40
75
  caller: Caller<S>,
41
- options: AIToolsOptions = {},
42
- ): AIToolsOf<Mods> {
43
- const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
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 }");
44
80
  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>;
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>>;
64
84
  }
package/src/fetch.ts CHANGED
@@ -1,4 +1,11 @@
1
- import { isDomainError, type CallerOptions, type ErrorKind, type Registry } from "./index.ts";
1
+ import { DomainError, isDomainError, 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);
2
9
 
3
10
  /** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
4
11
  export const statusOf: Record<ErrorKind, number> = {
@@ -13,8 +20,6 @@ export const statusOf: Record<ErrorKind, number> = {
13
20
  export interface FetchOptions<S extends object> {
14
21
  /** Build the scope for this request (session → actor, account, locale...). */
15
22
  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
23
  /** Mount point. Default "/". Functions live at `${basePath}${id}`, e.g. `/api/bookings.confirm`. */
19
24
  basePath?: string;
20
25
  /** Unexpected (non-domain) errors. Default: console.error. */
@@ -26,9 +31,8 @@ const json = (body: unknown, status = 200) =>
26
31
 
27
32
  /**
28
33
  * 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);
34
+ * Publishes only functions with `expose: true`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
30
35
  * queries also accept GET `?input=<json>`.
31
- * GET `{base}` lists what's exposed.
32
36
  */
33
37
  export function toFetchHandler<S extends object>(registry: Registry<S, any>, options: FetchOptions<S>) {
34
38
  const base = (options.basePath ?? "/").replace(/\/?$/, "/");
@@ -40,11 +44,6 @@ export function toFetchHandler<S extends object>(registry: Registry<S, any>, opt
40
44
  if (!path.startsWith(base)) return json({ error: { kind: "not_found", code: "route_not_found" } }, 404);
41
45
  const id = path.slice(base.length);
42
46
 
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
47
  const entry = exposed.get(id);
49
48
  if (!entry) return json({ error: { kind: "not_found", code: "function_not_found" } }, 404);
50
49
 
@@ -70,8 +69,7 @@ export function toFetchHandler<S extends object>(registry: Registry<S, any>, opt
70
69
 
71
70
  try {
72
71
  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) });
72
+ return json({ data: await registry.as(scope).run(entry.fn, input, { signal: request.signal }) });
75
73
  } catch (e) {
76
74
  if (isDomainError(e)) return json({ error: { kind: e.kind, code: e.code, details: e.details } }, statusOf[e.kind]);
77
75
  onError(e);