@feltdb/feltkit 0.3.37 → 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.
Files changed (122) hide show
  1. package/dist/app.d.ts +153 -3
  2. package/dist/app.js +159 -7
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.js +21 -0
  5. package/dist/appboundry/build.js.map +1 -1
  6. package/dist/appboundry/guest.js +4 -0
  7. package/dist/appboundry/guest.js.map +1 -1
  8. package/dist/client/index.d.ts +189 -0
  9. package/dist/client/index.js +201 -0
  10. package/dist/client/index.js.map +1 -1
  11. package/dist/clock.d.ts +24 -0
  12. package/dist/clock.js +49 -0
  13. package/dist/clock.js.map +1 -0
  14. package/dist/docs.d.ts +1 -1
  15. package/dist/docs.js +1 -0
  16. package/dist/docs.js.map +1 -1
  17. package/dist/event-stage.js +2 -0
  18. package/dist/event-stage.js.map +1 -1
  19. package/dist/index.d.ts +11 -1
  20. package/dist/index.js +1 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/policy.d.ts +9 -1
  23. package/dist/policy.js +16 -3
  24. package/dist/policy.js.map +1 -1
  25. package/dist/presence.d.ts +85 -0
  26. package/dist/presence.js +37 -0
  27. package/dist/presence.js.map +1 -0
  28. package/dist/quota.d.ts +72 -0
  29. package/dist/quota.js +143 -0
  30. package/dist/quota.js.map +1 -0
  31. package/dist/react/agent-control.d.ts +189 -0
  32. package/dist/react/agent-control.js +366 -0
  33. package/dist/react/agent-control.js.map +1 -0
  34. package/dist/react/index.d.ts +14 -1
  35. package/dist/react/index.js +41 -0
  36. package/dist/react/index.js.map +1 -1
  37. package/dist/runtime/activity.d.ts +8 -0
  38. package/dist/runtime/activity.js.map +1 -1
  39. package/dist/runtime/agent-control.d.ts +18 -0
  40. package/dist/runtime/agent-control.js +34 -1
  41. package/dist/runtime/agent-control.js.map +1 -1
  42. package/dist/runtime/agent.js +16 -4
  43. package/dist/runtime/agent.js.map +1 -1
  44. package/dist/runtime/assemble.js +1 -1
  45. package/dist/runtime/assemble.js.map +1 -1
  46. package/dist/runtime/authority.d.ts +38 -0
  47. package/dist/runtime/authority.js +13 -2
  48. package/dist/runtime/authority.js.map +1 -1
  49. package/dist/runtime/capabilities.js +2 -1
  50. package/dist/runtime/capabilities.js.map +1 -1
  51. package/dist/runtime/changes.d.ts +17 -0
  52. package/dist/runtime/changes.js +65 -2
  53. package/dist/runtime/changes.js.map +1 -1
  54. package/dist/runtime/context.d.ts +114 -0
  55. package/dist/runtime/contract.js +9 -3
  56. package/dist/runtime/contract.js.map +1 -1
  57. package/dist/runtime/events.js +17 -1
  58. package/dist/runtime/events.js.map +1 -1
  59. package/dist/runtime/integrations.js +7 -7
  60. package/dist/runtime/integrations.js.map +1 -1
  61. package/dist/runtime/invocations.d.ts +19 -2
  62. package/dist/runtime/invocations.js +16 -3
  63. package/dist/runtime/invocations.js.map +1 -1
  64. package/dist/runtime/policies.d.ts +5 -2
  65. package/dist/runtime/policies.js.map +1 -1
  66. package/dist/runtime/presence-host.d.ts +84 -0
  67. package/dist/runtime/presence-host.js +303 -0
  68. package/dist/runtime/presence-host.js.map +1 -0
  69. package/dist/runtime/providers.d.ts +5 -1
  70. package/dist/runtime/providers.js +11 -5
  71. package/dist/runtime/providers.js.map +1 -1
  72. package/dist/runtime/resource-access.d.ts +137 -0
  73. package/dist/runtime/resource-access.js +177 -0
  74. package/dist/runtime/resource-access.js.map +1 -0
  75. package/dist/runtime/runtime.d.ts +73 -0
  76. package/dist/runtime/runtime.js +594 -37
  77. package/dist/runtime/runtime.js.map +1 -1
  78. package/dist/runtime/sessions.d.ts +11 -0
  79. package/dist/runtime/sessions.js +15 -0
  80. package/dist/runtime/sessions.js.map +1 -1
  81. package/dist/runtime/tenancy.d.ts +59 -0
  82. package/dist/runtime/tenancy.js +128 -0
  83. package/dist/runtime/tenancy.js.map +1 -1
  84. package/dist/runtime/workers.d.ts +123 -0
  85. package/dist/runtime/workers.js +291 -0
  86. package/dist/runtime/workers.js.map +1 -0
  87. package/dist/server/index.d.ts +0 -19
  88. package/dist/server/index.js +44 -4
  89. package/dist/server/index.js.map +1 -1
  90. package/dist/server/mcp.d.ts +8 -15
  91. package/dist/server/mcp.js +40 -3
  92. package/dist/server/mcp.js.map +1 -1
  93. package/dist/server/project.js +6 -5
  94. package/dist/server/project.js.map +1 -1
  95. package/dist/server/tenancy.d.ts +7 -0
  96. package/dist/server/tenancy.js +31 -0
  97. package/dist/server/tenancy.js.map +1 -1
  98. package/dist/server/watch.d.ts +10 -0
  99. package/dist/server/watch.js +88 -0
  100. package/dist/server/watch.js.map +1 -0
  101. package/dist/testing/index.d.ts +3 -1
  102. package/dist/testing/index.js +3 -2
  103. package/dist/testing/index.js.map +1 -1
  104. package/docs/AGENT-CONTROL.md +130 -4
  105. package/docs/APPBOUNDRY.md +37 -0
  106. package/docs/ARCHITECTURE.md +6 -2
  107. package/docs/AUTH.md +35 -0
  108. package/docs/COMPONENTS.md +71 -0
  109. package/docs/GUARANTEES.md +4 -4
  110. package/docs/PRESENCE-AND-SIGNALING-PROPOSAL.md +152 -0
  111. package/docs/README.md +3 -2
  112. package/docs/SECURITY.md +71 -3
  113. package/docs/TRANSACTIONS.md +48 -0
  114. package/docs/UPSTREAM-GAPS.md +16 -2
  115. package/package.json +13 -13
  116. package/skills/.claude-plugin/marketplace.json +1 -1
  117. package/skills/.claude-plugin/plugin.json +1 -1
  118. package/skills/feltkit-agent/SKILL.md +1 -1
  119. package/skills/feltkit-build/SKILL.md +11 -1
  120. package/skills/feltkit-data/SKILL.md +1 -1
  121. package/skills/feltkit-operations/SKILL.md +1 -1
  122. package/skills/feltkit-services/SKILL.md +1 -1
package/dist/app.d.ts CHANGED
@@ -13,9 +13,37 @@ import type { Schema } from "@appport/sdk";
13
13
  import { type Doc, type InferShape, type ShapeInput, type Simplify } from "./schema.js";
14
14
  import type { ActionCtx, AgentCtx, MutationCtx, QueryCtx } from "./runtime/context.js";
15
15
  import { type ClaimDeclaration } from "./runtime/claims.js";
16
+ import { type QuotaDeclaration, type QuotaSpec } from "./quota.js";
16
17
  declare const APP: unique symbol;
17
18
  declare const COLLECTION: unique symbol;
18
19
  declare const FUNCTION: unique symbol;
20
+ /**
21
+ * A transient-message channel (`app.channel`, K2): an AppPort event that carries a message to one scope
22
+ * (a recipient: a connection, a call), authorized for each sender and for each recipient at subscribe and
23
+ * at every delivery, never written to FeltDB. See `FeltKitApp.channel`.
24
+ */
25
+ export interface ChannelConfig {
26
+ /** Who may send: a permission (checked against the sender's roles), plus `authorize.send` when declared. */
27
+ readonly send: Access;
28
+ /** Who may receive: a permission, plus `authorize.receive` (required) for the scope, at subscribe and per delivery. */
29
+ readonly receive: Access;
30
+ readonly authorize: {
31
+ readonly send?: (request: ChannelSendRequest) => boolean | Promise<boolean>;
32
+ readonly receive: (request: ChannelReceiveRequest) => boolean | Promise<boolean>;
33
+ };
34
+ /** The largest message, as JSON bytes. Default 64 KiB. */
35
+ readonly maxBytes: number;
36
+ readonly quota?: readonly QuotaSpec[];
37
+ }
38
+ export interface ChannelReceiveRequest {
39
+ principal: import("./runtime/authority.js").Principal | null;
40
+ scope: string;
41
+ /** Read-only, the application's data (tenant-scoped to the recipient). */
42
+ db: import("./runtime/data.js").DatabaseReader;
43
+ }
44
+ export interface ChannelSendRequest extends ChannelReceiveRequest {
45
+ message: unknown;
46
+ }
19
47
  /** An ephemeral event declared with `app.event` (see there). */
20
48
  export interface EventDefinition<Payload = unknown> {
21
49
  readonly name: string;
@@ -23,6 +51,8 @@ export interface EventDefinition<Payload = unknown> {
23
51
  /** Who may observe it: a permission, "authenticated" or "public". Always declared. */
24
52
  readonly access: Access;
25
53
  readonly description?: string;
54
+ /** Set for a channel (`app.channel`): sent with ctx.channels.send, never ctx.events.publish. */
55
+ readonly channel?: ChannelConfig;
26
56
  /** Type only. */
27
57
  readonly __payload?: Payload;
28
58
  }
@@ -193,6 +223,16 @@ export interface FeltKitOptions {
193
223
  authenticate?: (request: AuthenticateRequest) => PrincipalInput | null | Promise<PrincipalInput | null>;
194
224
  /** Session lifetime. Default 7 days. */
195
225
  sessionTtlMs?: number;
226
+ /**
227
+ * Guests (K4): people without an account, admitted by a guest link to one record (`ctx.grants.guestLink`).
228
+ * `roles`: the roles a guest link may give (each declared in `roles`; keep them narrow); `ttlMs`: a link's
229
+ * default lifetime (default 24 h, at most 30 days). A guest reaches only functions declaring
230
+ * `resource: { …, guests: true }`, and only its own record. See docs/AUTH.md ("Guests").
231
+ */
232
+ guests?: {
233
+ roles: readonly string[];
234
+ ttlMs?: number;
235
+ };
196
236
  /**
197
237
  * A mutation (`"<module>:<export>"`) FeltKit runs when a session ends, so state bound to that session can end
198
238
  * too (docs/AUTH.md, "When a session ends"). It runs as the session's principal (as recorded on the session,
@@ -356,6 +396,13 @@ export interface FeltKitOptions {
356
396
  * runtime/providers.ts and docs/PROVIDERS.md.
357
397
  */
358
398
  providers?: Record<string, import("./providers.js").ProviderDeclaration>;
399
+ /**
400
+ * Quotas for every function of the application (K3), on top of each function's own `quota`: at most
401
+ * `limit` calls in any `windowMs`, counted per principal across all functions ("principal") or for
402
+ * the whole application ("function" here means every call). Checked before the handler runs; a
403
+ * refusal is RATE_LIMITED with details.retryAfterMs (HTTP 429, Retry-After). See src/quota.ts.
404
+ */
405
+ quotas?: QuotaDeclaration;
359
406
  activity?: {
360
407
  /** What to record. Default: "all" in development/test, "writes" in production. */
361
408
  record?: "all" | "writes" | "errors";
@@ -721,15 +768,52 @@ export interface FunctionConfig<Kind extends FunctionKind, A extends ShapeInput,
721
768
  sequenceConflicts: number;
722
769
  };
723
770
  /**
724
- * Mutations only. `"required"`: an agent, service or API key may never run it directly, on any
771
+ * Mutations and actions. `"required"`: an agent, service, worker or API key may never run it directly, on any
725
772
  * interface (HTTP, AppPort, MCP, a job it queued). It may discover it and propose it
726
773
  * (`feltkit_agent_propose`); the proposal runs only after a person approves it, as the
727
774
  * proposer, with the proposer's own permissions (`access` still applies to it and to the
728
- * approver). People call it directly. See docs/GUARANTEES.md (Agents).
775
+ * approver). People call it directly. A worker (or any non-person caller) may also run it with a person's
776
+ * approval of exactly that call (`ctx.grants.approve`, named as `x-appport-approval`). See docs/GUARANTEES.md (Agents).
729
777
  */
730
778
  approval?: "required";
731
779
  /** Queries and mutations: the record it acts on must be the caller's. See OwnerDeclaration. */
732
780
  owner?: OwnerDeclaration;
781
+ /**
782
+ * How often a caller may run it (K3): `{ per: "principal", limit: 30, windowMs: 10_000 }`, or several.
783
+ * `per` is "principal", "function" (everyone together), "arg:<argument>" or "principal+arg:<argument>".
784
+ * Enforced before the handler (and before the policies and the authorize hook), on every interface;
785
+ * the (limit+1)th call in a window is RATE_LIMITED with details.retryAfterMs. See src/quota.ts.
786
+ */
787
+ quota?: QuotaDeclaration;
788
+ /**
789
+ * The record this function acts on (K4, K6, K7): `{ collection, id: "<argument>", by?: "<unique field>",
790
+ * guests?: true, agents?: "grant" }`. `id` names the argument holding the record's id, or with `by` a value
791
+ * of that unique field (a meeting's `code`). With `guests: true`, a guest admitted to that record by a guest
792
+ * link may call it (guests are refused by every function that does not say so); with `agents: "grant"`, an
793
+ * agent or service may call it only with a live grant for that record (`ctx.grants.admitAgent`). Checked at
794
+ * the execution boundary before the policies and the authorize hook; refusals are durable evidence.
795
+ */
796
+ resource?: {
797
+ collection: CollectionDefinition;
798
+ id: string;
799
+ by?: string;
800
+ guests?: boolean;
801
+ agents?: "grant";
802
+ };
803
+ /**
804
+ * Who may call it at all, before `access` is checked. Enforced at dispatch on every surface (HTTP, AppPort, MCP,
805
+ * the agent's tools):
806
+ *
807
+ * - `"public"` (default): anyone `access` admits.
808
+ * - `"worker"`: only a registered worker (`ctx.grants.registerWorker`), under a work grant naming it.
809
+ * - `"service"`: only a service principal (an API key, a runtime component, an operator-issued service session).
810
+ * - `"internal"`: no surface at all: only the application's own code calls it (`ctx.runQuery` / `ctx.runMutation`
811
+ * from an action, a job handler, an inbound webhook handler, `auth.onSessionEnd`). Every surface answers
812
+ * FUNCTION_NOT_FOUND; it is never published as a capability, listed to agents, or shown as a tool.
813
+ *
814
+ * Internal calls (the list above) pass every visibility; `access` still applies to them, as the caller.
815
+ */
816
+ visibility?: FunctionVisibility;
733
817
  handler: (ctx: Kind extends "query" ? QueryCtx : Kind extends "action" ? ActionCtx : MutationCtx, args: Simplify<InferShape<A>>) => R | Promise<R>;
734
818
  }
735
819
  export interface FunctionDefinition<Kind extends FunctionKind = FunctionKind, Args = any, Result = any> {
@@ -751,6 +835,12 @@ export interface FunctionDefinition<Kind extends FunctionKind = FunctionKind, Ar
751
835
  readonly approval?: "required";
752
836
  /** The record it acts on must be the caller's (queries and mutations). */
753
837
  readonly owner?: OwnerDeclaration;
838
+ /** Call limits (K3). */
839
+ readonly quota?: readonly QuotaSpec[];
840
+ /** The record it acts on, and who besides its role holders may reach it (guests, granted agents). */
841
+ readonly resource?: import("./runtime/resource-access.js").ResourceDeclaration;
842
+ /** Who may call it at all (default "public"); see FunctionConfig.visibility. */
843
+ readonly visibility?: FunctionVisibility;
754
844
  readonly handler: (ctx: any, args: any) => unknown;
755
845
  readonly app: FeltKitApp;
756
846
  /** Type-only markers. */
@@ -879,6 +969,37 @@ export declare class FeltKitApp<O extends FeltKitOptions = FeltKitOptions> {
879
969
  access: Access;
880
970
  description?: string;
881
971
  }): EventDefinition<S extends Schema<infer T> ? T : unknown>;
972
+ /**
973
+ * A channel of transient messages (K2): WebRTC signaling, typing, a raised hand, reactions. A message is
974
+ * sent to one scope (a recipient: a connection id, a call) with `ctx.channels.send(channel, scope,
975
+ * message)` from a mutation, delivered after it commits, at most once, to whoever is subscribed to that
976
+ * scope now (`client.subscribe(channel, { scope }, listener)` / `useEvent`), and **never written to
977
+ * FeltDB**: no record, no journal entry, no backup; the activity log records the sending call's
978
+ * metadata only (never a payload).
979
+ *
980
+ * Authority is the channel's, declared here: the sender needs `access.send` (and `authorize.send` when
981
+ * declared); each recipient needs `access.receive` and `authorize.receive` for the scope, asked when it
982
+ * subscribes and again before every delivery, so a revoked recipient gets nothing more, and a wildcard
983
+ * subscription never carries a message its holder may not receive. `quota` limits each sender.
984
+ *
985
+ * export const signaling = app.channel("call.signal", {
986
+ * message: s.object({ kind: s.enum(["offer", "answer", "ice"]), sdp: s.string({ maxLength: 65_536 }) }),
987
+ * access: { send: "calls.signal", receive: "calls.signal" },
988
+ * authorize: { receive: async ({ principal, scope, db }) => (await db.get(connections, scope))?.holder === principal?.id },
989
+ * quota: { per: "principal", limit: 60, windowMs: 60_000 },
990
+ * });
991
+ */
992
+ channel<S extends Schema>(name: string, config: {
993
+ message: S;
994
+ access: {
995
+ send: Access;
996
+ receive: Access;
997
+ };
998
+ authorize: ChannelConfig["authorize"];
999
+ maxBytes?: number;
1000
+ quota?: QuotaDeclaration;
1001
+ description?: string;
1002
+ }): EventDefinition<S extends Schema<infer T> ? T : unknown>;
882
1003
  /**
883
1004
  * An application agent: a handler that runs after a mutation commits, **as the agent** (principal
884
1005
  * type "agent", `roles`, never the triggering caller's authority), through the same authority as
@@ -906,6 +1027,24 @@ export declare class FeltKitApp<O extends FeltKitOptions = FeltKitOptions> {
906
1027
  * definitions (rename-safe) and the resource by its collection, both checked here.
907
1028
  */
908
1029
  policy<const R extends PolicyRule>(rule: R): R;
1030
+ /**
1031
+ * Presence (K1): a collection whose records are leases, bound to their holder and ending exactly once
1032
+ * (left, removed, expired, session-ended, replaced). Hold one with `ctx.presence.join(peers, fields)`,
1033
+ * renew it with `ctx.presence.renew`, end it with `ctx.presence.end`; read live leases with `ctx.db`
1034
+ * as usual (expired and ended ones are left out). A lease not renewed within `ttlMs` ends at that time
1035
+ * without anyone asking, and live queries over the collection re-run. `onEnd` names an `app.agent` run
1036
+ * after each end. See src/presence.ts and docs/PRESENCE-AND-SIGNALING-PROPOSAL.md.
1037
+ *
1038
+ * export const peers = app.presence("peers", { callId: s.string(), name: s.string() }, { ttlMs: 45_000 });
1039
+ */
1040
+ presence<S extends ShapeInput>(name: string, shape: S, options: {
1041
+ ttlMs: number;
1042
+ onEnd?: AgentDefinition | string;
1043
+ history?: boolean;
1044
+ tenant?: CollectionOptions["tenant"];
1045
+ indexes?: CollectionOptions["indexes"];
1046
+ description?: string;
1047
+ }): CollectionDefinition<S>;
909
1048
  collection<S extends ShapeInput>(name: string, shape: S, options?: CollectionOptions): CollectionDefinition<S>;
910
1049
  /**
911
1050
  * A business audit trail: an append-only collection of events about the app's own subjects, each
@@ -996,13 +1135,24 @@ export declare class FeltKitApp<O extends FeltKitOptions = FeltKitOptions> {
996
1135
  * `ctx.runMutation`) and the agent's proposals, all as the caller, so it can never bypass a
997
1136
  * function's authority. It can use the environment's model (`ctx.model.generate`) and stream
998
1137
  * events to its caller (`client.action(ref, args, { onEvent })`); the caller cancels by closing
999
- * the stream (`ctx.signal`). Not an AppPort capability: expose a mutation for that.
1138
+ * the stream (`ctx.signal`).
1139
+ *
1140
+ * Published with `capability`, it is an AppPort `consequential` capability with idempotency support: the
1141
+ * application-callable way to make an external effect (open a pull request, a payment). `ctx.effect.begin()` records
1142
+ * the effect before it is attempted, and an unknown outcome is never repeated by a retry (see ActionCtx.effect).
1143
+ * `approval: "required"` makes non-person callers need a person's approval of the exact call.
1000
1144
  */
1001
1145
  action<A extends ShapeInput = {}, R = unknown>(config: FunctionConfig<"action", A, R>): ActionDefinition<Simplify<InferShape<A>>, Awaited<R>>;
1146
+ /** A resource binding (FunctionConfig.resource), checked when the function is declared, and frozen. */
1147
+ private checkResource;
1002
1148
  /** An owner declaration, checked when the function is declared (never at a call), and frozen. */
1003
1149
  private checkOwner;
1004
1150
  private define;
1005
1151
  }
1152
+ /** Whether `field` has a single-field unique constraint on `collection` (it then names at most one record). */
1153
+ export declare function uniqueField(collection: CollectionDefinition, field: string): boolean;
1154
+ /** Who may call a function at all, before `access` (see FunctionConfig.visibility). */
1155
+ export type FunctionVisibility = "public" | "worker" | "service" | "internal";
1006
1156
  /** Define a FeltKit application. */
1007
1157
  export declare function feltkit<const O extends FeltKitOptions>(options: O): FeltKitApp<O>;
1008
1158
  export declare function isFeltKitApp(value: unknown): value is FeltKitApp;
package/dist/app.js CHANGED
@@ -8,6 +8,8 @@ import { defineSurface } from "./surfaces.js";
8
8
  import { REFERENCE_KEYWORD, RESERVED_FIELDS, s, shapeToObjectSchema } from "./schema.js";
9
9
  import { checkRetryPolicy } from "./runtime/transactions.js";
10
10
  import { claimSpecProblem } from "./runtime/claims.js";
11
+ import { checkQuota } from "./quota.js";
12
+ import { LEASE_FIELDS, MAX_LEASE_TTL_MS, MIN_LEASE_TTL_MS, PRESENCE } from "./presence.js";
11
13
  const APP = Symbol.for("feltkit.app");
12
14
  const COLLECTION = Symbol.for("feltkit.collection");
13
15
  const FUNCTION = Symbol.for("feltkit.function");
@@ -21,6 +23,12 @@ export const RESERVED_COLLECTIONS = new Set([
21
23
  // AppPort Services (every service it can construct on the shared instance)
22
24
  "files",
23
25
  "file_audit_events",
26
+ // AppPort Services 0.21: content-addressed file objects, resumable uploads and usage metering.
27
+ "file_objects",
28
+ "file_object_chunks",
29
+ "file_uploads",
30
+ "file_usage",
31
+ "intelligence_usage",
24
32
  "service_effect_evidence",
25
33
  "notifications",
26
34
  "notification_deliveries",
@@ -160,6 +168,21 @@ export class FeltKitApp {
160
168
  if (accounts.password === false && !accounts.magicLink && !options.auth?.providers)
161
169
  throw new TypeError("auth.accounts.password: false leaves no way to sign in: enable magicLink or a provider.");
162
170
  }
171
+ if (options.quotas !== undefined) {
172
+ const quotas = checkQuota(options.quotas, "feltkit({ quotas })");
173
+ if (quotas.some((q) => q.per.includes("arg:")))
174
+ throw new TypeError('feltkit({ quotas }): an application-wide quota is per "principal" or "function"; per-argument quotas belong on a function.');
175
+ }
176
+ const guests = options.auth?.guests;
177
+ if (guests !== undefined) {
178
+ if (!guests || !Array.isArray(guests.roles) || guests.roles.length === 0)
179
+ throw new TypeError('auth.guests needs the roles a guest may hold: { roles: ["guest"] }.');
180
+ for (const role of guests.roles)
181
+ if (!options.roles?.[role])
182
+ throw new TypeError(`auth.guests names role "${role}", which is not declared in roles.`);
183
+ if (guests.ttlMs !== undefined && (!Number.isInteger(guests.ttlMs) || guests.ttlMs < 60_000 || guests.ttlMs > 30 * 24 * 3_600_000))
184
+ throw new TypeError("auth.guests.ttlMs is from one minute to 30 days.");
185
+ }
163
186
  validateComponents(options.components, options.roles);
164
187
  validateProviders(options.providers);
165
188
  const tenant = options.auth?.tenant;
@@ -269,6 +292,51 @@ export class FeltKitApp {
269
292
  this.events.set(name, definition);
270
293
  return definition;
271
294
  }
295
+ /**
296
+ * A channel of transient messages (K2): WebRTC signaling, typing, a raised hand, reactions. A message is
297
+ * sent to one scope (a recipient: a connection id, a call) with `ctx.channels.send(channel, scope,
298
+ * message)` from a mutation, delivered after it commits, at most once, to whoever is subscribed to that
299
+ * scope now (`client.subscribe(channel, { scope }, listener)` / `useEvent`), and **never written to
300
+ * FeltDB**: no record, no journal entry, no backup; the activity log records the sending call's
301
+ * metadata only (never a payload).
302
+ *
303
+ * Authority is the channel's, declared here: the sender needs `access.send` (and `authorize.send` when
304
+ * declared); each recipient needs `access.receive` and `authorize.receive` for the scope, asked when it
305
+ * subscribes and again before every delivery, so a revoked recipient gets nothing more, and a wildcard
306
+ * subscription never carries a message its holder may not receive. `quota` limits each sender.
307
+ *
308
+ * export const signaling = app.channel("call.signal", {
309
+ * message: s.object({ kind: s.enum(["offer", "answer", "ice"]), sdp: s.string({ maxLength: 65_536 }) }),
310
+ * access: { send: "calls.signal", receive: "calls.signal" },
311
+ * authorize: { receive: async ({ principal, scope, db }) => (await db.get(connections, scope))?.holder === principal?.id },
312
+ * quota: { per: "principal", limit: 60, windowMs: 60_000 },
313
+ * });
314
+ */
315
+ channel(name, config) {
316
+ const where = `app.channel("${name}")`;
317
+ if (!config || typeof config !== "object")
318
+ throw new TypeError(`${where} needs { message, access, authorize }.`);
319
+ const unknownKeys = Object.keys(config).filter((k) => !["message", "access", "authorize", "maxBytes", "quota", "description"].includes(k));
320
+ if (unknownKeys.length)
321
+ throw new TypeError(`${where}: unknown option ${unknownKeys.map((k) => `"${k}"`).join(", ")}.`);
322
+ const send = checkAccess(config.access?.send, `${where}: access.send`);
323
+ const receive = checkAccess(config.access?.receive, `${where}: access.receive`);
324
+ if (typeof config.authorize?.receive !== "function")
325
+ throw new TypeError(`${where}: authorize.receive is required: who may receive on a scope is the channel's decision, asked at subscribe and before every delivery.`);
326
+ if (config.authorize.send !== undefined && typeof config.authorize.send !== "function")
327
+ throw new TypeError(`${where}: authorize.send is a function.`);
328
+ const maxBytes = config.maxBytes ?? 65_536;
329
+ if (!Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > 1_048_576)
330
+ throw new TypeError(`${where}: maxBytes is an integer from 1 to 1048576.`);
331
+ const quota = config.quota === undefined ? undefined : checkQuota(config.quota, where);
332
+ if (quota?.some((q) => q.per.includes("arg:")))
333
+ throw new TypeError(`${where}: a channel's quota is per "principal" or "function".`);
334
+ const definition = this.event(name, { payload: config.message, access: receive, ...(config.description ? { description: config.description } : {}) });
335
+ const channel = Object.freeze({ send, receive, authorize: Object.freeze({ ...config.authorize }), maxBytes, ...(quota ? { quota } : {}) });
336
+ const frozen = Object.freeze({ ...definition, channel });
337
+ this.events.set(name, frozen);
338
+ return frozen;
339
+ }
272
340
  /**
273
341
  * An application agent: a handler that runs after a mutation commits, **as the agent** (principal
274
342
  * type "agent", `roles`, never the triggering caller's authority), through the same authority as
@@ -354,6 +422,10 @@ export class FeltKitApp {
354
422
  if (collection !== undefined && (typeof collection === "string" || this.collections.get(collection.name) !== collection)) {
355
423
  throw new TypeError(`app.policy(${rule.id}): resource.collection must be a collection of this application.`);
356
424
  }
425
+ const by = rule.resource?.by;
426
+ if (by !== undefined && collection !== undefined && typeof collection !== "string" && !uniqueField(collection, by)) {
427
+ throw new TypeError(`app.policy(${rule.id}): resource.by "${by}" must be a field of ${collection.name} with its own unique constraint (unique: [["${by}"]]), so it names one record.`);
428
+ }
357
429
  for (const via of (rule.when ?? []).flatMap(viaCollections)) {
358
430
  if (typeof via === "string" || this.collections.get(via.name) !== via)
359
431
  throw new TypeError(`app.policy(${rule.id}): owner.via.collection must be a collection of this application.`);
@@ -361,6 +433,43 @@ export class FeltKitApp {
361
433
  this.policies.push(rule);
362
434
  return rule;
363
435
  }
436
+ /**
437
+ * Presence (K1): a collection whose records are leases, bound to their holder and ending exactly once
438
+ * (left, removed, expired, session-ended, replaced). Hold one with `ctx.presence.join(peers, fields)`,
439
+ * renew it with `ctx.presence.renew`, end it with `ctx.presence.end`; read live leases with `ctx.db`
440
+ * as usual (expired and ended ones are left out). A lease not renewed within `ttlMs` ends at that time
441
+ * without anyone asking, and live queries over the collection re-run. `onEnd` names an `app.agent` run
442
+ * after each end. See src/presence.ts and docs/PRESENCE-AND-SIGNALING-PROPOSAL.md.
443
+ *
444
+ * export const peers = app.presence("peers", { callId: s.string(), name: s.string() }, { ttlMs: 45_000 });
445
+ */
446
+ presence(name, shape, options) {
447
+ const where = `app.presence("${name}")`;
448
+ if (!options || !Number.isInteger(options.ttlMs) || options.ttlMs < MIN_LEASE_TTL_MS || options.ttlMs > MAX_LEASE_TTL_MS)
449
+ throw new TypeError(`${where}: ttlMs is an integer from ${MIN_LEASE_TTL_MS} to ${MAX_LEASE_TTL_MS} (milliseconds).`);
450
+ for (const field of Object.keys(LEASE_FIELDS))
451
+ if (field in shape)
452
+ throw new TypeError(`${where}: "${field}" is a lease field FeltKit keeps; name yours differently.`);
453
+ let onEnd;
454
+ if (options.onEnd !== undefined) {
455
+ onEnd = typeof options.onEnd === "string" ? options.onEnd : options.onEnd?.name;
456
+ if (typeof onEnd !== "string" || (typeof options.onEnd !== "string" && this.agents.get(onEnd) !== options.onEnd))
457
+ throw new TypeError(`${where}: onEnd names an app.agent of this application.`);
458
+ }
459
+ if (options.history !== undefined && typeof options.history !== "boolean")
460
+ throw new TypeError(`${where}: history is true or false.`);
461
+ const known = new Set(Object.keys(options).filter((k) => !["ttlMs", "onEnd", "history", "tenant", "indexes", "description"].includes(k)));
462
+ if (known.size)
463
+ throw new TypeError(`${where}: unknown option ${[...known].map((k) => `"${k}"`).join(", ")}.`);
464
+ const definition = this.collection(name, { ...shape, ...LEASE_FIELDS }, {
465
+ ...(options.tenant ? { tenant: options.tenant } : {}),
466
+ indexes: [{ fields: ["live"] }, { fields: ["session"] }, { fields: ["holder"] }, ...(options.indexes ?? [])],
467
+ description: options.description ?? `Presence leases (app.presence, ttl ${options.ttlMs} ms).`,
468
+ });
469
+ const config = Object.freeze({ ttlMs: options.ttlMs, history: options.history ?? true, ...(onEnd ? { onEnd } : {}) });
470
+ Object.defineProperty(definition, PRESENCE, { value: config });
471
+ return definition;
472
+ }
364
473
  collection(name, shape, options = {}) {
365
474
  if (!/^[a-z][a-zA-Z0-9_]{0,62}$/.test(name)) {
366
475
  throw new TypeError(`Collection name "${name}" must start with a lowercase letter and contain only letters, digits, and "_".`);
@@ -655,16 +764,37 @@ export class FeltKitApp {
655
764
  }
656
765
  action(input) {
657
766
  const config = input;
658
- if (config?.capability)
659
- throw new TypeError("An action cannot be an AppPort capability: it is not a transaction and makes no single, verifiable change. Expose a mutation as the capability, and call it from the action.");
660
- if (config?.approval)
661
- throw new TypeError("approval applies to mutations. An action changes state only through mutations and proposals, which carry their own approval rules.");
662
767
  if (config?.retry)
663
768
  throw new TypeError("retry applies to mutations.");
664
769
  if (config?.owner !== undefined)
665
770
  throw new TypeError("owner applies to queries and mutations: an action reads and writes only through them, which carry their own ownership rules.");
666
771
  return this.define("action", input);
667
772
  }
773
+ /** A resource binding (FunctionConfig.resource), checked when the function is declared, and frozen. */
774
+ checkResource(input, kind, args) {
775
+ const where = `app.${kind}({ resource })`;
776
+ if (kind === "action")
777
+ throw new TypeError(`${where}: resource applies to queries and mutations (an action reaches records only through them).`);
778
+ const r = input;
779
+ if (!r || typeof r !== "object" || Array.isArray(r))
780
+ throw new TypeError(`${where} is { collection, id, by?, guests?, agents? }.`);
781
+ const unknownKeys = Object.keys(r).filter((k) => !["collection", "id", "by", "guests", "agents"].includes(k));
782
+ if (unknownKeys.length)
783
+ throw new TypeError(`${where}: unknown member ${unknownKeys.map((k) => `"${k}"`).join(", ")}.`);
784
+ if (!isCollectionDefinition(r.collection) || this.collections.get(r.collection.name) !== r.collection)
785
+ throw new TypeError(`${where}: collection must be a collection of this application.`);
786
+ if (typeof r.id !== "string" || !Object.prototype.hasOwnProperty.call(args, r.id))
787
+ throw new TypeError(`${where}: id names the argument holding the record's id or key (${Object.keys(args).join(", ") || "none declared"}).`);
788
+ if (r.by !== undefined && (typeof r.by !== "string" || !uniqueField(r.collection, r.by)))
789
+ throw new TypeError(`${where}: by "${String(r.by)}" must be a field of ${r.collection.name} with its own unique constraint (unique: [["${String(r.by)}"]]).`);
790
+ if (r.guests !== undefined && typeof r.guests !== "boolean")
791
+ throw new TypeError(`${where}: guests is true or false.`);
792
+ if (r.guests === true && !this.options.auth?.guests)
793
+ throw new TypeError(`${where}: guests: true needs auth.guests (the roles a guest may hold).`);
794
+ if (r.agents !== undefined && r.agents !== "grant")
795
+ throw new TypeError(`${where}: agents is "grant" (or omitted).`);
796
+ return Object.freeze({ collection: r.collection, id: r.id, ...(r.by !== undefined ? { by: r.by } : {}), ...(r.guests ? { guests: true } : {}), ...(r.agents ? { agents: "grant" } : {}) });
797
+ }
668
798
  /** An owner declaration, checked when the function is declared (never at a call), and frozen. */
669
799
  checkOwner(input, kind, access, args) {
670
800
  const where = `app.${kind}({ owner })`;
@@ -743,13 +873,25 @@ export class FeltKitApp {
743
873
  if (config.approval !== undefined) {
744
874
  if (config.approval !== "required")
745
875
  throw new TypeError(`approval must be "required" (or omitted); got ${JSON.stringify(config.approval)}.`);
746
- if (kind !== "mutation")
747
- throw new TypeError("approval: \"required\" applies to mutations: a query changes nothing, so there is nothing to approve.");
876
+ if (kind === "query")
877
+ throw new TypeError("approval: \"required\" applies to mutations and actions: a query changes nothing, so there is nothing to approve.");
748
878
  if (config.access === "public")
749
879
  throw new TypeError("approval: \"required\" needs an access permission: an approval never grants one, and a public function has none to check.");
750
880
  }
751
881
  const owner = config.owner === undefined ? undefined : this.checkOwner(config.owner, kind, config.access, args);
882
+ const quota = config.quota === undefined ? undefined : checkQuota(config.quota, `app.${kind}()`, args);
883
+ const resource = config.resource === undefined ? undefined : this.checkResource(config.resource, kind, args);
884
+ if (config.visibility !== undefined && !VISIBILITIES.includes(config.visibility))
885
+ throw new TypeError(`app.${kind}(): visibility is ${VISIBILITIES.map((v) => `"${v}"`).join(", ")} (or omitted); got ${JSON.stringify(config.visibility)}.`);
886
+ if (config.visibility === "internal" && capability)
887
+ throw new TypeError(`app.${kind}(): an internal function is reached only by the application's own code, so it cannot be published as capability "${capability.name}".`);
888
+ if (config.visibility === "internal" && config.approval)
889
+ throw new TypeError(`app.${kind}(): approval: "required" governs callers on a surface; an internal function has none.`);
890
+ const visibility = config.visibility && config.visibility !== "public" ? config.visibility : undefined;
752
891
  return Object.freeze({
892
+ ...(resource ? { resource } : {}),
893
+ ...(visibility ? { visibility } : {}),
894
+ ...(quota ? { quota } : {}),
753
895
  [FUNCTION]: true,
754
896
  kind,
755
897
  ...(retry ? { retry: Object.freeze(retry) } : {}),
@@ -766,8 +908,18 @@ export class FeltKitApp {
766
908
  });
767
909
  }
768
910
  }
911
+ /** Whether `field` has a single-field unique constraint on `collection` (it then names at most one record). */
912
+ export function uniqueField(collection, field) {
913
+ if (!Object.prototype.hasOwnProperty.call(collection.shape, field))
914
+ return false;
915
+ return (collection.unique ?? []).some((u) => {
916
+ const fields = Array.isArray(u) ? u : u.fields;
917
+ return fields.length === 1 && fields[0] === field;
918
+ });
919
+ }
769
920
  /** Every member a function declaration may have (FunctionConfig). */
770
- const FUNCTION_CONFIG_KEYS = new Set(["args", "returns", "access", "description", "capability", "retry", "approval", "owner", "handler"]);
921
+ const FUNCTION_CONFIG_KEYS = new Set(["args", "returns", "access", "description", "capability", "retry", "approval", "owner", "quota", "resource", "visibility", "handler"]);
922
+ const VISIBILITIES = ["public", "worker", "service", "internal"];
771
923
  /** A reference field's target collection (`s.ref(...)`, optional or not), if it is one. */
772
924
  function referenceTarget(schema) {
773
925
  const json = schema?.toJSONSchema?.();