@tokamaq/sdk 0.0.0-stage → 0.1.0-dev.1

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.
Files changed (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1403 -2
  3. package/build-internals.ts +25 -0
  4. package/caller/agent-launch.ts +60 -0
  5. package/client.tsx +498 -0
  6. package/component-actions.ts +327 -0
  7. package/component-alerts.ts +136 -0
  8. package/component-attributes.ts +340 -0
  9. package/component-parts.tsx +1177 -0
  10. package/core-contracts/auth.ts +40 -0
  11. package/package.json +98 -4
  12. package/quit.ts +58 -0
  13. package/regions.tsx +94 -0
  14. package/screen-search.ts +211 -0
  15. package/send-file.ts +175 -0
  16. package/server-build-internals.ts +11 -0
  17. package/solid.ts +132 -0
  18. package/src/agent-command.ts +48 -0
  19. package/src/agent-info-cache.ts +34 -0
  20. package/src/agent-reports.ts +140 -0
  21. package/src/agent-turn.ts +289 -0
  22. package/src/api.ts +174 -0
  23. package/src/auth.ts +39 -0
  24. package/src/call-error.ts +37 -0
  25. package/src/caller-storage.ts +32 -0
  26. package/src/client.ts +163 -0
  27. package/src/database.ts +322 -0
  28. package/src/functions.ts +726 -0
  29. package/src/hooks.ts +141 -0
  30. package/src/host.ts +211 -0
  31. package/src/http-action.ts +55 -0
  32. package/src/index.ts +126 -0
  33. package/src/internal/contracts.ts +260 -0
  34. package/src/internal/machine-scope.ts +21 -0
  35. package/src/local.ts +22 -0
  36. package/src/plugin.ts +162 -0
  37. package/src/points.ts +79 -0
  38. package/src/protocol.ts +64 -0
  39. package/src/schema.ts +136 -0
  40. package/src/storage.ts +193 -0
  41. package/src/thread-context.ts +42 -0
  42. package/src/transport.ts +421 -0
  43. package/src/triggers.ts +87 -0
  44. package/src/unstable.ts +66 -0
  45. package/src/validators.ts +248 -0
  46. package/src/values.ts +98 -0
  47. package/src/visibility.ts +8 -0
  48. package/src/websocket-transport.ts +91 -0
  49. package/src/window-state-protocol.ts +7 -0
  50. package/src/within.ts +24 -0
  51. package/src/worker-limits.ts +5 -0
  52. package/tools/bundle.mjs +490 -0
  53. package/tools/client-entry.mjs +10 -0
  54. package/tools/contracts.mjs +254 -0
  55. package/tools/http-actions.mjs +42 -0
  56. package/tools/placement.mjs +535 -0
  57. package/tools/plugin-boundary.mjs +592 -0
  58. package/tools/plugin-compiler.mjs +125 -0
  59. package/tools/plugin-descriptor.ts +75 -0
  60. package/tools/points.mjs +340 -0
  61. package/tools/result-validator.mjs +83 -0
  62. package/tools/server-builtins.mjs +82 -0
  63. package/tools/server-files.mjs +34 -0
  64. package/tools/table-references.mjs +98 -0
  65. package/tools/worker.mjs +110 -0
  66. package/tsconfig.plugin-server.json +12 -0
  67. package/tsconfig.plugin-window.json +15 -0
  68. package/view.ts +27 -0
  69. package/web.d.ts +6 -0
  70. package/window-state-host.ts +228 -0
  71. package/window-state.ts +43 -0
@@ -0,0 +1,726 @@
1
+ import { isRemoteFunctionError } from "./call-error";
2
+ // Definitions close over handlers instead of exposing an unvalidated handler
3
+ // entry point. The registry and host always invoke the same validation path.
4
+ import { createDatabase } from "./database";
5
+ import type { DatabaseReader, DatabaseWriter } from "./database";
6
+ import type { HostBridge } from "./host";
7
+ import type { DataModel, ModelFromSchema, SchemaDefinition } from "./schema";
8
+ import { createStorage, type ActionStorage, type StorageReader, type StorageWriter } from "./storage";
9
+ import { createCallerStorage, type CallerStorage } from "./caller-storage";
10
+ import type { Fields, ObjectValue, Validator, ValidatorDescription } from "./validators";
11
+ import { v, validate } from "./validators";
12
+ import type { Id, JsonObject, JsonValue } from "./values";
13
+ import { jsonSnapshot } from "./values";
14
+ import { functionName, type FunctionReference } from "./api";
15
+ import { callHost, type RunnerCapability } from "./host";
16
+ import type { LocalProcess } from "./local";
17
+ import {
18
+ contractScope,
19
+ serverContracts,
20
+ withServerContracts,
21
+ type ContractContext,
22
+ } from "./internal/contracts";
23
+ import { bindMachineScope } from "./internal/machine-scope";
24
+ import { Visibility } from "./visibility";
25
+ import { bindPoint, type PointLifetime } from "./points";
26
+
27
+ export type FunctionKind = "query" | "mutation" | "action";
28
+ declare const machineId: unique symbol;
29
+ export type MachineId = string & { readonly [machineId]: true };
30
+ export type ActionTarget = "server" | "caller" | MachineId;
31
+
32
+ export type MachineFailure =
33
+ | Failure<"noMachine", null>
34
+ | Failure<"machineLost", null>
35
+ | Failure<"machineOffline", null>
36
+ | Failure<"machineForbidden", null>
37
+ | Failure<"machineLimit", null>
38
+ | Failure<"serverOnly", { message: string }>
39
+ | Failure<"runnerArtifactMismatch", { plugin: string; message: string }>
40
+ | Failure<"runnerCapabilityUnavailable", RunnerCapability>;
41
+ export interface ActionOptions {
42
+ on?: ActionTarget;
43
+ }
44
+
45
+ /** Authenticated caller, preserved across subscriptions and plugin calls. */
46
+ export interface User {
47
+ readonly id: string;
48
+ readonly name: string;
49
+ readonly role: "owner" | "admin" | "member";
50
+ }
51
+
52
+ export interface Device {
53
+ readonly id: string;
54
+ readonly name: string;
55
+ }
56
+
57
+ /** Identity used by standalone SDK hosts that do not provide a device. */
58
+ export const LOCAL_USER = "local";
59
+ export const FALLBACK_LOCAL_DEVICE: Device = Object.freeze({ id: "device:local", name: "This computer" });
60
+
61
+ export interface AuthContext {
62
+ readonly user: User;
63
+ readonly device: Device;
64
+ }
65
+
66
+ /** Host-owned metadata for this invocation. Anonymous calls have no user or device. */
67
+ export interface CallContext {
68
+ readonly user: User | null;
69
+ readonly device: Device | null;
70
+ readonly threadId?: Id<"threads">;
71
+ readonly depth: number;
72
+ }
73
+
74
+ export function callContext(
75
+ auth: AuthContext | null,
76
+ note?: CallContext | null,
77
+ threadId?: Id<"threads">,
78
+ ): CallContext {
79
+ const thread = note?.threadId ?? threadId;
80
+ return Object.freeze({
81
+ user: auth ? Object.freeze({ ...auth.user }) : null,
82
+ device: auth ? Object.freeze({ ...auth.device }) : null,
83
+ depth: note?.depth ?? 0,
84
+ ...(thread === undefined ? {} : { threadId: thread }),
85
+ });
86
+ }
87
+
88
+ /**
89
+ * The device of the server's own calls: a plugin's `maintenance` entry runs as
90
+ * the server, never as a person or one of their devices. Real devices have
91
+ * generated ids, so no window or local part can carry this one.
92
+ */
93
+ export const SERVER_DEVICE_ID = "device:server";
94
+
95
+ /** Whether the caller is the server itself (its maintenance), not a person's window or local part. */
96
+ export function isServerCall(auth: Pick<AuthContext, "device">): boolean {
97
+ return auth.device.id === SERVER_DEVICE_ID;
98
+ }
99
+
100
+ export type Failure<K extends string, D> = {
101
+ readonly failed: true;
102
+ readonly kind: K;
103
+ readonly data: D;
104
+ };
105
+
106
+ type WireValue<V, HasFailure extends boolean> = V extends void
107
+ ? null
108
+ : HasFailure extends true
109
+ ? V extends object
110
+ ? V extends readonly unknown[]
111
+ ? V
112
+ : "failed" extends keyof V
113
+ ? V
114
+ : V & { readonly failed?: undefined }
115
+ : V
116
+ : V;
117
+
118
+ export type WireResult<R> = WireValue<
119
+ Awaited<R>,
120
+ [Extract<Awaited<R>, Failure<string, unknown>>] extends [never] ? false : true
121
+ >;
122
+
123
+ /** Return an expected failure that callers can narrow by kind. A mutation returning it rolls back its writes. */
124
+ export function fail<const K extends string>(kind: K): Failure<K, null>;
125
+ export function fail<const K extends string, D extends JsonValue>(kind: K, data: D): Failure<K, D>;
126
+ export function fail(kind: string, data: JsonValue = null): Failure<string, JsonValue> {
127
+ return { failed: true, kind, data };
128
+ }
129
+
130
+ type FailureOf<T> = Extract<T, Failure<string, unknown>>;
131
+ type NarrowFailure<T> = [FailureOf<T>] extends [never] ? T & Failure<string, unknown> : FailureOf<T>;
132
+
133
+ /** Narrow a result to a failure, including when success is a primitive or null. */
134
+ export function isFailure<T>(value: T): value is NarrowFailure<T> {
135
+ // Keep this wire shape in sync with the server's failure_kind guard.
136
+ return (
137
+ value !== null &&
138
+ typeof value === "object" &&
139
+ "failed" in value &&
140
+ value.failed === true &&
141
+ "kind" in value &&
142
+ typeof value.kind === "string" &&
143
+ Object.hasOwn(value, "data")
144
+ );
145
+ }
146
+
147
+ /** Bind finite generated references to host-mediated calls, never import handlers. */
148
+ export type PluginCalls<T, K extends FunctionKind> =
149
+ T extends FunctionReference<infer Kind, infer A, infer R>
150
+ ? Kind extends K
151
+ ? (args: A) => Promise<R>
152
+ : never
153
+ : { readonly [P in keyof T]: PluginCalls<T[P], K> };
154
+
155
+ type RunFunction<K extends FunctionKind> = <A, R>(
156
+ reference: FunctionReference<K, A, R>,
157
+ args: NoInfer<A>,
158
+ ) => Promise<R>;
159
+
160
+ export interface QueryContext<M extends DataModel> extends ContractContext {
161
+ readonly auth: AuthContext;
162
+ readonly call: CallContext;
163
+ readonly db: DatabaseReader<M>;
164
+ readonly storage: StorageReader;
165
+ runQuery: RunFunction<"query">;
166
+ use<T>(api: T): PluginCalls<T, "query">;
167
+ }
168
+
169
+ export interface MutationContext<M extends DataModel> extends ContractContext {
170
+ readonly auth: AuthContext;
171
+ readonly call: CallContext;
172
+ readonly db: DatabaseWriter<M>;
173
+ readonly storage: StorageWriter;
174
+ runQuery: RunFunction<"query">;
175
+ runMutation: RunFunction<"mutation">;
176
+ use<T>(api: T): PluginCalls<T, "query" | "mutation">;
177
+ }
178
+
179
+ /** Actions have no database capability; each nested call owns its transaction. */
180
+ export interface ActionContext extends ContractContext {
181
+ readonly server: { url(): Promise<string | null> };
182
+ readonly storage: ActionStorage;
183
+ readonly auth: AuthContext;
184
+ readonly call: CallContext;
185
+ use<T>(api: T): PluginCalls<T, FunctionKind>;
186
+ readonly signal?: HostBridge["signal"];
187
+ readonly crypto: {
188
+ hashPassword(password: string): Promise<string>;
189
+ verifyPassword(password: string, hash: string): Promise<boolean>;
190
+ verifyAndRehashPassword(
191
+ password: string,
192
+ hash: string,
193
+ ): Promise<{
194
+ valid: boolean;
195
+ replacementHash?: string;
196
+ }>;
197
+ };
198
+ /** Requires a manifest env:<name> grant; unset values return null. */
199
+ env(name: string): Promise<string | null>;
200
+ runQuery: RunFunction<"query">;
201
+ runMutation: RunFunction<"mutation">;
202
+ runAction: RunAction;
203
+ }
204
+
205
+ interface RunAction {
206
+ <A, R>(reference: FunctionReference<"action", A, R>, args: NoInfer<A>): Promise<R>;
207
+ <A, R>(
208
+ reference: FunctionReference<"action", A, R>,
209
+ args: NoInfer<A>,
210
+ options: ActionOptions,
211
+ ): Promise<R | MachineFailure>;
212
+ }
213
+
214
+ export interface CallerActionContext extends Omit<ActionContext, "server" | "storage"> {
215
+ readonly storage: CallerStorage;
216
+ readonly signal: NonNullable<HostBridge["signal"]>;
217
+ readonly retiring?: HostBridge["signal"];
218
+ readonly proc: LocalProcess;
219
+ readonly withPrograms: <T>(
220
+ run: (forceStop: () => Promise<void>, context: CallerActionContext) => Promise<T>,
221
+ ) => Promise<T>;
222
+ }
223
+
224
+ class NoMachineError extends Error {
225
+ readonly kind = "noMachine";
226
+ }
227
+
228
+ export function requireActionMachine(message = "This needs a machine"): never {
229
+ throw new NoMachineError(message);
230
+ }
231
+
232
+ const definitionBrand = Symbol("tokamaq.function");
233
+
234
+ export interface FunctionDefinition<
235
+ K extends FunctionKind = FunctionKind,
236
+ A = unknown,
237
+ R = unknown,
238
+ V extends Visibility = Visibility,
239
+ > {
240
+ readonly [definitionBrand]: true;
241
+ readonly kind: K;
242
+ readonly visibility: V;
243
+ readonly args: ValidatorDescription;
244
+ readonly returns?: ValidatorDescription;
245
+ readonly on?: ActionTarget;
246
+ readonly _types?: { args: A; result: R };
247
+ invoke(args: unknown, host: HostBridge): Promise<JsonValue>;
248
+ invokeLocal?(args: unknown, host: HostBridge, auth: AuthContext, call: CallContext): unknown;
249
+ }
250
+
251
+ type ReturnValidator = Validator<unknown> | undefined;
252
+
253
+ type FunctionOptions<K extends FunctionKind, M extends DataModel, F extends Fields, R, S> = {
254
+ args?: F;
255
+ returns?: S;
256
+ on?: K extends "action" ? ActionTarget : never;
257
+ handler: (
258
+ ctx: K extends "query" ? QueryContext<M> : K extends "mutation" ? MutationContext<M> : ActionContext,
259
+ args: ObjectValue<F>,
260
+ ) => R;
261
+ };
262
+
263
+ type BuiltFunction<K extends FunctionKind, A, R, V extends Visibility, S> = FunctionDefinition<
264
+ K,
265
+ A,
266
+ WireResult<R>,
267
+ V
268
+ > &
269
+ (S extends Validator<unknown> ? { readonly returns: ValidatorDescription } : unknown);
270
+
271
+ export type FunctionBuilder<
272
+ K extends FunctionKind,
273
+ M extends DataModel,
274
+ V extends Visibility = typeof Visibility.Public,
275
+ > = <F extends Fields = Record<never, never>, R = unknown, S extends ReturnValidator = undefined>(
276
+ definition: FunctionOptions<K, M, F, R, S>,
277
+ ) => BuiltFunction<K, ObjectValue<F>, R, V, S>;
278
+
279
+ const serverOnlyMessage = "Machine management and the server address are only available beside the server";
280
+ class ServerOnlyError extends Error {
281
+ constructor() {
282
+ super(serverOnlyMessage);
283
+ }
284
+ }
285
+
286
+ /** Bind the typed action calls to a request-scoped host bridge. */
287
+ export function bindActionCall(bridge: HostBridge, kind: FunctionKind) {
288
+ return (reference: { [functionName]: string }, input: unknown, options?: ActionOptions) =>
289
+ callHost(bridge, "plugin.call", {
290
+ name: reference[functionName],
291
+ args: jsonSnapshot(input, "nested call args"),
292
+ kind,
293
+ ...(options?.on === undefined ? {} : { on: options.on }),
294
+ });
295
+ }
296
+
297
+ function actionContext(
298
+ bridge: HostBridge,
299
+ auth: AuthContext | null,
300
+ call: CallContext,
301
+ lifetime: PointLifetime,
302
+ on?: ActionTarget,
303
+ pointScope = bridge,
304
+ ): CallerActionContext {
305
+ const besideServer = async <T>(operation: () => Promise<T>): Promise<T> => {
306
+ if (bridge.proc) throw new ServerOnlyError();
307
+ return operation();
308
+ };
309
+ const machine = requireActionMachine;
310
+ const run = (kind: FunctionKind) => bindActionCall(bridge, kind);
311
+ const context = Object.freeze({
312
+ call,
313
+ storage: bridge.proc
314
+ ? createCallerStorage(bridge)
315
+ : on === undefined || on === "server"
316
+ ? createStorage(bridge, "action")
317
+ : createStorage(bridge, "caller"),
318
+ ...(on === undefined || on === "server"
319
+ ? { server: Object.freeze({ url: () => besideServer(() => callHost(bridge, "server.url", {})) }) }
320
+ : {}),
321
+ get auth() {
322
+ if (!auth) throw new Error("There is no caller before sign-in");
323
+ return auth;
324
+ },
325
+ [contractScope]: {
326
+ list: (key, id, options) => {
327
+ if (key.on === "caller") return (bridge.contracts ?? machine()).list(key, id, options);
328
+ return serverContracts(bridge).list(key, id, options);
329
+ },
330
+ },
331
+ use: <T>(api: T) => bindCalls(api, bridge),
332
+ signal: bridge.signal!,
333
+ retiring: bridge.retiring,
334
+ proc: bridge.proc ?? machine,
335
+ withPrograms: <T>(work: (stop: () => Promise<void>, ctx: CallerActionContext) => Promise<T>) =>
336
+ bridge.withPrograms?.((stop, scoped) =>
337
+ work(stop, actionContext(scoped, auth, call, lifetime, on, pointScope)),
338
+ ) ?? machine(),
339
+ crypto: Object.freeze({
340
+ hashPassword: (password: string) => callHost(bridge, "crypto.hashPassword", { password }),
341
+ verifyPassword: (password: string, hash: string) =>
342
+ callHost(bridge, "crypto.verifyPassword", { password, hash }),
343
+ verifyAndRehashPassword: (password: string, hash: string) =>
344
+ callHost(bridge, "crypto.verifyAndRehashPassword", { password, hash }),
345
+ }),
346
+ env: (name: string) => callHost(bridge, "action.env", { name }),
347
+ runQuery: (reference, args) =>
348
+ bridge.proc
349
+ ? run("query")(reference, args)
350
+ : callHost(bridge, "action.runQuery", {
351
+ name: reference[functionName],
352
+ args: jsonSnapshot(args, "nested call args"),
353
+ }),
354
+ runMutation: (reference, args) =>
355
+ bridge.proc
356
+ ? run("mutation")(reference, args)
357
+ : callHost(bridge, "action.runMutation", {
358
+ name: reference[functionName],
359
+ args: jsonSnapshot(args, "nested call args"),
360
+ }),
361
+ runAction: run("action"),
362
+ } as Omit<CallerActionContext, "storage"> & { readonly storage: StorageReader });
363
+
364
+ bindMachineScope(context, {
365
+ host: bridge,
366
+ besideServer: on === undefined || on === "server" ? besideServer : undefined,
367
+ });
368
+ return bindPoint(context, bridge, lifetime, pointScope) as CallerActionContext;
369
+ }
370
+
371
+ function builder<
372
+ K extends FunctionKind,
373
+ M extends DataModel,
374
+ V extends Visibility = typeof Visibility.Public,
375
+ >(kind: K, visibility: V, schema?: SchemaDefinition): FunctionBuilder<K, M, V> {
376
+ return <F extends Fields, R, S extends ReturnValidator>(definition: FunctionOptions<K, M, F, R, S>) => {
377
+ const description = v.object(definition.args ?? {}).description;
378
+ // The builder selects the matching context before calling the handler.
379
+ const handler = definition.handler as (
380
+ ctx: QueryContext<M> | MutationContext<M> | ActionContext | CallerActionContext,
381
+ args: ObjectValue<F>,
382
+ ) => R;
383
+ const returns = definition.returns?.description;
384
+ return Object.freeze({
385
+ [definitionBrand]: true as const,
386
+ kind,
387
+ visibility,
388
+ args: description,
389
+ ...(returns ? { returns } : {}),
390
+ ...(definition.on === undefined ? {} : { on: definition.on }),
391
+ ...(kind === "action" && definition.on === "caller"
392
+ ? {
393
+ // Contract members are called in the same worker and can receive
394
+ // live objects. Window calls still enter invoke() and validate JSON.
395
+ invokeLocal: (input: unknown, host: HostBridge, auth: AuthContext, call: CallContext) => {
396
+ const lifetime = { active: true };
397
+ let pending = false;
398
+ try {
399
+ const ctx = actionContext(host, auth, call, lifetime, definition.on);
400
+ const result: unknown = handler(ctx, input as Parameters<typeof handler>[1]);
401
+ if (result && typeof (result as PromiseLike<unknown>).then === "function") {
402
+ pending = true;
403
+ return Promise.resolve(result).finally(() => {
404
+ lifetime.active = false;
405
+ });
406
+ }
407
+ return result;
408
+ } finally {
409
+ if (!pending) lifetime.active = false;
410
+ }
411
+ },
412
+ }
413
+ : {}),
414
+ async invoke(input: unknown, host: HostBridge) {
415
+ // A snapshot both rejects lossy JSON and prevents a caller mutating args
416
+ // while a handler is suspended on a database operation.
417
+ const args = jsonSnapshot(input, "args");
418
+ validate(description, args);
419
+ // Direct definition invocation supports lightweight standalone hosts;
420
+ // server entry points always supply the authenticated caller below.
421
+ const auth =
422
+ host.auth === null
423
+ ? null
424
+ : Object.freeze({
425
+ user: Object.freeze(
426
+ host.auth?.user ?? host.user ?? { id: LOCAL_USER, name: "You", role: "owner" as const },
427
+ ),
428
+ device: Object.freeze(host.auth?.device ?? FALLBACK_LOCAL_DEVICE),
429
+ });
430
+ const call = callContext(
431
+ auth,
432
+ host.call,
433
+ host.proc && !host.call?.threadId ? threadArgument(description, args) : undefined,
434
+ );
435
+ const caller = () => {
436
+ if (!auth) throw new Error("There is no caller before sign-in");
437
+ return auth;
438
+ };
439
+
440
+ const run = (expected: FunctionKind) => (reference: { [functionName]: string }, input: unknown) => {
441
+ const payload = {
442
+ name: reference[functionName],
443
+ args: jsonSnapshot(input, "nested call args"),
444
+ };
445
+ return callHost(host, "plugin.call", { ...payload, kind: expected });
446
+ };
447
+ const lifetime = { active: true };
448
+ const ctx =
449
+ kind === "action"
450
+ ? actionContext(host, auth, call, lifetime, definition.on)
451
+ : bindPoint(
452
+ Object.freeze({
453
+ call,
454
+ get auth() {
455
+ return caller();
456
+ },
457
+ db:
458
+ kind === "query"
459
+ ? createDatabase<M>(host, false, schema)
460
+ : createDatabase<M>(host, true, schema),
461
+ storage: createStorage(host, kind),
462
+ runQuery: run("query"),
463
+ ...(kind === "mutation" ? { runMutation: run("mutation") } : {}),
464
+ [contractScope]: serverContracts(host),
465
+ use: <T>(api: T) => bindCalls(api, host),
466
+ }),
467
+ host,
468
+ lifetime,
469
+ );
470
+ if (kind !== "action") bindMachineScope(ctx, { host });
471
+
472
+ // The generic kind determines the context; the branch above enforces it
473
+ // at runtime as well. Plugin reference kinds are erased, so the kernel
474
+ // also enforces query-only calls. This cast never widens author types.
475
+ try {
476
+ const result = await handler(
477
+ ctx as Parameters<typeof handler>[0],
478
+ args as Parameters<typeof handler>[1],
479
+ );
480
+ const snapshot = jsonSnapshot(result === undefined ? null : result, "function result");
481
+ if (returns) validate(returns, snapshot, "result");
482
+ return snapshot;
483
+ } catch (error) {
484
+ if (error instanceof NoMachineError) return fail("noMachine", null);
485
+ if (error instanceof ServerOnlyError) return fail("serverOnly", { message: error.message });
486
+ if (
487
+ kind === "action" &&
488
+ isRemoteFunctionError(error) &&
489
+ error.kind === "runnerCapabilityUnavailable" &&
490
+ (error.data === "privateFunctions" || error.data === "serverContracts")
491
+ )
492
+ return fail("runnerCapabilityUnavailable", error.data);
493
+ throw error;
494
+ } finally {
495
+ lifetime.active = false;
496
+ }
497
+ },
498
+ }) as BuiltFunction<K, ObjectValue<F>, R, V, S>;
499
+ };
500
+ }
501
+
502
+ const CHAT_THREAD_ID_PREFIX = "chat/threads:";
503
+
504
+ // Caller action validators run in the worker; a qualified ID identifies its owner.
505
+ export function threadArgument(schema: ValidatorDescription, value: unknown): Id<"threads"> | undefined {
506
+ switch (schema.kind) {
507
+ case "id":
508
+ return schema.table === "threads" &&
509
+ typeof value === "string" &&
510
+ value.startsWith(CHAT_THREAD_ID_PREFIX)
511
+ ? (value as Id<"threads">)
512
+ : undefined;
513
+ case "optional":
514
+ return value === undefined ? undefined : threadArgument(schema.inner, value);
515
+ case "object":
516
+ for (const key of Object.keys(schema.fields).sort()) {
517
+ const id = threadArgument(schema.fields[key], (value as JsonObject)[key]);
518
+ if (id !== undefined) return id;
519
+ }
520
+ return;
521
+ case "array":
522
+ for (const item of value as unknown[]) {
523
+ const id = threadArgument(schema.item, item);
524
+ if (id !== undefined) return id;
525
+ }
526
+ return;
527
+ case "union":
528
+ for (const member of schema.members) {
529
+ try {
530
+ validate(member, value);
531
+ } catch {
532
+ continue;
533
+ }
534
+ return threadArgument(member, value);
535
+ }
536
+ }
537
+ }
538
+
539
+ function bindCalls<T>(api: T, host: HostBridge): PluginCalls<T, FunctionKind> {
540
+ const bind = (reference: unknown): unknown =>
541
+ new Proxy(() => {}, {
542
+ get(_target, key) {
543
+ if (typeof key !== "string") return undefined;
544
+ return bind((reference as Record<string, unknown>)[key]);
545
+ },
546
+ apply(_target, _thisArg, argumentsList) {
547
+ if (argumentsList.length !== 1) throw new Error("Plugin calls require one argument object");
548
+ return callHost(host, "plugin.call", {
549
+ name: (reference as { [functionName]: string })[functionName],
550
+ args: jsonSnapshot(argumentsList[0], "plugin call args"),
551
+ });
552
+ },
553
+ });
554
+ return bind(api) as PluginCalls<T, FunctionKind>;
555
+ }
556
+
557
+ /** Loose builders are useful without a schema; createFunctions adds table types. */
558
+ type LooseModel = Record<string, JsonObject>;
559
+ export const query = builder<"query", LooseModel>("query", Visibility.Public);
560
+ export const mutation = builder<"mutation", LooseModel>("mutation", Visibility.Public);
561
+ type ActionBuilder<V extends Visibility> = {
562
+ <F extends Fields = Record<never, never>, R = unknown>(definition: {
563
+ on: "caller";
564
+ returns?: Validator<unknown>;
565
+ args?: F;
566
+ handler: (ctx: CallerActionContext, args: ObjectValue<F>) => R;
567
+ }): FunctionDefinition<"action", ObjectValue<F>, WireResult<R | MachineFailure>, V> & {
568
+ readonly on: "caller";
569
+ };
570
+ <A = any, R = unknown>(definition: {
571
+ on: "caller";
572
+ returns?: Validator<unknown>;
573
+ args?: undefined;
574
+ handler: (ctx: CallerActionContext, args: A) => R;
575
+ }): FunctionDefinition<"action", A, WireResult<R | MachineFailure>, V> & { readonly on: "caller" };
576
+ <F extends Fields = Record<never, never>, R = unknown>(definition: {
577
+ on: MachineId;
578
+ args?: F;
579
+ handler: (ctx: CallerActionContext, args: ObjectValue<F>) => R;
580
+ }): FunctionDefinition<"action", ObjectValue<F>, WireResult<R | MachineFailure>, V> & {
581
+ readonly on: MachineId;
582
+ };
583
+ <F extends Fields = Record<never, never>, R = unknown>(definition: {
584
+ on?: "server";
585
+ returns?: Validator<unknown>;
586
+ args?: F;
587
+ handler: (ctx: ActionContext, args: ObjectValue<F>) => R;
588
+ }): FunctionDefinition<"action", ObjectValue<F>, WireResult<R>, V>;
589
+ };
590
+
591
+ function actionBuilder<V extends Visibility>(visibility: V): ActionBuilder<V> {
592
+ return builder<"action", LooseModel, V>("action", visibility) as ActionBuilder<V>;
593
+ }
594
+
595
+ export const action = actionBuilder(Visibility.Public);
596
+
597
+ export const internalQuery = builder<"query", LooseModel, typeof Visibility.Internal>(
598
+ "query",
599
+ Visibility.Internal,
600
+ );
601
+ export const internalMutation = builder<"mutation", LooseModel, typeof Visibility.Internal>(
602
+ "mutation",
603
+ Visibility.Internal,
604
+ );
605
+ export const internalAction = actionBuilder(Visibility.Internal);
606
+ /** Export a server function to dependencies without admitting window requests. */
607
+ export function pluginOnly<
608
+ D extends FunctionDefinition<FunctionKind, unknown, unknown, typeof Visibility.Public>,
609
+ >(definition: D): Omit<D, "visibility"> & { readonly visibility: typeof Visibility.PluginOnly } {
610
+ if (definition.visibility !== Visibility.Public)
611
+ throw new Error("Only non-internal server functions can be plugin-only");
612
+ return Object.freeze({ ...definition, visibility: Visibility.PluginOnly });
613
+ }
614
+
615
+ export function createFunctions<S extends SchemaDefinition>(
616
+ schema: S,
617
+ ): {
618
+ query: FunctionBuilder<"query", ModelFromSchema<S>>;
619
+ mutation: FunctionBuilder<"mutation", ModelFromSchema<S>>;
620
+ action: typeof action;
621
+ internalQuery: FunctionBuilder<"query", ModelFromSchema<S>, typeof Visibility.Internal>;
622
+ internalMutation: FunctionBuilder<"mutation", ModelFromSchema<S>, typeof Visibility.Internal>;
623
+ internalAction: typeof internalAction;
624
+ } {
625
+ return {
626
+ query: builder("query", Visibility.Public, schema),
627
+ mutation: builder("mutation", Visibility.Public, schema),
628
+ action,
629
+ internalQuery: builder("query", Visibility.Internal, schema),
630
+ internalMutation: builder("mutation", Visibility.Internal, schema),
631
+ internalAction,
632
+ };
633
+ }
634
+
635
+ export type FunctionRegistry = Readonly<Record<string, FunctionDefinition>>;
636
+
637
+ // Worker dispatch and the plugin registry can be bundled separately.
638
+ const registryPoints = Symbol.for("tokamaq.registryPoints");
639
+ type PointRegistry = FunctionRegistry & {
640
+ readonly [registryPoints]?: Record<string, readonly string[]>;
641
+ };
642
+
643
+ export function createRegistry(
644
+ modules: Record<string, object>,
645
+ contractMethods: Record<string, unknown> = {},
646
+ points?: Record<string, readonly string[]>,
647
+ ): FunctionRegistry {
648
+ const entries: [string, FunctionDefinition][] = [];
649
+ for (const [module, exports] of Object.entries(modules)) {
650
+ for (const [name, value] of Object.entries(exports)) {
651
+ if (
652
+ value !== null &&
653
+ typeof value === "object" &&
654
+ (value as Partial<FunctionDefinition>)[definitionBrand] === true
655
+ ) {
656
+ entries.push([`${module}:${name}`, value as FunctionDefinition]);
657
+ }
658
+ }
659
+ }
660
+ for (const [name, value] of Object.entries(contractMethods)) {
661
+ const method = value as FunctionDefinition | undefined;
662
+ if (method?.[definitionBrand] !== true) throw new Error(`Invalid contract method: ${name}`);
663
+ // Even a provider using a public builder gets a private contract address.
664
+ entries.push([name, Object.freeze({ ...method, visibility: Visibility.Internal })]);
665
+ }
666
+ const registry: FunctionRegistry = Object.fromEntries(entries);
667
+ if (points) Object.defineProperty(registry, registryPoints, { value: points });
668
+ return Object.freeze(registry);
669
+ }
670
+
671
+ /** Host inspection does not execute handlers or require a bridge. */
672
+ export function functionMetadata(registry: FunctionRegistry): {
673
+ name: string;
674
+ kind: FunctionKind;
675
+ args: ValidatorDescription;
676
+ returns?: ValidatorDescription;
677
+ visibility: Visibility;
678
+ on?: ActionTarget;
679
+ }[] {
680
+ return Object.entries(registry).map(([name, definition]) => ({
681
+ name,
682
+ kind: definition.kind,
683
+ args: definition.args,
684
+ ...(definition.returns ? { returns: definition.returns } : {}),
685
+ visibility: definition.visibility,
686
+ ...(definition.on === undefined ? {} : { on: definition.on }),
687
+ }));
688
+ }
689
+
690
+ export async function invokeFunction(
691
+ registry: FunctionRegistry,
692
+ request: { name: string; args: JsonValue },
693
+ host: HostBridge,
694
+ recordThread?: (threadId: Id<"threads">) => void,
695
+ ): Promise<JsonValue> {
696
+ if (!Object.hasOwn(registry, request.name)) throw new Error(`Unknown function: ${request.name}`);
697
+ const args = jsonSnapshot(request.args, "args");
698
+ const definition = registry[request.name];
699
+ validate(definition.args, args);
700
+ const thread = recordThread && threadArgument(definition.args, args);
701
+ if (thread) recordThread(thread);
702
+ const note = await callHost(host, "auth.current", { call: true });
703
+ const auth =
704
+ note && note.user !== null && note.device !== null ? { user: note.user, device: note.device } : null;
705
+ const threadId = note?.threadId ?? thread;
706
+ const invoke = () =>
707
+ definition.invoke(args, {
708
+ auth,
709
+ bundleSchema: host.bundleSchema,
710
+ hookPoints: note?.hookPoints,
711
+ pointOwner: {
712
+ name: request.name,
713
+ declared: (registry as PointRegistry)[registryPoints]?.[request.name],
714
+ },
715
+ call: callContext(auth, note, threadId),
716
+ signal: host.signal,
717
+ retiring: host.retiring,
718
+ proc: host.proc,
719
+ withPrograms: host.withPrograms,
720
+ contracts: host.contracts,
721
+ op: (name, payload) => host.op(name, payload),
722
+ });
723
+ return definition.kind === "query" || definition.kind === "mutation"
724
+ ? withServerContracts(host, invoke)
725
+ : invoke();
726
+ }